MCPcopy Create free account
hub / github.com/deepspeedai/DeepSpeed / defragment

Function defragment

deepspeed/runtime/zero/utils.py:215–243  ·  view source on GitHub ↗

move provided tensors into a contiguous flat buffer, with some additional measures taken to reduce memory fragmentation

(tensors: List[torch.Tensor])

Source from the content-addressed store, hash-verified

213
214
215def 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

Calls 8

get_only_unique_itemFunction · 0.90
get_acceleratorFunction · 0.90
collectMethod · 0.80
numelMethod · 0.45
copy_Method · 0.45
empty_cacheMethod · 0.45
toMethod · 0.45

Tested by

no test coverage detected