Skip to content

fix(calibration): normalize the tool schemas HF datasets store (#4934) - #5004

Closed
Qubitium wants to merge 3 commits into
mainfrom
fix/issue-4934
Closed

Qubitium wants to merge 3 commits into
mainfrom
fix/issue-4934

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4934
Follow-up to #4927 (fix of #4858).

Root cause

_tokenize_messages_value forwarded a row's tools/documents to apply_chat_template exactly as stored. Two layouts that real HF function-calling data arrives in were mishandled:

  1. tools stored as a JSON string (common, because Arrow cannot hold heterogeneous schemas). apply_chat_template raises ValueError: Tools should either be a JSON schema, or a callable ...; the rejecting-template fallback then re-rendered the row without tools, so the schema never reached the Hessian — the [BUG] Calibration messages rows: the tools column is silently dropped; tool schemas never reach the Hessian (101 of 236 intended tokens on Qwen2.5) #4858 symptom, with one warning for the whole run.
  2. tools as a list of dicts inside an HF Dataset. Arrow unifies struct schemas across rows, so every row's schema gains the other rows' parameter names as null (e.g. "properties": {"city": {...}, "tz": null}). The rendered tool block then differs from what inference sends, silently.

Measured on Qwen2.5-0.5B-Instruct (references: no tools 41, t1 176, t2 172):

calibration input parent fixed
list of dicts, real dict tools 176, 172 176, 172
list of dicts, JSON-string tools 41, 41 176, 172
HF Dataset, list tools 180, 177 176, 172
HF Dataset, JSON-string tools 41, 41 176, 172

Changes

  • New _normalize_template_input_value() in gptqmodel/utils/calibration.py: json.loads a str/bytes value of tools/documents, and recursively drop dict entries whose value is None (Arrow's injected nulls; a JSON schema never legitimately carries a null property definition). Containers are copied, so the caller's dataset rows are never mutated.
  • _tokenize_messages_value normalizes before forwarding, so the rejecting-template fallback is reserved for templates that genuinely do not support tools.
  • New tests/test_calibration_tools_formats_4934.py: 5 tests — HF Dataset with different schemas, HF Dataset with JSON-string tools, list-of-rows with JSON-string tools (each asserting exact token-id equality with apply_chat_template(messages, tools=<original list>)), a null-stripping safety case, and non-JSON text passthrough. Uses the real Qwen2.5-0.5B tokenizer and skips only with a precise reason.

Verification

  • Parent: 5 failed (exit 1). Fixed: 5 passed (exit 0).
  • tests/test_calibration_*.py tests/test_prepare_dataset.py: 267 passed, 5 skipped (pre-existing skips: ≥2 CUDA devices, missing TinyLlama path).
  • After merging current main (which now contains fix(calibration): keep messages conversations from numpy/pandas slices (#4936) #4994's _to_python_containers / _columnar_mapping_examples work — composed, no conflict): tests/test_calibration_tools_formats_4934.py tests/test_calibration_messages_formats_4936.py tests/test_prepare_dataset.py → 38 passed.
  • ruff check gptqmodel tests: clean.

Residual risk

  • Dropping None-valued dict entries also removes a legitimate "default": null (rare; per the issue's directive). A null type ({"type": "null"}) is preserved — only None values are dropped.
  • A documents string that decodes to a list/dict is parsed; scalar-looking text is kept verbatim.
  • Arrow unification that changes non-None value types is not addressed.
  • Only tools/documents are normalized, not other custom template kwargs.

#4927 forwarded a row's `tools`/`documents` to `apply_chat_template` exactly
as stored, but function-calling data on the Hub arrives in two layouts that a
template cannot consume verbatim:

* a JSON string, because Arrow cannot hold a different struct schema per row.
  The template raised `ValueError: Tools should either be a JSON schema, ...`
  and #4927's fallback re-rendered the row *without* the tools, so the schema
  still never reached the Hessian (#4858 again), with one warning per run.
* a list of dicts read from an HF `Dataset`, where Arrow unifies the struct
  schema across rows and gives every row every other row's parameter names
  with a `None` value, e.g. `"properties": {"city": {...}, "tz": null}`. The
  rendered tool block then silently differed from what inference sends.

Decode the string form and drop dict entries whose value is `None` before
forwarding. A real JSON-schema `null` is the string `"null"`
(`{"type": "null"}`) and a `None` list element is a legitimate JSON value, so
both survive; only Arrow's injected `None` entries are removed. The walk
copies every container, so the caller's rows are never mutated, and the
rejecting-template fallback now only covers templates that truly do not use
tools.

Measured with Qwen2.5-0.5B-Instruct (no tools 41, `t1` 176, `t2` 172), after
`prepare_calibration_dataset`:

| calibration input | before | after |
| --- | --- | --- |
| list of dicts, real dict tools | 176, 172 | 176, 172 |
| list of dicts, JSON-string tools | 41, 41 | 176, 172 |
| HF `Dataset`, list tools | 180, 177 | 176, 172 |
| HF `Dataset`, JSON-string tools | 41, 41 | 176, 172 |

Regression tests (red on the parent commit: 5 of 5 fail):
`tests/test_calibration_tools_formats_4934.py`.

Fixes #4934
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Coordination note: #4997 (root/tools-normalize-4934) fixes the same #4934 tool-column normalisation and also carries the docs/CI wiring (.github/workflows/awq_cpu.yml, docs/decision-transformer-calibration.md, tests/test_docs_contract_refs.py). Two PRs cannot both land — one of them should be closed as a duplicate before merging. Recommend keeping #4997 and, if useful, porting tests/test_calibration_tools_formats_4934.py into it.

A bare `pytest.skip(...)` inside the `except` block left that path as an
implicit fall-through return, mixing explicit and implicit returns in
`_qwen2_5_tokenizer()`. Raise the skip exception instead; behaviour is
unchanged (the test still skips with the same message).
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Superseded by #4997, which includes tests/test_calibration_tools_formats_4934.py from this PR (all 5 nodes kept, none weakened).

Adjustments made while folding it in:

  • The helper is renamed to this PR's _normalize_template_input_value() (the name introduced here) with _normalize_template_input_payload() on top, so both regression files exercise the same walk; the {"type": "null"} / enum: [None, "x"] / non-mutating assertions are unchanged.
  • The JSON decode now runs json.loads for any string and only recurses into a container, so "42" / "true" stay text — this PR's version.
  • _qwen2_5_tokenizer() falls back to the cached Qwen/Qwen2.5-0.5B-Instruct-AWQ repo (identical tokenizer files), so the real-tokenizer nodes run instead of skipping when only the quantized repo is cached offline.
  • Both regression files are added to the pre-merge AWQ CPU (unit) suite in .github/workflows/awq_cpu.yml.

Verified with the ported file copied onto unmodified origin/main: 9 failed, 7 passed (the two files together); green on #4997.

@Qubitium Qubitium closed this Nov 17, 2026
sLaffey pushed a commit to sLaffey/GPTQModel that referenced this pull request Nov 18, 2026
…odelCloud#4934) (ModelCloud#4997)

* fix(calibration): render Hub `tools` columns the way inference does (ModelCloud#4934)

ModelCloud#4927 forwarded a row's `tools`/`documents` to `apply_chat_template` exactly as
stored, which is not the layout an HF dataset yields:

* a JSON-string `tools` column (Arrow cannot hold a heterogeneous struct
  column) is rejected by the template ("Tools should either be a JSON schema,
  ..."), and the row was then rendered without any tools at all;
* an Arrow-unified struct column gives every row's JSON schema the other rows'
  parameter names as `null`, so the rendered block differs from what the model
  sees at inference;
* a one-tool payload stored as one object is not iterable for the templates,
  which take a list of schemas;
* `dataset[:]` splits only the four primary columns, so `tools`/`documents`
  were dropped before they could reach the template at all.

`_normalize_chat_template_payload()` now decodes an object/array JSON string,
drops the `null` mapping entries Arrow injects, and presents a one-tool payload
as the list the templates iterate. A plain (non-JSON) string is left alone, so
a `documents` text value is untouched. `_columnar_mapping_examples()` splits the
chat-template columns next to `messages`.

Red on unmodified main (test copied into an origin/main worktree): 5 failed,
6 passed. Green: 11 passed, including the pre-existing real-tokenizer node,
which now also finds the cached AWQ repo's tokenizer instead of skipping.

* test(calibration): port the HF tool-layout matrix and share one normalizer

Folds the extra coverage from ModelCloud#5004 (`tests/test_calibration_tools_formats_4934.py`)
into the ModelCloud#4934 fix so a single PR carries both:

* the helper is renamed to `_normalize_template_input_value()` (the name ModelCloud#5004
  introduced) with `_normalize_template_input_payload()` on top for the
  one-tool `tools` list wrapping, so both test files exercise the same walk;
* the JSON decode now runs `json.loads` for any string and only recurses into
  a container, so a document that reads as a JSON scalar (`"42"`, `"true"`)
  stays text and a real JSON-schema `null` (`{"type": "null"}`) survives;
* the ported tokenizer helper falls back to the cached
  `Qwen/Qwen2.5-0.5B-Instruct-AWQ` repo (identical tokenizer files) instead of
  skipping when only the quantized repo is cached offline;
* both regression files run in the pre-merge `AWQ CPU (unit)` suite.

Red on unmodified main with both files copied in: 9 failed, 7 passed.
Green here: 11 + 5 nodes, 39 passed together with the docs contract.

* test(calibration): raise the tokenizer skip exception explicitly (ModelCloud#4934)

A bare `pytest.skip(...)` after the offline-repo loop left that path as an
implicit fall-through return, mixing explicit and implicit returns in
`_offline_qwen_tokenizer()`. Raise the skip exception instead; the test still
skips with the same message.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant