Skip to content

fix(load): make transformers construction and post-load tying exclusive (#5421) - #5560

Merged
Qubitium merged 1 commit into
mainfrom
fix/5421-global-state-race
Nov 19, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5421-global-state-race

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

Summary

GPTQModel.load() of a tied-embedding checkpoint failed whenever a plain
transformers construction ran in another thread: a user's
AutoModelForCausalLM.from_pretrained or GPT-QModel's own
requantize(norm=NormConfig(teacher=...)) teacher.

transformers builds a model inside one init-context group
(PreTrainedModel.get_init_context): the local_torch_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 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 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 ties nothing and
_tie_weights_after_checkpoint_load is the only call that binds lm_head. It
ran 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 a
correct load fail as a "corrupted state"
(changed from torch.bfloat16 to torch.float32).

Measured on current main with a 16-layer GPTQ 4-bit tied checkpoint and a
dense from_pretrained loop 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 construction
    exclusive, not only the dtype window.
    • PreTrainedModel.get_init_context prepends the writer to the returned
      context list. ContextManagers enters the list in order through an
      ExitStack, so the writer is acquired before no_tie_weights /
      apply_patches and released after them.
    • PreTrainedModel._from_config holds it for the whole from_config
      construction, which opens apply_patches outside get_init_context and
      may have no dtype window.
    • init.no_tie_weights and apply_patches take it themselves, so a direct
      use is exclusive even without get_init_context.
  • gptqmodel/utils/model.py: _tie_weights_after_checkpoint_load takes the
    writer 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_state compares the settled
    default dtype under the writer.
  • gptqmodel/models/base.py: the requantize(norm=...) teacher
    from_pretrained takes model_load_lock(), like every other GPT-QModel-owned
    construction.
  • docs/concurrency.md: the new construction-exclusivity flow, before/after
    table, 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

# lint
bash format/check.sh
# All checks passed!

# new regressions (deterministic: each foreign window is held until the test releases it)
python -m pytest tests/test_construction_global_state_5421.py -q -ra
# 8 passed

# affected existing families
python -m pytest tests/test_compile_load_scope_5304.py tests/test_quantize_load_global_state_5301.py \
  tests/test_model_load_lock_4204.py tests/test_load_state_assertions.py \
  tests/test_concurrency_global_state_5390.py tests/test_hf_init_guard.py -q -ra
# 41 passed

python -m pytest tests/test_concurrent_load.py tests/test_compile_load_race_5209.py \
  tests/test_compile_lock_scope_5268.py -q -ra
# 10 passed

python -m pytest tests/test_lm_head_tied_detection.py tests/test_internvl_tied_head_4973.py \
  tests/test_internvl_untied_lm_head_4799.py tests/test_cpu_offload_device_map_tied_head_4866.py \
  tests/test_cpu_offload_tied_both_copies_4943.py tests/test_hf_gptqmodel_load_bridge.py \
  tests/test_lazy_turtle_materialize_map.py -q -ra
# 90 passed

python -m pytest tests/test_norm_guards.py tests/test_norm_lifecycle.py tests/test_norm_requant.py \
  tests/test_norm_review_regressions.py tests/test_embed_quant_api.py -q -ra
# 310 passed, 1 skipped (checkpoint not in the local cache)

# issue reproduction: 20 loads of a tied GPTQ 4-bit checkpoint next to a dense
# from_pretrained loop in another thread
# before: 7 failed (5 dtype flips, 2 missing lm_head.weight)
# after:  0 failed (20/20); a second 40-load run also 0 failed

Red evidence: the same test file against the unfixed tree (only the new
_default_dtype_outside_construction() call adapted back to the bare
torch.get_default_dtype()) fails 6 of 8 at their intended assertions:

Test Pre-fix failure
test_init_context_group_holds_the_writer_and_disables_tying the writer must be entered before every context
test_foreign_tie_window_blocks_a_from_config_construction construction ran inside a foreign no-tie window
test_post_load_tie_is_not_skipped_by_a_foreign_window the post-load tie was silently skipped
test_default_dtype_capture_waits_out_a_foreign_window the capture observed the foreign dtype
test_load_state_check_waits_out_a_foreign_window the check reported a change the load did not make
test_norm_teacher_load_takes_the_model_load_lock teacher from_pretrained ran outside the lock

The 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

  • This change alters a major logic flow and the required diagrams and docs
    page are included.
  • New-flow Mermaid diagram(s) describe the shipped code using real symbol names.
  • The removed/replaced mechanism is shown or tabulated with file:line evidence.
  • Failure and ambiguity paths are marked and visually distinct from success.
  • docs/concurrency.md repeats the diagrams, titled for the mechanism, and
    is linked from README.md.

Before (3a50258d6 / d10a08a65): only local_torch_dtype took the writer.
gptqmodel/utils/torch.py:install_model_global_state_dtype_guard() wrapped one
context; models/loader.py:2273,2770 read the dtype bare; utils/model.py
_tie_weights_after_checkpoint_load called model.tie_weights() bare;
models/base.py:3378 called the teacher from_pretrained bare.

Mechanism Before After
local_torch_dtype window writer writer (unchanged)
get_init_context group (no_tie_weights, apply_patches, meta device) no writer writer prepended to the context list
_from_config construction writer only when a dtype is given writer for the whole construction
init.no_tie_weights / apply_patches no writer writer for the patch window
post-load tie no writer; skipped inside a foreign window writer; waits for the foreign window
load default-dtype capture and check bare torch.get_default_dtype() both read under the writer
norm teacher from_pretrained no model_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" .-> L
Loading

Failure paths: a construction that cannot take the writer (a compiled call
already holds the reader) raises instead of upgrading; the load lock keeps
GPTQModel.load calls serialized; a load that really leaves a mixed dtype, a
meta 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:

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

Not applicable: no kernel or fusion change.

Notes

  • The guards are installed once per process and are idempotent; the writer is
    re-entrant, so nested constructions and a load that runs compiled code while
    it owns the writer keep working.
  • A transformers version without get_init_context / _from_config keeps the
    local_torch_dtype and patch-level guards; the wrappers skip silently when
    the symbol is absent.
  • A subclass that overrides get_init_context is still covered by the
    local_torch_dtype and patch-level guards, not by the group wrapper.

…#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
@Qubitium
Qubitium merged commit 3242b85 into main Nov 19, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/5421-global-state-race branch November 19, 2026 12:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants