Repository navigation
Port every supported model onto the Transformers 5.23 ABI; never patch Transformers - #4620
Conversation
|
I'll fix CI failures and address comments from users with write access that start with 'Devin'.
|
Devin Review🟢 Devin Review found nothing to fix · View findings |
Review: #4620 — local Transformers 5 models + checkpoint-Python gatingReviewed at head Some findings below were reproduced with tiny CPU models or with real Hub Verdict: request changes. The security direction is right: requiring both 🔴 Blocking1. ChatGLM, Baichuan, InternLM, InternLM2 and InternVL-Chat can no longer load their tokenizer at all (repro)
2. Kimi-Linear (non-K3) silently tokenizes differently from training (repro)
3. Building the Kimi-K2.5 processor wipes the shared tokenizer's special tokens (repro)
4. DeepSeek-V2: the caller's
5. Kimi-K3: loading the published checkpoint through the port fails on
🟠 Security / policy6. Tokenizer trust is silently downgraded instead of rejected
7. The remote-only layout guard is dead code, and its error message is misleading
8. Trust resolution now does uncached I/O on every call, even with
9. The norm-tuning teacher bypasses the definition loader
10. "Native first" is not what happens for several types
🟡 Packaging / deps11. Test-only assets ship in every wheel
12. Dependency cleanup
🔵 Minor
Process
What looks good
|
Follow-up review: #4620 at
|
| # | Finding | Status |
|---|---|---|
| 1 | ChatGLM/Baichuan/InternLM/InternLM2/InternVL tokenizers unloadable | ✅ Fixed. All five definitions now declare a package tokenizer_class |
| 2 | Kimi-Linear (non-K3) silently mis-tokenized | ✅ Fixed, re-verified. Using the real Kimi-Linear-48B-A3B-Instruct files, KimiTokenizerFactory now gives KimiLinearTokenizer, which matches the upstream TikToken reference on every probe string, including the contraction cases that differed before |
| 3 | Kimi-K2.5 processor wiped shared special tokens | ✅ Fixed with replace_extra_special_tokens=False |
| 4 | DeepSeek-V2 did not update the caller's cache | ✅ Mostly fixed. _cache_transaction restores in-place semantics and rolls back on failure. Static and offloaded caches still raise TypeError, so please document that limit |
| 5 | Kimi-K3 padded A_log failed to load |
✅ Fixed with _load_from_state_dict and ActiveKDAHeads |
| 6 | Tokenizer trust silently downgraded instead of rejected | hf.py:2732). Much lower impact now that ported families own their tokenizers, but unported families with trust and no bypass still fall back to a native tokenizer with no error |
| 7 | Dead remote-only layout guard | ✅ Fixed (removed) |
| 8 | Repeated, uncached trust probes; missing selection kwargs | trust_remote_code=False now returns with no I/O, and the writer forwards _config_load_kwargs. Still open: GPTQModel.export (auto.py:1256) and model_dequant.py:346 call resolve_trust_remote_code without subfolder/revision, and the trust=True path still re-parses config several times per load |
| 9 | Norm-tuning teacher bypassed the definition loader | ✅ Fixed (base.py:2771-2780) |
| 10 | "Native first" wording | ➖ PR description unchanged; it's a wording issue, not a blocker |
| 11 | Kimi-K2.5 test assets shipped in the wheel | ✅ Fixed (qualification_assets/ removed) |
| 12 | Dead python_version < "3.11" markers |
✅ Fixed. New dependencies were added, though; see below |
| minor | K3 batched-image mask, K2.5 bytes_to_unicode attribution |
✅ Fixed |
| minor | V4 MTP helpers hard-code 3 blocks; V4 test rtol=0, atol=0; V3 out_of_model_tensors hard-codes model.layers.61; K3 router bias not fp32 |
➖ Unchanged (all low severity) |
🔴 New blocking issue: CI failure is caused by this PR's timm dependency
In my first comment I said the AWQ CPU failure "looks environmental". That was wrong.
All three AWQ CPU jobs fail on 5a0b429d during test collection:
E RuntimeError: operator torchvision::nms does not exist
E ModuleNotFoundError: Could not import module 'PreTrainedModel'.
Root cause, from the install log:
- The workflow installs
torch==2.15.0from the CPU index. - It then runs
pip install -r requirements.txt. - This PR adds
timm>=1.0.22torequirements.txt. That pulls an unpinnedtorchvision-0.29.2from PyPI (Collecting torchvision (from timm>=1.0.22->-r requirements.txt)), which does not matchtorch 2.15.0+cpu. - Once a broken
torchvisionis importable, Transformers' lazyPreTrainedModelimport fails.
origin/main has no timm, and the same workflow passes on other branches today.
Suggested fix: timm is imported only by five vision ports:
deepseek_vl_v2/siglip_vit.pyinterns1/modeling_interns1.pyllava_qwen2/fastvit.pyminicpmv/modeling_minicpmv.pyopenvla/modeling_prismatic.py
These modules are already loaded lazily through LocalModelLoader. Move timm to an optional extra (for example gptqmodel[vision]) and raise a clear error from those ports when it is missing. That also keeps torchvision out of every text-only install. sentencepiece was also added as a hard dependency. It is lighter, but only the Baichuan, TeleChat2 and InternS1 tokenizers need it.
If timm must stay required, the CI install step needs to pin torchvision from the same CPU index as torch. Every downstream user would hit the same mismatch, though, so the extra is the better fix.
Shared-layer changes since the last review
These look correct:
local_model_loader_for_config: a presentmodel_typeis authoritative, and architecture inference needs a unique, complete match. OnlyMiniCPMForCausalLMis declared, and conflicting or partial matches fail closed.ensure_qwen_drive_registeredis skipped when a package loader owns the type.- The
return_tokenicerhandoff,processor_load_kwargsforwarding, and the teacher path.
🟡 Security sweep of all ports: minor hygiene items only
I found no checkpoint-code execution, no AutoX.register, no global Transformers patching, no pickle, and no hard-coded trust_remote_code=True (apart from docstrings). Small items:
ports/deepseek_vl_v2/siglip_vit.py:634:torch.load(ckpt_path, map_location="cpu")withoutweights_only. It is safe by default on the required torch ≥2.15, but makingweights_only=Trueexplicit would matchmimo_v2/modeling_mimo_v2.py:1776.ports/locateanything/processing_locateanything.py::117callsrequests.get(image, stream=True)with no timeout, so a calibration sample URL can hang quantization.:76still contains an upstream developer path (/home/zhidingy/workspace/...).
ports/nemotron_h_puzzle/read_checkpoint_headers.pyis a network-fetching maintainer script that ships in the runtime package. Consider moving it toscripts/.
Process
- The checklist item "Complete combined review and qualification for remaining model ports" is still unchecked, and the PR has grown from 456 to 1087 files since the first review.
- The earlier bugs were caught by reviewing samples, and every one came from synthetic fixtures. I'd again strongly suggest:
- landing the shared policy layer plus the already-qualified ports once CI is green;
- moving further ports to family-sized follow-ups, each with a real-checkpoint tokenizer/config test.
|
Rebased onto
One pre-existing issue on this branch, unrelated to the merge (it is present at |
|
Rebased/merged Also re-verified the |
|
Rebased/merged Conflicts resolved this round:
Also fixed a red-on-main test the merge surfaced: Post-merge verification (tokenicer 0.0.19 on |
Conflict status: Hymba is a semantic conflict, not a textual one
What main now has (#4891, "mamba": ("in_proj:0:nosrc", "out_proj:1", "conv1d:!", "x_proj.0:!", "dt_proj.0:!"),
"pre_moe_layernorm": ("pre_moe_layernorm:!",),
"moe:moe": {"experts": {"0": ("gate_proj:0", "up_proj:0", "down_proj:1")}},with the router handled by the generic non-quantized-consumer scan What this branch has (Hymba port, Measured, both directions (scratch worktree, CPU):
The last row is the real blocker: Suggested way forward (either is fine by me):
Until then this PR will keep showing |
Review of #4620 (head
|
#4620 removed the PreTrainedModel.save_pretrained wrapper that entered checkpoint_serialization(), so an HF-loaded Marlin/ExLlamaV2 model wrote its irreversible runtime layout (tile/shuffled qweight, empty qzeros/g_idx) plus qzeros_format markers under an ordinary checkpoint_format: gptq config. The directory could not be reloaded by GPTQModel.load or Transformers. Attach the guard to the loaded model instance in hf_gptqmodel_post_init, the bridge Transformers' GPTQ/AWQ quantizers already call. It is instance-scoped, so no Transformers class is touched. Bridge saves now refuse on runtime-layout kernels with the #4134 error and drop qzeros_format for checkpoint-layout kernels; GPTQModel.load/GPTQModel.save and read-only state_dict() callers are unchanged.
…ding (#6377) * fix(phi4): drop stale backoff/optimum require_pkgs expectation (#6365) The phi4mm definition was ported off Microsoft's remote code in #4620. The removed `speech_conformer_encoder` was the only `backoff` user, and nothing on the package-owned native path imports `optimum`; `backoff` is not installed in the CPU test environment, so restoring either requirement would reject a valid install. Keep `require_pkgs` empty and make the test assert that, with the reasoning documented next to the declaration. The port's optional torchvision/scipy imports already fail with LocalModelLoader's `gptqmodel[vision]`/`gptqmodel[audio]` install hint, so they do not need a load-time version check. * refactor(eval): drop dead GGUF quantization-config hiding (#6366) `_hide_unsupported_quantization_config_for_eval` and its lm-eval wrapper had no callers. The only reason to keep them was the assumption that Transformers cannot evaluate a GGUF quantization config, but Transformers 5.23 constructs `GgufConfig` from it and `AutoModelForCausalLM.from_pretrained` now loads and forwards such a checkpoint through `GgufHfQuantizer`. The hiding branch was therefore unreachable even if called. Remove both helpers, their now-unused `contextmanager` import, and the two tests that only exercised the deleted context managers. --------- Co-authored-by: agent <agent@local>
…6390) - test_muse_glimmer/test_solar_open definition-selection tests patched `auto.AutoConfig`, which `gptqmodel.models.auto` no longer re-exports; `check_and_get_model_definition()` now reads the config through `auto.load_model_config` (the same seam test_solar_open2.py uses). - The Solar Open tiny fixture now builds the vendored `gptqmodel.models.ports.native.solar_open` config/model. Since #4620 the definition loads through a LocalModelLoader whose `NativeForCausalLM._model_class()` rejects a `transformers.SolarOpenConfig` by design (`_require_vendored_config`), so `build_shell_model` raised "SolarOpenConfig is not a vendored GPT-QModel config". - TestMuseGlimmer reloads the fast-mode checkpoint with `EVAL_SINGLE_GPU = False` so a multi-accelerator host can spread it, and skips with a precise reason when the host exposes < 56 GiB of visible accelerator memory. Fast mode only quantizes 2 of 52 decoder layers, so the saved checkpoint keeps ~58 GB of bf16 weights (29.78 B params minus 0.97 B quantized); a single 48 GiB RTX 4090 OOMs in `accelerate.load_checkpoint_in_model` and cannot hold it. Slow mode quantizes every layer (~17 GB) and still runs. Measured on one pinned RTX 4090 (SM 8.9, 47.45 GiB), torch 2.15+cu132, transformers 5.23.0: models/test_muse_glimmer.py: 5 passed, 1 skipped models/test_solar_open.py (excluding the 100B TestSolarOpen): 6 passed Fixes #6384 Co-authored-by: agent <agent@local>
Summary
GPT-QModel now quantizes, runs inference and trains only on the Transformers 5.23 ABI, using package-owned model code for every supported model. It requires
transformers>=5.23.0,<5.24, Python 3.11+,tokenicer>=0.0.21anddefuser>=0.0.32.MODEL_MAPdefinitions (208 model types) load through a definition-ownedLocalModelLoader. That includes models Transformers implements natively: GPT-QModel carries its own copy, so a Transformers upgrade cannot change its math, module names or checkpoint keys.gptqmodel/models/ports/native/<family>(scripts/vendor_transformers_ports.py). A package-local registry (ports/native/auto:NativeConfig,Native<Task>,NativeProcessor,NativeTokenizer) resolvesmodel_typeto vendored classes only.gptqmodel/importstransformers.models.*, including top-level re-exports of model-family classes. Ports use only Transformers' framework layer:PreTrainedModel, configs,cache_utils,masking_utils, the attention registry, RoPE utilities,GradientCheckpointingLayer,GenerationMixin, outputs, initialization and processing/tokenization base classes.cache_position, no tuple or legacy caches, norope_scalingreads, noreturn_dicttuple plumbing, and realCachesubclasses.AutoConfig/AutoModelor the quantizer tables, or patchoptimum, OpenVINO,huggingface_hub(ModelScopepatch_hub), safetensors,torch.nn.init, Accelerate, Defuser or Triton. Weight-init suppression uses Transformers' publicno_init_weights(). Checkpoint Python for an unsupported model still requires bothtrust_remote_code=TrueandGPTQ_BYPASS_SAFETY_CHECKS=1, and it runs on unmodified Transformers 5.23.tests/test_model_port_policy.pychecks every definition, every port and the whole package. All of its pending lists are empty.tests/test_transformers_unpatched.pychecks that importing and using GPT-QModel leaves Transformers unchanged.AGENTS.md,docs/transformers5-model-ports.mdand the new.agents/skills/gptqmodel-model-portingskill.Notable fixes found while porting
transformers.*as custom code, which skips checkpoint conversion mappings. Vendored classes now derive fromNativePreTrainedModel, so Transformers-saved checkpoints (e.g. NemotronH, MoE expert fusion) load correctly.replace_fused_blocks, which swapped the global conversion mapping and loaded wrong MoE weights, is no longer used.partial_rotary_factorwas applied twice.NativeTokenizerignored the declared tokenizer class.register_transformers_equivalent. GPT-QModel registers its vendored tokenizer classes with it, so Tokenicer's normalization still applies and token IDs match Transformers exactly.Size
Most of the diff is the vendored Transformers 5.23 sources under
gptqmodel/models/ports/native/. They are kept byte-reproducible (scripts/vendor_transformers_ports.py) and excluded from ruff. Per-port documentation and test-only inventories were removed from the package; tests use SHA-256 digests or small fixtures undertests/fixtures/ports/.Validation (CPU: Python 3.14, Torch 2.15.0, Transformers 5.23.0, Tokenicer 0.0.21)
tests/test_native_port_parity.py: for every vendored family, built from Transformers' own model-tester configs and inputs, state_dict keys and shapes match, outputs are bit-identical, and a Transformers-saved checkpoint loads into the vendored class with identical outputs. Inkling (needs scipy) and RoBERTa (vendored only as a dependency) skip.tests/test_native_definition_loading_{0..3}.py: each wired definition loads a Transformers-saved checkpoint through its loader. Only vendored classes are instantiated, and logits are bit-equal to Transformers.A full CPU sweep of
tests/*.py,tests/module_tree/*.pyandtests/kernels/*.pypasses, except tests that need hardware or real checkpoints unavailable on the CPU host:/monstercheckpoints;tests/kernels/test_intel_cpu_xpu.py, whose CPU cases take about 5 minutes each on this host.Hardware- and optional-package-dependent tests now skip precisely instead of failing at collection.
Not verified here: GPU kernels, real-checkpoint quantization and evaluation runs, and Tenstorrent hardware.
Breaking changes
transformers.from_pretrainedof GPT-QModel checkpoints no longer gets GPT-QModel-only features: per-layerdynamicconfigs, per-expert MoE tensors, refusal of GPT-QModel-only formats, device-map backfill, or thesave_pretrainedlayout guard. UseGPTQModel.load. Transformers' own GPTQ path still uses GPT-QModel kernels through its documented hooks.ggufpackage (now in theggufextra), the direct-to-Torch dense GGUF import (KernelConfig.gguf_torch_dequant_loader) and Prism Q1_0_g128 dense import are dropped. GPT-QModel's native quantized GGUF loader is unchanged.clear_device_cacheis no longer replaced process-wide: GPT-QModel's offload hooks skip the per-forward cache flush on their own. Defuser 0.0.32 (ModelCloud/Defuser#75) scopes its cache flush to the devices a conversion uses ([MEM] Fused-expert MoE load on cuda:1 (inference load and quantize load with device=("cuda:1",)) creates a 386 MiB CUDA context on cuda:0: defuser's clear_memory() calls torch.cuda.synchronize() on the current device (#4863 class, MoE path) #5105), so the Defuserclear_memoryswap is gone too.🤖 Generated with Claude Code