Repository navigation
feat(decision-transformer): tokenizer-optional load and tensor calibration inputs (#4755) - #4894
Merged
Merged
Conversation
…ation inputs (#4755) Decision Transformer (`decision_transformer`) checkpoints ship no tokenizer and their forward consumes named tensors (`states`/`actions`/`rewards`/ `returns_to_go`/`timesteps`) instead of `input_ids`. Both assumptions in the text path blocked quantization before model selection: - `load_hf_tokenizer()` raised `Couldn't instantiate the backend tokenizer`. - `prepare_calibration_dataset()` rejected every tensor-only row with `unsupported calibration example structure`. Add the missing definition and the two opt-in hooks it needs, keeping every existing model on its current path: - `DecisionTransformerQModel` reuses the GPT-2 block tree under `encoder` (`ln_1`/`attn.c_attn`/`attn.c_proj`/`ln_2`/`mlp.c_fc`/`mlp.c_proj`). The 1-8 wide `embed_*`/`predict_*` heads stay native dtype, matching OpenVLA's non-decoder policy; they are still materialized from the lazy checkpoint shell because `embed_*` runs before the first block. - `require_load_tokenizer` (default `True`) skips both tokenizer call sites (`from_pretrained` and `from_quantized`) for definitions that set it `False`. The quantized-load path also treats a model that does not implement `get_input_embeddings`/`get_output_embeddings` (DT is not a causal LM) as having no tied embeddings instead of raising. - `calibration_inputs = "tensor_kwargs"` routes calibration rows through a new validator: each row must be a non-empty `Mapping[str, Tensor]` with a batch dimension, one row is one batch, and token-only options (`concat_size`, length sorting/padding) do not apply. The default `"token_ids"` path is byte-identical for text models, so a tensor row on a normal model still fails loudly. - `LoopProcessor` token-length accounting skips rows without `input_ids`. Tests - `tests/test_decision_transformer_4755.py` (CPU): registry/definition resolution, tensor-kwargs pass-through, gating on the definition flag, non-tensor rejection, and a full tiny DT (`n_layer=2`, `n_embd=32`) 4-bit quantization whose `action_preds`/`state_preds`/`return_preds` stay finite and keep their shapes, with `BaseQuantLinear` only under `.attn.`/`.mlp.`. It then saves the quantized model and reloads it (bfloat16) without a tokenizer. On `origin/main` the same file is `4 failed, 1 passed`; here it is `5 passed`. - `tests/module_tree/test_decision_transformer_model_tree.py` builds the real `DecisionTransformerModel` on `meta` and pins the decoder prefix/layer count, that every block weight owner resolves through `ModulePlan.find()`, the `:!` norm tags, and that the eight heads stay native and outside the block plan. - Fusion eligibility is recorded as not applicable in `fusable_models.json` (the GPT-2 tree has no separate QKV/gate-up role group) and the coverage doc counts are updated; the always-on registry contract passes. - Flow documentation: `docs/decision-transformer-calibration.md` (loader and calibration diagrams, before/after table with `file:line`, failure contract), linked from `README.md` and `docs/README.md`. - Registered module plans and calibration suites updated/run: 538 passed, 15 skipped, 3 xfailed (module-tree registry), 170 passed (calibration), plus module-tree ordering/tags (95), explicit plan/auto-detect (26), loader (11). Closes #4755.
This was referenced Nov 17, 2026
Qubitium
added a commit
that referenced
this pull request
Nov 17, 2026
…bles (#4941) (#4957) #4894 made ``ModelLoader`` read ``cls.require_load_tokenizer`` (with ``BaseQModel``'s default of ``True``) at ``gptqmodel/models/loader.py:2070`` and ``:2710``. #4926 declared it on the nine ``DummyQModel`` doubles in ``tests/test_local_model_paths.py`` but only swept that file, so two more plain-class doubles - which mirror ``BaseQModel``'s attributes by hand instead of inheriting them - were still red on main: tests/test_gguf_load_policy_env_removal.py:321 DummyQModel tests/test_lazy_turtle_conversion_cache.py:238 _DummyQModel Both raised ``AttributeError: type object 'DummyQModel' has no attribute 'require_load_tokenizer'`` from loader.py:2070 before the loader did any work, so the GGUF parser-selection guard and the ``.bin`` conversion offload-path guard were not running. Both doubles now declare ``require_load_tokenizer = True``, matching ``BaseQModel``'s default and #4926's wording. A full sweep of ``tests/`` for ``ModelLoader`` doubles (AST walk for classes decorated with ``ModelLoader``, plus every block carrying the doubles' ``require_trust_remote_code``/``require_pkgs``/``supports_desc_act`` markers) finds exactly these two beyond the nine already fixed; the other files that mention ``ModelLoader`` decorate real ``BaseQModel`` subclasses (``LlamaQModel``, ``OlmoeQModel``) and inherit the attribute. Adds ``tests/test_loader_double_contract_4941.py`` so this cannot come back a third time: it statically scans every test module for ``ModelLoader``-decorated classes (they are nested inside test functions, so importing would not expose them) and fails naming any double that does not declare the attribute, pins the two doubles from this issue, and checks ``BaseQModel`` still declares the default the doubles mirror. f160a40: 3 failed (both target tests + the new guard), 54 passed, 2 skipped this commit: 57 passed, 2 skipped
This was referenced Nov 17, 2026
Qubitium
pushed a commit
that referenced
this pull request
Nov 18, 2026
…dtype (#5038) The tensor-calibration path added in #4894 hands the caller's own tensors to `DecisionTransformerModel.forward`. Loading at the default bfloat16 and passing `torch.randn` rows - float32, the natural spelling - fails inside the first matmul: RuntimeError: mat1 and mat2 must have the same dtype, but got Float and BFloat16 The error comes from torch's kernel at capture time, not from the loader, and it says nothing about which calibration key or which dtype pair is wrong. `move_input_capture_example` now casts floating rows to the model's weight dtype for definitions that declare `calibration_inputs = "tensor_kwargs"`. Integer rows (timesteps, attention masks) keep their dtype, and every other definition is untouched because the cast is gated on that flag. tests/test_decision_transformer_calibration_dtype_4755.py 7 passed tests/test_decision_transformer_4755.py 5 passed tests/module_tree/test_decision_transformer_model_tree.py 6 passed tests/test_calibration_data_device.py 17 passed, 5 skipped format/check.sh clean The new tests cover the reported failure end to end (bf16 model, float32 rows, quantize, finite `action_preds`), the integer rows staying integer, an fp32 model being left alone, the same cast being a no-op when the dtypes already agree, and the token path not being cast.
sLaffey
pushed a commit
to sLaffey/GPTQModel
that referenced
this pull request
Nov 18, 2026
…ModelCloud#4923) (ModelCloud#4926) ModelCloud#4894 made the loader read `cls.require_load_tokenizer` (`gptqmodel/models/loader.py:2056`, `:2691`) with `BaseQModel`'s default at `gptqmodel/models/base.py:847`. The nine `DummyQModel` doubles in `tests/test_local_model_paths.py` mirror `BaseQModel`'s attributes by hand and were never updated, so the whole file raised AttributeError: type object 'DummyQModel' has no attribute 'require_load_tokenizer' on main: 11 failed, 18 passed. Each double now declares `require_load_tokenizer = True`, which is exactly what a real model class inherits. `tests/test_local_model_paths.py` goes to 29 passed, with and without tokenicer 0.0.19 on the path. Closes ModelCloud#4923. Refs ModelCloud#4894.
sLaffey
pushed a commit
to sLaffey/GPTQModel
that referenced
this pull request
Nov 18, 2026
…odelCloud#4941) (ModelCloud#4954) ModelCloud#4894 added `BaseQModel.require_load_tokenizer` and made `ModelLoader` read it as `cls.require_load_tokenizer` at two call sites. Only `BaseQModel` subclasses inherit the default, so every plain-class loader double (and any third-party definition that does not subclass it) aborted the whole load with AttributeError: type object 'DummyQModel' has no attribute 'require_load_tokenizer' ModelCloud#4926 patched the nine doubles in `tests/test_local_model_paths.py`; two more files were still red on main (`test_gguf_load_policy_env_removal.py:321`, `test_lazy_turtle_conversion_cache.py:238`), and the next double would have broken it again. The loader now resolves the flag through `_requires_tokenizer(cls)`, which returns `getattr(cls, "require_load_tokenizer", True)`: an absent attribute means "text model", which is what every definition did before ModelCloud#4894, and an explicit `False` is the only way to skip the text path (Decision Transformer). This fixes both call sites and every future double at once, instead of one file per round. Tests: new `tests/test_loader_tokenizer_flag_4941.py` drives the real `ModelLoader.from_pretrained` with the `.bin` harness from `test_lazy_turtle_conversion_cache.py`: - a double with no `require_load_tokenizer` must still load its tokenizer (red on main: AttributeError at loader.py:2070) - `require_load_tokenizer = False` must skip it - `require_load_tokenizer = True` must keep it - the helper's table: True -> True, False -> False, absent -> True main @ f160a40: 2 failed, 52 passed over the four loader files. With the fix: 61 passed, and 112 passed over all nine `ModelLoader` test files (the sweep the issue asked for). Closes ModelCloud#4941. Refs ModelCloud#4923, ModelCloud#4894.
sLaffey
pushed a commit
to sLaffey/GPTQModel
that referenced
this pull request
Nov 18, 2026
…elCloud#4967) (ModelCloud#4971) `tests/test_docs_contract_refs.py` was red on main again: four citations into `gptqmodel/models/base.py` were 114 lines out of the 8-line window, because base.py keeps growing under them (ModelCloud#4894, ModelCloud#4906, ModelCloud#4912, ModelCloud#4930): docs/awq-scale-folding.md _select_prev_op 5489 -> 5667 docs/calibration-replay.md capture_layer_type_replay_kwargs 4022 -> 4200 docs/calibration-replay.md _build_layer_type_position_embeddings 4005 -> 4183 docs/fp8-scale-semantics.md _decoder_fp8_scale_semantics 4752 -> 4930 Re-anchoring the numbers would rot again at the next base.py change, so the guard now accepts a symbol-anchored citation (`path.py::symbol`) and those four docs use it. The test still resolves the symbol in the source, so a renamed or removed symbol fails; only the line number stops being part of the contract. The line-number form stays for files that are not growing. Also re-anchored the stale `:5531` on the adjacent `:postnorm` row to `base.py::_select_prev_op` and `POST_NORM_FLAG` (base.py:560). And the test now runs pre-merge: it is the first file in the AWQ CPU `unit` suite, and `docs/**` plus the test itself are added to that workflow's path filter, so a base.py or docs change runs it. On unmodified main: 4 failed, 16 passed. With the fix: 20 passed. Copying only the new test onto main (docs still citing line numbers) also fails all four, which proves the new form is actually enforced. Closes ModelCloud#4967.
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.
Summary
Decision Transformer (
decision_transformer) checkpoints could not be quantized: they ship no tokenizer, soGPTQModel.load()failed inload_hf_tokenizer()before model selection, and their calibration samples are named tensors, whichprepare_calibration_dataset()rejected asunsupported calibration example structure.This PR registers a
DecisionTransformerQModeldefinition (GPT-2 decoder underencoder) and adds two definition-scoped opt-ins:require_load_tokenizer = Falseandcalibration_inputs = "tensor_kwargs". Text models keep the default tokenizer and token-id path unchanged; an unknowncalibration_inputsvalue fails closed.Closes #4755.
What Changed
gptqmodel/models/definitions/decision_transformer.py:loader = AutoModel, GPT-2 block tree underencoder(ln_1:!,attn.c_attn,attn.c_proj,ln_2:!,mlp.c_fc,mlp.c_proj), and aget_base_modules()override that materializesencoder.wte/wpe/drop/ln_fplus the eightembed_*/predict_*heads from the lazy checkpoint shell. The 1-8 wide heads stay native dtype, matching OpenVLA's non-decoder policy; quantizing them atgroup_size=32would be degenerate.BaseQModel.require_load_tokenizer: bool = Trueandcalibration_inputs: str = "token_ids"document both extension points.ModelLoaderskips tokenizer loading at both call sites (from_pretrained,from_quantized) when the definition opts out, and treats a model that does not implementget_input_embeddings/get_output_embeddings(DT is not a causal LM) as having no tied embeddings instead of raisingNotImplementedError.calibration.py:calibration_input_kind()validates the declared kind;_prepare_tensor_kwargs_dataset()accepts only a non-emptyMapping[str, Tensor]with a batch dimension, detaches values, uses one row per batch, and rejects token-only options (concat_size). The default token/text path is unchanged, so a tensor row on a normal model still fails.LoopProcessortoken-length accounting skips rows withoutinput_ids.MODEL_MAP["decision_transformer"],definitions/__init__.pyexport, registered plan fixture case, fusion non-applicability entry, supported-models row, and fusion coverage counts.docs/decision-transformer-calibration.mdwith the loader/calibration flow, before/after table, failure contract, module plan, and tests; linked fromREADME.mdanddocs/README.md.Out of scope: AWQ qualification for this layout (explicitly unverified, see below), attention/MLP fusion (no separate QKV or gate/up role group), and quantizing the heads.
Tests
Command (a local
kernelsbootstrap wrapper around pytest; the same node IDs run under plainpytest):tests/test_decision_transformer_4755.pyonorigin/main(red proof)tests/test_decision_transformer_4755.pyon this branchtests/module_tree/test_decision_transformer_model_tree.pytests/module_tree/test_registered_module_plans.py+test_registry_leaf_coverage.pytests/test_calibration_*.pybatch (12 files: config, mapping, normalisation, padding mask, input gaps, truncation, windows, text/ids precedence, messages/ids precedence, empty text, special tokens, attention sinks)tests/module_tree/test_definition_subset_ordering.py+test_moe_tags.pytests/module_tree/test_explicit_module_plan.py+test_auto_detect.pytests/test_loader.pytests/module_tree/test_fusable_models.py::test_registry_has_explicit_fusion_qualification_for_every_aliasruff checkon every changed Python fileThe red proof uses the same test file on a detached
origin/mainworktree: the definition/registry test, both tensor-calibration tests, and the full tiny quantize fail at tokenizer instantiation; only the gating test passes. The green run covers 4-bit quantization, finiteaction_preds/state_preds/return_predswith unchanged shapes, packedBaseQuantLinearmodules only under.attn./.mlp., and save plus tokenizer-less reload.Known pre-existing failures elsewhere in the suite (AWQ afmoe/flint scaling groups, granite relationships, MACaQ, calibration data device, generator calibration 4307, static-cache 4669, gemma4, EXL3 workspace) are unrelated and untouched.
Model Support / Module Plan
MODEL_MAPentry has an explicit registry plan case (registered_module_plans.json:decision_transformer→DecisionTransformerQModel,DecisionTransformerQModel/gptq).DecisionTransformerModelonmetaand verifies declared paths, checkpoint weight ownership, non-quantized:!tags, and the native heads.state_dict()owners.fusable_models.jsonwith an explicit non-applicability reason ("No separate, non-expert QKV or gate/up role group in the declared module tree.");docs/fusion-model-coverage.mdcounts are updated (206 registered, 104 not qualified).fusableconfig.Model test node IDs:
tests/module_tree/test_decision_transformer_model_tree.py::test_decoder_prefix_and_layer_counttests/module_tree/test_decision_transformer_model_tree.py::test_quantizable_specs_resolve_on_the_real_modeltests/module_tree/test_decision_transformer_model_tree.py::test_every_checkpoint_weight_owner_is_declaredtests/module_tree/test_decision_transformer_model_tree.py::test_norms_are_explicitly_not_quantizedtests/module_tree/test_decision_transformer_model_tree.py::test_heads_stay_native_and_out_of_the_block_plantests/module_tree/test_decision_transformer_model_tree.py::test_undeclared_descendants_are_rejectedtests/test_decision_transformer_4755.py::test_tiny_decision_transformer_quantizes_with_tensor_calibration(GPTQ end-to-end)AWQ onboarding safety
AWQ is explicitly unverified for this definition in this PR. The decoder blocks are GPT-2
Conv1Dprojections, but no real-model neutral-fold, candidate-search, or context/chunk parity run was performed for Decision Transformer, and no AWQ test node is claimed as validation. Only the GPTQ path and the shared tensor-calibration path are qualified here; a follow-up can onboard AWQ separately.Logic Flow Documentation
file:lineevidence.docs/decision-transformer-calibration.mdrepeats the diagrams and is linked fromREADME.mdanddocs/README.md.flowchart TD L["BaseQModel.from_pretrained<br/>BaseQModel.from_quantized"] --> T{"cls.require_load_tokenizer"} T -->|"True (default)"| H["load_hf_tokenizer(...)"] T -->|"False: DecisionTransformerQModel"| N["tokenizer = None"] H --> C["BaseQModel.quantize(CalibrationConfig)"] N --> C C --> P["prepare_calibration_dataset(qmodel)"] P --> K{"calibration_input_kind(qmodel)"} K -->|"token_ids (default)"| O["token/text normalization,<br/>length sort, pad collate"] K -->|"tensor_kwargs"| V["_prepare_tensor_kwargs_dataset"] V --> R{"non-empty Mapping[str, Tensor],<br/>every value ndim >= 1,<br/>concat_size unset?"} R -->|"no"| E["ValueError before any forward"] R -->|"yes"| B["detach tensors, one row per batch"] O --> W["LoopProcessor token-length accounting"] B --> X["LoopProcessor skips rows without input_ids"] W --> F["model(**example)"] X --> F style E fill:#ffe8e8,stroke:#cc3333 style N fill:#e8f0ff,stroke:#3366cc style B fill:#e8ffe8,stroke:#339933Before/after (full table in the docs page):
from_pretrainedtokenizergptqmodel/models/loader.py:2053:2051from_quantizedtokenizergptqmodel/models/loader.py:2685:2686get_input_embeddings()raised atgptqmodel/models/loader.py:2966try/except NotImplementedError_CALIBRATION_COLUMNSonly,gptqmodel/utils/calibration.py:137; raise at:812:481, validator at:173len(calibration_dataset),gptqmodel/looper/loop_processor.py:651token_rows,:650Review Requirements
I or an AI agent have:
require_load_processorprecedent, definition flags, registry fixtures).Kernel Accuracy Requirements
Not applicable: no kernel, fusion, or numerical kernel change.
Notes
DecisionTransformerConfiguseshidden_sizefor the block/head width;n_embdis not consumed. The tests set both to 32 so the tiny model is genuinely 32-wide.bos_token_id/eos_token_idwarnings because its vocabulary is empty; they are pre-existing and harmless.defuser 0.0.25 installed but >= 0.0.31 requiredis an environment warning, unrelated to this change.