MCPcopy Create free account
hub / github.com/AIS-SNU/Smart-Infinity / save_state_dict

Method save_state_dict

deepspeed/runtime/pipe/module.py:547–580  ·  view source on GitHub ↗
(self, save_dir, checkpoint_engine)

Source from the content-addressed store, hash-verified

545 return ckpt_files
546
547 def save_state_dict(self, save_dir, checkpoint_engine):
548 # Processes having the same model parallel rank on different data parallel instances
549 # have identical layer weights. We can distribute the task of saving the layer weights
550 # among the data parallel ranks. For example, if a pipeline stage has 9 layers and
551 # if there are 2 data parallel instances, rank 0 will save the first 5 layers and
552 # rank 1 will save the last 4.
553 dp_rank = self._grid.data_parallel_id
554 dp_size = self._grid.data_parallel_size
555 num_layers = len(self.forward_funcs)
556 if self.checkpoint_parallel_write_pipeline:
557 # spread layers evenly across data parallel ranks
558 offsets = ds_utils.partition_uniform(num_layers, dp_size)
559 start, end = offsets[dp_rank], offsets[dp_rank + 1]
560 else:
561 # data parallel rank 0 writes all layers
562 if dp_rank != 0:
563 return
564 start, end = 0, num_layers
565 layer_list = self.forward_funcs[start:end]
566
567 checkpoint_engine.makedirs(save_dir, exist_ok=True)
568 for idx, layer in enumerate(layer_list):
569 model_ckpt_path = self.ckpt_layer_path(save_dir, start + idx)
570 if not hasattr(layer, 'state_dict'):
571 continue
572 # We pass cloned tensors to torch.save() to avoid checkpoint bloat which occurs because torch.save()
573 # saves the underlying storage rather than the slice of the storage corresponding to individual tensors.
574 # This is a problem in DeepSpeed because we often allocate tensors using slices of large flattened buffers.
575 # Tensor cloning helps to avoid this problem because the storage of cloned tensors are closer to the true size.
576 # It is expected that the garbage collector will reclaim the cloned tensor storage to avoid memory bloat.
577 # See https://pytorch.org/docs/stable/notes/serialization.html#preserve-storage-sharing
578 orig_state_dict = layer.state_dict()
579 final_state_dict = type(orig_state_dict)({k: v.clone() for k, v in orig_state_dict.items()})
580 checkpoint_engine.save(final_state_dict, model_ckpt_path)
581
582 def load_state_dir(self, load_dir, checkpoint_engine, strict=True):
583 for idx, layer in enumerate(self.forward_funcs):

Callers 1

module_state_dictMethod · 0.80

Calls 4

ckpt_layer_pathMethod · 0.95
makedirsMethod · 0.80
state_dictMethod · 0.45
saveMethod · 0.45

Tested by

no test coverage detected