Skip to content

feat(decision-transformer): tokenizer-optional load and tensor calibration inputs (#4755) - #4894

Merged
Qubitium merged 1 commit into
mainfrom
root/decision-transformer-4755
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
root/decision-transformer-4755

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Decision Transformer (decision_transformer) checkpoints could not be quantized: they ship no tokenizer, so GPTQModel.load() failed in load_hf_tokenizer() before model selection, and their calibration samples are named tensors, which prepare_calibration_dataset() rejected as unsupported calibration example structure.

This PR registers a DecisionTransformerQModel definition (GPT-2 decoder under encoder) and adds two definition-scoped opt-ins: require_load_tokenizer = False and calibration_inputs = "tensor_kwargs". Text models keep the default tokenizer and token-id path unchanged; an unknown calibration_inputs value fails closed.

Closes #4755.

What Changed

  • New gptqmodel/models/definitions/decision_transformer.py: loader = AutoModel, GPT-2 block tree under encoder (ln_1:!, attn.c_attn, attn.c_proj, ln_2:!, mlp.c_fc, mlp.c_proj), and a get_base_modules() override that materializes encoder.wte/wpe/drop/ln_f plus the eight embed_*/predict_* heads from the lazy checkpoint shell. The 1-8 wide heads stay native dtype, matching OpenVLA's non-decoder policy; quantizing them at group_size=32 would be degenerate.
  • BaseQModel.require_load_tokenizer: bool = True and calibration_inputs: str = "token_ids" document both extension points.
  • ModelLoader skips tokenizer loading at both call sites (from_pretrained, from_quantized) when the definition opts out, and 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 NotImplementedError.
  • calibration.py: calibration_input_kind() validates the declared kind; _prepare_tensor_kwargs_dataset() accepts only a non-empty Mapping[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.
  • LoopProcessor token-length accounting skips rows without input_ids.
  • Registry: MODEL_MAP["decision_transformer"], definitions/__init__.py export, registered plan fixture case, fusion non-applicability entry, supported-models row, and fusion coverage counts.
  • Docs: docs/decision-transformer-calibration.md with the loader/calibration flow, before/after table, failure contract, module plan, and tests; linked from README.md and docs/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

  • Unit tests executed and passed.
  • Added new simple/fast CPU tests for this change.

Command (a local kernels bootstrap wrapper around pytest; the same node IDs run under plain pytest):

export CUDA_HOME=/usr/local/cuda PATH=/usr/local/cuda/bin:$PATH TORCH_CUDA_ARCH_LIST=8.0 \
  TORCH_NO_COMPILER_WRAPPER=1 GPTQ_BYPASS_SAFETY_CHECKS=1 LOGBAR_ANIMATION=0 \
  CUDA_VISIBLE_DEVICES=4 PYTHONPATH=$PWD
/root/venv-kernels/bin/python /tmp/root-rt.py <paths> -q -o addopts= -o log_cli=false -p no:cacheprovider
Path Result
tests/test_decision_transformer_4755.py on origin/main (red proof) 4 failed, 1 passed in 10.18s
tests/test_decision_transformer_4755.py on this branch 5 passed in 18.64s
tests/module_tree/test_decision_transformer_model_tree.py 6 passed (11 passed combined with the file above in 17.60s)
tests/module_tree/test_registered_module_plans.py + test_registry_leaf_coverage.py 538 passed, 15 skipped, 3 xfailed in 139.79s
tests/test_calibration_*.py batch (12 files: config, mapping, normalisation, padding mask, input gaps, truncation, windows, text/ids precedence, messages/ids precedence, empty text, special tokens, attention sinks) 170 passed in 104.33s
tests/module_tree/test_definition_subset_ordering.py + test_moe_tags.py 95 passed in 12.79s
tests/module_tree/test_explicit_module_plan.py + test_auto_detect.py 26 passed in 6.27s
tests/test_loader.py 11 passed in 5.33s
tests/module_tree/test_fusable_models.py::test_registry_has_explicit_fusion_qualification_for_every_alias 1 passed in 5.95s
ruff check on every changed Python file All checks passed

The red proof uses the same test file on a detached origin/main worktree: 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, finite action_preds/state_preds/return_preds with unchanged shapes, packed BaseQuantLinear modules 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

  • Every new MODEL_MAP entry has an explicit registry plan case (registered_module_plans.json: decision_transformer → DecisionTransformerQModel, DecisionTransformerQModel/gptq).
  • A model-specific module-plan test builds the real DecisionTransformerModel on meta and verifies declared paths, checkpoint weight ownership, non-quantized :! tags, and the native heads.
  • Runtime-created tensors are distinguished from checkpoint-owned weights: the heads are real checkpoint modules; the test reads state_dict() owners.
  • Fusion eligibility is recorded in fusable_models.json with an explicit non-applicability reason ("No separate, non-expert QKV or gate/up role group in the declared module tree."); docs/fusion-model-coverage.md counts are updated (206 registered, 104 not qualified).
  • No HF class-path allowlist or name heuristic was added to fusion declarations.
  • Fusion configs: not applicable, the definition declares no fusable config.
  • Fusion numerical qualification: not applicable, no fusion profile is admitted.
  • Registry and model-specific tests passed; no dependency skips in these nodes.

Model test node IDs:

  • tests/module_tree/test_decision_transformer_model_tree.py::test_decoder_prefix_and_layer_count
  • tests/module_tree/test_decision_transformer_model_tree.py::test_quantizable_specs_resolve_on_the_real_model
  • tests/module_tree/test_decision_transformer_model_tree.py::test_every_checkpoint_weight_owner_is_declared
  • tests/module_tree/test_decision_transformer_model_tree.py::test_norms_are_explicitly_not_quantized
  • tests/module_tree/test_decision_transformer_model_tree.py::test_heads_stay_native_and_out_of_the_block_plan
  • tests/module_tree/test_decision_transformer_model_tree.py::test_undeclared_descendants_are_rejected
  • tests/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 Conv1D projections, 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

  • This change alters two flows (tokenizer loading and calibration row preparation), so diagrams and a committed docs page are included.
  • Mermaid diagrams use real symbols from the shipped code.
  • The replaced mechanism is tabulated with file:line evidence.
  • Failure paths are marked in red and listed in a contract table.
  • docs/decision-transformer-calibration.md repeats the diagrams and is linked from README.md and docs/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:#339933
Loading

Before/after (full table in the docs page):

Mechanism Before After
from_pretrained tokenizer unconditional at gptqmodel/models/loader.py:2053 gated at :2051
from_quantized tokenizer unconditional at gptqmodel/models/loader.py:2685 gated at :2686
Embedding accessors get_input_embeddings() raised at gptqmodel/models/loader.py:2966 try/except NotImplementedError
Calibration rows _CALIBRATION_COLUMNS only, gptqmodel/utils/calibration.py:137; raise at :812 gated branch at :481, validator at :173
Token-length average len(calibration_dataset), gptqmodel/looper/loop_processor.py:651 token_rows, :650

Review Requirements

I or an AI agent have:

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions (require_load_processor precedent, definition flags, registry fixtures).
  • Avoided unnecessary monkeypatching and used the project's normal extension points.
  • Minimized and compacted the impacted code surface: both behaviors are gated by definition attributes; no generic any-dict calibration path.
  • Considered and eliminated potential regressions: text-model paths are byte-identical, and the calibration suite plus module-tree/loader suites pass.

Kernel Accuracy Requirements

Not applicable: no kernel, fusion, or numerical kernel change.

Notes

  • Transformers 5.20.2's DecisionTransformerConfig uses hidden_size for the block/head width; n_embd is not consumed. The tests set both to 32 so the tiny model is genuinely 32-wide.
  • The DT config emits benign bos_token_id/eos_token_id warnings because its vocabulary is empty; they are pre-existing and harmless.
  • Reloading a saved DT checkpoint requires bfloat16/float16 (TorchLinear rejects float32); the reload test uses bfloat16 and casts the sample.
  • defuser 0.0.25 installed but >= 0.0.31 required is an environment warning, unrelated to this change.

…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.
@Qubitium
Qubitium merged commit 76fd2c7 into main Nov 17, 2026
9 checks passed
@Qubitium
Qubitium deleted the root/decision-transformer-4755 branch November 17, 2026 18:08
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
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support Decision Transformer: tokenizer-optional load and tensor calibration inputs

1 participant