Repository navigation
fix(checkpoint): tighten metadata, tied-head, fallback and scale contracts - #4327
Merged
Merged
Conversation
…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.
This was referenced Nov 16, 2026
Merged
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.
This was referenced Nov 16, 2026
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.
5 tasks done
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.
TL;DR
This is the checkpoint/runtime-contract half of #4184. It fixes six findings from the review: checkpoint metadata (
offload_to_disk_path, indextotal_size, shard units), tiedlm_headdetection when the checkpoint stores a redundant head tensor, checkpoint scale dtype after Accelerate casting, thetorch.compileeager-fallback predicate, stream ownership of the cached uniform column group, and VPTQ'snorm_dim=0error-feedback Hessian. The GGUF, ExLlamaV2, NVFP4, HIP staging and ROCm BLAS findings are separate changes.1. Checkpoint metadata
offload_to_disk_pathinmeta/tmp/gptqmodel_*(config.py:5396)metadata.total_sizesum(TensorSource.num_bytes)(utils/model.py:3567)max_shard_sizeunitsKB/MB/GBmeant 1024^nKB/MB/GBdecimal,KiB/MiB/GiBbinary, bareK/M/Gunchangedflowchart 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:2pxA real 0.5B GPTQ save with
max_shard_size="200MB"now writestotal_size = 480263936, exactly the sum of tensor bytes, and the savedquantize_config.jsonhas nometa.offload_to_disk_path.2. Tied
lm_headwith a stored head tensorQwen3 checkpoints store
lm_head.weighteven thoughtie_word_embeddings=True.The old detector treated the checkpoint tensor as proof of an independent head,
so
lm_head=Trueproceeded and failed withNotImplementedError: Cannot copy out of meta tensor; no data!instead of theexplicit 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:2pxThe 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.compilefallback predicate_is_compiler_failuretreated any exception whose innermost frame lived undertorch/_dynamo,torch/_inductorortorch/_functorchas compiler-owned.That masked a user
ValueErroror an unrelatedAssertionErrorraised from acompiler-named file. The fallback is now limited to compiler-owned
RuntimeErrorand 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:2pxThe #4094 guard-assertion fallback and inductor's closed-pool
RuntimeErrorstill fall back; the two new tests pin the non-guard cases.
4. Checkpoint scale dtype
Accelerate casts floating buffers to the model dtype. For
scalesthatnarrowed FP16 to BF16, changed the dequantized weight, and a later
save_pretrained()republished the narrowed value. The loader now restoresevery
BaseQuantLinearscale buffer from the checkpoint dtype; Torch AWQ alsokeeps 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:2pxVerified on
ModelCloud/Qwen2.5-0.5B-Instruct-ci-test-bitblasloaded withdtype=torch.bfloat16, backend="torch": the model dtype is BF16 andq_proj.scalesstays FP16, matching the checkpoint.5. Stream-scoped uniform column group
_uniform_column_groupcached atorch.zerostensor. The fill is ordered onthe 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
(
Noneon 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:2pxA CUDA test creates the tensor under two streams and asserts different objects,
same-stream cache hits, and zero contents.
6. VPTQ
norm_dim=0With
enable_norm=True, norm_dim=0, VPTQ divides each input channel by its ownscale:
W' = (W - b) / s. The error in the original space ise = D e'withD = diag(s), so error feedback must useD H D. The previous code passed theraw
H; usingD^-1 H D^-1is 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:2pxMeasured on a 16x32 Gaussian weight and a well-conditioned Hessian (seed 0,
vector_lens=[-1, 4], 16 centroids, block size 8):HD^-1 H D^-1D H DThe independent oracle in
tests/test_vptq.pyperforms its own arithmetic andmatches the quantizer exactly for the
normandallvariants.7. Change inventory
quantization/config.py,models/writer.py,utils/model.pylooper/module_looper.pyutils/torch.pyutils/model.pyquantization/gptq.pyquantization/vptq.pyD H Derror feedbackdocs/checkpoint-and-runtime-contracts.md8. Tests / validation
tests/test_checkpoint_metadata_contracts.pytests/test_checkpoint_scale_dtype.pytests/test_lm_head_tied_detection.pytests/test_uniform_column_group_stream.pytests/test_torch_compile_fallback.pytests/test_checkpoint_compat.pytests/test_vptq.py(oracle/norm selection)group_size_remainderoracle failure also fails on the base revisiontests/qcfg,tests/test_reshard.py,tests/test_auto_module_decoder.pytests/test_awq_dequant_layouts.py,tests/test_required_qweight.pyA real 0.5B GPTQ save/reload confirms the index
total_sizeand the absence ofmeta.offload_to_disk_path.9. Reviewer notes
handle lock, NVFP4 operand cache, HIP staging lock and ROCm BLAS serialization
are separate changes.
changed here. Skipping an unreachable branch would leave those modules
unquantized; the existing error asks the caller to pass an explicit text-only
module_treeinstead. That needs a separate design decision.table above distinguishes
D H Dfrom the inverse direction.