Skip to content

fix(calibration): unpack DataFrame and NumPy object columns into rows (#4652) - #4656

Merged
Qubitium merged 1 commit into
mainfrom
fix/4652-calibration-container
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/4652-calibration-container

Conversation

@ZX-ModelCloud

@ZX-ModelCloud ZX-ModelCloud commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR

prepare_calibration_dataset now resolves the container before splitting rows, so Dataset.with_format("numpy")[:] object columns and DataFrame-like tables reach the same code path as an equivalent dict of columns. Net diff: +367/−38 across 4 source/docs files and 2 test files.

1. The problem

Two containers that already hold the exact columns prepare_calibration_dataset accepts were classified wrongly.

Mechanism (on main @ 959334876) Location Effect
_is_batched_column returns ndim >= 2 for any object with ndim, before looking at what the column holds gptqmodel/utils/calibration.py:145-147 Dataset.with_format("numpy")[:] gives a 1-D ndarray(dtype=object) of per-row arrays; it was classed as one token row
_pack_ids → torch.as_tensor(object_array) gptqmodel/utils/calibration.py:558 ValueError: failed to convert input_ids to tensor ... numpy.object_, blaming the data instead of the container
isinstance(calibration_dataset, Mapping) is the only columnar test gptqmodel/utils/calibration.py:366 A pandas.DataFrame is not a Mapping, so it fell through to raw_examples = list(calibration_dataset)
raw_examples = list(calibration_dataset) gptqmodel/utils/calibration.py:385,389,391 Iterating a frame yields its column labels: text frames calibrated on the literal string "text"; input_ids frames died on a misleading calibration_data_min_length error
mapping[name][row_index] used per column gptqmodel/utils/calibration.py:305 A pandas Series indexes [] by label, so even a converted frame would mis-read rows

Reproduced on main with a real tokenizer and real datasets/pandas objects:

torch  [[31, 14]]                       # baseline, correct
numpy  ValueError: failed to convert `input_ids` to tensor for calibration item 0
       cause: TypeError("can't convert np.ndarray of type numpy.object_")
frame  1 document  ->  input_ids [[token('text')]]   # 6 documents silently became 1
flowchart TD
    A["calibration input"] --> B{"isinstance(input, Mapping)"}
    B -- "yes" --> C["_is_columnar_mapping"]
    B -- "no (DataFrame, ANY table)" --> F["raw_examples = list(input)<br/>iterates COLUMN LABELS"]
    C -- "columnar (2-D)" --> I["_columnar_mapping_examples"]
    C -- "1-D object ndarray of rows" --> J["ONE token row"]
    J --> K["torch.as_tensor(object array)"]
    K --> X["ValueError: failed to convert input_ids"]
    F --> Y["calibrate on the literal text 'text'"]
    style X fill:#f8d7da,stroke:#c00
    style Y fill:#f8d7da,stroke:#c00
Loading

2. The new flow

prepare_calibration_dataset and the VLM split_calibration_dataset both resolve the container once, through the same helpers, before any row is read.

flowchart TD
    A["calibration input"] --> B{"_frame_columns(input)"}
    B -- "columns + to_dict list" --> C["columnar mapping"]
    B -- "not a table" --> D{"isinstance(input, Mapping)"}
    D -- "yes" --> C0["mapping as given"]
    D -- "no" --> H["iterate rows<br/>str / list[int] / Mapping"]
    C0 --> E["_is_columnar_mapping"]
    C --> E
    E -- "columnar" --> F["_columnar_mapping_examples<br/>_column_entries per column"]
    E -- "single row" --> H
    F --> G["one mapping per row"]
    G --> I["_pack_ids"]
    H --> I
    I --> J["_to_2d_long_tensor<br/>_unwrap_object_array"]
    I --> K["_normalize_attention_mask<br/>_unwrap_object_array"]
    J --> L["rows for collate / concat"]
    K --> L
    style L fill:#d4edda,stroke:#080
Loading

New symbols, all in gptqmodel/utils/calibration.py:

  • _column_entries(value) — the single decision for "how does this column yield one entry per row": 2-D array/tensor indexes by row, list/tuple is listed, 1-D ndarray/Series unwraps via tolist(), datasets Column (a Sequence without ndim) is listed, anything else returns None (not a row container).
  • _frame_columns(dataset) — a table (columns attribute + a row-wise to_dict) becomes the columnar mapping the module already understood. Tries to_dict("list"), to_dict(orient="list"), to_dict(as_series=False); a to_dict that understands none of them, or a column that is not a per-row sequence, returns None so the existing iterable handling still applies.
  • _unwrap_object_array(value) — turns an object-dtype ndarray into a list so torch.as_tensor can classify integer token ids; nested arrays/strings still fail with the same structural error.

_is_batched_column, _is_columnar_mapping (text/messages columns), _columnar_mapping_examples, and the two tensor conversions in _pack_ids/_normalize_attention_mask now route through them. split_calibration_dataset (gptqmodel/models/definitions/_vlm_calibration.py) calls _frame_columns before _mapping_rows, so VLM definitions keep byte-identical rows for numpy/pandas/torch formats.

3. Failure and ambiguity contract

Situation Before After
Dataset.with_format("numpy")[:] (1-D object column of rows) crash in tensor conversion unpacked into one row per element
Dataset.with_format("pandas")[:] / ds.to_pandas() column labels iterated → "text" unpacked into one row per element
pandas.DataFrame({"text": ...}) calibrated on "text" tokenized per document
pandas.DataFrame({"foo": ...}) misleading min-length error ValueError naming the accepted columns
plain {"input_ids": [7, 8, 9]} one token row unchanged
{"input_ids": np.array([7, 8, 9], dtype=object)} crash one token row (flat object column of scalars)
base_qwen3_vl.py (does not use the shared splitter) frame iterated as column labels ValueError naming the input type
object column whose elements are not integer ids failed to convert ... to tensor same ValueError, same wording

4. Change inventory

File ± lines Purpose
gptqmodel/utils/calibration.py +149/−35 _column_entries, _frame_columns, _unwrap_object_array; columnar classification and per-row indexing route through them
gptqmodel/models/definitions/_vlm_calibration.py +5 split_calibration_dataset normalizes a table before the row split
gptqmodel/models/definitions/base_qwen3_vl.py +8/−3 non-shared splitter rejects a table instead of iterating its labels
docs/vlm-calibration-input-normalization.md +46 container-resolution diagram, per-helper contract, before/after table
tests/test_calibration_mapping_input.py +108 6 new regression tests
tests/test_vlm_mapping_calibration_4308.py +51 3 new parametrized tests over every VLM definition in MAPPING_DEFINITIONS

5. Tests / guarantees

Test Invariant
test_dataset_formats_unpack_into_token_rows[numpy/pandas/torch/None] four containers of the same Dataset produce identical ids and masks
test_object_dtype_column_of_arrays_is_one_row_per_element 1-D object column of arrays is a column of rows
test_dataframe_columns_are_unpacked_into_token_rows DataFrame columns are read per row
test_dataframe_text_column_is_tokenized_per_row a text frame yields one row per document, not "text"
test_dataframe_without_calibration_columns_is_rejected fail closed with the accepted-column message
test_flat_object_column_is_still_one_token_row flat object column of scalars keeps its single-row meaning
test_numpy_formatted_dataset_columns_are_unpacked (13 VLM definitions) numpy columns reach the text path without loading the processor
test_dataframe_calibration_input_is_unpacked_into_rows (13 VLM definitions) frames are unpacked, not iterated as labels
test_qwen3_vl_rejects_dataframe_calibration_input the one definition outside the shared splitter fails closed

6. Validation

Red evidence — reverted only the three source files, kept the new tests:

git checkout -- gptqmodel/utils/calibration.py gptqmodel/models/definitions/_vlm_calibration.py gptqmodel/models/definitions/base_qwen3_vl.py
python -m pytest -q tests/test_calibration_mapping_input.py tests/test_vlm_mapping_calibration_4308.py
# 32 failed, 64 passed
#   test_dataset_formats_unpack_into_token_rows[numpy]  -> ValueError: failed to convert `input_ids` to tensor
#   test_dataset_formats_unpack_into_token_rows[pandas] -> same one-row failure
#   test_dataframe_text_column_is_tokenized_per_row     -> AssertionError: [[[1]]] == [[[4]], [[4]]]
#   test_numpy_formatted_dataset_columns_are_unpacked[...13 definitions] -> ValueError / processor load

Every failure is at the intended behavioural assertion (converted rows or tokenized documents), not at import or collection.

Green evidence, with the fix:

python -m pytest -q tests/test_calibration_mapping_input.py tests/test_vlm_mapping_calibration_4308.py
# 96 passed

python -m pytest -q tests/test_calibration_data_device.py tests/test_calibration_empty_text_4306.py \
  tests/test_calibration_input_gaps_4311.py tests/test_calibration_mapping_input.py \
  tests/test_calibration_normalisation.py tests/test_calibration_padding_mask.py \
  tests/test_calibration_special_tokens_4191.py tests/test_calibration_text_and_ids_precedence_4635.py \
  tests/test_calibration_truncation.py tests/test_calibration_windows.py \
  tests/test_generator_calibration_4307.py tests/test_vlm_calibration_metadata_columns_4455.py \
  tests/test_vlm_mapping_calibration_4308.py tests/test_vlm_multimodal_calibration_4371.py \
  tests/test_vlm_pretokenized_calibration.py tests/test_vlm_prepare_dataset_contract_4633.py \
  tests/test_multimodal_calibration_replay.py
# 398 passed

python -m pytest -q tests/test_multimodal_calibration_replay.py tests/test_multimodal_modality_calibration.py \
  tests/test_internvl_chat_calibration.py tests/test_vlm_multimodal_calibration_4371.py \
  tests/module_tree/test_parallel_branch_calibration.py tests/test_calibration_data_device.py
# 58 passed

ruff check gptqmodel tests/test_calibration_mapping_input.py tests/test_vlm_mapping_calibration_4308.py
# All checks passed!

End-to-end consumer check on a real 0.5B checkpoint:

prepare_dataset(ds)                      == prepare_dataset(ds.with_format("numpy")[:])   # token-identical
prepare_dataset(ds)                      == prepare_dataset(ds.with_format("pandas")[:])  # token-identical
prepare_dataset(ds)                      == prepare_dataset(ds.to_pandas())               # token-identical
prepare_dataset(pd.DataFrame({"text": ...}))  -> decodes back to the source documents
quantize(ds.with_format("numpy")[:])     -> completes; generate() returns coherent text
quantize(ds.to_pandas())                 -> completes; generate() returns coherent text

Format skips: the new tests import numpy/pandas through pytest.importorskip, so an environment without those optional dependencies would skip them; both were present in the run above and the nodes executed (no skips in the reported results). No GPU-gated test was added: the change is container classification, and the end-to-end quantize rows above are the consumer-level check.

Logic Flow Documentation

This change replaces the container-classification decision, so the reference page docs/vlm-calibration-input-normalization.md carries the new-flow diagram, the removed-mechanism table with file:line evidence, and the fail-closed paths; it is linked from README.md (line 141).

  • New-flow Mermaid diagram(s) describe the shipped code using real symbol names.
  • The removed/replaced mechanism is shown or tabulated with file:line evidence.
  • Failure and ambiguity paths are marked and visually distinct.
  • A reference page under docs/ repeats the diagrams, titled for the mechanism, and is linked from README.md.

Model Support / Module Plan

Not applicable: no MODEL_MAP entry, alias, module plan, or weight-owner declaration changes. base_qwen3_vl.py only changes the accepted calibration input container for an existing definition.

AWQ onboarding safety

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

Kernel Accuracy Requirements

Not applicable: no kernel, quantization math, or packed-format change.

Review Requirements

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Notes

…#4652)

prepare_calibration_dataset classified a container by isinstance(Mapping)
and by ndim only, so two containers that already hold the accepted columns
reached the wrong path:

* Dataset.with_format("numpy")[:] stores a ragged token column as a 1-D
  ndarray(dtype=object). It was read as a single token row, and
  torch.as_tensor then refused the object array with a message that blamed
  the data.
* A pandas DataFrame is not a Mapping, so it was iterated as its column
  labels: a text frame calibrated on the literal string "text" (or failed
  the minimum-length filter with a misleading error).

Resolve both containers before the row split. _column_entries yields one
entry per row for 2-D arrays, 1-D ndarray/Series and datasets Columns;
_frame_columns converts a DataFrame-like table (pandas, Polars) into the
columnar mapping the helper already understood; _unwrap_object_array lets
as_tensor accept an object array of integer token ids. Flat object columns
of scalars stay one token row, and split_calibration_dataset reuses the same
normalization so VLM definitions keep byte-identical rows. base_qwen3_vl.py,
which does not use the shared splitter, rejects a table explicitly instead
of iterating its column labels.

Regression tests cover Dataset with_format numpy/pandas/torch/none, a
text-only frame, a frame without calibration columns, a flat object column,
and every VLM definition in the shared-splitter parametrization.
@Qubitium
Qubitium merged commit 12c1273 into main Nov 17, 2026
5 checks passed
@Qubitium
Qubitium deleted the fix/4652-calibration-container branch November 17, 2026 08:50
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