fix: use sys.modules.get() to avoid KeyError in modeling_utils#45089
Open
Krishnachaitanyakc wants to merge 1 commit intohuggingface:mainfrom
Open
fix: use sys.modules.get() to avoid KeyError in modeling_utils#45089Krishnachaitanyakc wants to merge 1 commit intohuggingface:mainfrom
Krishnachaitanyakc wants to merge 1 commit intohuggingface:mainfrom
Conversation
Replace unsafe `sys.modules[cls.__module__]` bracket access with `sys.modules.get(cls.__module__)` in `_can_set_attn_implementation` and `_can_set_experts_implementation`. When a module has been deleted from sys.modules (e.g. during testing or dynamic reloading), bracket access raises KeyError. Using .get() returns None, which is then handled by the existing guard that already checks for missing __file__. Fixes huggingface#45003
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Fixes #45003
_can_set_attn_implementationand_can_set_experts_implementationinPreTrainedModelusesys.modules[cls.__module__], which raisesKeyErrorwhen a module has been removed fromsys.modulesat runtime. This can happen with:sys.modulesfor dependency managementChanges
sys.modules[cls.__module__]withsys.modules.get(cls.__module__)(2 locations)class_module is Noneguard before the existinghasattr(class_module, "__file__")checkFalse— the same safe fallback already used for modules without__file__(e.g., Jupyter notebooks)Why not a broader fix?
This is intentionally minimal (4 lines changed). The existing comment already acknowledges that module lookup can fail ("This can happen for a custom model in a jupyter notebook or repl"), and
sys.modules.get()is the standard safe-access pattern.Test plan
sys.modules.get()returnsNone(notKeyError) when module is absent —Nonecheck short-circuits toreturn FalseAI assistance was used in preparing this PR.