-
Notifications
You must be signed in to change notification settings - Fork 5
State dict serialization #51
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kaiyuan-li
wants to merge
9
commits into
meta-pytorch:main
Choose a base branch
from
kaiyuan-li:state_dict_serialization
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
9567b1f
create functions
kaiyuan-li 43427f6
add tests
kaiyuan-li c1da899
sync
kaiyuan-li dce528a
Merge branch 'main' into state_dict_serialization
kaiyuan-li 1b35e01
TorchstoreStateDict
kaiyuan-li f68ce3f
dtensor support
kaiyuan-li 25ca59b
sync
kaiyuan-li 24d46ac
sync
kaiyuan-li 298eb5d
sync
kaiyuan-li File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,8 +4,9 @@ | |
# This source code is licensed under the BSD-style license found in the | ||
# LICENSE file in the root directory of this source tree. | ||
|
||
from dataclasses import dataclass | ||
from logging import getLogger | ||
from typing import Optional | ||
from typing import Any, Dict, List, Optional, Tuple | ||
|
||
import torch | ||
from torch.distributed.checkpoint._nested_dict import ( | ||
|
@@ -95,3 +96,122 @@ def _state_dict_size(state_dict): | |
|
||
size += tensor.numel() * tensor.element_size() | ||
return size // (1024 * 1024) | ||
|
||
|
||
@dataclass | ||
class TensorReference: | ||
"""Metadata for a tensor in a tensor blob""" | ||
|
||
shape: Tuple[int, ...] | ||
dtype: torch.dtype | ||
offset: int # Byte offset in the blob | ||
size: int # Size in bytes | ||
|
||
|
||
def generate_tensor_blob(state_dict: Dict[str, Any]): | ||
""" | ||
Extract all tensors from state_dict and create a blob. Replace the tensors | ||
with corresponding references and returns a state_dict with only tensor references, | ||
and the tensor blob. | ||
|
||
Args: | ||
state_dict: Dictionary that may contain tensors at any level | ||
|
||
Returns: | ||
- Modified dictionary with tensors replaced by TensorReference objects | ||
- 1D uint8 tensor blob containing all serialized tensor data | ||
""" | ||
|
||
def _extract_recursive( | ||
obj: Dict[str, Any], | ||
tensor_list: List[Tuple[torch.Tensor, TensorReference]], | ||
path: str = "", | ||
): | ||
"""Recursively extract tensors and replace with TensorReference objects""" | ||
if isinstance(obj, torch.Tensor): | ||
# Create placeholder reference (offset will be filled later) | ||
ref = TensorReference( | ||
shape=tuple(obj.shape), | ||
dtype=obj.dtype, | ||
offset=-1, # Will be updated when building blob | ||
size=obj.numel() * obj.element_size(), | ||
) | ||
tensor_list.append((obj, ref)) | ||
return ref # Replace tensor with TensorReference | ||
elif isinstance(obj, dict): | ||
return { | ||
k: _extract_recursive(v, tensor_list, f"{path}.{k}") | ||
for k, v in obj.items() | ||
} | ||
elif isinstance(obj, (list, tuple)): | ||
return type(obj)( | ||
_extract_recursive(item, tensor_list, f"{path}[{i}]") | ||
for i, item in enumerate(obj) | ||
) | ||
else: | ||
return obj # Non-tensor data stays as-is | ||
|
||
tensor_list: List[Tuple[torch.Tensor, TensorReference]] = [] | ||
|
||
modified_state_dict = _extract_recursive(state_dict, tensor_list) | ||
|
||
if not tensor_list: | ||
return modified_state_dict, torch.empty(0, dtype=torch.uint8) | ||
|
||
# Calculate total size and update offsets | ||
current_offset = 0 | ||
|
||
for tensor, ref in tensor_list: | ||
ref.offset = current_offset | ||
current_offset += ref.size | ||
|
||
blob = torch.empty(current_offset, dtype=torch.uint8) | ||
|
||
# Copy tensor data using your efficient approach | ||
for tensor, ref in tensor_list: | ||
# Handle scalar tensors | ||
tensor_cpu = tensor.detach().cpu() | ||
if tensor_cpu.dim() == 0: | ||
tensor_cpu = tensor_cpu.unsqueeze(0) | ||
|
||
byte_view = tensor_cpu.view(torch.uint8).flatten() | ||
|
||
# Copy to blob | ||
blob[ref.offset : ref.offset + ref.size] = byte_view | ||
|
||
return modified_state_dict, blob | ||
|
||
|
||
def reconstruct_state_dict_from_tensor_blob( | ||
state_dict_with_tensor_refs: Dict[str, Any], blob: torch.Tensor | ||
) -> Dict[str, Any]: | ||
""" | ||
Reconstruct a state_dict which only contains tensor references by | ||
reconstructing the tensors using the tensor blob and the tensor references. | ||
Returns the reconstructed state dict. | ||
""" | ||
|
||
def _reconstruct_recursive(obj): | ||
if isinstance(obj, TensorReference): | ||
# Pre-allocate tensor with correct shape and dtype (TorchStore approach) | ||
tensor = torch.empty(obj.shape, dtype=obj.dtype) | ||
|
||
# Get byte view of the allocated tensor | ||
if tensor.dim() == 0: | ||
tensor_unsqueezed = tensor.unsqueeze(0) | ||
byte_view = tensor_unsqueezed.view(torch.uint8).flatten() | ||
else: | ||
byte_view = tensor.view(torch.uint8).flatten() | ||
|
||
# Copy bytes from blob into tensor's byte view | ||
tensor_bytes = blob[obj.offset : obj.offset + obj.size] | ||
byte_view.copy_(tensor_bytes) | ||
|
||
return tensor | ||
elif isinstance(obj, dict): | ||
return {k: _reconstruct_recursive(v) for k, v in obj.items()} | ||
elif isinstance(obj, (list, tuple)): | ||
return type(obj)(_reconstruct_recursive(item) for item in obj) | ||
else: | ||
return obj | ||
|
||
return _reconstruct_recursive(state_dict_with_tensor_refs) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we instead use flatten_state_dict instead of making this recursive?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you think about making this a class method of a "TorchStoreStateDict", or similar?
Then we can do things like:
and also store any necessary data as objects in the state dict.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done.