move provided tensors into a contiguous flat buffer, with some additional measures taken to reduce memory fragmentation
(tensors: List[torch.Tensor])
| 213 | |
| 214 | |
| 215 | def defragment(tensors: List[torch.Tensor]) -> torch.Tensor: |
| 216 | """move provided tensors into a contiguous flat buffer, with some additional |
| 217 | measures taken to reduce memory fragmentation""" |
| 218 | assert len(set(t.dtype for t in tensors)) == 1 |
| 219 | assert len(set(t.device for t in tensors)) == 1 |
| 220 | |
| 221 | cpu_buffer = torch.empty(sum(p.numel() for p in tensors), |
| 222 | dtype=get_only_unique_item(t.dtype for t in tensors), |
| 223 | device="cpu") |
| 224 | tensor_infos: List[Tuple[torch.Tensor, int, int]] = get_mapping_to_flat_buffer(tensors) |
| 225 | orig_device = get_only_unique_item(t.device for t in tensors) |
| 226 | |
| 227 | offset = 0 |
| 228 | for tensor, offset, tensor_numel in tensor_infos: |
| 229 | # move the tensor from device memory to host memory |
| 230 | cpu_buffer.narrow(0, offset, tensor_numel).copy_(tensor) |
| 231 | tensor.data = torch.empty(0, dtype=tensor.dtype, device=tensor.device) |
| 232 | |
| 233 | gc.collect() |
| 234 | get_accelerator().empty_cache() |
| 235 | |
| 236 | # copy tensors (now flattened and contiguous) back to GPU |
| 237 | device_buffer = cpu_buffer.to(orig_device) |
| 238 | |
| 239 | # restore device tensors |
| 240 | for tensor, offset, tensor_numel in tensor_infos: |
| 241 | tensor.data = device_buffer.narrow(0, offset, tensor_numel) |
| 242 | |
| 243 | return device_buffer |
no test coverage detected