memory.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # LICENSE HEADER MANAGED BY add-license-header
  2. #
  3. # Copyright 2018 Kornia Team
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. from typing import Any, Dict
  18. from kornia.core import Device, Module, Tensor, concatenate
  19. def batched_forward(
  20. model: Module, data: Tensor, device: Device, batch_size: int = 128, **kwargs: Dict[str, Any]
  21. ) -> Tensor:
  22. r"""Run the forward in micro-batches.
  23. When the just model.forward(data) does not fit into device memory, e.g. on laptop GPU.
  24. In the end, it transfers the output to the device of the input data tensor.
  25. E.g. running HardNet on 8000x1x32x32 tensor.
  26. Args:
  27. model: Any torch model, which outputs a single tensor as an output.
  28. data: Input data of Bx(Any) shape.
  29. device: which device should we run on.
  30. batch_size: "micro-batch" size.
  31. **kwargs: any other arguments, which accepts model.
  32. Returns:
  33. output of the model.
  34. Example:
  35. >>> patches = torch.rand(8000, 1, 32, 32)
  36. >>> sift = kornia.feature.SIFTDescriptor(32)
  37. >>> desc_batched = batched_forward(sift, patches, torch.device('cpu'), 128)
  38. >>> desc = sift(patches)
  39. >>> assert torch.allclose(desc, desc_batched)
  40. """
  41. model_dev = model.to(device)
  42. B: int = len(data)
  43. bs: int = batch_size
  44. if B > batch_size:
  45. out_list = []
  46. n_batches = int(B // bs + 1)
  47. for batch_idx in range(n_batches):
  48. st = batch_idx * bs
  49. if batch_idx == n_batches - 1:
  50. if (batch_idx + 1) * bs > B:
  51. end = B
  52. else:
  53. end = (batch_idx + 1) * bs
  54. else:
  55. end = (batch_idx + 1) * bs
  56. if st >= end:
  57. continue
  58. out_list.append(model_dev(data[st:end].to(device), **kwargs))
  59. out = concatenate(out_list, 0)
  60. return out.to(data.device)
  61. return model(data, **kwargs)