Repository navigation
fix(calibration): unpack DataFrame and NumPy object columns into rows (#4652) - #4656
Merged
Merged
Conversation
…#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.
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.
TL;DR
prepare_calibration_datasetnow resolves the container before splitting rows, soDataset.with_format("numpy")[:]object columns and DataFrame-like tables reach the same code path as an equivalentdictof 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_datasetaccepts were classified wrongly.main@959334876)_is_batched_columnreturnsndim >= 2for any object withndim, before looking at what the column holdsgptqmodel/utils/calibration.py:145-147Dataset.with_format("numpy")[:]gives a 1-Dndarray(dtype=object)of per-row arrays; it was classed as one token row_pack_ids→torch.as_tensor(object_array)gptqmodel/utils/calibration.py:558ValueError: failed to convert input_ids to tensor ... numpy.object_, blaming the data instead of the containerisinstance(calibration_dataset, Mapping)is the only columnar testgptqmodel/utils/calibration.py:366pandas.DataFrameis not aMapping, so it fell through toraw_examples = list(calibration_dataset)raw_examples = list(calibration_dataset)gptqmodel/utils/calibration.py:385,389,391"text";input_idsframes died on a misleadingcalibration_data_min_lengtherrormapping[name][row_index]used per columngptqmodel/utils/calibration.py:305Seriesindexes[]by label, so even a converted frame would mis-read rowsReproduced on
mainwith a real tokenizer and realdatasets/pandasobjects: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:#c002. The new flow
prepare_calibration_datasetand the VLMsplit_calibration_datasetboth 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:#080New 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/tupleis listed, 1-Dndarray/Seriesunwraps viatolist(),datasetsColumn(aSequencewithoutndim) is listed, anything else returnsNone(not a row container)._frame_columns(dataset)— a table (columnsattribute + a row-wiseto_dict) becomes the columnar mapping the module already understood. Triesto_dict("list"),to_dict(orient="list"),to_dict(as_series=False); ato_dictthat understands none of them, or a column that is not a per-row sequence, returnsNoneso the existing iterable handling still applies._unwrap_object_array(value)— turns an object-dtypendarrayinto alistsotorch.as_tensorcan classify integer token ids; nested arrays/strings still fail with the same structural error._is_batched_column,_is_columnar_mapping(text/messagescolumns),_columnar_mapping_examples, and the two tensor conversions in_pack_ids/_normalize_attention_masknow route through them.split_calibration_dataset(gptqmodel/models/definitions/_vlm_calibration.py) calls_frame_columnsbefore_mapping_rows, so VLM definitions keep byte-identical rows fornumpy/pandas/torchformats.3. Failure and ambiguity contract
Dataset.with_format("numpy")[:](1-D object column of rows)Dataset.with_format("pandas")[:]/ds.to_pandas()"text"pandas.DataFrame({"text": ...})"text"pandas.DataFrame({"foo": ...})ValueErrornaming the accepted columns{"input_ids": [7, 8, 9]}{"input_ids": np.array([7, 8, 9], dtype=object)}base_qwen3_vl.py(does not use the shared splitter)ValueErrornaming the input typefailed to convert ... to tensorValueError, same wording4. Change inventory
gptqmodel/utils/calibration.py_column_entries,_frame_columns,_unwrap_object_array; columnar classification and per-row indexing route through themgptqmodel/models/definitions/_vlm_calibration.pysplit_calibration_datasetnormalizes a table before the row splitgptqmodel/models/definitions/base_qwen3_vl.pydocs/vlm-calibration-input-normalization.mdtests/test_calibration_mapping_input.pytests/test_vlm_mapping_calibration_4308.pyMAPPING_DEFINITIONS5. Tests / guarantees
test_dataset_formats_unpack_into_token_rows[numpy/pandas/torch/None]Datasetproduce identical ids and maskstest_object_dtype_column_of_arrays_is_one_row_per_elementtest_dataframe_columns_are_unpacked_into_token_rowstest_dataframe_text_column_is_tokenized_per_row"text"test_dataframe_without_calibration_columns_is_rejectedtest_flat_object_column_is_still_one_token_rowtest_numpy_formatted_dataset_columns_are_unpacked(13 VLM definitions)numpycolumns reach the text path without loading the processortest_dataframe_calibration_input_is_unpacked_into_rows(13 VLM definitions)test_qwen3_vl_rejects_dataframe_calibration_input6. Validation
Red evidence — reverted only the three source files, kept the new tests:
Every failure is at the intended behavioural assertion (converted rows or tokenized documents), not at import or collection.
Green evidence, with the fix:
End-to-end consumer check on a real 0.5B checkpoint:
Format skips: the new tests import
numpy/pandasthroughpytest.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.mdcarries the new-flow diagram, the removed-mechanism table withfile:lineevidence, and the fail-closed paths; it is linked fromREADME.md(line 141).file:lineevidence.docs/repeats the diagrams, titled for the mechanism, and is linked fromREADME.md.Model Support / Module Plan
Not applicable: no
MODEL_MAPentry, alias, module plan, or weight-owner declaration changes.base_qwen3_vl.pyonly 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
Notes
_frame_columnsis intentionally permissive about which table type it accepts (pandas, Polars) but strict about shape: ato_dictit cannot drive, or a column that is not a per-row sequence, falls back to the previous iterable handling rather than raising.base_qwen3_vl.pystill does not use the shared splitter; converting it is the existing follow-up, not part of this fix.