Skip to content

fix(checkpoint): tighten metadata, tied-head, fallback and scale contracts - #4327

Merged
Qubitium merged 1 commit into
mainfrom
fix/4184-contracts
Nov 16, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/4184-contracts

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

TL;DR

This is the checkpoint/runtime-contract half of #4184. It fixes six findings from the review: checkpoint metadata (offload_to_disk_path, index total_size, shard units), tied lm_head detection when the checkpoint stores a redundant head tensor, checkpoint scale dtype after Accelerate casting, the torch.compile eager-fallback predicate, stream ownership of the cached uniform column group, and VPTQ's norm_dim=0 error-feedback Hessian. The GGUF, ExLlamaV2, NVFP4, HIP staging and ROCm BLAS findings are separate changes.

1. Checkpoint metadata

Mechanism Before After
offload_to_disk_path in meta published /tmp/gptqmodel_* (config.py:5396) omitted; legacy checkpoints still read it
index metadata.total_size on-disk file bytes, including headers sum(TensorSource.num_bytes) (utils/model.py:3567)
max_shard_size units every KB/MB/GB meant 1024^n KB/MB/GB decimal, KiB/MiB/GiB binary, bare K/M/G unchanged
flowchart TD
    A["save_quantized(state_dict)"] --> B["streaming_state_dict_to_shards"]
    B --> C["_plan_shards uses TensorSource.num_bytes"]
    B --> D["write or reuse each shard"]
    D --> E["index total_size = sum of entry.num_bytes"]
    A --> F["QuantizeConfig.to_dict"]
    F --> G["meta without offload_to_disk_path"]
    G --> H["portable quantize_config.json"]
    style E fill:#d1e7dd,stroke:#146c43,stroke-width:2px
    style H fill:#d1e7dd,stroke:#146c43,stroke-width:2px
Loading

A real 0.5B GPTQ save with max_shard_size="200MB" now writes
total_size = 480263936, exactly the sum of tensor bytes, and the saved
quantize_config.json has no meta.offload_to_disk_path.

2. Tied lm_head with a stored head tensor

Qwen3 checkpoints store lm_head.weight even though tie_word_embeddings=True.
The old detector treated the checkpoint tensor as proof of an independent head,
so lm_head=True proceeded and failed with
NotImplementedError: Cannot copy out of meta tensor; no data! instead of the
explicit tied-weights refusal.

flowchart TD
    A["lm_head = True"] --> B["find_tied_parameters(model)"]
    B -- "shared parameter" --> R["NotImplementedError<br/>tied weights"]
    B -- "no shared parameter" --> C{"config or text_config<br/>tie_word_embeddings?"}
    C -- "no" --> Q["quantize the head"]
    C -- "yes" --> D{"_tied_weights_keys declares<br/>lm_head.weight?"}
    D -- "yes" --> R
    D -- "no" --> E{"lm_head weight is meta?"}
    E -- "no" --> Q
    E -- "yes" --> F{"checkpoint has<br/>lm_head.weight?"}
    F -- "no" --> R
    F -- "yes" --> Q
    style R fill:#f8d7da,stroke:#b02a37,stroke-width:2px
    style Q fill:#d1e7dd,stroke:#146c43,stroke-width:2px
Loading

The config walk covers text_config / get_text_config() for composite models.
Repro before: meta-tensor copy failure. After: the tied-weights refusal fires
before calibration.

3. torch.compile fallback predicate

_is_compiler_failure treated any exception whose innermost frame lived under
torch/_dynamo, torch/_inductor or torch/_functorch as compiler-owned.
That masked a user ValueError or an unrelated AssertionError raised from a
compiler-named file. The fallback is now limited to compiler-owned
RuntimeError and dynamo's specific guard assertion.

flowchart TD
    A["compiled call raises exc"] --> B{"KeyboardInterrupt<br/>or SystemExit?"}
    B -- "yes" --> P["propagate"]
    B -- "no" --> C{"BackendCompilerFailed<br/>or TorchRuntimeError?"}
    C -- "yes" --> F["eager fallback"]
    C -- "no" --> D{"fullgraph?"}
    D -- "yes" --> P
    D -- "no" --> E{"TorchDynamoException<br/>in the cause chain?"}
    E -- "yes" --> F
    E -- "no" --> G{"innermost frame under<br/>_dynamo/_inductor/_functorch?"}
    G -- "no" --> P
    G -- "yes" --> H{"RuntimeError, or dynamo's<br/>Guard failed message?"}
    H -- "no" --> P
    H -- "yes" --> F
    style P fill:#f8d7da,stroke:#b02a37,stroke-width:2px
    style F fill:#d1e7dd,stroke:#146c43,stroke-width:2px
Loading

The #4094 guard-assertion fallback and inductor's closed-pool RuntimeError
still fall back; the two new tests pin the non-guard cases.

4. Checkpoint scale dtype

Accelerate casts floating buffers to the model dtype. For scales that
narrowed FP16 to BF16, changed the dequantized weight, and a later
save_pretrained() republished the narrowed value. The loader now restores
every BaseQuantLinear scale buffer from the checkpoint dtype; Torch AWQ also
keeps its bias at the checkpoint dtype.

flowchart TD
    A["accelerate.load_checkpoint_in_model"] --> B{"BaseQuantLinear<br/>has a scales buffer?"}
    B -- "yes" --> C["restore scales from checkpoint dtype"]
    B -- "no" --> D["leave the buffer"]
    C --> E["post_init/transform may still cast<br/>runtime operands"]
    style C fill:#d1e7dd,stroke:#146c43,stroke-width:2px
Loading

Verified on ModelCloud/Qwen2.5-0.5B-Instruct-ci-test-bitblas loaded with
dtype=torch.bfloat16, backend="torch": the model dtype is BF16 and
q_proj.scales stays FP16, matching the checkpoint.

5. Stream-scoped uniform column group

_uniform_column_group cached a torch.zeros tensor. The fill is ordered on
the creating stream, so a worker on another stream could read it before the
fill completed. The cache key now includes the current CUDA stream object
(None on CPU), which also keeps the stream alive while the entry exists.

flowchart TD
    A["_uniform_column_group(count, device)"] --> B{"device.type is cuda?"}
    B -- "no" --> C["cache key stream = None"]
    B -- "yes" --> D["torch.cuda.current_stream(device)"]
    D --> E["cache key stream object"]
    C --> F["torch.zeros(count, int32)"]
    E --> F
    style F fill:#d1e7dd,stroke:#146c43,stroke-width:2px
Loading

A CUDA test creates the tensor under two streams and asserts different objects,
same-stream cache hits, and zero contents.

6. VPTQ norm_dim=0

With enable_norm=True, norm_dim=0, VPTQ divides each input channel by its own
scale: W' = (W - b) / s. The error in the original space is e = D e' with
D = diag(s), so error feedback must use D H D. The previous code passed the
raw H; using D^-1 H D^-1 is worse than doing nothing.

flowchart LR
    A["W, H"] --> B["normalize per column<br/>W' = (W - b) / s"]
    B --> C["error feedback with<br/>D H D, D = diag(s)"]
    C --> D["de-normalize<br/>W_hat = W_hat' * s + b"]
    D --> E["report loss with the<br/>original H"]
    style C fill:#d1e7dd,stroke:#146c43,stroke-width:2px
Loading

Measured on a 16x32 Gaussian weight and a well-conditioned Hessian (seed 0,
vector_lens=[-1, 4], 16 centroids, block size 8):

Error-feedback Hessian True Hessian-weighted loss
raw H 0.2602
D^-1 H D^-1 0.3535
D H D 0.2200

The independent oracle in tests/test_vptq.py performs its own arithmetic and
matches the quantizer exactly for the norm and all variants.

7. Change inventory

Area File Purpose
Metadata quantization/config.py, models/writer.py, utils/model.py portable meta, tensor-byte total_size, HF shard units
Tied head looper/module_looper.py config/declared-key decision
Compile fallback utils/torch.py narrow compiler-owned failure predicate
Scale dtype utils/model.py restore checkpoint scale dtype
Stream cache quantization/gptq.py stream-keyed uniform group
VPTQ quantization/vptq.py D H D error feedback
Docs docs/checkpoint-and-runtime-contracts.md diagrams and contracts

8. Tests / validation

Test file Result
tests/test_checkpoint_metadata_contracts.py 4 passed
tests/test_checkpoint_scale_dtype.py 1 passed
tests/test_lm_head_tied_detection.py 5 passed
tests/test_uniform_column_group_stream.py 2 passed
tests/test_torch_compile_fallback.py 17 passed
tests/test_checkpoint_compat.py 22 passed
tests/test_vptq.py (oracle/norm selection) 9 passed; the pre-existing group_size_remainder oracle failure also fails on the base revision
tests/qcfg, tests/test_reshard.py, tests/test_auto_module_decoder.py 219 passed
tests/test_awq_dequant_layouts.py, tests/test_required_qweight.py 51 passed

A real 0.5B GPTQ save/reload confirms the index total_size and the absence of
meta.offload_to_disk_path.

9. Reviewer notes

  • This PR is intentionally a split of [BUG] Minor findings from a full-repo review (7.11.0 @ 6c3421c) #4184. The GGUF K-quant search, ExLlamaV2
    handle lock, NVFP4 operand cache, HIP staging lock and ROCm BLAS serialization
    are separate changes.
  • Item 9 (text-only calibration of an auto-detected second stack) is not
    changed here. Skipping an unreachable branch would leave those modules
    unquantized; the existing error asks the caller to pass an explicit text-only
    module_tree instead. That needs a separate design decision.
  • The VPTQ change is numerical: the oracle is independent and the measured loss
    table above distinguishes D H D from the inverse direction.

…racts (#4184)

- Do not publish the quantizer's local offload_to_disk_path in checkpoint meta;
  a loader chooses its own scratch directory. Legacy checkpoints still read it.
- Write the index metadata.total_size from tensor bytes instead of safetensors
  file sizes, and parse max_shard_size with Transformers' decimal KB/MB/GB and
  binary KiB/MiB/GiB units.
- Treat a config-declared tied lm_head as tied even when the checkpoint stores
  a redundant lm_head.weight, so the explicit refusal fires instead of a
  meta-tensor copy failure.
- Restore every quantized module's scales from the checkpoint dtype after
  Accelerate casts them to the model dtype.
- Narrow the torch.compile eager fallback to compiler-owned RuntimeError and
  dynamo's guard AssertionError; other compiler-frame errors propagate.
- Scope the cached uniform column group to the current CUDA stream.
- Use D H D for VPTQ norm_dim=0 error feedback, with the independent oracle
  updated and a measured loss comparison.
- Document the contracts and before/after mechanisms in
  docs/checkpoint-and-runtime-contracts.md.
@Qubitium
Qubitium merged commit 82ab6f1 into main Nov 16, 2026
5 of 9 checks passed
@Qubitium
Qubitium deleted the fix/4184-contracts branch November 16, 2026 08:40
Qubitium added a commit that referenced this pull request Nov 16, 2026
…4361)

Eight free-threaded workers forwarding after clear_weight_cache() each entered _ensure_q_handle's slow path and built their own native q-matrix; seven leaked. Add a module-level rebuild lock with a double-checked fast path, and take the same lock in clear_weight_cache so a release cannot race a publish. Steady-state forwards keep the lock-free fast path.

This is the only finding from #4184 that is still an actionable small bug on current main; the others were already fixed by #4327/#3492 or need larger work and are deferred in the PR disposition table.
Qubitium added a commit that referenced this pull request Nov 17, 2026
…4846)

Section A of #4769, each item fixed at its test double/oracle/expectation.
No library behaviour was changed.

Fixed:
- test_exl3_workspace_release / test_offload_base_modules_restored: give the
  ModuleLooper doubles the state loop() now reads (_inflight_layer,
  _dangling_threads, Device-SMI handles, and a real model for the success
  path). Before: AttributeError while handling the injected failure; after:
  7 passed.
- test_local_model_paths: the fake loaded models are SimpleNamespace doubles
  with log_kv_cache_estimate, matching GPTQModel.load. Before: AttributeError
  on a bare object(); after: 29 passed.
- test_diffusion_gemma_support: the hand-built DiffusionGemmaQModel double now
  carries quantize_config.activation_mode. Before: AttributeError; after: the
  post-quantize sync test passes.
- test_tenstorrent_support: window starts follow the current
  iter_calibration_windows spacing (0, 18, 37, 56). Before: the stale
  [0, 14, 28, 42] oracle.
- test_model::test_dequantize_model_awq: the fixture packs the real AWQ GEMM
  [0, 2, 4, 6, 1, 3, 5, 7] interleave instead of natural order, which is what
  dequantize_model reverses. Before: 95/128 elements differed.
- test_fallback: the sym=True oracle uses zero = 2 ** (bits - 1) for every
  strategy, not an asymmetric zero point. Before: 32/32 zero mismatches.
- test_gsq_method_adapters: FP8 pack_calibrated keeps the checkpoint bias in
  FP32 on purpose; assert that dtype and value instead of FP16.
- test_serialization: offload_to_disk_path is deliberately absent from the
  checkpoint meta (#4327); assert its absence instead of its presence.
- test_norm_lifecycle: quantize() now materializes the model and keeps the v2
  runtime zero layout (#4380/#4426/#4063); assert no meta/inference parameters
  and validate_tuning_model(model.model) instead of the stale reload-only
  guard.
- test_vptq_memory_4391: the legacy reference allocates >= 2 full-size
  temporaries on torch 2.15, not exactly 3; pin that it is worse than the
  chunked path instead of an exact torch-version-dependent count.
- test_jamba_support: the module tree declares mamba.x_proj (#4245); update
  the simple list and the dense-mixer assertions.
- test_marlin_jit: with desc_act=False and one group, g_idx is all zeros, not
  arange(in_features).
- test_dynamic::test_skip_module: replace brittle paris/king keyword matching
  on greedy output with a coherence check on the continuation.
- test_allspark_awq_cuda: install the checkpoint tensors as buffers, as a real
  load does, instead of Parameters that _kernel_bias caches as a second
  parameter (which leaked _bias_value into state_dict).
- test_bits_new: select the bit width with parameterized.expand([2, 3, 4, 8])
  instead of the BITS environment variable (AGENTS.md: behaviour comes from
  config/API, not env).
- test_checkpoint_method_compatibility: use group_size=128 for the native AWQ
  GEMV/LLM-AWQ formats (GEMV accepts 64/128, LLM-AWQ only 128) and widen the
  fixture to hidden_size=128 for LLM-AWQ, whose in_features must divide 128.
  Gate the ~30-minute subprocess matrix behind the new opt-in
  checkpoint_recovery marker (same mechanism as gptq_cuda_e2e) so the file no
  longer always times out in a 600 s slot. Target cases
  test_format_checkpoint_recovery[awq-gemv], [awq-llm-awq] and both eora
  variants pass with -m checkpoint_recovery.

Skipped because this host is CUDA sm_80, not ROCm:
- every ROCm/gfx1201-only item belongs to #4770 and was not touched.

Deferred:
- tests/test_quant_batch.py::test_diff_batch: an FP32-calibration +
  dequantized-weight rewrite OOMs here (GPU 5 has ~14 GiB free while a shared
  83 GiB process holds the card), so it was not shipped unverified.
- test_bits_new was exercised for bits=2 against a 15M local model only; the
  1B eval of the other widths does not fit the 600 s slot here.

Environment-only failures seen while validating (not changed):
- test_serialization.py::test_gptq_v1_serialization and
  test_save_keeps_live_model_inference: flash_attn_2_cuda undefined symbol.
- test_diffusion_gemma_support.py::test_diffusion_gemma_generic_defusion_preserves_forward:
  defuser 0.0.25 is older than the required 0.0.31.
- test_jamba_support.py::test_tiny_jamba_gptq_quantization_smoke: mamba-ssm is
  not installed.

Validation (CUDA_VISIBLE_DEVICES=5, sm_80):
- 13 touched files in one run: 380 passed, 110 skipped, 4 failed (the three
  environment-only causes above).
- test_model.py -k dequantize_model: 12 passed, 1 skipped.
- test_marlin_jit.py::test_marlin_cuda_smoke_build_and_forward: 1 passed.
- test_dynamic.py::TestDynamic::test_skip_module: 1 passed (flash-attn
  auto-enable disabled locally because the host extension has an undefined
  symbol; the committed test still hits that environment failure).
- test_checkpoint_method_compatibility.py default: 4 passed, 95 skipped;
  -m checkpoint_recovery targeted AWQ GEMV/LLM-AWQ cases: 4 passed.
- test_bits_new.py::Test::test_quant_and_eora_0 (bits=2, 15M model): 1 passed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants