Skip to content

Add matched solver/format planning and validate CPU GPTQ to MXFP4 - #4725

Open
Qubitium wants to merge 9 commits into
mainfrom
format-solver-cpu-proof
Open

Qubitium wants to merge 9 commits into
mainfrom
format-solver-cpu-proof

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Add CPU-only, executable feasibility proofs that solver choice can be separated from target numeric format. GPTQ/AWQ reference equations and the existing GSQ categorical primitive directly optimize legal hardware-format payloads; RCO's existing budget math and discrete allocator accept their actual storage costs.

Now includes the selected matched-config API and a qualified CPU GPTQ → MXFP4 lifecycle on Qwen2. quantize(config=...) automatically prints and validates model.plan() before calibration; unsupported combinations fail closed. export and legacy method-based paths remain available.

What Changed

  • Typed solvers/formats, MatchedQuantizeConfig(QuantizeConfig), declared-role/glob/regex Matcher, isolated per-run config snapshots, and automatic planning.

  • Public quantize(CalibrationConfig(dataset=...), config=...) integrates main's calibration API: shared preparation, minimum length, sorting, concatenation and BOS-only statistic masking; old calibration kwargs/bare datasets are rejected.

  • CPU blocked GPTQ and stage-group replay, packed-only MXFP4 inference, and versioned sharded safetensors save/load/re-save.

  • Matched API, lifecycle diagram, measured Qwen2.5-0.5B results and limits.

  • Finite CPU emulation of packed affine INT4, MXFP4, NVFP4, MXFP8 E4M3/E5M2, and ordinary per-tensor FP8 E4M3. FP4/FP8 element conversion needs no native low-precision dtype.

  • Exact stored-scale projection, canonical packed payloads, GPTQ activation-order handling, explicit AWQ input transforms, GSQ hard-payload acceptance, and RCO exact-bit budget checks.

  • Reproducible correlated-linear experiments with calibration/held-out data, RTN and INT4-then-convert controls, independent normal-equation/codebook/allocation oracles.

  • Mechanism, equations, measured results, format sources, and limits, linked from README.

  • nvfp8 deliberately fails closed: NVIDIA's cited documentation names ordinary FP8, MXFP8, and NVFP4, not a distinct NVFP8 encoding.

Format RTN held-out NMSE GPTQ AWQ GSQ INT4 GPTQ → target
INT4 0.00534112 0.00342318 0.00385958 0.00104479 0.00439254
MXFP4 0.0113250 0.00727645 0.00915358 0.00288845 0.0167267
NVFP4 0.00747384 0.00409037 0.00480865 0.00146463 0.0108059
MXFP8 E4M3 0.000602801 0.000367831 0.000382461 0.000110863 0.00383871
MXFP8 E5M2 0.00294736 0.00175956 0.00150680 0.000667239 0.00611203
FP8 E4M3 0.000630071 0.000346621 0.000408602 0.000134189 0.00417484

Means over seeds 0/1/2, weights 8×64, calibration 256×64, held-out 512×64, CPU FP64 arithmetic with format-constrained stored scales. All 18 format/seed pairs improved over RTN for each solver. These synthetic results are not LLM-quality guarantees or a solver ranking. RCO selects NVFP4/INT4/FP8 using 9,152 of 9,600 bits and exactly matches exhaustive allocation.

Qwen2.5-0.5B CPU validation

All 168 decoder projections, FP32 source, four CPU threads, 2,048 WikiText-2 training tokens for calibration. Held-out evaluation uses eight 128-token rows (1,016 next-token predictions), not full-corpus perplexity.

Measurement Result
Quantization 227.8 seconds
Dense → MXFP4 smoke perplexity 30.108 → 37.806
Packed target bytes / complete safetensors bytes 190,095,360 / 735,084,816
Save → load → forward → re-save → reload → forward All tensor hashes and logits exact
Greedy generated token IDs after reload Exact

The quality regression is real; this is lifecycle validation, not accuracy parity. Native GPU layouts/kernels, MoE replay, AWQ/MXFP8 model lifecycles, activation quantization, and GIL=0 remain unqualified.

Tests

CI

All checks pass. The branch previously carried its own copy of
.github/workflows/awq_cpu.yml; main removed that workflow in #5117 (the AWQ CPU
suites moved out of pull-request CI), so merging main dropped it here as well and
the two red AWQ jobs no longer run. Nothing is disabled or bypassed.

Local verification on origin/main @ eea7f19d9 (aarch64, torch 2.11):

PYTHONPATH=$PWD GPTQ_BYPASS_SAFETY_CHECKS=1 S=1 python -m pytest -q \
  tests/test_format_reference.py tests/test_format_solver_reference.py \
  tests/test_matched_quantize_config.py tests/test_mxfp4_solver_kernel.py
# 186 passed

bash format/check.sh
# ruff 0.14.2 / All checks passed!

Attention-sink calibration and quality diagnosis

The matched CPU path now accepts the public CalibrationConfig directly
and honors its BOS-only exclusion policy. Forward tokens/masks are unchanged;
only Hessian statistic rows are filtered. Shared tokenizer-BOS lookup avoids
divergence from the legacy runner. All-excluded input fails before mutation.

Same-model/same-held-out-token controls (1,016 predictions; not full WikiText):

Method Perplexity
FP32 30.10793
RTN, original scales 37.93984
GPTQ, original scales 37.80622
GPTQ, existing BOS-sink option enabled 37.80622
GPTQ, 8,192 calibration tokens, BOS-sink option enabled 34.45291
GPTQ, diagnostic first-position statistic exclusion 38.03082
RTN, per-block weight-MSE scale search 36.37713

The public sink option drops zero rows for this BOS-less tokenizer; the enabled
run reproduces the original quantized logit hashes exactly. Native inspection
does find non-BOS positional sinks, but explicitly removing first-position
statistics in a separate native-replay diagnostic worsens this small evaluation.
The scale-search control uses E8M0 exponent offsets -2/-1/0/+1 and is diagnostic,
not a newly shipped solver recipe. Fixed-grid GPTQ math matches the independent
oracle; the original 2,048-token recipe gives almost no PPL gain over RTN on
this small evaluation. These controls do not establish a general quality ranking.

Increasing the calibration prefix from 16 to 64 windows (2,048 to 8,192 tokens)
improves GPTQ perplexity to 34.45291 with the unchanged solver/scales recipe.
The source-model logit hashes and held-out tokens are identical. BOS exclusions
remain zero; public save/load/re-save again preserves payloads and logits exactly.
This control supports calibration sensitivity, not a full-corpus quality claim.

python -m pytest tests/test_matched_quantize_config.py tests/test_mxfp4_solver_kernel.py tests/test_calibration_attention_sinks.py tests/test_save_kwargs_validation_4686.py tests/test_format_reference.py tests/test_format_solver_reference.py -q -ra --tb=short
# 199 passed, 1 skipped: optional Llama-3.2 tokenizer unavailable.
python -m pytest tests/test_matched_quantize_config.py tests/test_calibration_attention_sinks.py -q -ra --tb=short
# Final localized rerun: 52 passed, same 1 skip.
bash format/check.sh
# Passed.
python -m scripts.validate_matched_mxfp4 --output /path/to/new-validation-directory --exclude-attention-sinks
# 168 modules; zero BOS exclusions; save/load/re-save payloads/logits exact.
python -m scripts.validate_matched_mxfp4 --output /path/to/new-8192-validation-directory --exclude-attention-sinks --calibration-samples 64
# Same held-out tokens; PPL 34.45291; exact serialization roundtrips.

Red evidence: the new exact-Hessian/forward-context regression fails on the
preceding revision because it rejects the sink option, and passes with this
change. Coverage includes interior BOS, padding, non-BOS first tokens, strict
flag typing, and all-statistics-excluded failure before mutation.

Calibration API integration

Merged main's public CalibrationConfig API while retaining config= for the
independent solver/format targets. quantize() validates and plans before
consuming data, binds the model-owned preparer on a copy, and passes all preparation
settings through. Batch size other than one and adapter calibration fail closed.
An explicit tokenizer uses Tokenicer and persists through save/load. Caller-owned
configuration and forward context remain unchanged by sink-statistic exclusion.

model.quantize(
    CalibrationConfig(dataset=calibration, exclude_attention_sinks=True),
    config=MatchedQuantizeConfig(
        matcher=Matcher.attention(), solver=solvers.GPTQ(), format=formats.MXFP4(),
    ),
)
python -m pytest tests/test_matched_quantize_config.py tests/test_calibration_config.py tests/test_calibration_attention_sinks.py tests/test_format_reference.py tests/test_format_solver_reference.py tests/test_mxfp4_solver_kernel.py tests/test_calibration_normalisation.py tests/test_calibration_mapping_input.py tests/test_calibration_padding_mask.py tests/test_calibration_truncation.py tests/test_calibration_windows.py tests/test_generator_calibration_4307.py -q -ra --tb=short
# 333 passed, 1 skipped in 17.39s: optional Llama-3.2 tokenizer unavailable.
python -m pytest tests/test_save_kwargs_validation_4686.py tests/test_quant_bits_validation.py tests/test_config_serialization_roundtrip_4201.py tests/test_config_per_module_validation_4200.py tests/test_stage_inputs_capture.py tests/module_tree/test_registered_module_plans.py -q -ra --tb=short
# 660 passed in 7.09s; no skips.
python -m pytest tests/test_matched_quantize_config.py -q -ra --tb=short
# Final config-reuse regression: 44 passed; no skips.
bash format/check.sh
# Passed.
python -m scripts.validate_matched_mxfp4 --output /path/to/new-calibration-api-validation --exclude-attention-sinks
# 168 modules, 242.3s; save/load/re-save payloads and logits exact.

The revalidated 0.5B run matches the pre-migration run exactly: all 458
checkpoint tensors, dense/quantized held-out logit hashes, greedy token IDs,
storage counts, and perplexity. The shared preparation removes no rows from
these equal-length windows. The BOS-less tokenizer still excludes zero sink rows.

Red evidence: test_calibration_config_object_reaches_matched_sink_statistics
fails on the pre-adaptation runner with TypeError: 'CalibrationConfig' object is not iterable; it passes after integration. New consumer-level coverage uses
row lists, mappings, columns, tensors and a one-shot generator across native,
ascending and descending order, minimum-length filtering, interior BOS, text
concatenation with a BOS separator, padded tails, and tokenizer/packed-logit
roundtrips, and caller-owned configuration reuse across models. Existing
shared-calibration tests also cover the legacy runner.

Prior lifecycle and reference validation

python -m pytest tests/test_matched_quantize_config.py tests/test_mxfp4_solver_kernel.py tests/test_save_kwargs_validation_4686.py tests/test_format_reference.py tests/test_format_solver_reference.py -q --tb=short
# 167 passed in 10.88s; no skips
python -m pytest tests/test_quant_bits_validation.py tests/test_config_serialization_roundtrip_4201.py tests/test_config_per_module_validation_4200.py tests/test_stage_inputs_capture.py tests/module_tree/test_registered_module_plans.py -q --tb=short
# 655 passed in 7.12s; no skips
python -m scripts.validate_matched_mxfp4 --output /path/to/new-validation-directory
# Full-model results above; repeated public serialization exact.

New regressions cover automatic planning before calibration, unsupported/empty/overlapping matches, independent normal-equation solves and scalar decodes, configuration propagation, partial-failure cleanup, transactional save, corrupted layout metadata, packed storage after forward/reload, padded SDPA, and FP16/BF16/FP64 native-load roundtrips. Lower-precision whole-model casts also alter nonpersistent RoPE buffers: planning/saving now reject them rather than silently changing reload numerics. Use load(dtype=...) instead. Initial sharded-save tests caught missing per-shard metadata and failed before the writer correction.

Environment repair: the snapshot's cached PyPcre wheel raised SIGILL in an unchanged GGUF config test. Rebuilding the same 0.6.4 version with --no-cache-dir --no-binary=pypcre fixed it; the complete baseline suite above then passed, with no code workaround or skipped cases.

  • New simple, fast, targeted tests added and executed.
  • Independent arithmetic oracles and second-consumer transitions covered.
python -m pytest tests/test_format_reference.py tests/test_format_solver_reference.py -q --disable-warnings --tb=short
# 125 passed, 6.82 seconds; no skips
python -m pytest tests/test_gsq_training_math.py tests/test_rco.py tests/test_rco_paper.py -q -ra --disable-warnings --tb=short
# 52 passed, 2 skipped in 59.57 seconds: MPS unavailable / no MPS FP64 storage
python -m scripts.prove_format_solvers --json results.json --markdown results.md
# CPU results above; RCO exhaustive-optimum assertion passes
bash format/check.sh
# ruff 0.14.2: all checks passed
Invariant / trigger Test Red evidence Green evidence
E8M0 scale at a power boundary and either FP64 neighbour test_e8m0_scale_selection_at_power_boundary_neighbours 9 failures with the initial ceil(log2()) implementation, which rounded above-boundary values back onto the boundary All 15 cases pass with frexp mantissa comparison
Signed-zero payload through decode → encode → pack test_zero_tiny_outliers_and_rtn_grid_idempotence Initial prototype erased negative zero by adding an absent affine zero point All six formats pass
GPTQ projection with physical groups and activation order test_gptq_matches_independent_constrained_least_squares New feasibility test, not a pre-existing production bug All six formats × both orders match independently re-solved normal equations exactly
Hard payload, not a soft loss or post-conversion test_solver_improves_real_hard_target_payload_not_just_soft_loss, conversion control New feasibility tests Actual packed-forward improvements, immutable inputs, second-consumer parity
AWQ transform cannot be dropped test_awq_keeps_transform_and_optimizes_target_format_objective Explicit wrong-transform control loses accuracy Independently enumerated search objective and explicit forward agree
GSQ hard acceptance and local RNG test_gsq_frozen_scales_hard_guard_and_rng_ownership, identity-metric control RTN cannot improve for the identity metric Actual payload gains on correlated inputs; no invented identity-metric gain
RCO storage overhead and infeasible budgets allocation and manifold tests Under-budget allocations must fail, AWQ transform cannot be free Exhaustive optimum, autograd budget normal, tangent/retraction checks

Model Support / Module Plan

Qwen2 adds an explicit non-inherited CPU GPTQ/MXFP4 capability. No MODEL_MAP, module-tree paths, AWQ overrides, or fusion qualifications change. Real tiny Qwen2 models verify semantic selectors, all seven decoder projections, unmatched weights and native replay. The existing registry/consumer suite passes; unqualified definitions and fused/remote-code/lazy-source models fail closed.

AWQ onboarding safety

No new model/format combination is AWQ-scaling-qualified by this PR; AWQ/MXFP8 requests are explicitly rejected by the new planner. The reference is a standalone linear objective and retains the FP32 input transform explicitly. Production graph folding, residual branches, replay, clipping, and model-specific qualification remain out of scope.

Logic Flow Documentation

flowchart TD
    A["BaseQModel.quantize: validate unbound CalibrationConfig"] --> B["BaseQModel.plan: resolve_plan"]
    A -->|invalid API| X["Fail before weight mutation"]
    B --> C["ModulePlan roles and declared paths"]
    C --> D{"Solver/format/model lifecycle supported?"}
    D -->|no| X
    D -->|yes| E["Print all assignments; validate call options"]
    E -->|unsupported options| X
    E -->|valid| P["CalibrationConfig.bind: model.prepare_dataset"]
    P --> Q["Normalize, filter, concatenate, sort and batch"]
    Q -->|invalid data| X
    Q -->|valid| R["Separate statistic masks from forward masks"]
    R -->|no retained statistics| X
    R -->|valid| F["quantize_model: capture first decoder inputs"]
    F --> G["Replay stage group; Hessian.capture excludes padding and configured BOS rows"]
    G --> H["solve_gptq_hessian: legal E2M1 on stored E8M0 scales"]
    H --> I["MXFP4Linear: packed bytes and scale bytes only"]
    I --> J["Replay updated layer; propagate hidden states"]
    J -->|next group/layer| G
    J -->|complete| K["BaseQModel.save: save_checkpoint"]
    G -->|failure| Y["Remove hooks; incomplete model cannot retry/save"]
    K --> L["Staging: safetensors shards and solution manifest"]
    L -->|publish| M["GPTQModel.load: load_checkpoint"]
    M --> N["Validate schema/layout/dtypes; reconstruct packed modules"]
    N --> O["Forward with bounded temporary decode; no dense cache"]
    classDef failure fill:#fee,stroke:#c22
    class X,Y failure
Loading
Boundary Before / legacy New explicit config path
quantization/config.py:4775 Method factory Typed solver/format or unchanged legacy factory
models/base.py:2103 Method-homogeneous looper plan → stage-group CPU runner
models/base.py:2136, quantization/solver_format.py:75 Matched prototype bypassed preparation with raw rows Public CalibrationConfig, copied binding and shared filtering/sort/concatenation before statistics
models/base.py:3435, models/loader.py:2489 Existing writers/loaders Versioned per-module solution manifest and packed CPU module
  • Reference flow and production boundary documented in docs/format-solver-feasibility.md and linked from README.
  • Failure paths and unchanged production mechanism are explicit.
flowchart TD
    A["W, calibration X, target format"] --> V{"Valid finite CPU problem?"}
    V -->|No| E["ValueError; no solution published"]
    V -->|Yes| G["fit_grid: legal stored scales and blocks"]
    G --> Q["solve_gptq: target projection and error feedback"]
    G --> S["solve_gsq: categorical relaxation and hard guard"]
    V -->|Yes| W["solve_awq: diagonal transform and target-grid search"]
    Q --> P["FormatGrid.pack"]
    S --> P
    W --> P
    P --> F["SolverResult.forward: temporary CPU decode"]
    P --> R["allocate_rco: measured errors and exact storage costs"]
    R --> B{"Feasible budget?"}
    B -->|No| E
    B -->|Yes| O["Assignment verified against exhaustive oracle"]
    style E fill:#fee,stroke:#c33
Loading
Production mechanism, unchanged Proof boundary
quantizer.py:232, gptq.py:452: affine quantizer metadata Reference target projection replaces the affine assumption in the reconstruction equations
awq_processor.py:3675: affine pseudo-quantization Search target-format loss with explicit inverse-input transform
gsq_training.py:30, rco.py Reuse actual categorical primitive and allocation math on legal hardware candidates
models/auto.py:1242, quantization/protocol.py:31: export API/fields No change; migration deferred until production consumers are qualified

Review Requirements

  • Reviewed numerical boundaries, storage costs, APIs, and scope.
  • No monkeypatching of the algorithms under test.
  • No shared mutable RNG/tensor caches or production behavior switches.
  • New path is opt-in through typed config; legacy method lifecycle preserved; no CI workflow edits.

Kernel Accuracy Requirements

A CPU MXFP4 correctness kernel is added, with at most 128 output rows of temporary decode and no persistent expanded weights. Independent FP32/FP64 scalar-decoded Torch oracles, exact blocked-GPTQ codes and repeated packed-state/forward transitions pass. CPU codec tests cover every finite code, every rounding midpoint and adjacent FP64 inputs, saturation, signed zero, scale boundaries, and independent packed-word decoding. Native Torch FP8 casts agree in the finite range. No GPU, native FP4 instruction, swizzle, or broad model-quality qualification is claimed; the bounded 0.5B CPU smoke metrics are above.

Notes

Canonical proof packing is not a vendor/checkpoint layout. AWQ transform overhead counts unless safely folded upstream. GSQ scales are frozen; RCO uses an additive reconstruction objective, not full-model KL training. GIL=0/concurrent execution, generalized model/format coverage and removing export remain follow-ups. The new Qwen2 CPU path includes calibration and versioned safetensors checkpoints. The proof has bounded small fixtures but is not a memory-scalable production solver.

Link to Devin session: https://app.devin.ai/sessions/87000f2a80ad4de69b7daf41c9100d28
Open in Devin Desktop: https://app.devin.ai/desktop/session/87000f2a80ad4de69b7daf41c9100d28?variant=devin
Requested by: @Qubitium

@devin-ai-integration

Copy link
Copy Markdown
Contributor

I'll fix CI failures and address comments from users with write access that start with 'Devin'.

  • Disable automatic comment, CI, and merge conflict monitoring

Comment thread scripts/prove_format_solvers.py Fixed
@devin-ai-integration devin-ai-integration Bot changed the title Prove solver-to-hardware-format feasibility with CPU reference math Add matched solver/format planning and validate CPU GPTQ to MXFP4 Nov 17, 2026

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Devin Review

@devin-ai-integration

Copy link
Copy Markdown
Contributor

Devin Review

🟢 Devin Review found nothing to fix · View findings

Keep main's FP8 load-only guard in quantize() alongside the
solver/format planning path.
@Qubitium
Qubitium marked this pull request as ready for review November 19, 2026 03:20
Keep both attn_mask helpers: main's align_single_head_capture (used by the
capture path) and this branch's tokenizer_bos_token_id (used by the
BOS-only statistic masking).
@Qubitium
Qubitium marked this pull request as draft November 19, 2026 11:35
@Qubitium
Qubitium marked this pull request as ready for review November 20, 2026 01:06
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.

1 participant