Repository navigation
perf(awq): size routed-expert reservoirs from their own captures (#5284) - #5327
Merged
Qubitium merged 1 commit intoNov 19, 2026
Merged
Conversation
…elCloud#5284) ModelCloud#5295 memoized the capture policy and skipped merges that cannot enter, but two costs remained on the routed-expert path: * every routed expert kept the layer-wide plan budget (906 rows on OLMoE) instead of the pre-ModelCloud#5175 per-expert rule (max(largest capture, captures); mean 254, median 203), so the clip search and the replay forward ran on ~3.6x the rows. The reservoir still keeps the lowest priorities, so the kept set stays a uniform sample of the stream. * a growing budget re-seeded from ``inputs``, which cannot work because provenance is materialized only at replay, so growth silently dropped every kept row. Carry the rows the buffer already holds. * the merge concatenated the kept priorities with the capture and wrote every surviving captured row into a slot. Select the drop set from the ``overflow`` largest kept priorities plus the capture and write only the surviving captured rows. Accuracy on full 16-layer OLMoE-1B-7B (128 C4 docs, batch_size=1, RTX 4090): PPL 11.2870 with the layer-wide cap vs 11.2814 with the per-expert rule, i.e. no measurable loss, and quantize 655-690 s -> 490 s (measured with the rule monkeypatched on main). On a 7-layer truncation the whole change is 997 s -> 541 s. Tests: tests/test_awq_moe_quant_speed_5284.py (6, CPU-only).
Qubitium
marked this pull request as ready for review
November 19, 2026 01:55
This was referenced Nov 19, 2026
Qubitium
added a commit
that referenced
this pull request
Nov 19, 2026
Qubitium
added a commit
that referenced
this pull request
Nov 22, 2026
…h Transformers (#4620) * Build vendored configs for package-loader cases in the gemma/olmo plan coverage test Co-Authored-By: Claude Opus 5.5 <[email protected]> * Point merged tests at vendored configs and owned loaders - axk2 subset-ordering and qwen4_exp untagged-leaf tests build the vendored AXK2/Qwen4Exp configs the package-owned loaders require. - MoE expert coverage builds the vendored bailing_hybrid config, which the package-owned Bailing loader routes to the vendored hybrid model. - qwen3: Qwen3.5 text loads through a LocalModelLoader, not AutoModelForCausalLM. - trust_remote_code override and custom-tokenizer bypass tests used phi3/mpt, which now return early through their LocalModelLoader; exercise the same Transformers-native branch with biogpt, which GPT-QModel does not define. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Point norm-teacher and Qwen3-Omni embedding tests at vendored classes The GPT-2 teacher and the Qwen3-Omni wrapper are now built from the vendored Transformers 5.23 ports that their definitions load, so the teacher forward probe and the thinker-getter patch observe the classes that actually run. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Use vendored gpt2/qwen3_5_moe_text classes in norm-teacher and out-of-model tensor tests Co-Authored-By: Claude Opus 5.5 <[email protected]> * Give vendored classes Defuser's native treatment without patching Transformers Defuser keys runtime patches, expert specs and construction-time block replacements by transformers.models class path, so vendored fused blocks (Phi3/GLM/GLM4/GLM-OCR/Zamba2 gate_up, DBRX/Longcat experts, GLM4V MLP) were left unsplit. _convert_model_with_defuser now presents each vendored class to Defuser under its transformers.models path through a temporary per-class alias subclass, then restores the vendored class (or keeps a vendored-module subclass carrying what Defuser added to the class). defuser.replace_fused_blocks() is no longer called: it patches Transformers modules and swaps Transformers' global checkpoint conversion mapping, which made native-saved Mixtral/Qwen-MoE checkpoints load with missing fused expert keys into vendored classes. Construction-time replacements are applied after construction under the same keys (MoE blocks via the generic experts pass, dense GLM4V MLP via Defuser's runtime split). The per-definition after_defuser_conversion stopgaps (phi3, glm, glm4v, dbrx, internvl_chat) are removed. Co-Authored-By: Claude Opus 5.5 <[email protected]> * native.auto: build text task classes from a composite config's text_config Mirror Transformers' auto factory: when the resolved task class is declared on config.text_config, _from_config/from_pretrained build from that sub-config and carry the parent's quantization config. Dots3 Note now uses NativeForCausalLM directly; Dots3NoteTextForCausalLM is removed. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Native definition loading: drop the replace_fused_blocks xfails GPT-QModel no longer calls defuser.replace_fused_blocks, so native-saved Mixtral and Qwen3-Omni-MoE checkpoints load into the vendored classes with every expert weight and native logits. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: reset the memoized AVX512-BF16 probe instead of calling removed cache_clear has_avx512_bf16() now memoizes into cpu_features._AVX512_BF16 (a plain module global, so traced forwards stay compilable) instead of lru_cache. The feature-detection tests still called .cache_clear(); reset the global through monkeypatch so the real probe runs against the faked cpuinfo. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: skip AVX512-BF16 checkpoint-invariant cases on hosts without the ISA The torch_cpu_avx512 GPTQ/AWQ cases construct a kernel that raises avx512_bf16_error() on hosts without AVX512-BF16. Skip exactly those parametrizations; every other CPU kernel case still runs. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Select deepseek_v32/flint/jamba/qwen3_vl_moe/xing4_0 definitions from real tiny config.json The selection tests patched AutoConfig.from_pretrained, which the loader no longer calls (it reads config.json via get_config_dict, then the definition's vendored/LocalModelLoader config), so the fake ids hit HFValidationError. Write a real config.json with the vendored config class into tmp_path. Xing4.0 is an owned port (require_trust_remote_code=False since 72cf9850); assert that and cover both trust settings. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(cpu): rebuild int4pack qweight on a meta move; gate AVX512 audit params rebuild_gptq_qweight asked _ret_idx_is_identity (torch.equal) on meta g_idx after a device move to meta, which has no meta kernel. A meta tensor carries no values, so the inverse permutation is skipped and only the checkpoint layout is rebuilt (test_device_move_restores_checkpoint_layout). The TorchCpuAvx512* params of the audit tests need the AVX512-BF16 kernel; skip them via has_avx512_bf16(). The native pack_block shape check skips when the JIT extension cannot be built (no ninja). Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: run the in-memory qzero-format invariant on CPU The fixture hard-coded RTNConfig(device="cuda:0") although the invariant (BACKEND.TORCH keeps the v2 runtime qzeros in memory and emits v1 words in state_dict) is device-independent, so it errored on every CPU host. Quantize on CPU and pin dtype=float16 on the load: a CPU load otherwise defaults the unquantized layers to bfloat16, which made the live-vs-reloaded (FP16) logits differ by bf16 rounding rather than by the qzero layout under test. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: port flash module-tree test to vendored configs and the package-owned Ripple fixture The test imported the removed _reference_dir helper (collection crash) and built configs with transformers.AutoConfig, which the native loader now rejects. Build configs from the vendored CONFIG_MAPPING and load the tiny Ripple model through the package-owned _load_tiny_model, so the Ripple tree test runs offline instead of skipping on missing custom code. Co-Authored-By: Claude Opus 5.5 <[email protected]> * cpu_policy_4396: load from a real tiny llama config.json instead of patching AutoConfig GPTQModel.from_pretrained now reads config.json through get_config_dict and the vendored config, so the AutoConfig patch no longer applied and 'fake/model' went to the Hub. Write a real unquantized llama config into tmp_path; the definition load stays stubbed. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Build real vendored config.json dirs in model-type selection tests The definition selectors read config.json through PreTrainedConfig.get_config_dict and the package-owned loaders, not AutoConfig.from_pretrained, so mocking AutoConfig no longer intercepted anything and the fake /tmp/<name> and Hub ids failed with HFValidationError / LocalEntryNotFoundError. Each test now saves the vendored config class for its model_type into tmp_path and selects from it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(rocm): gate the Triton-dependent kernel contract cases ParoTritonLinear imports Triton at module scope, so the registry does not register it on a host without Triton; the registry audit now expects that. MacaqTritonLinear's device validation requires Triton, so its ROCm acceptance cases skip when Triton is missing. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: give partially-built LazyTurtle its native-fp32 name cache in sync_all_meta progress tests sync_all_meta now resolves native fp32 slots through LazyTurtle._native_fp32_names, which __init__ creates; the tests build the turtle with __new__ and must set it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(loader): describe a CUDA host to auto_select_device in the #4705/#4734 fakes auto_select_device reads the import-time HAS_CUDA/IS_ROCM flags, not torch.cuda.is_available(), so on a CPU-only host the default resolved to CPU and the capability-group assertions never ran. Patch the flags alongside the capability fakes. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Select Ovis2.6-MoE and RefinedWeb definitions from real config.json Ovis2.6-MoE has no vendored CONFIG_MAPPING entry; save the port's tiny Ovis2_6_Moe_Config instead of mocking AutoConfig. RefinedWeb: keep the case-insensitive registry contract on select_model_definition, and add a real legacy RW config.json per casing. The RW LocalModelLoader canonicalizes those to native Falcon, so the checkpoint resolves to FalconQModel (an RwgQModel subclass). Co-Authored-By: Claude Opus 5.5 <[email protected]> * gemma4: drop the pre-5.23 KV-store disable hook; test the 5.23 contract on vendored classes Transformers 5.23 (and the vendored gemma4 port) derives store_full_length_kv from kv_sharing_modes, which marks no layer when num_kv_shared_layers == 0, so _disable_unused_gemma4_full_length_kv_store was a no-op kept for older Transformers. Remove it. The two tests that asserted the old flags on transformers.Gemma4ForCausalLM covered only that back-compat; replace them with vendored-model tests that pin the 5.23 contract (no store / empty captured shared_kv_states without a KV-shared tail; producer layers store with one). The text selection test now writes a real vendored gemma4_text config.json. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(hw-parity): skip the Paro/GGUF Triton launch tables without Triton Both tables live in Triton kernel modules (Paro's imports Triton at module scope; GGUF defines its SM89 table only when Triton imports), matching the importorskip the parametrized launch-table check already uses. Co-Authored-By: Claude Opus 5.5 <[email protected]> * paro_benchmark: import ParoTritonLinear lazily so CPU-only helpers load without Triton make_paro_config and the calibration tokenizer helper live in gptqmodel.utils.paro_benchmark, which imported ParoTritonLinear (and thus triton) at module scope. On a Triton-less host every importer crashed, including test_paro.py and test_calibration_special_tokens_4191.py at collection. Import the Triton module only where the kernel comparison clones a ParoTritonLinear. Regression test blocks triton in a subprocess. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(macaq): run the torch-only module tests without Triton _quantized_module_pair built MacaqTritonLinear unconditionally, so three MacaqLinear (CPU) tests failed on a host without Triton. The Triton half is built only when triton_mxfp4_available(); its callers were already gated. The recorded-Triton-kernel restore and the Triton source pin skip without Triton. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: compare reloaded ERNIE router to the AWQ-compensated fp32 router Since 2c448107 restored ERNIE-4.5-MoE AWQ scale search, the post_attention_layernorm fold compensates the native-fp32 router gate, so the saved router intentionally differs from the unquantized reference. Assert it stays fp32, actually changed, and reloads bit-exact from the quantized model. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: skip the HF GPTQ v2 qzeros bridge cases without optimum Every case loads through AutoModelForCausalLM, whose GPTQ quantizer needs the optional `hf` extra (optimum). Skip at module level like the other optimum bridge tests instead of failing with ImportError. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(cpu): reset the published CPU capability globals instead of lru_cache #5070 replaced the lru_cache on has_avx512_bf16/has_cpu_bf16x3_precision with module globals so a traced forward never enters the probe; the tests still called .cache_clear(). Reset the globals through monkeypatch instead. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(macaq): observe the W4A16 Triton-module torch tail on CPU The test replaces the only Triton launch (dequant_w4_to_bf16) but still hit mxfp4_w4a16_linear's TRITON_AVAILABLE gate on a host without Triton; lift the gate in the test so the FP32-reduce tail is still checked on CPU. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Finish the pending model-import and stale-pattern ports - llama aliases resolve through native.auto CONFIG_MAPPING / MODEL_FOR_CAUSAL_LM_MAPPING and the vendored Llama/StableLm classes. - lfm3_vl uses the vendored LFM3-VL model/config/processor and vendored Qwen2-VL/Qwen3-VL media processors. - unlimited_ocr is vendored from Transformers 5.23 (parity fixture added) and the port binds the vendored classes. - internvl_chat uses the vendored LlamaTokenizer. load_hf_tokenizer declares every vendored tokenizer class to Tokenicer as the Transformers class of the same name (tokenicer.register_transformers_equivalent), so Tokenicer's class-gated normalization keeps token ids identical. Requires tokenicer>=0.0.21; no fallback. - num_logits_to_keep is a parse-time config field (falcon_h1, nemotron_h, zamba2 convert it once to logits_to_keep). - Intern-S1: regression test that a per-expert MoE checkpoint reloads with no missing/unexpected keys through the attached qwen3_moe conversion. PENDING_MODEL_IMPORT_PORTS and PENDING_STALE_PATTERN_PORTS are now empty. Co-Authored-By: Claude Opus 5.5 <[email protected]> * requirements(tenstorrent): pin tokenicer==0.0.20 to meet the project floor requirements.txt requires tokenicer>=0.0.20 for the Transformers 5 ports (d2910af4); the Tenstorrent manifest still pinned 0.0.17. Not re-validated on Tenstorrent hardware. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: check the bitsandbytes ignored-layer converter only with bitsandbytes convert_bitsandbytes_shard resolves the optional bitsandbytes runtime up front, so bundling it with the four CPU converters made the whole ignored-layer test fail without that package. Split it into its own test with importorskip; the nvfp4/awq/gptq/compressed-pack cases always run. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test: run NF12 perf-helper and Marlin import tests correctly on CPU hosts - validate_nf12: fake torch.cuda.Event alongside synchronize; a CPU torch build refuses to construct the dummy Event, so the device-targeting assertion never ran. - marlin_import_min: gate on requires_nvidia_cuda(); the CUDA-only extension cannot load without a CUDA device. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: make the W4A import-policy subprocess checks Triton-aware test_fp8_replay_import_does_not_require_native_fp4_apis asserted the block-scaled FP4 reason, but W4ANVFP4Linear.validate_once() reports a missing Triton packer first, so on a Triton-less host the CPU replay part passed and the final assert failed. Keep the CPU replay check everywhere and assert the reason that is actually reachable on this host. test_w4a_modules_import_without_gluon_mma_v2 imports Triton's Gluon ampere module in its subprocess; skip it when that module is absent. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Make dataset-loader test hermetic; skip AWQ Hub inference tests without CUDA or cached checkpoint - test_dataset_loading pulled imdb from the Hub; load a 20-row local jsonl fixture with the same percentage-slice split instead and assert the rows it returns. - AWQ llm-awq/Mistral inference tests load onto cuda from Hub-only checkpoints; skip precisely when CUDA is absent or the checkpoint is not in the local HF cache. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: use torch's fp32 atol for DeepSeek-V2 cached-vs-full retry parity The port is bit-identical to native Transformers 5.23 DeepseekV2, and the native model shows the same fp32 reduction-order drift between cached decode and a full forward. One element exceeded atol=2e-6 (3.5e-6 at rel 5e-5). Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: run AWQ Triton dispatch logic and Paro suites on Triton-less hosts test_awq_rank_and_empty and test_awq_fp16_matmul_heuristic replace both AWQ Triton kernel entry points with fakes, but monkeypatching by dotted path imported the real kernel module (and triton). Stand in an empty module when triton is absent so the dispatch/heuristic logic still runs on CPU; skip only the cases that construct a Triton module or import ParoTritonLinear. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test_integration: skip CUDA, optimum and Hub-only cases precisely - *_cuda cases and test_llm_awq load onto cuda: skip without CUDA. - GPTQConfig quantize and the Optimum load bridge need the optional `hf` extra (optimum): skip when it is not installed. - test_llm_awq also needs ModelCloud/opt-125m-llm-awq in the local HF cache. CPU torch_fused load cases still run against the local TinyLlama checkpoint. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(gguf): keep Q1_0 launch-config data importable without Triton The Q1_0 G128 fixed launch configs were defined inside the `if _TRITON_AVAILABLE` block while the module-level selectors that return them are not, so calling a selector on a Triton-less host raised NameError (caught by the selector tests on CPU). Hoist the plain-data dicts. Tests: the GGUF dequant-dtype test now pins both the FP16 (narrow) and BF16 (FP32 dense fallback, per _use_fp32_gguf_weight) policies instead of assuming input dtype on every host; GGUFTritonKernel construction needs Triton, so that format-rejection test importorskips it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: DeepSeek-V4 causality check tolerates MoE regrouping reduction order Perturbing suffix tokens changes routed-expert token groups, so fp32 prefix logits move by ~7e-9; native Transformers 5.23 DeepseekV4 shows the identical drift and the port is bit-identical to it. Use the test's existing fp32 cached-parity tolerance instead of exact equality. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(vl): expect #4889 edge-pad stripping on pre-tokenized calibration rows The base prepare_dataset strips contiguous pad positions at row edges so the length sort and collation see real lengths (#4889). The Gemma3-VL and Qwen3.5-MoE pre-tokenized routing tests still expected the padded widths. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: let ROCm gating and Paro ROCm/training suites collect without Triton ParoTritonLinear's module imports Triton at module scope (the kernel registry treats it as an optional backend), so importing it at test-module scope crashed collection of every CPU-only test in these files. Import it only in the tests that need it and skip those without triton. In the ROCm gating suite, also recompute Marlin's import-time build refusal as a ROCm host would (on a GPU-less host it was frozen to 'requires CUDA'), and skip the GGUF Triton validate_once success check when triton is absent. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(moe_tags): check config-resolved MoE roots on the effective tree Intern-S1, InternVL-Chat, MiniCPM and Xverse declare a dense static tree and add the routed :moe root in _resolve_effective_module_tree, so the static-only check found no root. Build a tiny meta MoE model, resolve the effective tree and assert the root/placeholder/AWQ-capture contract on it. Nemotron-H Puzzle's mixer root deliberately opts out of token-row packing (shared Mamba/attention mixer); assert that opt-out explicitly. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(offload): keep identity-shared meta parameters shared when the lazy shell materializes Run-exit recovery fills the modules a failed run never reached from the source checkpoint, one module at a time. A parameter shared by identity while still on meta (an lm_head tied in session to the input embedding) was filled once per owner from that owner's own checkpoint key, silently splitting it into two tensors. test_qwen2_5_omni_lm_head::test_omni_lm_head_rejects_shared_weights caught it: the tied-head rejection left the model untied. materialize_remaining_meta_modules and the weight-only base-module fill now rebind every other owner of a shared meta parameter to the tensor its first owner received. Adds tests/test_materialize_shared_meta_parameters.py. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: skip Triton-kernel-module suites cleanly when triton is absent test_dequant_launch_config, test_kernel_policy_snapshot_4555, test_nvfp4_accumulate_bounds_4551 and test_triton_autotuner_concurrency import modules that import triton at module scope; every case in them exercises a Triton kernel module, so a module-level importorskip replaces the collection crash on CPU-only hosts. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: Raon1-mini fp64 oracle parity uses torch's fp32 atol The pinned Raon source computes norms, mHC mixing, conv and recurrent state in float32 (the port run in float64 still differs from the float64 oracle by ~1e-6). One rda/no-expert element hit 4.5e-6 on logits of magnitude ~3. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(norm): expect the headless qwen2_vl_text norm candidate Qwen2VLQModel now declares ["model.language_model.norm", "language_model.norm", "norm"] so the native headless Qwen2VLTextModel resolves its root norm; the list-flattening regression test still asserted the two-entry declaration. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: skip peft/tabulate/triton-dependent tests when the package is absent test_quant_and_eora_transformers and test_olora_finetuning_xpu import peft at module scope; test_awq_triton_benchmark imports a script that needs tabulate and the AWQ Triton kernels; test_kernel_config's ParoTritonLinear policy check imports a Triton module. The olora fine-tune also needs CUDA and the local checkpoint/dataset, so it now skips when those are missing. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: skip Evalution and ModelScope suites when the optional package is absent test_eval, test_eval_runtime, test_mmlupro and test_simple_quant assert on results from tests/eval.py, which needs the optional Evalution package; skip them up front instead of loading/quantizing a model and then raising. test_modelscope set GPTQMODEL_USE_MODELSCOPE before importing gptqmodel, which refuses to import without modelscope; skip before setting the flag. Co-Authored-By: Claude Opus 5.5 <[email protected]> * zamba: drop the dead legacy mixer monkey_patch; tests build vendored Zamba The vendored Transformers 5.23 ZambaMambaMixer has no slow_forward / cuda_kernels_forward, so ZambaQModel.monkey_patch never rebound anything (it logged and skipped). Remove it with require_monkeypatch. Deleted the three tests that only covered that removed legacy path (slow fallback, CUDA fast path - which also crashed on CPU hosts via .to('cuda') - and the 5.22 no-op). The selection test writes a real vendored zamba config.json instead of patching AutoConfig; the remaining tests use the vendored config/model. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: gate MLX generate on the Metal probe and FlashAttention-2 on flash_attn + CUDA test_mlx now uses accelerator_gates.mlx_metal_skip_reason (the MLX suites' existing gate) instead of failing with 'requires Apple Silicon' elsewhere; test_flash_attention needs the optional flash_attn package and a CUDA device. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(torch): publish TorchLinear decode caches through the eager path Since #5070 a CPU TorchLinear compiles dequantize_weight in post_init, and the traced graph decodes zero-points inline without publishing _zeros_cache, so the state-load invalidation test asserted a cache the compiled forward never builds. Build it with the eager class method, then assert load_state_dict clears it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * marlin_device_profile: resolve a bare int ordinal as a CUDA index torch.device(0) resolves the ordinal against the current accelerator, so on a torch build with no visible accelerator it raised 'Cannot access accelerator device when none is available' (test_explicit_device_zero_is_not_treated_as_unset failed on CPU hosts), and on a mixed host it could name a non-CUDA device. Build torch.device('cuda', index) for integer devices. Also skip the GPU-only linalg eigh test when CUDA/ROCm is unavailable. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(kv-cache): measure only the cache layers Transformers 5.23 allocated Gemma3n on 5.23 builds a cache layer per decoder layer and leaves the KV-shared tail's keys/values as None, so the oracle crashed on .numel(). Count the allocated layers; the estimate still has to match their number and bytes. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: stub the per-stream Marlin workspace in the CPU-shaped bias dtype test #4859 made MarlinLinear.forward borrow a lock workspace keyed by the active CUDA stream. The bias-width test fakes every Marlin launch on a CPU module, so the new stream lookup hit torch.cuda on a host without CUDA. Return the module's canonical workspace instead; the bias/scale dtype assertions are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(moe coverage): build minimax from its vendored config and exercise shared_mlp The sweep passed Transformers' native MiniMaxConfig into the package-owned MiniMax-Text-01 loader; build every LocalModelLoader config from the definition's own config class instead. The default config has no shared MLP, so the declared shared_mlp branch never resolved: set shared_intermediate_size like the released shared-expert checkpoints. Bailing's eh_proj belongs to the package-owned Ling MTP layers, which the native Ling 2.5 hybrid model has no counterpart for; accept it as an alternate branch when self_attn resolves. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(awq #4760): give the DeepSeek-V2 fake layer its MLA attention owners DeepSeekV2QModel.awq_get_modules_for_scaling now drops the q_a/kv_a latent norm and o_proj folds, reading module.self_attn on every decoder layer. The MoE-only fake layer had no self_attn; add the three owners it reads. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: run the TORCH packable round-trip on CPU when CUDA is absent BACKEND.TORCH is device-agnostic, but test_packable always loaded it on 'cuda', so the CPU host failed with 'No devices detected for accelerator family cuda' instead of checking the packed buffers. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(looper): fail EoRA construction directly in the #4862 release test Calibration and adapter samples are now prepared once before any processor is built (#4869/#4935), so the bad adapter row no longer failed the EoRA constructor and no processor existed to release. Inject the failure at the EoRA constructor instead and assert the already-built GPTQ processor is released; the empty-dataset case now matches the up-front preparation error. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: skip the TritonV2Linear benchmark without CUDA or triton TestTriton loads BACKEND.TRITON (TritonV2Linear declares DEVICE.CUDA only) and moves inputs to .cuda(); on a CPU host the load refused DEVICE.CPU. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(vlm): route Unlimited-OCR, Ovis2.6 and Qwen-Drive calibration through the shared contract The native ports of Unlimited-OCR and Ovis2.6 replaced their prepare_dataset with a shortcut that returned any `input_ids` dict list untouched, so pre-tokenized text rows skipped the base text path, a columnar mapping was iterated as its key names (calibrating on the text "attention_mask"), and concat_size/sort/min_length were ignored (#4633 regression). Both now delegate to prepare_vlm_calibration_dataset; the new `accept_processor_rows` option keeps rows their own processor already built (input_ids plus pixel_values/grid_thws) as ready batches under the conversation contract. Qwen-Drive loads no processor; a chat conversation now fails with a clear error (after the shared concat_size rejection) instead of "list-based calibration example must contain only integers". Qwen2-VL/Qwen2.5-VL prepare_dataset read self.model.config before delegating, which crashed for a wrapper built without its model; the headless-text check now tolerates that (Qwen2-VL uses the same _is_text_model helper as Qwen2.5-VL). The contract tests used a leading attention-mask zero, which the base path now strips as padding (#4889); they use an interior (caller-built) mask zero that is kept as given. New tests cover processor-prepared rows and the Qwen-Drive error. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Expect the vendored UnlimitedOcrConfig in the support test Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: Baichuan public AWQ round trip expects folded pre-norm gains d2d318f7 restored AWQ scale search for Baichuan, so input_layernorm and post_attention_layernorm gains now carry the searched scales. Drop the stale 'no scaling groups' assertion (it was vacuous with empty features), require both gains to change, and keep every other dense tensor bit-exact. Co-Authored-By: Claude Opus 5.5 <[email protected]> * tests: Ovis2.6 reload parity allows fp32 ulps from unaligned mmap weights Reloaded weights are bit-exact but are safetensors mmap views at unaligned offsets (native Transformers 5.23 from_pretrained does the same); CPU GEMMs round differently for unaligned operands (cloning the reloaded params into aligned storage restores exact equality). Use a tight fp32 tolerance for the reload logits/scores comparisons; keep weights and fp16/bf16 logits exact. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(gptq): pin #4430 adoption-time Hessian source release Since #4430 adopt_hessian_from synchronizes and drops the follower's deferred reference to leader.H, so the old test (which expected the source to linger until the fallback clone) indexed an empty deferral list. Assert the new invariant: events synchronized at adoption, no deferred source, the source is freed with the leader, and the fallback clone never sees it. Fails if the follower release in adopt_hessian_from is removed. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(qwen moe converter): defuse the vendored classes through the loader path The test built Transformers' own Qwen MoE classes, called bare defuser and hard-coded thinker.model.layers, which the 5.23 Omni thinker no longer has. Build the package-owned native ports the definitions load, defuse through _convert_model_with_defuser and read the definition's own layer node. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Sweep transformers.models imports out of package code - AWQ fold sources: vendored norm/activation classes (now including the vendored Cohere/Cohere2 LayerNorm that definitions load) plus framework modules; identical Transformers classes of unsupported models are matched by class path without importing them. - writer: tokenizer_config via native.auto.get_tokenizer_config (plain JSON). - glm5 core/flash/MTP helpers, W4A Llama stream, TT Llama and TT block-float build through vendored classes / NativeConfig; the exported TT modeling file names the top-level transformers class for external loaders. - sglang reads the config through load_model_config. - Qwen2-VL/Qwen3-VL/Qwen2.5-Omni bases use a native.auto LocalModelLoader and load processors through it; llama/nemotron_h alias descriptors fall back to BaseQModel.loader instead of importing AutoModelForCausalLM. - PARO rotary memoization recognizes vendored rotary classes. - Remaining Auto* uses (BaseQModel default loader/processor, hf config/support probes, compressed-tensors dequant) serve only unsupported models and carry an inline policy-exception comment. DeepSeek V4.1 helpers stay pending: Transformers 5.23 has no deepseek_v41 family to vendor. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Port policy guard: scan all of gptqmodel/ for transformers.models imports A new test fails on any transformers.models.* import or top-level model-family re-export (AutoConfig, AutoModelFor*, ...) anywhere in the package, outside an explicit, commented exception list (unsupported-model paths) and a shrink-only pending set (DeepSeek V4.1, absent from Transformers 5.23). Stale exceptions fail too. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(save): keep distinct empty tensors in the shared-storage filter get_state_dict_for_save keyed tensors by storage pointer. Every empty allocation reports the same null storage, so QQQ per-channel modules' empty s_group buffers collapsed into one key and all but one were dropped from the export; the reload then failed 'Missing required quantized weights' (test_checkpoint_quant_buffer_dtypes_4458, test_gsq_method_adapters QQQ round trip). Key empty tensors by identity. Adds a unit regression. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(awq): keep the MoE block signature on the bypass all-experts replay _all_experts_replay_forward swapped the MoE block's forward for a bare (hidden_states, **kwargs) wrapper. _prepare_module_forward treats a **kwargs forward as a Hymba-style catch-all (#4891) and synthesizes position_ids, which the wrapper then passed into Qwen3MoeSparseMoeBlock.forward (TypeError, test_awq_moe_bypass_4223). functools.wraps keeps the block's real signature visible to the kwarg filters. Adds a unit regression. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test_qqq_inference: load the local QQQ checkpoint and bound generation The test loaded HandH1998/QQQ-Llama-3-8b-g128 by Hub id, which fails offline. Use the local copy (skip when missing), and stop after 16 new tokens: the Paris/city answer lands in the first few tokens, while 512 tokens on the uncached CPU INT4 expansion ran past the 900s timeout. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test_post_quant_eora: calibrate from the local C4 shard; skip without CUDA allenai/c4 from the Hub is not resolvable offline (only a different config is cached). Use the local C4 shard the other calibration tests share, and skip when the checkpoints or shard are missing. At its 512-row/rank-256 scale the EoRA generation completed only layer 0's first subset in 29 minutes on CPU, so it requires CUDA. Co-Authored-By: Claude Opus 5.5 <[email protected]> * LazyTurtle: apply Transformers' submodule-scoped conversion renames (fixes Qwen2-Audio) Transformers' get_model_conversion_mapping also applies the map registered for each nested submodule class, scoped to that submodule: Qwen2AudioModel maps the checkpoint's language_model.model.* to language_model.* under model.. LazyTurtle only reversed the top-level qwen2_audio map, so it looked for language_model.embed_tokens.weight, never found it, left embed_tokens on meta, and the tiny Qwen2-Audio GPTQ smoke died with 'Tensor.item() cannot be called on meta tensors' during input capture. infer_hf_conversion_map_reversed now prepends reversed, prefix-scoped 1:1 renames from nested submodule classes. Regression test: test_lazy_turtle_maps_nested_qwen2_audio_model_keys_to_checkpoint (fails before). The Qwen2-Audio selection test writes a real vendored config.json. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Port DeepSeek V4.1 text decoder and dSpark stages onto the Transformers 5.23 ABI Package-owned config/modeling/Engram hashing under gptqmodel/models/ports/deepseek_v41, derived from DeepSeek-V4.1-Flash inference code (MIT). Rebind the V4.1 definition and utils/v41_* helpers to the port so nothing imports transformers.models.deepseek_v41, and empty the shrink-only pending set in the port policy guard. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Point merged tests at the vendored Llama/K2 loaders; pin Tenstorrent tokenicer 0.0.21 The Llama config, tied-embedding placement and K2-Horizon local-checkpoint tests still expected Transformers' own classes or the removed models.auto.AutoConfig. The Tenstorrent manifest pinned tokenicer 0.0.20, below the new 0.0.21 floor. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Test the DeepSeek V4.1 port against DeepSeek's reference inference code The oracle fixture is inference/model.py and engram.py at the pinned revision with dense FP32 storage and the TileLang kernels re-expressed in PyTorch. Covers RoPE, Engram hashing, layer-by-layer prefill, cached decode, dSpark drafting, image routing, generation, unfused experts, replay frontiers, V41Source block loading and the full-size runtime-to-checkpoint key inventory. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Document the DeepSeek V4.1 port and its unregistered status Co-Authored-By: Claude Opus 5.5 <[email protected]> * Check V41Source main-input preparation against the port's Engram tables and RoPE Co-Authored-By: Claude Opus 5.5 <[email protected]> * Check joint dSpark anchors against independent histories Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(awq): keep id()-keyed capture lists alive while collapsing features _layer_input_features caches the concatenated replay tensor and the token-row replay kwargs by tuple(id(tensor)). Since #5233 a routed expert's reservoir is materialized as a fresh buffer view that is dropped as soon as the module's entry is replaced, so CPython can reuse that id for the next module's view. The cache then handed expert N's down_proj the up_proj's 16-wide rows and AWQ aborted with 'does not accept the 16-channel source input' (flaky; reproduced by the vendored DeepSeek V4 hash-MoE AWQ test and Hymba's MoE AWQ test). Hold every keyed list until the loop ends. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(deepseek_v4): rely on the loader's runtime-key guard (#5131) for norm aliases The PR scoped Transformers' .kv_norm. <- .norm. rename to compressor and indexer norms so the packed checkpoint's model.norm.weight survived reload. That also stopped the HF source-layout chain layers.N.attn.norm.weight -> self_attn.kv_norm.weight. main's #5162 makes _checkpoint_key_converter a fixed point on the runtime names, which protects model.norm.weight generically, so drop the override and keep the full Transformers map. Co-Authored-By: Claude Opus 5.5 <[email protected]> * refactor: remove every Transformers/Optimum/OpenVINO bridge from package init GPT-QModel never patches, monkeypatches or registers into Transformers or the HF ecosystem. Delete the import-time installers in gptqmodel/__init__.py: - _patch_transformers_gptq_device_map_compat (GptqHfQuantizer hook wrap) - _patch_transformers_gptqmodel_gguf_quantizer_compat and _patch_transformers_refusing_quantizers (AUTO_QUANTIZER/CONFIG mapping registration, AutoHfQuantizer.from_config replacement) - _patch_transformers_save_pretrained_runtime_layout_guard (PreTrainedModel.save_pretrained wrap) - _patch_openvino_gptqmodel_compat (supported_quant_types replacement) - _patch_optimum_gptqmodel_load_bridge, _patch_transformers_gptq_quantizer_bridge, _patch_transformers_awq_gptqmodel_load_bridge and their _ensure_* retries - modelscope's patch_hub() (which patches huggingface_hub/transformers); ModelScope downloads keep going through modelscope.snapshot_download The bridge-only modules utils/hf_load.py, utils/hf_refusing_quantizer.py and utils/hf_gguf_quantizer.py, the create_quant_module transfer_from repair path, and the bridge retries inside hf_select_quant_linear_v2/hf_gptqmodel_post_init go with them. The public hf_* entry points Transformers itself calls stay. GPT-QModel-only checkpoint features (dynamic per-module configs, per-expert MoE tensors, refusal of GPT-QModel-only quant methods, the save_pretrained runtime-layout guard) are no longer reachable through plain AutoModel*.from_pretrained; load such checkpoints with GPTQModel.load. Save-time warnings now say so instead of promising an HF refusal. Bridge-only tests are deleted; remaining tests that asserted the registrations now assert the save-time warnings or transformers' own state. Co-Authored-By: Claude Opus 5.5 <[email protected]> * refactor(hf): stop patching torch.nn.init, PreTrainedModel.post_init and Transformers' GGUF loader - suspend_hf_weight_init: drop GPT-QModel's own process-wide replacement of torch.nn.init.{kaiming_uniform_,uniform_,normal_}. Transformers' public no_init_weights() context already silences every torch initializer and PreTrainedModel.init_weights; the reference-counted outer scope stays. - record_construction_dtypes: remove the scoped PreTrainedModel.post_init swap. The fp32 parameter that motivated it (#4888) is the Hymba mixer's A_log, and Hymba is now a package-owned port, so the port declares `_keep_in_fp32_modules_strict = ["A_log"]`. Transformers keeps it fp32 and assert_loaded_model_state exempts it through that declaration. - GGUF: remove the wrappers that replaced modeling_gguf_pytorch_utils.load_gguf_checkpoint / is_gguf_available, the Prism Q1_0_g128 attributes written into Transformers, and internal_gguf.install_runtime(), which planted GPT-QModel's reader as sys.modules["gguf"]. A `.gguf` file now loads through Transformers' stock GGUF integration, so the real `gguf` package is required (added to the `gguf` extra). Dropped features: GGUF loading without the `gguf` package, the direct-to-Torch dense Qwen3 import (KernelConfig.gguf_torch_dequant_loader is removed; its retired env var now says the feature was removed), and the Prism Q1_0_g128 dense import on Transformers builds without native support. GPT-QModel's own native quantized GGUF loader is unchanged. - _MONKEY_PATCH_LOCK is gone: nothing patches anymore. GGUF metadata tests that need Transformers' reader importorskip `gguf`. Co-Authored-By: Claude Opus 5.5 <[email protected]> * refactor: call a locked safetensors save_file instead of replacing safetensors' patch_safetensors_save_file() replaced safetensors.torch.save_file process-wide with a locked wrapper. GPT-QModel's writers (checkpoint shards, offload bundles, input cache, EXL3 frontier, v41 checkpoint, dequantizer, Tenstorrent block-float) now call gptqmodel.utils.safe.safetensors_save_file, which serializes the same call behind one lock without touching the safetensors module, so other libraries keep the original callable. Co-Authored-By: Claude Opus 5.5 <[email protected]> * refactor: drop the dead modeling_utils.check_support_param_buffer_assignment override Transformers 5.23 no longer defines check_support_param_buffer_assignment, so assigning it only added a foreign attribute to transformers.modeling_utils. GPT-QModel never writes into Transformers modules. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test: forbid every HF-ecosystem patch in test_transformers_unpatched The allow-list is now empty (the save_pretrained guard is gone) and the snapshot also covers the quantizer registry (AUTO_QUANTIZER_MAPPING, AUTO_QUANTIZATION_CONFIG_MAPPING, AutoHfQuantizer, GptqHfQuantizer, AwqQuantizer), Transformers' GGUF modules, torch.nn.init, safetensors.torch and, when installed, optimum.gptq / OpenVINO's GPTQ patcher. A fourth phase loads a tiny quantized GPTQ checkpoint with GPTQModel.load on the CPU torch backend and resolves a .gguf path, and the legacy probe rejects GPT-QModel's reader posing as sys.modules['gguf']. Against da2292b59 the test fails at import with the refusing quantizers, the AutoHfQuantizer/GPTQ/AWQ hooks, save_pretrained and safetensors' save_file all reported. Co-Authored-By: Claude Opus 5.5 <[email protected]> * refactor: drop bridge-only capability check and stale AWQ bridge warning validate_device_map_capability_groups only ran from the deleted HF load bridge, and the dynamic-AWQ save warning still told users to import gptqmodel for a native AWQ bridge that no longer exists. The warning now names GPTQModel.load. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs: GPT-QModel never patches the HF ecosystem; load checkpoints with GPTQModel.load README, AGENTS.md, the porting skill and docs/transformers5-model-ports.md state the rule (no patching, monkeypatching or registering into Transformers/Optimum/OpenVINO/safetensors/huggingface_hub, not even scoped) and point at tests/test_transformers_unpatched.py. hf-interop, peft, macaq, checkpoint-interop, tenstorrent, kernel-config, gguf-load-policy and the dispatch docs drop the removed bridges, refusing quantizers, save_pretrained guard and direct GGUF loader, and note GGUF loading needs the gguf package. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test: align GGUF extra and block-float tests with the unpatched Transformers The gguf extra now requires the gguf package (Transformers' GGUF loader needs it), and the block-float test that exercised GPT-QModel's refusing quantizer in Transformers' registry is gone with the registration. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Preserve Defuser serialization and vendor the remaining OCR and VL processor selection * Drop the Defuser clear_memory swap; require defuser>=0.0.32 Defuser 0.0.32 (ModelCloud/Defuser#75) scopes its accelerator cache flush to the devices a conversion uses and never touches an uninitialized runtime, so a CPU/meta conversion no longer claims cuda:0 (#5105). GPT-QModel calls Defuser unmodified: defuser_conversion_scope, its lock and model_accelerator_devices are removed, and the regression test now proves a CPU conversion synchronizes nothing while Defuser's clear_memory stays untouched. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Give native Kimi-Linear a package-owned loader; policy covers every definition class auto.py dispatches non-K3 kimi_linear configs to KimiLinearNativeQModel outside MODEL_MAP; it inherited BaseQModel's AutoModelForCausalLM and built transformers.models.kimi_linear. The loader-policy guard now walks every BaseQModel subclass under gptqmodel/ (plus MODEL_MAP values). Co-Authored-By: Claude Opus 5.5 <[email protected]> * NativeProcessor: resolve sub-processors from the checkpoint's declared types Sub-processors were resolved only by config.model_type, so qwen3_vl_moe (no image-processor table entry; checkpoints declare Qwen2VLImageProcessor[Fast]) and diffusion_gemma (Gemma4 feature extractor/image/video) failed under require_load_processor. Declared image/video/feature-extractor types are now read the way Transformers 5.23's Auto*Processor reads them (nested processor_config.json, legacy files, Fast/Pil backend variants) and resolved through _by_name only; model_type table and the processor's *_class follow. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Lint: kimi native tree test config literal Co-Authored-By: Claude Opus 5.5 <[email protected]> * cleanroom(mobilellm): behavioral spec, license scope, golden fixtures Phase-1 clean-room deliverables: SPEC.md and SCOPE.md under cleanroom/mobilellm, 8 deterministic tiny fp32 fixtures (1.3 MB) under tests/fixtures/cleanroom/mobilellm. Generator script not committed (imports the FAIR-licensed port). Co-Authored-By: Claude Opus 5.5 <[email protected]> * cleanroom(instella): behavioral spec, scope, golden fixtures Co-Authored-By: Claude Opus 5.5 <[email protected]> * Remove restricted Instella sources (and the test that paraphrases them) for clean-room reimplementation Co-Authored-By: Claude Opus 5.5 <[email protected]> * Remove restricted MobileLLM port sources for clean-room reimplementation Co-Authored-By: Claude Opus 5.5 <[email protected]> * Parity: compare every call variant of every vendored class; restore verbatim DecisionTransformer tuple path The parity test only ran the default forward. It now also checks output_hidden_states, output_attentions (eager), return_dict=False (alone and with all outputs), use_cache plus a cached decode step, loss with labels and greedy generate, comparing output structure, keys, caches and tensors bit-exactly. Native failures are the oracle (same exception type) and are listed in NATIVE_UNSUPPORTED. Calls are reseeded (diffusion_gemma draws random numbers), multiple-choice heads get 3-D inputs, so roberta is covered too. The modernized DecisionTransformerModel returned 4/6 tensors for return_dict=False where Transformers returns 3; can_return_tuple cannot express that, so the file is the verbatim generator output again with an exact, reasoned stale-pattern exception. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Stop patching Accelerate, Triton and the Omni model classes - Drop the import-time replacement of accelerate.utils.modeling.clear_device_cache. GPT-QModel attaches its own GPTQModelAlignDevicesHook (same placement, every move with clear_cache=False) through its own disk_offload/attach and simple_dispatch_model, and adopts stock hooks that Transformers' from_pretrained(device_map=...) attached on its own model instance only. - Qwen Omni: install thinker-resolving embedding getters on the loaded model instance (after_defuser_conversion) instead of assigning them onto the vendored classes; drop the dead Transformers-class fallback. - Triton: GPT-QModel kernels use gptqmodel.utils.triton_jit.jit, a JITFunction subclass carrying the single-flight compile lock. Remove the global Autotuner/JITFunction patches (TritonPatch); GPT-QModel kernels use the package-owned CustomizedTritonAutoTuner, never triton.autotune. Co-Authored-By: Claude Opus 5.5 <[email protected]> * instella: clean-room config/modeling from SPEC.md plus golden-fixture tests Co-Authored-By: Claude Opus 5.5 <[email protected]> * Parity: hand-written bart/opt tiny-config tests; llama4 runs every call variant llama4 now goes through the shared variant harness; the native Llama4VisionModel crashes on output_attentions alone (reads output[2] of a 2-tuple), so that one variant is a documented native bug checked against native's hidden-states+attentions call instead. Co-Authored-By: Claude Opus 5.5 <[email protected]> * cleanroom(minicpm_o): behavioral spec, scope and golden fixtures for ChatTTS-derived TTS pieces Co-Authored-By: Claude Opus 5.5 <[email protected]> * cleanroom(locateanything): behavioral spec, scope and golden fixtures SPEC.md describes config, checkpoint interface, MoonViT/connector math, block-diffusion visibility rules, localization sampler/generate loop and processor contracts. SCOPE.md classifies every port file (all upstream- derived modules restricted under the NVIDIA License 3.3). Fixtures cover Qwen2 GQA/MQA-tied/sliding and Qwen3 variants, masks, sampler and processor. Co-Authored-By: Claude Opus 5.5 <[email protected]> * mobilellm: clean-room Apache-2.0 reimplementation from behavioral spec Rebuilds gptqmodel.models.ports.mobilellm on the vendored Llama port from cleanroom/mobilellm/SPEC.md only, adds the golden-fixture test and drops the spec directory after acceptance. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Excise ChatTTS-derived MiniCPM-o functions for clean-room reimplementation Co-Authored-By: Claude Opus 5.5 <[email protected]> * Remove NVIDIA-licensed LocateAnything sources for clean-room reimplementation Co-Authored-By: Claude Opus 5.5 <[email protected]> * Make the vendor generator the source of truth for ports/native Hand edits to vendored files are now recorded as scripts/vendor_patches/<family>.patch and applied (strictly: every hunk must match) after copying, so --refresh reproduces the committed tree byte for byte. --record-patches re-derives the patches from the committed tree and proves they reproduce it. native/MANIFEST.json pins every generated file (sha256 + verbatim/patched/ generated). The registry is the generator's output again (the committed copy had glm_ocr hand-moved out of sorted order). tests/test_native_vendor_manifest.py verifies the manifest and regenerates the tree from the Transformers 5.23 sources (installed wheel or $GPTQMODEL_TRANSFORMERS_SRC; skipped when absent), asserting byte equality. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Remove the LocateAnything test that restates the restricted equations Co-Authored-By: Claude Opus 5.5 <[email protected]> * instella: black-box port tests, docs update; drop clean-room spec Co-Authored-By: Claude Opus 5.5 <[email protected]> * Keep converted MoE experts in the routed-loop order and self-contained Defuser's construction-time Linear*SparseMoeBlock replacements (mixtral, qwen2_moe, qwen3_moe, qwen3_next, qwen3_omni_moe, glm4_moe_lite) run run_routed_experts: each expert sees its token rows ordered by top-k slot, then token. GPT-QModel converts the vendored block afterwards, so its experts fell through to linear_loop, which feeds rows token-major; AWQ scale search is row-order sensitive and moved expert scales away from main. Converted @use_experts_implementation experts now carry their forward on the instance: the routed-loop forward for those families, Defuser's own linear_loop_experts_forward otherwise. The model no longer resolves 'linear_loop' in Transformers' experts registry at call time, so a pickled converted model loads and runs in a fresh process. Co-Authored-By: Claude Opus 5.5 <[email protected]> * locateanything: clean-room configuration, NOTICE and license line Co-Authored-By: Claude Opus 5.5 <[email protected]> * Never resolve Transformers classes from checkpoint names; package-owned tokenizer selection - loader: the flash-attention probe resolved getattr(transformers, config.architectures[0]), importing an arbitrary Transformers model module and reading Transformers' class instead of the vendored one. It now uses the class the definition's loader builds (Native* registry by model_type, the loader's class, or the port module/registry for factories). - native auto: _by_name checks Transformers' lazy export table before getattr, so refusing a model-family name no longer imports that module. - load_hf_tokenizer: definitions whose loader names no tokenizer class now construct it through NativeTokenizer, which mirrors Transformers 5.23 AutoTokenizer selection (forced-backend ids, byte-level LlamaTokenizer, known-wrong hub classes; vendored TOKENIZER_CLASSES and the 5.23 lists are generated into _registry) but resolves declared names to vendored/framework classes only. Tokenicer still normalizes the instance; remote-only tokenizers (yi, stablelm_epoch) keep their path. - thinker embeddings: drop the getattr(transformers, ...) fallback. - policy: AST guard for dynamic transformers lookups; runtime subprocess guard that supported loads import no transformers.models family module. Co-Authored-By: Claude Opus 5.5 <[email protected]> * locateanything: clean-room localization sampler and fixture tests Co-Authored-By: Claude Opus 5.5 <[email protected]> * Extend the unpatched guard to Accelerate, Defuser, torch, Triton and model classes - tests/test_transformers_unpatched.py now also snapshots accelerate (utils.modeling/memory, hooks and hook classes, big_modeling), every defuser module, safetensors, huggingface_hub, torch.nn and torch._C device props, Triton (when importable) and the class __dict__ of every model class the loads instantiated; it runs a GPT-QModel disk offload and the Omni definition hooks. Empty allowlist. - Remove the remaining global third-party patches it found: the rocm_llc torch/Inductor back-port (KernelConfig.rocm_llc removed; the module only reports cache geometry), BitBLAS auto_detect_nvidia_target rebinding, and the GraniteMoeHybrid mamba class forward (now bound per instance). - tests/test_offload_hooks_no_cache_flush.py covers the GPT-QModel hook. - Docs: list Accelerate/Defuser/torch/Triton in the no-patch policy. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Lint Co-Authored-By: Claude Opus 5.5 <[email protected]> * Pin transformers>=5.23.0,<5.24 and drop dead version branches The vendored native ports are Transformers 5.23 sources bound to its framework ABI, so the requirement is pinned to the 5.23 minor; docs, AGENTS.md and the porting skill explain that a bump is a re-vendor plus parity. CI per-test overrides that installed Transformers 4.x/main are removed. The always-true Qwen3.5 (>=5.2) and dtype (>=4.56) version branches are gone. A policy test ties the pin to the vendored version. Co-Authored-By: Claude Opus 5.5 <[email protected]> * locateanything: clean-room image processor, processor and fixture tests Co-Authored-By: Claude Opus 5.5 <[email protected]> * locateanything: clean-room vision tower, decoder masks, model and localization generate Co-Authored-By: Claude Opus 5.5 <[email protected]> * locateanything: black-box contract tests, docs license row; drop clean-room spec Co-Authored-By: Claude Opus 5.5 <[email protected]> * minicpm_o: clean-room TTS codec and sampling components Implement ConvNeXtBlock, GFSQ, DVAEDecoder, DVAE, the windowed repetition penalty processor, both gen_logits factories, ConditionalChatTTS.generate and ConditionalChatTTS.decode_to_mel_specs from the behavioral spec. Fix the quantizer-constant defect: the dependency's non-persistent buffers are restored by ConditionalChatTTS._init_weights after from_pretrained and kept real on meta shells, so a loaded model decodes like a fresh one. Add golden-fixture tests plus a MiniCPM-o 2.6 save/load decode regression, rewrite NOTICE, and drop the cleanroom spec directory. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Tests: inject the legacy tokenizer choice into the package selector Co-Authored-By: Claude Opus 5.5 <[email protected]> * Re-record the vendored manifest after the generated tokenizer registry tables Co-Authored-By: Claude Opus 5.5 <[email protected]> * Skip expert-forward binding for objects that are not modules The sibling construction-replacement pass already returns early when the model has no modules(); loader tests pass lightweight fakes through the conversion. Co-Authored-By: Claude Opus 5.5 <[email protected]> * loader: drop the unused defuser_conversion_scope import Only the deleted Transformers bridge (utils/hf_load.py) used it, and ruff's F401 gate fails on the unused import. * test(fp8): drop the transformers-side refusal test The port registers no refusing quantizer (docs/hf-interop.md), so plain transformers keeps its warn-and-random-init behaviour and these two parametrizations cannot pass. tests/test_fp8.py: 20 passed. * fix(ports): address the CodeQL review threads - tests/test_converted_moe_experts.py: pop the cached expert row before the assert so the assertion stays side-effect free. - interns2_preview: replace the no-op self-assignment with pass. The two qwen3_omni_moe hits are verbatim vendored Transformers code and stay as-is; the xverse hit is a false positive (the conditional oracle returns four values for return_cache=True). * Track current main's AWQ expert digests in the routed-order test Main's AWQ changes (#5284, #5265, #5275, #5310) moved the tiny-MoE expert scales; the PR's vendored path still matches main bit-exactly (mixtral and qwen3_moe re-run on 556f4b22d). Co-Authored-By: Claude Opus 5.5 <[email protected]> * chore(ports): drop the duplicated diffusion_lm initializer * Fix tests left stale by the review and main merges - defuser floor tests expect 0.0.32 (0.0.31 is now below the floor). - Kimi-Linear module-tree and registry-leaf tests build the vendored config: auto.py dispatches a plain kimi_linear config to KimiLinearNativeQModel, not its MODEL_MAP entry. - InternLM tokenizer test: without the definition's binding, InternLM is refused as checkpoint-Python-only and InternLM2 follows Transformers 5.23's incorrect-hub-class rule (generic backend), which diverges on NUL bytes. - bitsandbytes payload case skips precisely when bitsandbytes is absent. - Drop the FP8 quantization boundary test: main #5242 removed FP8 export (quantize_fp8_weight), which broke collection of the whole file. - #5207 re-save test pins BACKEND.TORCH for every load and requires exact equality: auto-selection picked TorchAtenLinear on reload, one bf16 step from the in-session TorchLinear. Same failure existed on main. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Update #5284 reservoir tests for #5327's drop-set merge #5327 replaced the merge with a drop-set search (two topk calls) and may pair surviving rows with displaced slots differently, without updating #5284's tests. Assert the contracts instead of the call count and slot layout: losing captures short-circuit, ties and winners take the merge path, a single winner takes the displaced slot, and the kept rows (keyed by provenance) match the reference algorithm. Same failures existed on main. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(moe): pin the mixtral AWQ digest to what main actually produces 7fc25cedc recorded 96206e02 for mixtral, but neither a worktree at main 5470d9d40 nor this branch produces it here: both yield b9a9ecfd byte-for-byte for every expert qweight/qzeros/scales tensor. The qwen3_moe value matches. Re-recorded from the verified run. tests/test_converted_moe_experts.py: 9 passed. * fix(paro): register ParoTritonLinear on hosts without Triton The Paro Triton kernel imported its Triton GEMM at module scope, so on a Triton-less host the class never registered and the kernel registry (and the docs compile matrix check generated from it) depended on the host: test_docs_matrix_matches_the_declarations failed with stale=['ParoTritonLinear']. Guard the optional Triton import like the other Triton kernels and report the missing package from validate_once. Regression test blocks Triton in a fresh interpreter and requires the kernel to register and validate as unavailable. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(kernels): skip Triton kernel cases precisely when Triton is absent These files imported Triton kernel modules at module scope, so a host without Triton failed at collection instead of skipping. - Whole-file Triton suites (every case drives or reads a Triton kernel module): module-level pytest.importorskip("triton") before the import. - AWQ Ada/RDNA4 plan tests: the scheduler tables are Triton-free, so only the two kernel-rejection checks import the kernel module (after importorskip); the plan-table cases keep running on CPU. - GPTQ Ada/ROCm GEMM tests: guard the kernel imports with HAS_TRITON and mark only the cases (and fused-gate params) that read the Triton launch table; the TorchLinear dispatch/fallback cases keep running on CPU. - Paro Triton CUDA-graph test also requires a GPU (every case builds on CUDA). Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(w4a): import W4A Triton kernels only where Triton exists test_w4afp8_gb10 and test_w4a_nvfp4_gb10 imported the Triton kernel entry points at module scope, so a Triton-less host failed collection (and test_w4a_stream with it, via the shared oracle helper). Every case that calls those kernels already carries GLUON_FP8, which requires Triton; the config, replay and headroom cases now run on CPU. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(w4a): check NVFP4 weight freshness before loading the FP8 kernel W4ANVFP4Linear._forward_fp8_operand imported the Triton FP8 GEMM before validating the operand and the packed-weight layout, so on a host without Triton a stale cache surfaced as ModuleNotFoundError instead of the documented "changed since post_init" refusal (test_nvfp4_fp8_staging_cannot_launder_a_stale_packed_cache). Import the kernel only after fp8_weight_operand() has validated the layout. test_rocm_kernels_refuse_before_lowering calls the Triton kernel modules directly, so it now importorskips Triton. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(gguf): keep the SM89 Q4_K/Q5_K/Q6_K launch table importable without Triton _GGUF_SM89_QK_SHAPES was defined inside the `if _TRITON_AVAILABLE` block while the module-level selectors that read it are not, so the selector module could not be used (and test_gguf_ada_fixed_launch failed at collection with ImportError) on a host without Triton. Hoist the plain-data table to module scope, as was done for the Q1_0 configs. The CPU selector cases in test_gguf_ada_fixed_launch are the regression coverage. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(awq): skip AWQ Triton schedule cases when Triton is absent Building AwqGEMMTritonLinear runs its validate_once, which needs Triton, so the schedule-slot cases errored on a Triton-less host. The shared module builder…
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.
Follow-up to #5284. #5295 closed the capture-policy lookup and the merge that cannot accept any row; two costs remained on the routed-expert path.
Fix
Per-expert reservoir budget. A routed expert sized its reservoir from the layer-wide token-row plan (906 rows on OLMoE) although it only ever sees its own captures. It now uses
max(largest capture, capture count)- the pre-#5175 rule (mean 254, median 203 on the full model). The reservoir still keeps the lowest priorities, so the kept set stays a uniform sample of the stream (#5233/#5236 unchanged).Growing budget keeps its rows. The resize path re-seeded from
inputs, but provenance is materialized only at replay, so a budget that grew silently dropped every kept row. A resize now carries the rows the buffer holds, clamped to the new cap.Incremental merge. The kept set is the
budget_caplowest priorities ofkept + captured, so only theoverflowlargest kept rows can be displaced. Select the drop set from those plus the capture and write only the surviving captured rows, instead of concatenating the kept priorities and writing every surviving captured row into a slot.flowchart TD subgraph before["Before"] A1["layer-wide budget 906"] --> B1["clip search + replay<br/>on 906 rows per expert"] C1["cat(kept, capture) + topk<br/>mask + nonzero + arange"] --> D1["write every surviving<br/>capture row into a slot"] E1["budget grows"] --> F1["re-seed from inputs<br/>-> kept rows dropped"] end subgraph after["After"] A2["own budget max(largest, captures)<br/>mean 254"] --> B2["clip search + replay<br/>on ~254 rows per expert"] C2["drop set = top overflow of<br/>(top overflow kept) + capture"] --> D2["write only the rows<br/>that survive"] E2["budget grows"] --> F2["carry the kept rows"] endEvidence
Speed - 2-layer OLMoE, 128 C4 docs,
batch_size=1, one RTX 4090, alternating runs on the same tree pair_record_input_featuremain35d97a7 (with #5295)2.5x faster (165.4 s -> 65.5 s). The host was shared with other jobs, so the per-stage totals vary run to run; the wall time is consistent.
Accuracy - full 16-layer OLMoE (measurement posted on #5284 for the same rule)
quantize()No measurable accuracy change: the 3.6x larger sample bought nothing.
Tests
tests/test_awq_moe_quant_speed_5284.py(6 tests, CPU-only): 3 failed / 3 passed onmain35d97a7; 6 passed here.uvx [email protected] check gptqmodel docs/eora tests setup.pyclean.docs/moe-awq-calibration.mdgains a section on reservoir capacity, the merge, and the growth contract.Not verified
batch_size > 1end-to-end wall time.