Repository navigation
fix(models): serialize model loads and reject corrupted state (#4129) - #4140
Merged
Merged
Conversation
) Concurrent GPTQModel.load() calls entered transformers from_pretrained with no lock. That call saves/sets/restores the process-wide default dtype and builds through meta-device and no-init contexts, so two dense loads interleaved them and returned mixed fp16/fp32 models, a meta lm_head, untied embeddings, and a process default dtype stuck at fp16. - wrap ModelLoader.from_pretrained/from_quantized in a process-wide RLock - assert default dtype, materialized floating params, and uniform/requested dtype after every build - reference-count suspend_hf_weight_init so overlapping entries do not re-enable init mid-build - drop the cross-run AWQ_BATCH_SIZE env channel in favour of an explicit awq_batch_size argument - document the serialized load contract and the safety net
Qubitium
added a commit
that referenced
this pull request
Nov 16, 2026
… guard (#4170) (#4209) #4140's assert_loaded_model_state() required every floating parameter to share one dtype. transformers deliberately keeps the modules named by _keep_in_fp32_modules (fp16 loads) and _keep_in_fp32_modules_strict (fp16 and bf16 loads) in float32 via _get_dtype_plan, so valid checkpoints failed with "model load left a corrupted state" (Ernie4.5-MoE gate.weight/moe_statics, GPT-OSS norms, T5/mT5 wo, DeepSeek-V3.2 indexer.weights_proj). Exclude a parameter from both dtype checks only when it is float32 and its full name matches a declaration, collected from the model and its submodules. Matching mirrors transformers 5.22: each entry is compiled as a regex with "*" -> ".*" and searched against the whole parameter name. Undeclared float32 parameters, declared modules left in a half dtype, and pinned parameters on the meta device still raise, so the #4140 protection is intact. Tests cover Ernie4.5-MoE (native and QuantizeConfig(offload_to_disk=False) + bfloat16), a tiny GPT-OSS in fp16, the negative controls (undeclared fp32 leakage and cleared declarations), and the #4140 suites.
This was referenced Nov 17, 2026
Merged
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.
Fixes #4129
TL;DR
GPTQModel.load()entered transformers'from_pretrainedwith no lock. Thatcall mutates process-global state (
torch.set_default_dtype, the meta-deviceand no-init contexts), so two overlapping loads interleaved it and returned
mixed fp16/fp32 models with a meta
lm_headand untied embeddings, while theprocess default dtype was left at fp16. Model construction is now serialized
behind
_MODEL_LOAD_LOCK, every build is checked byassert_loaded_model_state,suspend_hf_weight_initis reference-counted, andthe cross-run
AWQ_BATCH_SIZEenv channel is gone.quantize()on alreadyloaded models remains concurrent.
1. Root cause
ModelLoader.from_pretrained(reached from the publicGPTQModel.load) calls_hf_loader_from_pretrained_with_dynamic_module_retry, which callsloader.from_pretrainedwith no lock:gptqmodel/models/loader.py:1260_hf_loader_from_pretrained_with_dynamic_module_retrygptqmodel/models/loader.py:1262and:1287loader.from_pretrained(...)ModelLoader.from_pretrainedat:1853,:1982,:2027, andModelLoader.from_quantizedat:2258(AutoConfig.from_pretrained) /the shell build.
transformers'
from_pretrainedsaves, sets and restorestorch.set_default_dtype(transformers/modeling_utils.py:235-240) and buildsparameters through the meta-device and no-init contexts. Those are process
globals, not thread-locals. Two dense loads in different threads interleave
them; the result is a model with mixed fp16/fp32 parameters, a tied weight left
on the meta device, untied embeddings, and a default dtype stuck at fp16.
Two adjacent stateful paths made it worse:
gptqmodel/utils/hf.py:304(before this PR)suspend_hf_weight_initsaved andrestored the process-wide init patches per entry. The first caller to leave
re-enabled init for a thread still building, and the second exit restored the
no-op stubs for the rest of the process.
gptqmodel/models/base.py:2627(before this PR) wroteos.environ["AWQ_BATCH_SIZE"]duringquantize();gptqmodel_post_init(
gptqmodel/utils/model.py:1759) read it at load time to size theAwqExllamaV2scratch. One run could size another run's scratch.Before/after mechanism
loader.from_pretrained(models/loader.py:1262, reached from:1853)_MODEL_LOAD_LOCK(models/loader.py:1232), held by_serialized_model_load(:1235) aroundfrom_pretrained(:2095) andfrom_quantized(:3291)assert_loaded_model_state(utils/hf.py:386), called atmodels/loader.py:1879,:2085,:3283utils/hf.py:304before)_HF_INIT_LOCK/_HF_INIT_DEPTH/_HF_INIT_SUSPENSION(utils/hf.py:306-381)models/base.py:2627+ env readutils/model.py:1759awq_batch_sizeargument (utils/model.py:1740, default 1)2. New flow
flowchart TD A["thread 1: GPTQModel.load"] --> B["acquire _MODEL_LOAD_LOCK (RLock)"] C["thread 2: GPTQModel.load"] --> D{"lock free"} D -- no --> E["wait for the other load"] B --> F["transformers from_pretrained or from_config"] F --> G["assert_loaded_model_state"] G -- "mixed dtype, meta param, changed default dtype" --> H["RuntimeError: corrupted model never returned"] G -- "consistent" --> I["release lock, return model"] E --> B I --> DThe lock is an
RLockbecausefrom_pretrainedcan callfrom_quantizedonthe same thread (native GGUF), and because the guard is re-entrant by design.
3. Fail-before / pass-after
Hardware: AMD Radeon AI PRO R9700 (gfx1201), ROCm 10.1,
HIP_VISIBLE_DEVICES=0only, Python 3.14.10 free-threading build, torch
2.16.0.dev20261025+rocm10.1. Both models are loaded withdevice="cpu"; no GPU is used. The CUDA venv (cu130t) re-runs the sameCPU-only tests. The RTX 5090 was never used.
The repro is the child embedded in
tests/test_concurrent_load.py: two threadsload
Qwen2.5-0.5B-InstructandQwen3-0.6BwithGPTQConfig(bits=4, group_size=128, offload_to_disk=False)anddtype=torch.float16, 6 rounds, underPYTHON_GIL=0andPYTHON_GIL=1.Before (unmodified base
6f9ad69e6, worktree/tmp/failbefore4129-concur):After (this branch, after merging
origin/main):An earlier before-run on the same host measured 5/6 (GIL=0) and 6/6 (GIL=1);
the counts are timing-dependent, as the issue notes. The after side was run
twice: the standalone child (12 rounds) and the pytest test (another 12 rounds),
both
0/6per GIL mode.Exact commands:
4. Safety net fires
tests/test_load_state_assertions.pyunit-tests the helper; a deliberateviolation raises with a concrete message (real output):
The
offload_to_diskmeta shell is exempt from the dtype/meta checks becauseit is intentionally meta until
LazyTurtlefills each layer. Objects withoutnamed_parameters(the MLX runtime model) only get the default-dtype check.5. Plausible items: verdicts
AWQ_BATCH_SIZEenv leak — real, fixed. Removed the writer(
models/base.py:2627on main) and the reader (utils/model.py:1759onmain).
gptqmodel_post_init(..., awq_batch_size=...)is now an explicitargument defaulting to 1.
grep -rn AWQ_BATCH_SIZE gptqmodel testshas noreader/writer left (only the explanatory docstring). The value was written by
quantize()but read by a later load, so it was always a cross-runchannel, not a same-run one.
suspend_hf_weight_init— real, fixed. Reference-counted; overlappingentries keep the patches until the last exit. Tests cover cross-thread
overlap, nested entries, and an overlapping exception.
ParoQuantTritonLinearwall-clock plan choice — real, NOT fixed here._time_plan/_select_plantime fused vs dense insideforward, so undercontention the plan and output bits can depend on other threads. Changing the
dispatch policy is a numerics/perf decision owned by the ParoQuant kernel and
is out of scope for load serialization; this PR does not touch
paroquant_triton.py. Recorded as a known limitation.6. Docs
docs/concurrency.md: resource count 4 -> 5, new section 4. Model loadsare serialized (flowchart, safety net, refcounted init suspension, no
cross-run AWQ scratch), 3 contract rows, and the measured 6/6 -> 0/6 and
5/6 -> 0/6 validation rows. Linked from
README.md:259anddocs/README.md:163.pytorch_gil_0_compat.md: newtorch.set_default_dtype/torch.get_default_dtyperow and manual finding 11.7. Tests
rocm101t,HIP_VISIBLE_DEVICES=0)pytest tests/test_load_state_assertions.py tests/test_hf_init_guard.py tests/test_concurrent_load.py -qpytest tests/test_concurrency_guards.py tests/test_loader.py tests/test_trust_remote_code_isolation.py tests/test_writer_instance_attrs.py tests/test_awq_loader_dtype.py -qpytest tests/test_hf_gptqmodel_load_bridge.py -qpytest tests/test_concurrency_guards.py -q(CUDAcu130t, CPU paths)pytest tests/test_load_state_assertions.py tests/test_hf_init_guard.py tests/test_concurrent_load.py -q(CUDAcu130t)ruff check gptqmodel docs/eora tests setup.pyPre-existing failures, reproduced identically on the unmodified base worktree
(
6f9ad69e6) and unchanged on currentorigin/main, not caused by this PR:tests/test_rocm_default_env.py::test_quantization_is_reproducible_across_processes— the test's own hashing line calls
.view(torch.uint8)on a 0-dim Longtensor (
RuntimeError: self.dim() cannot be 0 to view Long as Byte).tests/test_marlin_cpu_offload_post_init.py4 parametrizations — extrastate_dict()keys on the current torch/transformers build.tests/test_q4_exllama_v2.py3 tests — ExLlamaV2 runtime unavailable onthis ROCm host.
8. Reviewer notes
AutoConfig.from_pretrainedand the quantized shell build.quantize()isuntouched and stays concurrent; this only serializes construction.
returned. Dense loads with no explicit dtype require uniform floating
parameters; if a model legitimately mixes dtypes at load time it will fail
loudly rather than silently continue.
from_quantizedonly requires materialized floating parameters (not uniformdtype), because quantized checkpoints keep their own scale dtypes; a
CPU-offloaded map is exempt.