Skip to content

fix(calibration): drop Arrow-injected nulls from messages before the chat template (#5082) - #5112

Merged
Qubitium merged 1 commit into
mainfrom
fix/5082-arrow-messages-normalize
Nov 18, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5082-arrow-messages-normalize

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

Summary

Fixes #5082.

#4997 normalized the tools/documents columns for Arrow-backed calibration
rows but left the messages column of those same rows unnormalized. Arrow
stores one struct type per column, so every turn gains a None value for each
key another turn uses, and every tool call's arguments mapping gains the other
rows' argument names:

# Dataset.from_list([row_with_city, row_with_query])
{"role": "user", "content": "...", "tool_calls": None}
{"role": "assistant", "content": "", "tool_calls": [
    {"type": "function", "function": {"name": "get_weather",
     "arguments": {"city": "Paris", "query": None}}}]}

That reaches apply_chat_template unchanged, so calibration renders a different
conversation than inference:

  • Qwen2.5/Qwen3 (silent): the tool block becomes
    {"name": "get_weather", "arguments": {"city": "Paris", "query": null}}, so
    every tool-call row is calibrated on tokens the model never sees (+5 tokens
    per call in the issue's two-row fixture).
  • Llama-3.x (hard failure): the template tests 'tool_calls' in message, so
    the injected tool_calls: None on a user turn reaches
    message.tool_calls|length and raises
    TypeError: object of type 'NoneType' has no len().

Every Arrow-backed input shape is affected: Dataset, Dataset[:],
Dataset.to_pandas(), with_format("numpy"), list(Dataset).

What Changed

  • gptqmodel/utils/calibration.py: new _normalize_chat_messages() walk, called
    from _tokenize_messages_value() before the template runs. It drops mapping
    entries whose value is None, recursively, and copies every container so the
    caller's rows are never mutated.
  • Two values are deliberately kept because they are not Arrow padding:
    • content: None, which is how an OpenAI-style tool-call turn spells "no
      text" and which templates such as DeepSeek-R1 test with
      message.content is none;
    • arguments stored as a JSON string, which raw-text templates insert
      verbatim (DeepSeek-R1 writes it into a json block). Decoding it into a
      mapping, as the issue's suggested fix proposed, would corrupt that prompt
      and turn a working dataset into TypeError: can only concatenate str.
  • Behavior note: an explicit None argument value is indistinguishable from
    Arrow's injected padding for the same key, so it is dropped as well. That is
    the same rule [BUG] #4927 (fix of #4858) incomplete: tools from HF datasets still don't render as at inference (JSON-string tools column dropped; Arrow-unified tool schemas gain null properties) #4934 already applies to a tools schema's properties; a
    None element inside a list is still preserved.
  • .github/workflows/awq_cpu.yml: the new regression file runs in the existing
    pre-merge AWQ CPU (unit) calibration suite.

Tests

Red evidence: the new test file with only the calibration.py change reverted
in the same worktree, so the rest of the tree is the fix:

# fix reverted
cd tests && HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 python -m pytest -q test_calibration_messages_arrow_5082.py
# 9 failed, 1 passed

The failures are the reported defect, not import or collection errors: the
Llama nodes fail inside the template with
TypeError: object of type 'NoneType' has no len(), and the Qwen nodes differ
from the plain-row token ids.

Green:

cd tests && HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 python -m pytest -q -rs test_calibration_messages_arrow_5082.py
# 10 passed

python -m pytest -q -rs test_calibration_messages_arrow_5082.py \
  test_calibration_tools_formats_4934.py test_calibration_messages_formats_4936.py \
  test_calibration_messages_tools_4858.py test_calibration_messages_ids_precedence_4670.py \
  test_prepare_dataset.py test_docs_contract_refs.py
# 86 passed

bash format/check.sh
# All checks passed!

The real tokenizers (Qwen2.5-0.5B-Instruct, Llama-3.2-1B-Instruct,
DeepSeek-R1-Distill-Llama-8B) run against cached files locally; none of the new
nodes skips. The issue's own repro now prints identical token counts for the
list and Dataset shapes:

Qwen2.5-0.5B-Instruct list [212, 207, 164]
Qwen2.5-0.5B-Instruct Dataset [212, 207, 164]
Llama-3.2-1B-Instruct list [210, 207, 173]
Llama-3.2-1B-Instruct Dataset [210, 207, 173]

Coverage in tests/test_calibration_messages_arrow_5082.py:

  • test_hf_dataset_messages_match_the_plain_rows[qwen2.5|llama3.2] — token
    equality with apply_chat_template on the original Python list, plus the
    list-input control.
  • test_every_arrow_backed_input_shape_matches_the_plain_rows[...] — Dataset,
    [:], to_pandas(), with_format("numpy")[:], list(Dataset).
  • test_llama3_2_dataset_does_not_raise_on_tool_calls_none — the crash half,
    asserting the rendered prompts equal the plain-row prompts.
  • test_json_string_arguments_stay_verbatim_for_raw_text_templates — the
    DeepSeek-R1 raw json block stays {"city": "Paris"} and token ids match.
  • test_normalize_chat_messages_keeps_content_none_and_does_not_mutate — the
    None rules and the no-mutation guarantee.

Not exercised: no quantization run was performed, since the change is confined
to calibration tokenization; the token ids produced for the affected rows are
compared directly. GPU paths are untouched by this change.

Model Support / Module Plan

Not applicable: no model, alias, definition, or module-plan change.

AWQ onboarding safety

Not applicable: no model/alias onboarding and no AWQ grouping, search, replay,
or folding change.

Logic Flow Documentation

Not applicable as a new mechanism. The single decision point
(_tokenize_messages_value → template) is unchanged; only the conversation
payload it hands to the template is normalized, exactly like the existing
tools/documents normalization from #4997. There is no new branch, fallback,
or selection order, and the failure path (template rejects the optional inputs)
is unmodified.

Review Requirements

AI-assisted code is welcome. Draft PR.

  • Reviewed this PR.
  • Matches existing project structure, APIs, and conventions (the new walk
    mirrors _normalize_template_input_value).
  • No monkeypatching; the existing extension point is reused.
  • Minimized and compacted the impacted code surface (one helper, one call).
  • Considered and eliminated potential regressions (list rows, JSON-string
    tools, multi-part content, content: None, documents column).

Kernel Accuracy Requirements

Not applicable: no kernel or fusion change.

Notes

  • The issue also proposed decoding JSON-string arguments into a mapping. That
    is intentionally not done: it silently breaks raw-text templates such as
    DeepSeek-R1, and the decoded form is not what those datasets send at
    inference. The regression covers that case.
  • content: None injection is left in place. Templates that concatenate a
    plain turn's content also fail on the plain Python rows, so it is not an
    Arrow-specific difference.

#4997 normalized the `tools`/`documents` columns only. The `messages` column
of the same rows keeps Arrow's unified struct schema, so every turn gains
`tool_calls: None` (and any other key some turn uses) and every tool call's
`arguments` mapping gains the other rows' argument names with a `None` value.

Templates then see a different conversation than the plain Python rows:

* Qwen2.5/Qwen3 render `{"city": "Paris", "query": null}`, silently
  calibrating tool-call rows on tokens inference never emits;
* Llama-3.x tests `'tool_calls' in message`, so an injected `tool_calls: None`
  turns a user turn into a tool call and raises
  `TypeError: object of type 'NoneType' has no len()`.

`_normalize_chat_messages()` drops dict entries whose value is `None` before
`apply_chat_template`, for every Arrow-backed shape (`Dataset`, `[:]`,
`to_pandas()`, `with_format("numpy")`, `list(Dataset)`). Two values are kept
because they are not Arrow padding: `content: None`, which an OpenAI-style
tool-call turn uses and DeepSeek-R1 tests with `is none`, and `arguments`
stored as a JSON string, which raw-text templates insert verbatim. An explicit
`None` argument value is indistinguishable from the injected padding, so it is
dropped too, matching the `tools` rule from #4934.

Red (fix reverted, same test file): 9 failed, 1 passed -- the Llama nodes fail
with the reported `TypeError`. Green: 10 passed, plus 32 pre-existing nodes in
the #4934/#4936/#4858/#4670 files.
@ZX-ModelCloud
ZX-ModelCloud marked this pull request as ready for review November 18, 2026 04:40
@Qubitium
Qubitium merged commit 46931fb into main Nov 18, 2026
11 checks passed
@Qubitium
Qubitium deleted the fix/5082-arrow-messages-normalize branch November 18, 2026 04:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants