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

Function defragment

deepspeed/runtime/zero/utils.py:224–252  ·  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

222
223
224def defragment(tensors: List[torch.Tensor]) -> torch.Tensor:
225 """move provided tensors into a contiguous flat buffer, with some additional
226 measures taken to reduce memory fragmentation"""
227 assert len(set(t.dtype for t in tensors)) == 1
228 assert len(set(t.device for t in tensors)) == 1
229
230 cpu_buffer = torch.empty(sum(p.numel() for p in tensors),
231 dtype=get_only_unique_item(t.dtype for t in tensors),
232 device="cpu")
233 tensor_infos: List[Tuple[torch.Tensor, int, int]] = get_mapping_to_flat_buffer(tensors)
234 orig_device = get_only_unique_item(t.device for t in tensors)
235
236 offset = 0
237 for tensor, offset, tensor_numel in tensor_infos:
238 # move the tensor from device memory to host memory
239 cpu_buffer.narrow(0, offset, tensor_numel).copy_(tensor)
240 tensor.data = torch.empty(0, dtype=tensor.dtype, device=tensor.device)
241
242 gc.collect()
243 get_accelerator().empty_cache()
244
245 # copy tensors (now flattened and contiguous) back to GPU
246 device_buffer = cpu_buffer.to(orig_device)
247
248 # restore device tensors
249 for tensor, offset, tensor_numel in tensor_infos:
250 tensor.data = device_buffer.narrow(0, offset, tensor_numel)
251
252 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