Skip to content

fix(models): serialize model loads and reject corrupted state (#4129) - #4140

Merged
Qubitium merged 4 commits into
mainfrom
fix/issue-4129-load-serialization
Nov 15, 2026
Merged

Qubitium merged 4 commits into
mainfrom
fix/issue-4129-load-serialization

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4129

TL;DR

GPTQModel.load() entered transformers' from_pretrained with no lock. That
call mutates process-global state (torch.set_default_dtype, the meta-device
and no-init contexts), so two overlapping loads interleaved it and returned
mixed fp16/fp32 models with a meta lm_head and untied embeddings, while the
process default dtype was left at fp16. Model construction is now serialized
behind _MODEL_LOAD_LOCK, every build is checked by
assert_loaded_model_state, suspend_hf_weight_init is reference-counted, and
the cross-run AWQ_BATCH_SIZE env channel is gone. quantize() on already
loaded models remains concurrent.

1. Root cause

ModelLoader.from_pretrained (reached from the public GPTQModel.load) calls
_hf_loader_from_pretrained_with_dynamic_module_retry, which calls
loader.from_pretrained with no lock:

  • gptqmodel/models/loader.py:1260 _hf_loader_from_pretrained_with_dynamic_module_retry
  • gptqmodel/models/loader.py:1262 and :1287 loader.from_pretrained(...)
  • reached from ModelLoader.from_pretrained at :1853, :1982, :2027, and
    ModelLoader.from_quantized at :2258 (AutoConfig.from_pretrained) /
    the shell build.

transformers' from_pretrained saves, sets and restores
torch.set_default_dtype (transformers/modeling_utils.py:235-240) and builds
parameters 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_init saved and
    restored 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) wrote
    os.environ["AWQ_BATCH_SIZE"] during quantize(); gptqmodel_post_init
    (gptqmodel/utils/model.py:1759) read it at load time to size the
    AwqExllamaV2 scratch. One run could size another run's scratch.

Before/after mechanism

Mechanism Before After
Model construction unguarded loader.from_pretrained (models/loader.py:1262, reached from :1853) _MODEL_LOAD_LOCK (models/loader.py:1232), held by _serialized_model_load (:1235) around from_pretrained (:2095) and from_quantized (:3291)
Post-load invariant none; a corrupted model was returned assert_loaded_model_state (utils/hf.py:386), called at models/loader.py:1879, :2085, :3283
Init suspension per-entry save/restore (utils/hf.py:304 before) refcounted _HF_INIT_LOCK / _HF_INIT_DEPTH / _HF_INIT_SUSPENSION (utils/hf.py:306-381)
AWQ scratch size env write models/base.py:2627 + env read utils/model.py:1759 explicit awq_batch_size argument (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 --> D
Loading

The lock is an RLock because from_pretrained can call from_quantized on
the 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=0
only, Python 3.14.10 free-threading build, torch
2.16.0.dev20261025+rocm10.1. Both models are loaded with
device="cpu"; no GPU is used. The CUDA venv (cu130t) re-runs the same
CPU-only tests. The RTX 5090 was never used.

The repro is the child embedded in tests/test_concurrent_load.py: two threads
load Qwen2.5-0.5B-Instruct and Qwen3-0.6B with
GPTQConfig(bits=4, group_size=128, offload_to_disk=False) and
dtype=torch.float16, 6 rounds, under PYTHON_GIL=0 and PYTHON_GIL=1.

Before (unmodified base 6f9ad69e6, worktree /tmp/failbefore4129-concur):

GIL=0: ROUND 0..5 all BAD -> bad_rounds=6/6
       ROUND 0 {'Qwen2.5': ["meta=['lm_head.weight']", 'UNTIED'],
                'Qwen3': ["dtypes={'torch.float16': 310, 'torch.float32': 1}", 'UNTIED']}
       ROUND 3 {'Qwen3': ['UNTIED', 'default_dtype_after=torch.float16'],
                'Qwen2.5': ["dtypes={'torch.float32': 291}", "meta=['lm_head.weight']", 'UNTIED', 'default_dtype_after=torch.float16']}
GIL=1: ROUND 0 ok, ROUND 1..5 BAD -> bad_rounds=5/6
       ROUND 1 {'Qwen2.5': ["dtypes={'torch.float16': 227, 'torch.float32': 64}", "meta=['lm_head.weight']", 'UNTIED', 'default_dtype_after=torch.float16'],
                'Qwen3': ['UNTIED', 'default_dtype_after=torch.float16']}

After (this branch, after merging origin/main):

GIL=0: ROUND 0..5 ok -> bad_rounds=0/6
GIL=1: ROUND 0..5 ok -> bad_rounds=0/6

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/6 per GIL mode.

Round before GIL=0 before GIL=1 after GIL=0 after GIL=1
0 BAD ok ok ok
1 BAD BAD ok ok
2 BAD BAD ok ok
3 BAD BAD ok ok
4 BAD BAD ok ok
5 BAD BAD ok ok
bad rounds 6/6 5/6 0/6 0/6

Exact commands:

# before (base worktree, no fix)
cd /tmp/failbefore4129-concur && HIP_VISIBLE_DEVICES=0 PYTHONPATH=$PWD \
  /opt/venvs/rocm101t/bin/python -m pytest tests/test_concurrent_load.py -q

# after (this branch)
cd /root/stableabi/gptqmodel-concur && HIP_VISIBLE_DEVICES=0 PYTHONPATH=$PWD \
  /opt/venvs/rocm101t/bin/python -m pytest tests/test_concurrent_load.py -q
# 1 passed in 33.85s (the test runs both GIL modes, 6 rounds each)

4. Safety net fires

tests/test_load_state_assertions.py unit-tests the helper; a deliberate
violation raises with a concrete message (real output):

mixed-dtype -> RuntimeError: demo.load: model load left a corrupted state: floating parameters are not all torch.float16: {'torch.float32': 1}
meta-tied   -> RuntimeError: demo.load: model load left a corrupted state: 1 floating parameter(s) stayed on the meta device, e.g. ['p']
dtype-stuck -> RuntimeError: demo.load: model load left a corrupted state: torch.get_default_dtype() changed from torch.float32 to torch.float16

The offload_to_disk meta shell is exempt from the dtype/meta checks because
it is intentionally meta until LazyTurtle fills each layer. Objects without
named_parameters (the MLX runtime model) only get the default-dtype check.

5. Plausible items: verdicts

  • AWQ_BATCH_SIZE env leak — real, fixed. Removed the writer
    (models/base.py:2627 on main) and the reader (utils/model.py:1759 on
    main). gptqmodel_post_init(..., awq_batch_size=...) is now an explicit
    argument defaulting to 1. grep -rn AWQ_BATCH_SIZE gptqmodel tests has no
    reader/writer left (only the explanatory docstring). The value was written by
    quantize() but read by a later load, so it was always a cross-run
    channel, not a same-run one.
  • suspend_hf_weight_init — real, fixed. Reference-counted; overlapping
    entries keep the patches until the last exit. Tests cover cross-thread
    overlap, nested entries, and an overlapping exception.
  • ParoQuantTritonLinear wall-clock plan choice — real, NOT fixed here.
    _time_plan / _select_plan time fused vs dense inside forward, so under
    contention 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 loads
    are 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:259 and
    docs/README.md:163.
  • pytorch_gil_0_compat.md: new torch.set_default_dtype /
    torch.get_default_dtype row and manual finding 11.

7. Tests

Command (ROCm rocm101t, HIP_VISIBLE_DEVICES=0) Result
pytest tests/test_load_state_assertions.py tests/test_hf_init_guard.py tests/test_concurrent_load.py -q 12 passed
pytest 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 -q all passed (part of the 43-pass batch)
pytest tests/test_hf_gptqmodel_load_bridge.py -q 21 passed
pytest tests/test_concurrency_guards.py -q (CUDA cu130t, CPU paths) 8 passed
pytest tests/test_load_state_assertions.py tests/test_hf_init_guard.py tests/test_concurrent_load.py -q (CUDA cu130t) 12 passed
ruff check gptqmodel docs/eora tests setup.py All checks passed!

Pre-existing failures, reproduced identically on the unmodified base worktree
(6f9ad69e6) and unchanged on current origin/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 Long
    tensor (RuntimeError: self.dim() cannot be 0 to view Long as Byte).
  • tests/test_marlin_cpu_offload_post_init.py 4 parametrizations — extra
    state_dict() keys on the current torch/transformers build.
  • tests/test_q4_exllama_v2.py 3 tests — ExLlamaV2 runtime unavailable on
    this ROCm host.

8. Reviewer notes

  • The lock is process-wide and covers the whole build, including
    AutoConfig.from_pretrained and the quantized shell build. quantize() is
    untouched and stays concurrent; this only serializes construction.
  • The safety net is deliberately fail-closed: a mixed/meta model is never
    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_quantized only requires materialized floating parameters (not uniform
    dtype), because quantized checkpoints keep their own scale dtypes; a
    CPU-offloaded map is exempt.

)

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
Comment thread tests/test_hf_init_guard.py Dismissed
@Qubitium
Qubitium merged commit 67ebd21 into main Nov 15, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4129-load-serialization branch November 15, 2026 11:51
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant