-
Notifications
You must be signed in to change notification settings - Fork 26.4k
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
fix: extend the unwrap_model function and save unwrapped model state dict instead of wrapped #29780
fix: extend the unwrap_model function and save unwrapped model state dict instead of wrapped #29780
Conversation
…children layers and save_unwrap_model state_dict instead of wrapped_model_state_dict
@alanwaketan can you also take a look please ? |
You can replicate the wrapping and unwrapping using this script:
|
The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update. |
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.
LGTM! I'm not sure what's the process of adding a test case in HF though...
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.
Thanks for digging into this and fixing!
We should add a test to make sure that:
- Models relying on the previous
unwrap
behaviour still work - This fixes the issue - add a test which would fail without this change
src/transformers/modeling_utils.py
Outdated
except AttributeError: | ||
unwrapped_module = module # Handle cases where wrapped module is inaccessible |
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.
Could you give an example of when this happens? It seems weird we'd have hasattr(module, "module")
evaluate as True
but then we can't do getattr(module, "module")
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.
Yes, you are right @amyeroberts. It does seem weird, I don't remember why I implemented like this, but thanks for pointing it out. I also can't think of an example.
I am fixing it.
@amyeroberts I had to change the So, how should we proceed here? |
@amyeroberts here is a small snippet for the test: import torch
import torch_xla
import torch.nn as nn
from transformers import AutoModelForCausalLM
from torch_xla.experimental.spmd_fully_sharded_data_parallel import SpmdFullyShardedDataParallel as FSDPv2
import torch_xla.distributed.spmd as xs
import torch_xla.runtime as xr
import numpy as np
import unittest
def compare_state_dict_keys(state_dict_keys_model1, state_dict_keys_model2):
for key1, key2 in zip(state_dict_keys_model1, state_dict_keys_model2):
if key1 != key2:
# print(f"Keys are not equal")
# print(key1, key2)
return False
return True
# Original `unwrap_model` function
def original_unwrap_model(model: nn.Module) -> nn.Module:
"""Original unwrap implementation for comparison."""
if hasattr(model, "module"):
return original_unwrap_model(model.module)
else:
return model
def unwrap_model_new(model: nn.Module) -> nn.Module:
"""
Recursively unwraps a module and its child sublayers.
Args:
model (nn.Module): Module to unwrap.
Returns:
nn.Module: The unwrapped module.
"""
def recursive_unwrap(module):
if hasattr(module, "module"):
unwrapped_module = recursive_unwrap(getattr(module, "module"))
else:
unwrapped_module = module # Handle cases where wrapped module is inaccessible
# Unwrap child sublayers recursively
for name, child in module.named_children():
setattr(module, name, recursive_unwrap(child))
return unwrapped_module
# Start with top-level unwrapping
unwrapped_model = recursive_unwrap(model)
return unwrapped_model
class TestUnwrap(unittest.TestCase):
def test_compatibility_with_original_behavior(self):
model_id = "mistralai/Mistral-7B-v0.1"
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16)
num_devices = xr.global_runtime_device_count()
xs.set_global_mesh(xs.Mesh(np.array(range(num_devices)), (num_devices, 1), axis_names=("fsdp", "tensor")))
wrapped_model = FSDPv2(model)
unwrapped_model_old = original_unwrap_model(wrapped_model)
state_dict_keys_model1 = list(unwrapped_model_old.state_dict().keys())
unwrapped_model_new = unwrap_model_new(wrapped_model)
state_dict_keys_model2 = list(unwrapped_model_new.state_dict().keys())
assert compare_state_dict_keys(state_dict_keys_model1, state_dict_keys_model2) == True
def test_nested_unwrap_modules(self):
model_id = "mistralai/Mistral-7B-v0.1"
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16)
orig_state_dict_keys = list(model.state_dict().keys())
num_devices = xr.global_runtime_device_count()
xs.set_global_mesh(xs.Mesh(np.array(range(num_devices)), (num_devices, 1), axis_names=("fsdp", "tensor")))
def nested_wrap(model):
layer = getattr(getattr(model, "model"), "embed_tokens")
wrapped_layer = FSDPv2(layer)
setattr(getattr(model, "model"), "embed_tokens", wrapped_layer)
return FSDPv2(model)
wrapped_model = nested_wrap(model)
unwrapped_model_old = original_unwrap_model(wrapped_model)
old_state_dict_keys = list(unwrapped_model_old.state_dict().keys())
unwrapped_model_new = unwrap_model_new(wrapped_model)
new_state_dict_keys = list(unwrapped_model_new.state_dict().keys())
assert compare_state_dict_keys(old_state_dict_keys, orig_state_dict_keys) == False
assert compare_state_dict_keys(new_state_dict_keys, orig_state_dict_keys) == True
# if __name__ == "__main__":
# test_unwrap = TestUnwrap()
# test_unwrap.test_compatibility_with_original_behavior()
# test_unwrap.test_nested_unwrap_modules() It can be run using: python -m unittest test_unwrap_model.py
|
New proposal for this, which @shub-kris's work here can still be done: This should be merged/worked on in the following order:
|
@muellerzr how about this PR going? I found the upstreaming |
Point 1&2 both have been merged. @muellerzr can you help to go to step 3? |
If @shub-kris wants to rebase, the changes in |
This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread. Please note that issues that do not follow the contributing guidelines are likely to be ignored. |
What does this PR do?
This PR pushes two changes:
unwrap_model(model).state_dict()
wheneverif isinstance(unwrap_model(model), supported_classes)
unwrap_model()
so that any wrapper on the children layer of model can also be unwrapped correctly.With the existing
unwrap_model()
only the outermost layer is unwrapped and it fails when we use wrapping withfsdp
as it doesn't go through the children layers or modules.For example:
A Wrapped Model
When unwrapped using existing
unwrap_model()
leads toBut when using the change mentioned in this repo:
Fixes #29659
Before submitting
Pull Request section?
to it if that's the case.
documentation guidelines, and
here are tips on formatting docstrings.
Who can review?
@amyeroberts @muellerzr @pacman100
Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.