Repository navigation
fix(load): make transformers construction and post-load tying exclusive (#5421) - #5560
Merged
Merged
Conversation
…#5421) transformers builds a model inside one init-context group: the default-dtype window, a class-wide PreTrainedModel.tie_weights no-op (init.no_tie_weights) and the registered class swaps (apply_patches). Only the dtype window held the model-global-state writer, so a plain from_pretrained in another thread could disable tying while a GPT-QModel load built or re-tied its shell. A tied checkpoint then failed with 'does not provide tensors for 1 non-quantized parameter(s): lm_head.weight'. The tie that matters for a quantized load is the post-load one: the shell is built with weight init suspended, so post_init does not tie and _tie_weights_after_checkpoint_load is the only call that binds lm_head. It ran outside the writer as well, which is why guarding only the construction window did not close the failure. Hold the writer for every consumer of those patches: - PreTrainedModel.get_init_context prepends it to the init contexts, so the whole group (no_tie_weights, apply_patches, meta device) is exclusive. - PreTrainedModel._from_config holds it for the from_config construction. - init.no_tie_weights and apply_patches take it themselves. - _tie_weights_after_checkpoint_load takes it around the tie. - The load's default-dtype capture and the assert_loaded_model_state check both read under it, so a foreign dtype window cannot report a false 'corrupted state'. - The requantize(norm=...) teacher load takes the model-load lock like every other GPT-QModel-owned construction. The writer is still held for construction only, not for a load's weight I/O, packing or kernel post-init (#5304). Fixes #5421
ZX-ModelCloud
marked this pull request as ready for review
November 19, 2026 12:01
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
GPTQModel.load()of a tied-embedding checkpoint failed whenever a plaintransformers construction ran in another thread: a user's
AutoModelForCausalLM.from_pretrainedor GPT-QModel's ownrequantize(norm=NormConfig(teacher=...))teacher.transformers builds a model inside one init-context group
(
PreTrainedModel.get_init_context): thelocal_torch_dtypewindow, aclass-wide
PreTrainedModel.tie_weightsno-op (init.no_tie_weights) andthe registered class swaps (
apply_patches). Only the dtype window held themodel-global-state writer, so another thread could disable tying while a
GPT-QModel shell was built or re-tied. A tied checkpoint (which stores only
model.embed_tokens.weight) then failed withdoes not provide tensors for 1 non-quantized parameter(s): lm_head.weight.The tie that matters for a quantized load is the post-load one: the shell is
built with weight init suspended, so
post_initties nothing and_tie_weights_after_checkpoint_loadis the only call that bindslm_head. Itran outside the writer too, which is why guarding only the construction window
did not close the failure.
A second symptom had the same cause: the load captured and compared
torch.get_default_dtype()with a bare call, so a foreign dtype window made acorrect load fail as a "corrupted state"
(
changed from torch.bfloat16 to torch.float32).Measured on current
mainwith a 16-layer GPTQ 4-bit tied checkpoint and adense
from_pretrainedloop in another thread: 7 of 20 loads failed(5 default-dtype flips, 2 missing
lm_head.weight). With this PR: 0 of 20,and 0 of 40 on a second run.
Fixes #5421
What Changed
gptqmodel/utils/torch.py: the import-time guard now makes constructionexclusive, not only the dtype window.
PreTrainedModel.get_init_contextprepends the writer to the returnedcontext list.
ContextManagersenters the list in order through anExitStack, so the writer is acquired beforeno_tie_weights/apply_patchesand released after them.PreTrainedModel._from_configholds it for the wholefrom_configconstruction, which opens
apply_patchesoutsideget_init_contextandmay have no dtype window.
init.no_tie_weightsandapply_patchestake it themselves, so a directuse is exclusive even without
get_init_context.gptqmodel/utils/model.py:_tie_weights_after_checkpoint_loadtakes thewriter around the tie, so a foreign window cannot turn it into a no-op.
gptqmodel/models/loader.py: new_default_dtype_outside_construction()reads the default dtype under the writer; both load entry points use it.
gptqmodel/utils/hf.py:assert_loaded_model_statecompares the settleddefault dtype under the writer.
gptqmodel/models/base.py: therequantize(norm=...)teacherfrom_pretrainedtakesmodel_load_lock(), like every other GPT-QModel-ownedconstruction.
docs/concurrency.md: the new construction-exclusivity flow, before/aftertable, failure table and validation rows.
tests/test_construction_global_state_5421.py: deterministic regressions.The writer is still held for construction only — not for a load's weight I/O,
packing or kernel post-init — so the #5304 contract is unchanged.
No API or behavior change for serial callers.
Tests
Red evidence: the same test file against the unfixed tree (only the new
_default_dtype_outside_construction()call adapted back to the baretorch.get_default_dtype()) fails 6 of 8 at their intended assertions:test_init_context_group_holds_the_writer_and_disables_tyingthe writer must be entered before every contexttest_foreign_tie_window_blocks_a_from_config_constructiontest_post_load_tie_is_not_skipped_by_a_foreign_windowtest_default_dtype_capture_waits_out_a_foreign_windowtest_load_state_check_waits_out_a_foreign_windowtest_norm_teacher_load_takes_the_model_load_lockfrom_pretrainedran outside the lockThe two remaining nodes are the import-time guard assertions (they describe the
fix itself) and the consumer-level race smoke test, which does not detect the
defect deterministically because a tiny fixture's construction window is short;
the deterministic nodes above are the detectors.
Model Support / Module Plan
Not applicable: no model type, alias, definition or module-plan change.
AWQ onboarding safety
Not applicable: no AWQ grouping/search/replay/fold change.
Logic Flow Documentation
page are included.
file:lineevidence.docs/concurrency.mdrepeats the diagrams, titled for the mechanism, andis linked from
README.md.Before (
3a50258d6/d10a08a65): onlylocal_torch_dtypetook the writer.gptqmodel/utils/torch.py:install_model_global_state_dtype_guard()wrapped onecontext;
models/loader.py:2273,2770read the dtype bare;utils/model.py_tie_weights_after_checkpoint_loadcalledmodel.tie_weights()bare;models/base.py:3378called the teacherfrom_pretrainedbare.local_torch_dtypewindowget_init_contextgroup (no_tie_weights,apply_patches, meta device)_from_configconstructioninit.no_tie_weights/apply_patchestorch.get_default_dtype()from_pretrainedmodel_load_lock()model_load_lock()flowchart TD A["thread 1: GPTQModel.load"] --> B["_MODEL_LOAD_LOCK<br/>whole load"] B --> C["from_config: global-state writer<br/>init-context group"] C --> D["weight I/O, packing"] D --> E["_tie_weights_after_checkpoint_load<br/>global-state writer"] E --> F["assert_loaded_model_state<br/>dtype read under writer"] G["thread 2: user from_pretrained"] --> H["get_init_context<br/>global-state writer"] H --> I["no_tie_weights / apply_patches<br/>inside the writer"] I --> J["cls(config): construction"] H -. "excludes C and E" .-> C H -. "excludes C and E" .-> E K["thread 3: compiled forward"] --> L["global-state reader"] C -. "excludes L only while<br/>construction runs" .-> L D -. "does not exclude" .-> LFailure paths: a construction that cannot take the writer (a compiled call
already holds the reader) raises instead of upgrading; the load lock keeps
GPTQModel.loadcalls serialized; a load that really leaves a mixed dtype, ameta tied weight or a changed default dtype still raises.
Review Requirements
AI-assisted code is welcome. Open the PR as a draft. Mark it ready only after
review and after GitHub confirms the pushed head has no conflicts with the
current remote base.
I or an AI agent (such as Codex or Claude) have:
Kernel Accuracy Requirements
Not applicable: no kernel or fusion change.
Notes
re-entrant, so nested constructions and a load that runs compiled code while
it owns the writer keep working.
get_init_context/_from_configkeeps thelocal_torch_dtypeand patch-level guards; the wrappers skip silently whenthe symbol is absent.
get_init_contextis still covered by thelocal_torch_dtypeand patch-level guards, not by the group wrapper.