Skip to content

Add materialize_meta_tensors to reverse dispatch_model (#3866)#4078

Open
discobot wants to merge 1 commit into
huggingface:mainfrom
discobot:fix/3866-materialize-meta-tensors
Open

Add materialize_meta_tensors to reverse dispatch_model (#3866)#4078
discobot wants to merge 1 commit into
huggingface:mainfrom
discobot:fix/3866-materialize-meta-tensors

Conversation

@discobot

Copy link
Copy Markdown

What does this PR do?

Fixes #3866.

The blocker is twofold: AlignDevicesHook.init_hook keeps the real values of offloaded weights only in hook.weights_map and leaves meta placeholders on the module, and dispatch_model wraps model.to to raise as soon as any parameter is on meta. Notably, removing the hooks is not enough: AlignDevicesHook.detach_hook only restores weights that were on a real device before dispatch, so for models whose weights went straight from the checkpoint to the offload folder (load_checkpoint_and_dispatch, from_pretrained(device_map=...)) the offloaded weights stay on meta with no public way back.

This PR adds materialize_meta_tensors(model, target_device="cpu") in big_modeling.py: it detaches all hooks (which also unwraps to/cuda), loads the weights still on meta from each offload hook's weights_map (mirroring AlignDevicesHook.pre_forward, including the int8 fp16 statistics), reties tied parameters, drops hf_device_map, and moves the model to target_device. The model is then a regular module again and .to() works for the CPU-parking round-trip described in the issue.

Four new CPU-runnable tests in tests/test_big_modeling.py cover the dispatch_model and load_checkpoint_and_dispatch flows, tied weights, and offload_buffers=True; outputs match the un-dispatched reference and .to() no longer raises or warns afterwards.

On the API shape: @SunMarc suggested a context manager or a dispatch_model flag — I went with the plain function from the issue since it is the primitive both of those can be built on (a context manager only needs to re-dispatch with the saved device map on exit). Happy to add either on top if preferred.

Before submitting

Who can review?

@SunMarc

…ce#3866)

Models dispatched with offloaded modules keep their offloaded weights on the meta device, so they cannot be moved with .to() afterwards. This adds materialize_meta_tensors, which loads the offloaded weights back from the hooks' weights_map, removes all the hooks added by Accelerate and places the model on the requested device, making it a regular movable module again. It also covers weights that were never on a real device (the load_checkpoint_and_dispatch flow), which detaching the hooks alone cannot recover. Requested in huggingface#3866.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature Request: Add API to Materialize Meta Tensors for Device Movement

1 participant