🧩

gptqmodel-torch-oracle-numerics

gptqmodel-torch-oracle-numerics · v
作者 ModelCloud 公开目录收录

简介

Validate quantization math, packed formats, and inference kernels against a Torch oracle, including linear bias storage and epilogues. Enforce quantized persistent weight storage for inference, dispatch, and cache changes. Adjudicate near-tie mismatches.

通过你的 Agent 添加

安装目录:gptqmodel-torch-oracle-numerics/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。

点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。

或者手动安装

Claude Code~/.claude/skills/gptqmodel-torch-oracle-numerics/
Codex CLI~/.codex/skills/gptqmodel-torch-oracle-numerics/
DeepSeek Harness~/.agents/skills/gptqmodel-torch-oracle-numerics/

包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可; 目录名不用换,也不要把包直接解压到 skills 根目录。 技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。

技能正文


SPDX-FileCopyrightText: 2026 ModelCloud.ai

SPDX-License-Identifier: Apache-2.0

name: gptqmodel-torch-oracle-numerics description: Validate quantization math, packed formats, and inference kernels against a Torch oracle, including linear bias storage and epilogues. Enforce quantized persistent weight storage for inference, dispatch, and cache changes. Adjudicate near-tie mismatches.

Torch oracle for numerical changes

Contracts first. Read and honour contracts/ before acting. In particular, read the kernel forward dtype contract: one activation dtype per module, and output dtype equals input dtype. A different dtype on a later call is a bug. Contracts outrank this skill.

At a glance

For changes or audits of quantizers, packers, inference kernels, dispatch, fusion and weight storage, compare the path with an independent Torch oracle: same inputs/configuration, separate arithmetic, never the kernel's outputs or intermediates as expected values. Test boundaries, storage after repeated forwards, and the acceptance limits on target hardware. Select packers, threads and paths via config/API arguments, not environment variables. Start in gptqmodel/{quantization,nn_modules/qlinear}/ and gptqmodel_ext/; fusion and MLX test inventories are listed below.

Persistent inference weight storage

The repository-wide storage rule in AGENTS.md is an acceptance gate for all quantization methods and all inference backends and devices. Temporary dequantization for the current computation is allowed; moving an expanded cache to another device, marking it non-persistent, or hiding it behind an opt-in flag does not make it allowed. After an operation finishes consuming temporary weights, no inference-owned reference may retain a dense, dequantized, or expanded copy for reuse. Apply the gate to optimized and fallback paths, eager execution, JIT/compiled execution, warmup, and optional configurations. Disabling a prohibited cache by default is not a fix; environment flags and public opt-in APIs are not exceptions.

Judge storage by representation and lifetime, not names or dtypes. Native quantized weights, packed alternate layouts, scales, zero points, format codebooks, and indexing metadata may persist. Full-layer unpacked INT4 codes stored as INT8, or reconstructed FP16/BF16/FP32 weights, may not. This rule is about expanded weight copies, not ordinary activation/KV caches or weights already stored in their native quantized format.

Keep dequantized scratch local to its consuming computation, preferably in bounded tiles. Release references once all consuming work completes, including asynchronous work. Do not retain it in module attributes, buffers, containers, closures, global/thread-local caches, compiled graph constants, or backend objects. persistent=False, detaching a tensor, offloading it to CPU, and changing its precision do not change its lifetime. Allocator-reserved free memory is not a live weight cache; do not add per-forward allocator flushes. Explicit export/dequantization APIs and independent test oracles may return dense tensors to callers without installing them as inference caches.

For changed inference/storage paths:

  • Inspect persistent state after the first and repeated forwards, including each supported fallback and opt-in path. Add targeted regression coverage that demonstrates no dense/expanded weight is retained; do not only check a cache's name or serialization behavior.
  • Verify allowed packed caches invalidate on weight/scale mutation or replacement, checkpoint loading, device moves, and dtype casts made before the first forward. A dtype cast after a forward must raise (forward dtype contract). Exercise the shared explicit-clear contract for inference tensors without version counters.
  • Report retained weight/cache bytes and temporary dequantization storage alongside accuracy and speed. Distinguish unchanged checkpoint storage, additional packed caches, and transient scratch. A historical dense-cache benchmark may be shown only as a clearly labeled comparison, never as an eligible production optimization.
  • Remove violations encountered in the implementation under review. Record any remaining audited violations with file references; do not claim that documentation alone establishes compliance for every existing kernel.

Fusion backends

Fusion backend changes must preserve AUTO's native kernel selection. Each newly admitted kernel needs an explicit native-layout contract and actual-device numerical tests; a portable substitution or mocked dispatch does not qualify it. Cover supported activation dtypes, unequal QKV widths, gate/up, native shape boundaries, workspace and descriptor lifecycle, mutation, direct source calls, exact packed-weight restoration, and persistent storage. Keep the kernel inventory and measured device report in tests/module_tree/test_fusion_kernel_backends.py current; unavailable architectures, dependencies, and formats need explicit coverage reasons. Model-level fusion eligibility is covered by gptqmodel-model-plan-tests.

Linear bias

Trace the bias from pack or load to the final epilogue for each affected path, including dispatch and fallbacks. Select regressions from the kernel bias examples.

  • Preserve the registered bias's checkpoint values, dtype, logical shape, and column order through loading, post_init, forward, and re-save. At pack time follow the format's bias storage contract independently of scales and activations. Prove exact representability before a required narrowing or reject the pack before writing the checkpoint. Derive padded, permuted, or converted launch operands without rewriting the registered tensor.
  • For FP16/BF16 outputs, keep the floating reduction, scaled product, and bias add at FP32 or higher. Scale integer accumulators in that wide epilogue. Add the bias once to the complete reduction before the single cast to the public output dtype. Reuse _numerics.py helpers whose selected device and dtype branch preserves this ordering, including under autocast.
  • Keep eligible native paths for bias-free and representable cases. A narrow launch operand requires an exact value round trip and a native epilogue that adds it before rounding. For wider bias, use a supported wide native epilogue or add the bias to a wide native result. Exercise the supported fallback or explicit rejection when the native path cannot honor the contract.

Acceptance limits

  • Quantization: Packed codes, indices, and other discrete outputs must match exactly except for adjudicated floating-point rounding ties described below. Floating quantization outputs must satisfy both relative and absolute tolerances of 1e-6 or tighter away from those ties. For scale-dependent matrix intermediates such as Hessians, apply the 1e-6 limit to normalized matrix error ||actual - oracle|| / ||oracle||, and check for nonfinite values. Use a float64 Torch oracle for accumulated matrices when float32 accumulation error would consume the allowed tolerance.
  • Inference: Floating outputs may use relative and absolute tolerances up to 2e-3. Discrete outputs, including selected token IDs, must match exactly when the test fixes sampling and tie behavior.

Quantization boundary cases

For every changed packer or quantizer, test values exactly at and one representable input step on each side of relevant rounding thresholds. Also cover clamp/saturation endpoints, positive and negative values, zero (including signed zero when its packed bits matter), and scale or zero-point selection ties when the format has them. Exercise casts used by supported input dtypes. Random inputs are supplemental; they cannot replace boundary cases.

Compare complete packed bytes or codes with the independent Torch oracle. Reproduce any specified format precision and tie rule exactly: a packer with defined bytes cannot claim a rounding exception. For iterative quantizers that do not specify bitwise equivalence to Torch, investigate each code mismatch before rejecting a path or replacing GPU arithmetic with a slower Torch-matching operation. Trace the pre-rounding value, scale, zero point, and preceding updates; measure its distance in code units from the half-step. Adjudicate suspected ties with independent higher-precision arithmetic on the same source values and Hessian, including their actual stored precision. A one-ULP change may flip a code at a true half-step without indicating an inaccurate kernel. Check that mismatches away from proven ties still meet the exact-code and 1e-6 floating limits. Keep explicit threshold-neighbor and endpoint tests; do not turn a broad numerical tolerance into a blanket code exception. Report total mismatches, adjudicated tie mismatches, maximum output drift, maximum floating drift away from ties, and the reference precision in the PR.

For integer reductions or offset products, derive the last safe size from the operand bounds and intermediate dtype. Test it and the first overflowing size against an independently widened oracle (widen before multiplying). For reductions use same-sign extremal terms so cancellation cannot hide wrap; check the scaled public output as well as the raw sum. For offsets, probe the index arithmetic without allocating an oversized tensor.

Running and reporting

Use representative sizes and supported dtypes. Synchronize asynchronous backends before reading results or timing them. Run the tests on the target hardware. Report the tested shapes, dtypes, tolerances, observed errors, and benchmark method in the pull request.

MLX kernels

For MLX weight quantizers, packers, and inference kernels, include every projection in tests/qwen38_27b_shapes.py: full-attention Q/K/V/O, fused linear-attention QKV/O, and MLP gate/up/down. Use the checkpoint's bfloat16 dtype where the kernel supports it. Compare quantization against the independent Torch oracle over the complete output, including every packed byte or an individually adjudicated quantizer tie. Compare inference outputs using the limits above. Benchmark every applicable projection shape against the corresponding main-branch path with inputs already resident; report per-shape timings and the aggregation method. Keep small boundary tests in addition to this model-scale matrix. If a projection or dtype cannot run, name the specific limitation and cover the closest supported configuration.

For every MLX inference kernel, test FP16 and BF16 activations separately. Assert output.dtype == input.dtype for each supported activation dtype and compare both outputs against an independent Torch oracle. Keep the FP32 arithmetic comparison separate from the visible-output comparison. Also compare the visible output with the Torch oracle rounded to the same dtype, so kernel error can be distinguished from mandatory output rounding. Report both error measurements; keep rtol=atol=2e-3 or tighter and do not hide raw-oracle drift caused by low-precision output rounding.

Execution paths and failures

Cover each execution path used by the kernel, including native and dense fallback paths when both exist. If FP16 or BF16 is unsupported, test its explicit rejection and document the limitation instead of omitting that dtype.

For a graph-capture claim, warm up the actual format on device, capture, then replay with changed input and compare with eager output. A compile trace alone is not capture evidence. Check the negative dispatch case too: a per-format probe may narrow support, never re-enable a subclass that opted out. See the GGUF capture tests.

If an optimized path exceeds a limit, investigate the numerical cause before changing it. Fix genuine arithmetic or format errors and rerun the A/B tests. Record unresolved mismatches as merge blockers; retain a faster accurate path when only proven natural rounding ties differ, with the evidence above.

正文来自原始仓库, 版权归作者所有,许可:Apache-2.0。 权利人认为有不妥,可申请下架。

原始仓库

作者的项目地址:https://github.com/ModelCloud/GPTQModel

标签

没有标签

同类 Skill