Skip to content

Fix KeyError in extract_model_from_parallel for partial torch.compile#3881

Merged
SunMarc merged 2 commits intohuggingface:mainfrom
amanzoni1:fix-extract-model-compiled-submodules
Dec 16, 2025
Merged

Fix KeyError in extract_model_from_parallel for partial torch.compile#3881
SunMarc merged 2 commits intohuggingface:mainfrom
amanzoni1:fix-extract-model-compiled-submodules

Conversation

@amanzoni1
Copy link
Contributor

What does this PR do?

This PR fixes a KeyError: '_orig_mod' crash within the extract_model_from_parallel utility (called by accelerator.unwrap_model and subsequently by the transformers.Trainer) when attempting to unwrap a model that contains compiled submodules but is not compiled at the top level.

The original code assumed that if has_compiled_regions(model) returned True, the top-level model object must necessarily have the _orig_mod attribute (or be a wrapper that exposes it via __dict__), leading to the crash when the model was only partially compiled.

The fix introduces a safe check (if "_orig_mod" in model.__dict__:) before attempting to access the attribute in the elif has_compiled: block.

Fixes #3879

Before submitting

  • This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
  • [ x ] Did you read the contributor guideline,
    Pull Request section?
  • [ x ] Was this discussed/approved via a Github issue or the forum? Please add a link
    to it if that's the case.
  • Did you make sure to update the documentation with your changes? Here are the
    documentation guidelines, and
    here are tips on formatting docstrings.
  • [ x ] Did you write any new necessary tests?

Who can review?

@SunMarc
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.

Copy link
Member

@SunMarc SunMarc left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this ! Would that solve your issue @Giuseppe5 ?

@Giuseppe5
Copy link
Contributor

Giuseppe5 commented Dec 11, 2025

I believe so, I'm going to test it locally and let you know if something else breaks.

Thanks a lot @amanzoni1 and @SunMarc!

@HuggingFaceDocBuilderDev

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.

@SunMarc SunMarc merged commit 696e6cf into huggingface:main Dec 16, 2025
25 checks passed
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.

Bug in accelerator.unwrap_model

4 participants