From 01e47bcc0945de46a386d07a90906bb2f54746e8 Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Tue, 1 Dec 2026 23:23:41 +0000 Subject: [PATCH 1/7] Avoid Python lists when converting Arrow targets to tensors --- .../kumo_core/diskgraph/runtime_adapter.py | 169 ++++++++++-------- .../tests/test_runtime_adapter_targets.py | 160 +++++++++++++++++ 2 files changed, 257 insertions(+), 72 deletions(-) create mode 100644 packages/kumo-core/tests/test_runtime_adapter_targets.py diff --git a/packages/kumo-core/src/kumo_core/diskgraph/runtime_adapter.py b/packages/kumo-core/src/kumo_core/diskgraph/runtime_adapter.py index 9f3c281e23..1560ff2740 100644 --- a/packages/kumo-core/src/kumo_core/diskgraph/runtime_adapter.py +++ b/packages/kumo-core/src/kumo_core/diskgraph/runtime_adapter.py @@ -19,6 +19,7 @@ import numpy as np import pandas as pd import pyarrow as pa +import pyarrow.compute as pc import torch from diskgraph.runtime_batch import ( RuntimeBatch, @@ -1008,35 +1009,47 @@ def _shape_multilabel_target( sep = None if target_encoder is not None: sep = getattr(target_encoder.tensor_mapper, "sep", None) - values = _array_to_multilabel_lists(target, sep=sep or "|") + if isinstance(target, pa.ChunkedArray): + target = target.combine_chunks() + if pa.types.is_string(target.type) or pa.types.is_large_string(target.type): + target = pc.split_pattern(target, pattern=sep or "|") + flat = pc.list_flatten(target) + keep = pc.and_(pc.is_valid(flat), pc.not_equal(flat, "")) + elif ( + pa.types.is_list(target.type) + or pa.types.is_large_list(target.type) + or pa.types.is_fixed_size_list(target.type) + ): + flat = pc.list_flatten(target) + keep = pc.is_valid(flat) + else: + flat = target + keep = pc.is_valid(flat) + + if flat is target: + lengths = np.ones(len(target), dtype=np.int64) + else: + lengths = pc.fill_null(pc.list_value_length(target), 0).to_numpy() + offsets = np.empty(len(target) + 1, dtype=np.int64) + offsets[0] = 0 + np.cumsum(lengths, out=offsets[1:]) + valid_prefix = np.empty(len(flat) + 1, dtype=np.int64) + valid_prefix[0] = 0 + np.cumsum( + pc.fill_null(keep, False).to_numpy(zero_copy_only=False), out=valid_prefix[1:] + ) + offsets = valid_prefix[offsets] + flat = pc.filter(flat, keep) + if target_encoder is None: - mapped = [[int(v) for v in row] for row in values] + indices = _values_to_tensor(flat.cast(pa.int64(), safe=False), dtype=torch.long) else: - mapping = cast( - MultiCategoricalTensorMapper, target_encoder.tensor_mapper - ).mapping - mapped = [] - for row in values: - labels, indices = _target_label_indices(list(row), mapping) - if (indices < 0).any(): - unknown = [ - labels[i] for i, idx in enumerate(indices) if idx < 0 - ] - raise ValueError( - "TT-NG multilabel target contains labels not present in " - f"target encoder mapping: {unknown[:5]}") - mapped.append([int(i) for i in indices]) - - flat: list[int] = [] - offsets = [0] - for row in mapped: - flat.extend(row) - offsets.append(len(flat)) + indices = _categorical_indices(flat, target_encoder, offsets=offsets) return MultiNestedTensor( - num_rows=len(mapped), + num_rows=len(target), num_cols=1, - values=torch.tensor(flat, dtype=torch.long), - offset=torch.tensor(offsets, dtype=torch.long), + values=indices, + offset=torch.from_numpy(offsets), ) @@ -1058,75 +1071,87 @@ def _coerce_numeric_label(value: Any) -> Any: def _target_label_indices( - values: list[Any], + values: np.ndarray, mapping: pd.Index, -) -> tuple[list[Any], np.ndarray]: - candidates = [values] - string_values = [str(v) for v in values] - if string_values != values: - candidates.append(string_values) - numeric_values = [_coerce_numeric_label(v) for v in values] - if numeric_values != values: - candidates.append(numeric_values) - + offsets: np.ndarray | None = None, +) -> tuple[np.ndarray, np.ndarray]: indices = mapping.get_indexer(values) - for candidate in candidates: + if (indices >= 0).all(): + return values, indices + unresolved_rows = ( + np.diff(np.r_[0, np.cumsum(indices < 0)][offsets]) > 0 + if offsets is not None + else None + ) + for coerce in (str, _coerce_numeric_label): + candidate = ( + values.astype(str) + if coerce is str + else np.fromiter(map(coerce, values), dtype=object, count=len(values)) + ) candidate_indices = mapping.get_indexer(candidate) - if (candidate_indices >= 0).all(): - return candidate, candidate_indices + if offsets is None: + if (candidate_indices >= 0).all(): + return candidate, candidate_indices + continue + invalid_prefix = np.empty(len(values) + 1, dtype=np.int64) + invalid_prefix[0] = 0 + np.cumsum(candidate_indices < 0, out=invalid_prefix[1:]) + # Apply coercion only when every label in an unresolved row matches. + valid_rows = (np.diff(invalid_prefix[offsets]) == 0) & unresolved_rows + unresolved_rows &= ~valid_rows + use_candidate = np.repeat(valid_rows, np.diff(offsets)) + indices[use_candidate] = candidate_indices[use_candidate] + if (indices >= 0).all(): + return values, indices return values, indices def _categorical_indices( target: pa.Array | pa.ChunkedArray, target_encoder: TargetEncoder, + *, + offsets: np.ndarray | None = None, ) -> torch.Tensor: - values = _arrow_array_to_pylist(target) + values = target.to_numpy(zero_copy_only=False) - mapping = cast(CategoricalTensorMapper, target_encoder.tensor_mapper).mapping - values, indices = _target_label_indices(values, mapping) + mapping = cast( + CategoricalTensorMapper | MultiCategoricalTensorMapper, + target_encoder.tensor_mapper, + ).mapping + values, indices = _target_label_indices(values, mapping, offsets) if (indices < 0).any(): unknown = [values[i] for i, idx in enumerate(indices) if idx < 0] + kind = "categorical" if offsets is None else "multilabel" raise ValueError( - "TT-NG categorical target contains labels not present in target " - f"encoder mapping: {unknown[:5]}") - return torch.tensor(indices, dtype=torch.long) - - -def _array_to_multilabel_lists( - values: pa.Array | pa.ChunkedArray, *, sep: str -) -> list[list[Any]]: - if isinstance(values, pa.ChunkedArray): - values = values.combine_chunks() - py_values = values.to_pylist() - - out: list[list[Any]] = [] - for value in py_values: - if value is None: - out.append([]) - elif isinstance(value, str): - out.append([v for v in value.split(sep) if v != ""]) - elif isinstance(value, (list, tuple, np.ndarray)): - out.append([v for v in list(value) if v is not None]) - else: - out.append([value]) - return out + f"TT-NG {kind} target contains labels not present in target " + f"encoder mapping: {unknown[:5]}" + ) + return torch.from_numpy(indices).long() def _arrow_array_to_tensor(values: ArrowArray) -> torch.Tensor: if isinstance(values, pa.ChunkedArray): values = values.combine_chunks() - if isinstance(values, pa.Array) and pa.types.is_list(values.type): - return torch.tensor(values.to_pylist(), dtype=torch.float32) + if isinstance(values, pa.Array) and ( + pa.types.is_list(values.type) + or pa.types.is_large_list(values.type) + or pa.types.is_fixed_size_list(values.type) + ): + if len(values) == 0: + return torch.empty(0, dtype=torch.float32) + if values.null_count: + raise ValueError("Dense targets must contain non-null lists") + lengths = pc.list_value_length(values).to_numpy(zero_copy_only=False) + width = int(lengths[0]) + if not np.all(lengths == width): + raise ValueError("Dense targets must contain non-null, equal-length lists") + return _values_to_tensor(pc.list_flatten(values), dtype=torch.float32).reshape( + len(values), width + ) return _values_to_tensor(values, dtype=torch.float32) -def _arrow_array_to_pylist(values: pa.Array | pa.ChunkedArray) -> list[Any]: - if isinstance(values, pa.ChunkedArray): - values = values.combine_chunks() - return values.to_pylist() - - def _all_present(values: ArrowArray) -> bool: """``True`` iff ``values`` is a non-empty Arrow array with no ``None`` entries. ``False`` for a bare ``ChunkedArray`` (callers only ever pass diff --git a/packages/kumo-core/tests/test_runtime_adapter_targets.py b/packages/kumo-core/tests/test_runtime_adapter_targets.py new file mode 100644 index 0000000000..5e71bfca47 --- /dev/null +++ b/packages/kumo-core/tests/test_runtime_adapter_targets.py @@ -0,0 +1,160 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Target conversion from Arrow buffers to task tensors.""" + +import pyarrow as pa +import pytest +import torch +from kumo_core.diskgraph.runtime_adapter import _shape_target +from kumo_core.encoders.target.categorical import CategoricalTargetEncoder +from kumo_core.encoders.target.multicategorical import MultiCategoricalTargetEncoder +from kumo_core.encoders.tensor_mapper import ( + CategoricalTensorMapper, + MultiCategoricalTensorMapper, +) +from kumoapi.task import TaskType +from torch_frame.data import MultiNestedTensor + + +@pytest.mark.parametrize("chunked", [False, True]) +@pytest.mark.parametrize( + "list_type", + [pa.list_(pa.float32()), pa.large_list(pa.float32()), pa.list_(pa.float32(), 2)], +) +def test_dense_targets_preserve_slice_and_shape( + chunked: bool, list_type: pa.DataType +) -> None: + """Dense targets retain only the selected rows across Arrow list types.""" + target = pa.array([[9, 9], [1, 2], [3, 4], [9, 9]], type=list_type).slice(1, 2) + if chunked: + target = pa.chunked_array([target.slice(0, 1), target.slice(1)]) + + result = _shape_target(target, "regression") + + assert isinstance(result, torch.Tensor) + torch.testing.assert_close(result, torch.tensor([[1.0, 2.0], [3.0, 4.0]])) + + +@pytest.mark.parametrize("chunked", [False, True]) +@pytest.mark.parametrize("encoded", [False, True]) +@pytest.mark.parametrize( + "task_type", ["multilabel_classification", "multilabel_ranking"] +) +def test_multilabel_offsets_skip_nulls( + chunked: bool, encoded: bool, task_type: str +) -> None: + """Null parents and children do not contribute labels or shift offsets.""" + target = pa.array([[9], [1, None, 2], [], None, [2], [9]]).slice(1, 4) + if chunked: + target = pa.chunked_array([target.slice(0, 2), target.slice(2)]) + encoder = ( + MultiCategoricalTargetEncoder( + MultiCategoricalTensorMapper([[2, 10], [1, 5]], sep="|") + ) + if encoded + else None + ) + + result = _shape_target(target, task_type, encoder) + + assert isinstance(result, MultiNestedTensor) + torch.testing.assert_close( + result.values, torch.tensor([1, 0, 0] if encoded else [1, 2, 2]) + ) + torch.testing.assert_close(result.offset, torch.tensor([0, 2, 2, 2, 3])) + + +def test_multilabel_strings_preserve_mapping_and_separator() -> None: + """String splitting drops empty tokens and maps numeric string labels.""" + target = pa.chunked_array([["1;;2", ""], [None, "2;"]]) + encoder = MultiCategoricalTargetEncoder( + MultiCategoricalTensorMapper([[2, 10], [1, 5]], sep=";") + ) + + result = _shape_target(target, "multilabel_classification", encoder) + + assert isinstance(result, MultiNestedTensor) + torch.testing.assert_close(result.values, torch.tensor([1, 0, 0])) + torch.testing.assert_close(result.offset, torch.tensor([0, 2, 2, 2, 3])) + + +def test_categorical_numeric_string_mapping() -> None: + """Chunked numeric strings follow the encoder's category order.""" + encoder = CategoricalTargetEncoder( + TaskType.MULTICLASS_CLASSIFICATION, + CategoricalTensorMapper([[2, 10], [1, 5]]), + ) + + result = _shape_target( + pa.chunked_array([["1"], ["2", "1"]]), "multiclass_classification", encoder + ) + + assert isinstance(result, torch.Tensor) + torch.testing.assert_close(result, torch.tensor([[1], [0], [1]])) + + +@pytest.mark.parametrize( + "target", + [ + pa.array([], type=pa.list_(pa.int64())), + pa.array([[], []], type=pa.list_(pa.int64())), + ], +) +def test_empty_dense_targets(target: pa.Array) -> None: + """Empty dense targets retain their row dimension.""" + result = _shape_target(target, None) + + assert isinstance(result, torch.Tensor) + assert result.shape == ((0,) if len(target) == 0 else (2, 0)) + + +def test_ragged_dense_targets_raise() -> None: + """Dense tensors reject targets with differing row widths.""" + with pytest.raises(ValueError, match="equal-length"): + _shape_target(pa.array([[1], [2, 3]]), "regression") + + +@pytest.mark.parametrize("target", [pa.array(["1", "01"]), pa.array([["1"], ["01"]])]) +def test_multilabel_mapping_coercion_is_per_row(target: pa.Array) -> None: + """Rows may require different conversions to match mixed label types.""" + encoder = MultiCategoricalTargetEncoder( + MultiCategoricalTensorMapper([[1, 10], ["01", 5]], sep="|") + ) + + result = _shape_target(target, "multilabel_classification", encoder) + + assert isinstance(result, MultiNestedTensor) + torch.testing.assert_close(result.values, torch.tensor([0, 1])) + torch.testing.assert_close(result.offset, torch.tensor([0, 1, 2])) + + +@pytest.mark.parametrize( + "task_type", ["static_link_prediction", "temporal_link_prediction"] +) +def test_link_prediction_preserves_large_integer_ids(task_type: str) -> None: + """Link prediction IDs retain int64 precision and a flat shape.""" + result = _shape_target(pa.array([2**54 + 1, 2**54 + 3]), task_type) + + assert isinstance(result, torch.Tensor) + torch.testing.assert_close(result, torch.tensor([2**54 + 1, 2**54 + 3])) + + +def test_dense_float32_target_shares_arrow_buffer() -> None: + """Contiguous float32 targets need no allocation for the tensor values.""" + target = pa.array([[1.0, 2.0], [3.0, 4.0]], type=pa.list_(pa.float32())) + + result = _shape_target(target, "regression") + + assert isinstance(result, torch.Tensor) + assert result.data_ptr() == target.values.buffers()[1].address + + +def test_multilabel_unknown_label_raises() -> None: + """Unmapped labels keep the multilabel validation error.""" + encoder = MultiCategoricalTargetEncoder( + MultiCategoricalTensorMapper([["known", 10]], sep="|") + ) + + with pytest.raises(ValueError, match="multilabel target.*unknown"): + _shape_target(pa.array([["unknown"]]), "multilabel_classification", encoder) From 920099e26aefda0e8cfdcec537350cfed0a52cc2 Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Wed, 2 Dec 2026 06:43:23 +0000 Subject: [PATCH 2/7] Reuse target tensor mappers in the runtime adapter --- .../kumo_core/diskgraph/runtime_adapter.py | 211 +----------------- .../tests/test_runtime_adapter_targets.py | 210 ++++++++--------- .../generic/test_diskgraph_runtime_adapter.py | 111 ++++++--- .../test_diskgraph_lightning_data.py | 64 ++++++ test/train/test_diskgraph_nested_trainer.py | 1 + 5 files changed, 249 insertions(+), 348 deletions(-) diff --git a/packages/kumo-core/src/kumo_core/diskgraph/runtime_adapter.py b/packages/kumo-core/src/kumo_core/diskgraph/runtime_adapter.py index 1560ff2740..a78e26c8c0 100644 --- a/packages/kumo-core/src/kumo_core/diskgraph/runtime_adapter.py +++ b/packages/kumo-core/src/kumo_core/diskgraph/runtime_adapter.py @@ -14,12 +14,9 @@ import warnings from collections.abc import Mapping from dataclasses import dataclass, field, replace -from typing import Any, TypeAlias, TypedDict, cast +from typing import Any, TypeAlias, TypedDict -import numpy as np -import pandas as pd import pyarrow as pa -import pyarrow.compute as pc import torch from diskgraph.runtime_batch import ( RuntimeBatch, @@ -30,31 +27,19 @@ RuntimeTask, ) from torch_frame import TensorFrame -from torch_frame.data import MultiNestedTensor from torch_geometric.data import HeteroData from torch_geometric.sampler.base import HeteroSamplerOutput from kumo_core.diskgraph.metadata import normalize_diskgraph_edge_type from kumo_core.encoders.target.base import TargetEncoder from kumo_core.encoders.tensor_frame import get_tf -from kumo_core.encoders.tensor_mapper import ( - CategoricalTensorMapper, - MultiCategoricalTensorMapper, - TensorMapper, -) +from kumo_core.encoders.tensor_mapper import TensorMapper # A column value as handed across the diskgraph FFI boundary: the wheel # always builds these through pyarrow (see diskgraph-pybind's py_*_array # helpers), so this is Arrow-or-absent, never a plain Python list. ArrowArray: TypeAlias = pa.Array | pa.ChunkedArray | None -_CLASSIFICATION_TASK_TYPES = frozenset({ - "binary_classification", - "multiclass_classification", - "multilabel_classification", - "multilabel_ranking", -}) - # LP targets are RHS node ids — must stay int64 (float32 loses ids > 2**24). _LINK_PRED_TASK_TYPES = frozenset({ "temporal_link_prediction", @@ -481,7 +466,7 @@ def _normalize_task_payload(task: RuntimeTask) -> NormalizedTask: # Set target only when one is present (predict has none). The wheel # emits ``task.target`` as a RecordBatch for multi-TARGET; unwrap the - # single column to an Array for ``_shape_target``. + # single column to an Array for target mapping. target = task.target if target is not None: if isinstance(target, pa.RecordBatch): @@ -803,7 +788,12 @@ def _attach_seed_table( target = task.target if target is not None and task_type != "forecasting": - seed_block.y = _shape_target(target, task_type, target_encoder) + if task_type in _LINK_PRED_TASK_TYPES: + seed_block.y = _values_to_tensor(target, dtype=torch.long).view(-1) + else: + if target_encoder is None: + raise ValueError("A target encoder is required for non-LP targets") + seed_block.y = target_encoder.tensor_mapper(target) target_mask = task.target_mask if target_mask is not None: # bool[B], True == TARGET1 PK did not resolve to an RHS node id. @@ -969,189 +959,6 @@ def _attach_lp_exclude( seed_block.exclude_rhs_index = exclude_rhs_index -def _shape_target( - target: pa.Array | pa.ChunkedArray, - task_type: str | None, - target_encoder: TargetEncoder | None = None, -) -> torch.Tensor | MultiNestedTensor: - """Promote target to the shape expected by the Kumo task modules. - - ``target`` has already passed through ``_normalize_task_payload``, which - unwraps any single-column TT-NG multi-TARGET ``RecordBatch`` into a plain - Arrow array -- so this never sees a ``RecordBatch``. - """ - # LP targets are int64 RHS node ids — keep 1-D; get_ground_truth reads - # ``batch[lhs].y`` as node ids. - if task_type in _LINK_PRED_TASK_TYPES: - return _values_to_tensor(target, dtype=torch.long).view(-1) - if task_type in {"multilabel_classification", "multilabel_ranking"}: - return _shape_multilabel_target(target, target_encoder) - - if (task_type is not None and task_type in _CLASSIFICATION_TASK_TYPES - and target_encoder is not None): - return _categorical_indices(target, target_encoder).long().view(-1, 1) - - y = _arrow_array_to_tensor(target) - - if task_type is None: - return y - if task_type in _CLASSIFICATION_TASK_TYPES: - return y.long().view(-1, 1) - if y.dim() == 1: - return y.to(dtype=torch.float32).view(-1, 1) - return y.to(dtype=torch.float32) - - -def _shape_multilabel_target( - target: pa.Array | pa.ChunkedArray, - target_encoder: TargetEncoder | None, -) -> MultiNestedTensor: - sep = None - if target_encoder is not None: - sep = getattr(target_encoder.tensor_mapper, "sep", None) - if isinstance(target, pa.ChunkedArray): - target = target.combine_chunks() - if pa.types.is_string(target.type) or pa.types.is_large_string(target.type): - target = pc.split_pattern(target, pattern=sep or "|") - flat = pc.list_flatten(target) - keep = pc.and_(pc.is_valid(flat), pc.not_equal(flat, "")) - elif ( - pa.types.is_list(target.type) - or pa.types.is_large_list(target.type) - or pa.types.is_fixed_size_list(target.type) - ): - flat = pc.list_flatten(target) - keep = pc.is_valid(flat) - else: - flat = target - keep = pc.is_valid(flat) - - if flat is target: - lengths = np.ones(len(target), dtype=np.int64) - else: - lengths = pc.fill_null(pc.list_value_length(target), 0).to_numpy() - offsets = np.empty(len(target) + 1, dtype=np.int64) - offsets[0] = 0 - np.cumsum(lengths, out=offsets[1:]) - valid_prefix = np.empty(len(flat) + 1, dtype=np.int64) - valid_prefix[0] = 0 - np.cumsum( - pc.fill_null(keep, False).to_numpy(zero_copy_only=False), out=valid_prefix[1:] - ) - offsets = valid_prefix[offsets] - flat = pc.filter(flat, keep) - - if target_encoder is None: - indices = _values_to_tensor(flat.cast(pa.int64(), safe=False), dtype=torch.long) - else: - indices = _categorical_indices(flat, target_encoder, offsets=offsets) - return MultiNestedTensor( - num_rows=len(target), - num_cols=1, - values=indices, - offset=torch.from_numpy(offsets), - ) - - -def _coerce_numeric_label(value: Any) -> Any: - if not isinstance(value, str): - return value - stripped = value.strip() - if stripped == "" or stripped != value: - return value - try: - int_value = int(stripped) - except ValueError: - try: - float_value = float(stripped) - except ValueError: - return value - return float_value if np.isfinite(float_value) else value - return int_value if stripped == str(int_value) else value - - -def _target_label_indices( - values: np.ndarray, - mapping: pd.Index, - offsets: np.ndarray | None = None, -) -> tuple[np.ndarray, np.ndarray]: - indices = mapping.get_indexer(values) - if (indices >= 0).all(): - return values, indices - unresolved_rows = ( - np.diff(np.r_[0, np.cumsum(indices < 0)][offsets]) > 0 - if offsets is not None - else None - ) - for coerce in (str, _coerce_numeric_label): - candidate = ( - values.astype(str) - if coerce is str - else np.fromiter(map(coerce, values), dtype=object, count=len(values)) - ) - candidate_indices = mapping.get_indexer(candidate) - if offsets is None: - if (candidate_indices >= 0).all(): - return candidate, candidate_indices - continue - invalid_prefix = np.empty(len(values) + 1, dtype=np.int64) - invalid_prefix[0] = 0 - np.cumsum(candidate_indices < 0, out=invalid_prefix[1:]) - # Apply coercion only when every label in an unresolved row matches. - valid_rows = (np.diff(invalid_prefix[offsets]) == 0) & unresolved_rows - unresolved_rows &= ~valid_rows - use_candidate = np.repeat(valid_rows, np.diff(offsets)) - indices[use_candidate] = candidate_indices[use_candidate] - if (indices >= 0).all(): - return values, indices - return values, indices - - -def _categorical_indices( - target: pa.Array | pa.ChunkedArray, - target_encoder: TargetEncoder, - *, - offsets: np.ndarray | None = None, -) -> torch.Tensor: - values = target.to_numpy(zero_copy_only=False) - - mapping = cast( - CategoricalTensorMapper | MultiCategoricalTensorMapper, - target_encoder.tensor_mapper, - ).mapping - values, indices = _target_label_indices(values, mapping, offsets) - if (indices < 0).any(): - unknown = [values[i] for i, idx in enumerate(indices) if idx < 0] - kind = "categorical" if offsets is None else "multilabel" - raise ValueError( - f"TT-NG {kind} target contains labels not present in target " - f"encoder mapping: {unknown[:5]}" - ) - return torch.from_numpy(indices).long() - - -def _arrow_array_to_tensor(values: ArrowArray) -> torch.Tensor: - if isinstance(values, pa.ChunkedArray): - values = values.combine_chunks() - if isinstance(values, pa.Array) and ( - pa.types.is_list(values.type) - or pa.types.is_large_list(values.type) - or pa.types.is_fixed_size_list(values.type) - ): - if len(values) == 0: - return torch.empty(0, dtype=torch.float32) - if values.null_count: - raise ValueError("Dense targets must contain non-null lists") - lengths = pc.list_value_length(values).to_numpy(zero_copy_only=False) - width = int(lengths[0]) - if not np.all(lengths == width): - raise ValueError("Dense targets must contain non-null, equal-length lists") - return _values_to_tensor(pc.list_flatten(values), dtype=torch.float32).reshape( - len(values), width - ) - return _values_to_tensor(values, dtype=torch.float32) - - def _all_present(values: ArrowArray) -> bool: """``True`` iff ``values`` is a non-empty Arrow array with no ``None`` entries. ``False`` for a bare ``ChunkedArray`` (callers only ever pass diff --git a/packages/kumo-core/tests/test_runtime_adapter_targets.py b/packages/kumo-core/tests/test_runtime_adapter_targets.py index 5e71bfca47..c33c8494a9 100644 --- a/packages/kumo-core/tests/test_runtime_adapter_targets.py +++ b/packages/kumo-core/tests/test_runtime_adapter_targets.py @@ -1,160 +1,144 @@ # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Target conversion from Arrow buffers to task tensors.""" +"""Target conversion at the runtime adapter's seed-table boundary.""" + +from unittest.mock import patch import pyarrow as pa import pytest import torch -from kumo_core.diskgraph.runtime_adapter import _shape_target +from kumo_core.diskgraph.runtime_adapter import NormalizedTask, _attach_seed_table +from kumo_core.encoders.target.base import TargetEncoder from kumo_core.encoders.target.categorical import CategoricalTargetEncoder from kumo_core.encoders.target.multicategorical import MultiCategoricalTargetEncoder +from kumo_core.encoders.target.numerical import NumericalTargetEncoder from kumo_core.encoders.tensor_mapper import ( CategoricalTensorMapper, MultiCategoricalTensorMapper, ) from kumoapi.task import TaskType from torch_frame.data import MultiNestedTensor +from torch_geometric.data import HeteroData @pytest.mark.parametrize("chunked", [False, True]) @pytest.mark.parametrize( - "list_type", - [pa.list_(pa.float32()), pa.large_list(pa.float32()), pa.list_(pa.float32(), 2)], + ("task_type", "target", "encoder"), + [ + ("regression", pa.array([1.0, None, 3.0]), NumericalTargetEncoder(10, 2)), + (None, pa.array([1.0, 2.0]), NumericalTargetEncoder(10, 2)), + ( + "multiclass_classification", + pa.array(["known", "unknown", None]), + CategoricalTargetEncoder( + TaskType.MULTICLASS_CLASSIFICATION, + CategoricalTensorMapper([["known", 10]]), + ), + ), + ( + "multilabel_classification", + pa.array([["known", None], [], None, ["unknown"]]), + MultiCategoricalTargetEncoder( + MultiCategoricalTensorMapper([["known", 10]], sep="|") + ), + ), + ( + "multilabel_ranking", + pa.array(["known;other", "", None]), + MultiCategoricalTargetEncoder( + MultiCategoricalTensorMapper([["known", 10], ["other", 5]], sep=";") + ), + ), + ], ) -def test_dense_targets_preserve_slice_and_shape( - chunked: bool, list_type: pa.DataType +def test_seed_target_uses_tensor_mapper( + chunked: bool, + task_type: str | None, + target: pa.Array | pa.ChunkedArray, + encoder: TargetEncoder, ) -> None: - """Dense targets retain only the selected rows across Arrow list types.""" - target = pa.array([[9, 9], [1, 2], [3, 4], [9, 9]], type=list_type).slice(1, 2) + """Delegate Arrow conversion without applying the later training transform.""" if chunked: target = pa.chunked_array([target.slice(0, 1), target.slice(1)]) + expected = encoder.tensor_mapper(target) + task = NormalizedTask(input_ids=None, seed_node_id=None, target=target) + hetero = HeteroData() + + with ( + patch.object( + encoder.tensor_mapper, "forward", wraps=encoder.tensor_mapper.forward + ) as mapper, + patch.object(encoder, "encode_tensor") as encode_tensor, + ): + _attach_seed_table( + hetero, task, "train_table", task_type=task_type, target_encoder=encoder + ) - result = _shape_target(target, "regression") - - assert isinstance(result, torch.Tensor) - torch.testing.assert_close(result, torch.tensor([[1.0, 2.0], [3.0, 4.0]])) + mapper.assert_called_once() + encode_tensor.assert_not_called() + result = hetero["train_table"].y + if isinstance(expected, MultiNestedTensor): + assert isinstance(result, MultiNestedTensor) + torch.testing.assert_close(result.values, expected.values) + torch.testing.assert_close(result.offset, expected.offset) + else: + torch.testing.assert_close(result, expected, equal_nan=True) -@pytest.mark.parametrize("chunked", [False, True]) -@pytest.mark.parametrize("encoded", [False, True]) @pytest.mark.parametrize( - "task_type", ["multilabel_classification", "multilabel_ranking"] + "task_type", ["static_link_prediction", "temporal_link_prediction"] ) -def test_multilabel_offsets_skip_nulls( - chunked: bool, encoded: bool, task_type: str -) -> None: - """Null parents and children do not contribute labels or shift offsets.""" - target = pa.array([[9], [1, None, 2], [], None, [2], [9]]).slice(1, 4) +@pytest.mark.parametrize("chunked", [False, True]) +def test_link_prediction_bypasses_mapper(task_type: str, chunked: bool) -> None: + """LP targets remain flat int64 node IDs without invoking the mapper.""" + target = pa.array([2**54 + 1, 2**54 + 3], type=pa.int64()) if chunked: - target = pa.chunked_array([target.slice(0, 2), target.slice(2)]) - encoder = ( - MultiCategoricalTargetEncoder( - MultiCategoricalTensorMapper([[2, 10], [1, 5]], sep="|") - ) - if encoded - else None - ) + target = pa.chunked_array([target.slice(0, 1), target.slice(1)]) + task = NormalizedTask(input_ids=None, seed_node_id=None, target=target) + hetero = HeteroData() + encoder = NumericalTargetEncoder(0, 1) - result = _shape_target(target, task_type, encoder) + with patch.object(encoder.tensor_mapper, "forward") as mapper: + _attach_seed_table( + hetero, task, "train_table", task_type=task_type, target_encoder=encoder + ) - assert isinstance(result, MultiNestedTensor) + mapper.assert_not_called() torch.testing.assert_close( - result.values, torch.tensor([1, 0, 0] if encoded else [1, 2, 2]) - ) - torch.testing.assert_close(result.offset, torch.tensor([0, 2, 2, 2, 3])) - - -def test_multilabel_strings_preserve_mapping_and_separator() -> None: - """String splitting drops empty tokens and maps numeric string labels.""" - target = pa.chunked_array([["1;;2", ""], [None, "2;"]]) - encoder = MultiCategoricalTargetEncoder( - MultiCategoricalTensorMapper([[2, 10], [1, 5]], sep=";") - ) - - result = _shape_target(target, "multilabel_classification", encoder) - - assert isinstance(result, MultiNestedTensor) - torch.testing.assert_close(result.values, torch.tensor([1, 0, 0])) - torch.testing.assert_close(result.offset, torch.tensor([0, 2, 2, 2, 3])) - - -def test_categorical_numeric_string_mapping() -> None: - """Chunked numeric strings follow the encoder's category order.""" - encoder = CategoricalTargetEncoder( - TaskType.MULTICLASS_CLASSIFICATION, - CategoricalTensorMapper([[2, 10], [1, 5]]), + hetero["train_table"].y, torch.tensor([2**54 + 1, 2**54 + 3]) ) - result = _shape_target( - pa.chunked_array([["1"], ["2", "1"]]), "multiclass_classification", encoder - ) - - assert isinstance(result, torch.Tensor) - torch.testing.assert_close(result, torch.tensor([[1], [0], [1]])) - @pytest.mark.parametrize( - "target", - [ - pa.array([], type=pa.list_(pa.int64())), - pa.array([[], []], type=pa.list_(pa.int64())), - ], + "task_type", + ["static_link_prediction", "temporal_link_prediction", "forecasting", "regression"], ) -def test_empty_dense_targets(target: pa.Array) -> None: - """Empty dense targets retain their row dimension.""" - result = _shape_target(target, None) - - assert isinstance(result, torch.Tensor) - assert result.shape == ((0,) if len(target) == 0 else (2, 0)) +def test_absent_target_does_not_attach_y(task_type: str) -> None: + """Unlabeled batches do not require an encoder or attach target tensors.""" + hetero = HeteroData() + task = NormalizedTask(input_ids=None, seed_node_id=None) + _attach_seed_table(hetero, task, "train_table", task_type=task_type) -def test_ragged_dense_targets_raise() -> None: - """Dense tensors reject targets with differing row widths.""" - with pytest.raises(ValueError, match="equal-length"): - _shape_target(pa.array([[1], [2, 3]]), "regression") + assert "y" not in hetero["train_table"] -@pytest.mark.parametrize("target", [pa.array(["1", "01"]), pa.array([["1"], ["01"]])]) -def test_multilabel_mapping_coercion_is_per_row(target: pa.Array) -> None: - """Rows may require different conversions to match mixed label types.""" - encoder = MultiCategoricalTargetEncoder( - MultiCategoricalTensorMapper([[1, 10], ["01", 5]], sep="|") +def test_forecasting_skips_target_without_encoder() -> None: + """Forecasting keeps its separate sequence supervision path.""" + hetero = HeteroData() + task = NormalizedTask( + input_ids=None, seed_node_id=None, target=pa.array([[1.0, 2.0]]) ) - result = _shape_target(target, "multilabel_classification", encoder) + _attach_seed_table(hetero, task, "train_table", task_type="forecasting") - assert isinstance(result, MultiNestedTensor) - torch.testing.assert_close(result.values, torch.tensor([0, 1])) - torch.testing.assert_close(result.offset, torch.tensor([0, 1, 2])) + assert "y" not in hetero["train_table"] -@pytest.mark.parametrize( - "task_type", ["static_link_prediction", "temporal_link_prediction"] -) -def test_link_prediction_preserves_large_integer_ids(task_type: str) -> None: - """Link prediction IDs retain int64 precision and a flat shape.""" - result = _shape_target(pa.array([2**54 + 1, 2**54 + 3]), task_type) - - assert isinstance(result, torch.Tensor) - torch.testing.assert_close(result, torch.tensor([2**54 + 1, 2**54 + 3])) - - -def test_dense_float32_target_shares_arrow_buffer() -> None: - """Contiguous float32 targets need no allocation for the tensor values.""" - target = pa.array([[1.0, 2.0], [3.0, 4.0]], type=pa.list_(pa.float32())) - - result = _shape_target(target, "regression") - - assert isinstance(result, torch.Tensor) - assert result.data_ptr() == target.values.buffers()[1].address - - -def test_multilabel_unknown_label_raises() -> None: - """Unmapped labels keep the multilabel validation error.""" - encoder = MultiCategoricalTargetEncoder( - MultiCategoricalTensorMapper([["known", 10]], sep="|") - ) +def test_supervised_target_requires_encoder() -> None: + """A missing supervised target encoder raises a clear configuration error.""" + task = NormalizedTask(input_ids=None, seed_node_id=None, target=pa.array([1.0])) - with pytest.raises(ValueError, match="multilabel target.*unknown"): - _shape_target(pa.array([["unknown"]]), "multilabel_classification", encoder) + with pytest.raises(ValueError, match="target encoder is required"): + _attach_seed_table(HeteroData(), task, "train_table", task_type="regression") diff --git a/test/data/generic/test_diskgraph_runtime_adapter.py b/test/data/generic/test_diskgraph_runtime_adapter.py index 1fdd623d35..d8feb016a1 100644 --- a/test/data/generic/test_diskgraph_runtime_adapter.py +++ b/test/data/generic/test_diskgraph_runtime_adapter.py @@ -35,6 +35,7 @@ from kumo_core.encoders.target.multicategorical import ( MultiCategoricalTargetEncoder, ) +from kumo_core.encoders.target.numerical import NumericalTargetEncoder from kumo_core.encoders.tensor_mapper import ( CategoricalTensorMapper, MultiCategoricalTensorMapper, @@ -140,14 +141,16 @@ def _populated_batch() -> RuntimeBatch: def test_empty_batch_yields_seed_block_only() -> None: batch = _empty_batch(n_inputs=3) hetero, raw_features, raw_row_ids = runtime_batch_to_hetero( - batch, train_table_name="train_table" + batch, + train_table_name="train_table", + target_encoder=NumericalTargetEncoder(0, 1), ) # Seed block is populated. seed = hetero["train_table"] assert torch.equal(seed.input_id, torch.tensor([0, 1, 2])) assert torch.equal(seed.batch, torch.tensor([0, 1, 2])) - assert torch.equal(seed.y, torch.tensor([0.0, 1.0, 0.0])) + assert torch.equal(seed.y, torch.tensor([[0.0], [1.0], [0.0]])) # No time or weight when the columns are all-null. assert "time" not in seed assert "weight" not in seed @@ -162,7 +165,10 @@ def test_empty_batch_yields_seed_block_only() -> None: def test_populated_batch_builds_graph_and_seed_block() -> None: batch = _populated_batch() hetero, _raw_features, _raw_row_ids = runtime_batch_to_hetero( - batch, train_table_name="train_table") + batch, + train_table_name="train_table", + target_encoder=NumericalTargetEncoder(0, 1), + ) # Graph topology. assert torch.equal(hetero["User"].n_id, torch.tensor([100, 101, 102, 200])) @@ -186,7 +192,7 @@ def test_populated_batch_builds_graph_and_seed_block() -> None: torch.tensor([1_700_000_000, 1_700_500_000, 1_700_600_000]) * 1_000_000_000, ) - assert torch.allclose(seed.y, torch.tensor([1.0, 0.0, 1.0])) + assert torch.allclose(seed.y, torch.tensor([[1.0], [0.0], [1.0]])) assert torch.allclose(seed.weight, torch.tensor([0.5, 1.0, 1.5])) @@ -196,8 +202,11 @@ def test_epoch_second_seed_timestamps_are_normalized_to_ns() -> None: [1_700_000_000, 1_700_000_001], type=pa.int64() ) - hetero, _, _ = runtime_batch_to_hetero(batch, - train_table_name="train_table") + hetero, _, _ = runtime_batch_to_hetero( + batch, + train_table_name="train_table", + target_encoder=NumericalTargetEncoder(0, 1), + ) expected = torch.tensor( [1_700_000_000_000_000_000, 1_700_000_001_000_000_000]) @@ -243,7 +252,7 @@ def test_multiclass_target_record_batch_uses_target_encoder_mapping() -> None: ) -def test_multiclass_target_record_batch_maps_numeric_strings() -> None: +def test_multiclass_target_record_batch_keeps_numeric_strings_unmapped() -> None: batch = _empty_batch(n_inputs=3) batch.task.target = pa.RecordBatch.from_arrays( [pa.array(["1", "2", "1"], type=pa.string())], @@ -263,7 +272,7 @@ def test_multiclass_target_record_batch_maps_numeric_strings() -> None: assert torch.equal( hetero["train_table"].y, - torch.tensor([[1], [0], [1]], dtype=torch.long), + torch.tensor([[-1], [-1], [-1]], dtype=torch.long), ) @@ -293,7 +302,7 @@ def test_multilabel_target_record_batch_builds_multi_nested_tensor() -> None: ) -def test_multilabel_target_record_batch_maps_numeric_strings() -> None: +def test_multilabel_target_record_batch_keeps_numeric_strings_unmapped() -> None: batch = _empty_batch(n_inputs=3) batch.task.target = pa.RecordBatch.from_arrays( [pa.array(["1|2", "", "2"], type=pa.string())], @@ -311,12 +320,8 @@ def test_multilabel_target_record_batch_maps_numeric_strings() -> None: y = hetero["train_table"].y assert isinstance(y, MultiNestedTensor) - assert torch.equal(y.values, torch.tensor([1, 0, 0])) + assert torch.equal(y.values, torch.tensor([-1, -1, -1])) assert torch.equal(y.offset, torch.tensor([0, 2, 2, 3])) - assert torch.equal( - target_encoder.encode_tensor(y), - torch.tensor([[1., 1.], [0., 0.], [1., 0.]]), - ) def test_multilabel_ranking_target_record_batch_builds_multi_nested_tensor( @@ -346,7 +351,7 @@ def test_multilabel_ranking_target_record_batch_builds_multi_nested_tensor( ) -def test_multilabel_ranking_target_record_batch_maps_numeric_strings() -> None: +def test_multilabel_ranking_target_record_batch_keeps_numeric_strings_unmapped() -> None: batch = _empty_batch(n_inputs=3) batch.task.target = pa.RecordBatch.from_arrays( [pa.array(["1|2", "", "2"], type=pa.string())], @@ -364,12 +369,8 @@ def test_multilabel_ranking_target_record_batch_maps_numeric_strings() -> None: y = hetero["train_table"].y assert isinstance(y, MultiNestedTensor) - assert torch.equal(y.values, torch.tensor([1, 0, 0])) + assert torch.equal(y.values, torch.tensor([-1, -1, -1])) assert torch.equal(y.offset, torch.tensor([0, 2, 2, 3])) - assert torch.equal( - target_encoder.encode_tensor(y), - torch.tensor([[1., 1.], [0., 0.], [1., 0.]]), - ) def test_forecasting_skips_seed_y_for_sequence_target() -> None: @@ -435,7 +436,10 @@ def test_columnar_native_batch_shape_matches_diskgraph_iterator_output( ) hetero, raw_features, raw_row_ids = runtime_batch_to_hetero( - batch, train_table_name="train_table", task_type="binary_classification" + batch, + train_table_name="train_table", + task_type="binary_classification", + target_encoder=NumericalTargetEncoder(0, 1), ) assert hetero["train_table"].input_id.tolist() == [0, 1, 2] @@ -458,7 +462,10 @@ def test_columnar_native_batch_shape_matches_diskgraph_iterator_output( def test_populated_batch_returns_raw_features_aligned_with_n_id() -> None: batch = _populated_batch() _, raw_features, raw_row_ids = runtime_batch_to_hetero( - batch, train_table_name="train_table") + batch, + train_table_name="train_table", + target_encoder=NumericalTargetEncoder(0, 1), + ) assert "User" in raw_features rb = raw_features["User"] @@ -495,7 +502,10 @@ def test_record_batches_concat_when_engine_emits_multiple_hops() -> None: ) } _, raw_features, raw_row_ids = runtime_batch_to_hetero( - batch, train_table_name="train_table") + batch, + train_table_name="train_table", + target_encoder=NumericalTargetEncoder(0, 1), + ) assert raw_features["User"].num_rows == 4 assert raw_features["User"].column("age").to_pylist() == [41, 22, 35, 19] @@ -519,8 +529,11 @@ def test_empty_edge_type_lands_as_2x0_tensor() -> None: num_sampled_edges_dict=[], ) } - hetero, _, _ = runtime_batch_to_hetero(batch, - train_table_name="train_table") + hetero, _, _ = runtime_batch_to_hetero( + batch, + train_table_name="train_table", + target_encoder=NumericalTargetEncoder(0, 1), + ) edge_type = ("User", "follows", "User") assert hetero[edge_type].edge_index.shape == (2, 0) assert hetero[edge_type].edge_index.dtype == torch.long @@ -572,6 +585,7 @@ def test_bidirectional_output_reuses_pyg_reverse_edge_transform() -> None: batch, train_table_name="train_table", bidirectional_output=True, + target_encoder=NumericalTargetEncoder(0, 1), ) forward = ("transactions", "article_id", "articles") @@ -630,8 +644,11 @@ def test_unsampled_schema_node_types_are_backfilled_empty() -> None: ], ) } - hetero, _, _ = runtime_batch_to_hetero(batch, - train_table_name="train_table") + hetero, _, _ = runtime_batch_to_hetero( + batch, + train_table_name="train_table", + target_encoder=NumericalTargetEncoder(0, 1), + ) # Every schema node type is present; the unsampled ones are empty blocks. assert "products" in hetero.node_types assert "ratings" in hetero.node_types @@ -681,6 +698,7 @@ def test_grouped_lp_batch_missing_rhs_has_empty_rhs_block() -> None: hetero, _, _ = runtime_batch_to_hetero( batch, train_table_name="train_table", + target_encoder=NumericalTargetEncoder(0, 1), ) # node_id_dict (what shallow_rhs/hybrid forward read) always has the RHS. node_id_dict = { @@ -701,13 +719,16 @@ def test_partial_optional_columns_are_skipped() -> None: [1_700_000_000, None, 1_700_600_000], type=pa.int64() ) batch.task.weight = pa.array([0.5, None, 1.5], type=pa.float64()) - hetero, _, _ = runtime_batch_to_hetero(batch, - train_table_name="train_table") + hetero, _, _ = runtime_batch_to_hetero( + batch, + train_table_name="train_table", + target_encoder=NumericalTargetEncoder(0, 1), + ) seed = hetero["train_table"] assert "time" not in seed assert "weight" not in seed # target was fully populated, so it survives. - assert torch.equal(seed.y, torch.tensor([0.0, 1.0, 0.0])) + assert torch.equal(seed.y, torch.tensor([[0.0], [1.0], [0.0]])) def _user_mapper_bank() -> dict[str, dict[str, TensorMapper]]: @@ -734,7 +755,10 @@ def test_attach_tensor_frames_populates_hetero_tf() -> None: RecordBatch via get_tf, and attaches hetero[ns].tf.""" batch = _populated_batch() hetero, raw_features, _ = runtime_batch_to_hetero( - batch, train_table_name="train_table") + batch, + train_table_name="train_table", + target_encoder=NumericalTargetEncoder(0, 1), + ) # Replace the sample RecordBatch with an `age`-only one so the # mapper bank fitted above lines up. age_only = pa.RecordBatch.from_arrays( @@ -770,6 +794,7 @@ def test_runtime_batch_to_hetero_attaches_tf_when_mapper_bank_passed() -> None: train_table_name="train_table", mapper_bank=_user_mapper_bank(), feature_schema=_user_feature_schema(), + target_encoder=NumericalTargetEncoder(0, 1), ) assert hasattr(hetero["User"], "tf") @@ -934,6 +959,7 @@ def test_backfilled_type_with_mapper_gets_empty_shaped_tf() -> None: train_table_name="train_table", mapper_bank=_user_mapper_bank(), feature_schema=_user_feature_schema(), + target_encoder=NumericalTargetEncoder(0, 1), ) assert "User" in hetero.node_types assert hetero["User"].n_id.numel() == 0 @@ -992,12 +1018,14 @@ def test_runtime_batch_to_hetero_rejects_partial_mapper_args() -> None: batch, train_table_name="train_table", mapper_bank=_user_mapper_bank(), + target_encoder=NumericalTargetEncoder(0, 1), ) with pytest.raises(ValueError, match="both be provided"): runtime_batch_to_hetero( batch, train_table_name="train_table", feature_schema=_user_feature_schema(), + target_encoder=NumericalTargetEncoder(0, 1), ) @@ -1098,13 +1126,21 @@ def test_multi_channel_runtime_uses_requested_channel() -> None: } lhs, _, lhs_row_ids = runtime_batch_to_hetero( - batch, train_table_name="train_table", channel="lhs") + batch, + train_table_name="train_table", + channel="lhs", + target_encoder=NumericalTargetEncoder(0, 1), + ) assert "User" in lhs.node_types assert "Item" not in lhs.node_types assert torch.equal(lhs_row_ids["User"], torch.tensor([10])) rhs, _, rhs_row_ids = runtime_batch_to_hetero( - batch, train_table_name="train_table", channel="rhs") + batch, + train_table_name="train_table", + channel="rhs", + target_encoder=NumericalTargetEncoder(0, 1), + ) assert "Item" in rhs.node_types assert "User" not in rhs.node_types # rhs feature side: User block isn't in this channel, so no row_ids. @@ -1374,6 +1410,7 @@ def test_neighbor_node_time_normalized_to_ns_int64_seconds() -> None: train_table_name="train_table", task_type="binary_classification", time_col_dict={"User": "event_time"}, + target_encoder=NumericalTargetEncoder(0, 1), ) assert hetero["User"].time.tolist() == [ 1700 * 1_000_000_000, 1701 * 1_000_000_000 @@ -1417,6 +1454,7 @@ def test_neighbor_node_time_timestamp_resolution_normalized_to_ns() -> None: train_table_name="train_table", task_type="binary_classification", time_col_dict={"User": "event_time"}, + target_encoder=NumericalTargetEncoder(0, 1), ) assert hetero["User"].time.tolist() == [SEC * 1_000_000_000] @@ -1510,6 +1548,7 @@ def test_ttng_seed_supervision_relation_not_backfilled_as_node_type() -> None: task_type="binary_classification", mapper_bank=mapper_bank, feature_schema=feature_schema, + target_encoder=NumericalTargetEncoder(0, 1), ) node_types = set(hetero.node_types) @@ -1536,6 +1575,7 @@ def test_legacy_path_without_feature_schema_keeps_edge_endpoint_backfill( train_table_name="train_table", seed_node_type="products", task_type="binary_classification", + target_encoder=NumericalTargetEncoder(0, 1), ) node_types = set(hetero.node_types) # Legacy back-fill DOES create the edge-endpoint blocks (unchanged behavior). @@ -1678,6 +1718,7 @@ def _to_hetero_with_txns( pk_col_dict={"Transaction": "txn_id"}, time_col_dict={"Transaction": "created_at"}, attach_pkeys=attach_pkeys, + target_encoder=NumericalTargetEncoder(0, 1), ) return hetero @@ -1724,6 +1765,7 @@ def test_skipped_namespace_still_gets_a_tensor_frame(num_nodes: int) -> None: "links_v1": {}, }, feature_schema=_link_feature_schema(), + target_encoder=NumericalTargetEncoder(0, 1), ) assert "Ownership" not in raw_features, ( @@ -1762,6 +1804,7 @@ def test_featureless_train_predict_encoder_parity( mapper_bank=mapper_bank, feature_schema=schema, attach_pkeys=False, + target_encoder=NumericalTargetEncoder(0, 1), ) batch = _link_batch() batch.raw_features["Ownership"] = RuntimeFeatureBlock( @@ -1774,6 +1817,7 @@ def test_featureless_train_predict_encoder_parity( mapper_bank=mapper_bank, feature_schema=schema, pk_col_dict={"Ownership": "ownership_id"}, + target_encoder=NumericalTargetEncoder(0, 1), ) encoder = TensorFrameEncoder( name="Ownership", @@ -1806,6 +1850,7 @@ def test_skipping_a_namespace_leaves_topology_untouched() -> None: "links_v1": {}, }, feature_schema=_link_feature_schema(), + target_encoder=NumericalTargetEncoder(0, 1), ) assert hetero["Ownership"].num_nodes == 2 diff --git a/test/train/datamodule/test_diskgraph_lightning_data.py b/test/train/datamodule/test_diskgraph_lightning_data.py index 417afaf49b..77a7924576 100644 --- a/test/train/datamodule/test_diskgraph_lightning_data.py +++ b/test/train/datamodule/test_diskgraph_lightning_data.py @@ -43,6 +43,7 @@ DiskgraphValidRHS, _ShuffleStreamState, ) +from kumo_core.encoders.target.numerical import NumericalTargetEncoder from kumo_core.encoders.tensor_mapper import ( CategoricalTensorMapper, NumericalTensorMapper, @@ -428,6 +429,7 @@ def _run_shutdown_probe_consumer(ready_fd: int, release_fd: int) -> None: eval_batch_size=1, num_workers=2, prefetch_factor=2, + target_encoder=NumericalTargetEncoder(0, 1), ) dm._pk_col_dict = {"User": "pk"} dm._time_col_dict = {} @@ -632,6 +634,7 @@ def test_constructor_reads_train_table_name_and_schema() -> None: sampling_plan=SamplingPlan(), train_batch_size=2, eval_batch_size=1, + target_encoder=NumericalTargetEncoder(0, 1), ) assert dm._train_table_name == "my_train" assert dm._feature_schema["node_types"]["User"]["mapper_key"] == "users_v1" @@ -656,6 +659,7 @@ def test_split_info_bounds_drive_native_stage_times(tmp_path) -> None: sampling_plan=SamplingPlan(), train_batch_size=2, eval_batch_size=1, + target_encoder=NumericalTargetEncoder(0, 1), ) assert dm._stage_time_dict == { @@ -698,6 +702,7 @@ def test_constructor_rejects_missing_train_table_name() -> None: sampling_plan=SamplingPlan(), train_batch_size=2, eval_batch_size=1, + target_encoder=NumericalTargetEncoder(0, 1), ) @@ -715,6 +720,7 @@ def test_set_shuffle_stream_id_propagates_to_task_iterator( train_batch_size=2, eval_batch_size=1, base_seed=10, + target_encoder=NumericalTargetEncoder(0, 1), ) dm.set_shuffle_stream_id(7) list(dm.train_dataloader()) @@ -761,6 +767,7 @@ def test_train_dataloader_len_honors_max_steps_per_epoch(tmp_path, ) -> None: train_batch_size=10, eval_batch_size=1, max_steps_per_epoch=3, + target_encoder=NumericalTargetEncoder(0, 1), ) assert len(dm.train_dataloader()) == 3 @@ -777,6 +784,7 @@ def test_train_dataloader_iteration_stops_at_max_steps_per_epoch( train_batch_size=10, eval_batch_size=1, max_steps_per_epoch=3, + target_encoder=NumericalTargetEncoder(0, 1), ) assert len(list(dm.train_dataloader())) == 3 assert len(calls["history"]) == 1 @@ -800,6 +808,7 @@ def test_lightning_fit_reopens_train_iterator_with_new_shuffle_stream( train_batch_size=2, eval_batch_size=1, max_steps_per_epoch=1, + target_encoder=NumericalTargetEncoder(0, 1), ) model = _fit_smoke_model(dm) @@ -820,6 +829,7 @@ def test_lightning_epoch_ends_after_configured_train_batches( train_batch_size=10, eval_batch_size=1, max_steps_per_epoch=3, + target_encoder=NumericalTargetEncoder(0, 1), ) model = _fit_smoke_model(dm) @@ -841,6 +851,7 @@ def test_epoch_cap_does_not_change_wheel_training_population( train_batch_size=10, eval_batch_size=1, max_steps_per_epoch=3, + target_encoder=NumericalTargetEncoder(0, 1), ) model = _fit_smoke_model(dm, max_epochs=1) @@ -861,6 +872,7 @@ def test_train_dataloader_len_honors_min_steps_per_epoch(tmp_path, ) -> None: train_batch_size=10, eval_batch_size=1, min_steps_per_epoch=3, + target_encoder=NumericalTargetEncoder(0, 1), ) assert len(dm.train_dataloader()) == 3 @@ -897,6 +909,7 @@ def test_train_iter_replays_wheel_when_natural_lt_max_batches( train_batch_size=10, eval_batch_size=1, min_steps_per_epoch=5, + target_encoder=NumericalTargetEncoder(0, 1), ) # Advertised length. assert len(dm.train_dataloader()) == 5 @@ -928,6 +941,7 @@ def test_val_dataloader_does_not_replay_wheel_iterator( sampling_plan=SamplingPlan(), train_batch_size=2, eval_batch_size=1, + target_encoder=NumericalTargetEncoder(0, 1), ) batches = list(dm.val_dataloader()) assert len(batches) == 2 @@ -957,6 +971,7 @@ def test_eval_dataloader_honors_max_steps_without_replay( train_batch_size=2, eval_batch_size=2, **{f"max_{stage}_steps": max_steps}, + target_encoder=NumericalTargetEncoder(0, 1), ) loader = getattr(dm, f"{stage}_dataloader") @@ -977,6 +992,7 @@ def test_predict_dataloader_len_counts_local_worker_shards(tmp_path) -> None: train_batch_size=1024, eval_batch_size=1024, num_workers=16, + target_encoder=NumericalTargetEncoder(0, 1), ) assert len(dm.predict_dataloader()) == 208 @@ -1003,6 +1019,7 @@ def test_train_dataloader_chains_refit_stages( train_batch_size=1, eval_batch_size=1, train_stages=("train", "val"), + target_encoder=NumericalTargetEncoder(0, 1), ) batches = list(dm.train_dataloader()) @@ -1036,6 +1053,7 @@ def test_capped_refit_interleaves_all_training_stages( eval_batch_size=1, max_steps_per_epoch=10, train_stages=("train", "val"), + target_encoder=NumericalTargetEncoder(0, 1), ) batches = list(dm.train_dataloader().dataset) @@ -1065,6 +1083,7 @@ def test_runtime_options_are_passed_to_wheel_iterator( "disjoint": False, "adaptive": True }, + target_encoder=NumericalTargetEncoder(0, 1), ) list(dm.train_dataloader()) @@ -1113,6 +1132,7 @@ def test_binary_weighted_seed_sampling_sets_train_epoch_length_and_runtime_optio "false_weight": 1.0, "true_weight": 9.0, }, + target_encoder=NumericalTargetEncoder(0, 1), ) loader = dm.train_dataloader() @@ -1179,6 +1199,7 @@ def test_weighted_seed_sampling_allocates_across_refit_stages( "false_weight": 1.0, "true_weight": 9.0, }, + target_encoder=NumericalTargetEncoder(0, 1), ) batches = list(dm.train_dataloader().dataset) @@ -1224,6 +1245,7 @@ def test_weighted_seed_sampling_validates_every_refit_stage(tmp_path, ) -> None: "false_weight": 1.0, "true_weight": 9.0, }, + target_encoder=NumericalTargetEncoder(0, 1), ) @@ -1265,6 +1287,7 @@ def test_binary_weighted_seed_sampling_rejects_drop_last_train( "false_weight": 1.0, "true_weight": 9.0, }, + target_encoder=NumericalTargetEncoder(0, 1), ) with pytest.raises(ValueError, match="drop_last_train=True"): @@ -1355,6 +1378,7 @@ def test_weighted_seed_sampling_uses_row_weight_mass_for_epoch_length( max_steps_per_epoch=4, min_steps_per_epoch=1, weighted_seed_sampling={"use_sample_weights": True}, + target_encoder=NumericalTargetEncoder(0, 1), ) list(dm.train_dataloader()) @@ -1418,6 +1442,7 @@ def test_weighted_seed_sampling_combines_row_and_class_weight_mass( "false_weight": 1.0, "true_weight": 2.0, }, + target_encoder=NumericalTargetEncoder(0, 1), ) list(dm.train_dataloader()) @@ -1445,6 +1470,7 @@ def test_each_stage_method_passes_correct_stage( sampling_plan=SamplingPlan(), train_batch_size=2, eval_batch_size=1, + target_encoder=NumericalTargetEncoder(0, 1), ) _ = list(getattr(dm, method_name)()) assert calls["kwargs"]["stage"] == stage @@ -1459,6 +1485,7 @@ def test_dataloader_yields_hetero_from_task_batch_iterator( sampling_plan=SamplingPlan(), train_batch_size=2, eval_batch_size=1, + target_encoder=NumericalTargetEncoder(0, 1), ) batches = list(dm.train_dataloader()) assert len(batches) == 1 @@ -1478,6 +1505,7 @@ def test_explain_selection_capture_returns_stage_node_ids() -> None: sampling_plan=SamplingPlan(), train_batch_size=2, eval_batch_size=2, + target_encoder=NumericalTargetEncoder(0, 1), ) dm.begin_explain_selection_capture("test") @@ -1499,6 +1527,7 @@ def test_stage_inputs_requires_explain_selection_capture() -> None: sampling_plan=SamplingPlan(), train_batch_size=2, eval_batch_size=2, + target_encoder=NumericalTargetEncoder(0, 1), ) with pytest.raises(RuntimeError, match="explain selection capture"): @@ -1516,6 +1545,7 @@ def test_explain_dataloader_uses_selected_stage_node_ids( eval_batch_size=2, num_workers=3, persistent_workers=True, + target_encoder=NumericalTargetEncoder(0, 1), ) loader = dm.explain_dataloader("test", torch.tensor([10, 12])) @@ -1539,6 +1569,7 @@ def test_explain_dataloader_maps_pred_stage_to_predict_runtime_stage( sampling_plan=SamplingPlan(), train_batch_size=2, eval_batch_size=2, + target_encoder=NumericalTargetEncoder(0, 1), ) list(dm.explain_dataloader("pred", torch.tensor([10, 12]))) @@ -1557,6 +1588,7 @@ def test_explain_dataloader_pred_resolves_only_entity( eval_batch_size=2, resolve_entity_node_type="User", resolve_target_node_type="Article", + target_encoder=NumericalTargetEncoder(0, 1), ) list(dm.explain_dataloader("test", torch.tensor([10, 12]))) @@ -1593,6 +1625,7 @@ def test_explain_selection_capture_forces_single_worker_eval_loader() -> None: eval_batch_size=2, num_workers=4, persistent_workers=True, + target_encoder=NumericalTargetEncoder(0, 1), ) dm.begin_explain_selection_capture("test") @@ -1613,6 +1646,7 @@ def test_pred_explain_selection_capture_forces_single_worker_predict_loader( eval_batch_size=2, num_workers=4, persistent_workers=True, + target_encoder=NumericalTargetEncoder(0, 1), ) dm.begin_explain_selection_capture("pred") @@ -1635,6 +1669,7 @@ def test_dataloader_passes_through_loader_kwargs( num_workers=2, pin_memory=True, persistent_workers=True, + target_encoder=NumericalTargetEncoder(0, 1), ) loader = dm.train_dataloader() assert loader.num_workers == 2 @@ -1653,6 +1688,7 @@ def test_dataloader_passes_through_prefetch_factor( eval_batch_size=1, num_workers=2, prefetch_factor=4, + target_encoder=NumericalTargetEncoder(0, 1), ) assert dm.train_dataloader().prefetch_factor == 4 @@ -2424,6 +2460,7 @@ def test_worker_pool_callback_closes_truncated_and_failed_phases( sampling_plan=SamplingPlan(), train_batch_size=2, eval_batch_size=1, + target_encoder=NumericalTargetEncoder(0, 1), ) phases = [] monkeypatch.setattr(dm, 'shutdown_dataloader_workers', phases.append) @@ -2447,6 +2484,7 @@ def test_predict_callback_deferral_does_not_skip_writer_owned_barrier( sampling_plan=SamplingPlan(), train_batch_size=2, eval_batch_size=1, + target_encoder=NumericalTargetEncoder(0, 1), ) events = [] monkeypatch.setattr( @@ -2472,6 +2510,7 @@ def test_predict_worker_shutdown_deferral_is_nested_and_base_exception_safe( sampling_plan=SamplingPlan(), train_batch_size=2, eval_batch_size=1, + target_encoder=NumericalTargetEncoder(0, 1), ) with pytest.raises(KeyboardInterrupt, match='synthetic cancellation'): @@ -2490,6 +2529,7 @@ def test_worker_pool_callback_reaps_processes_on_exception() -> None: sampling_plan=SamplingPlan(), train_batch_size=2, eval_batch_size=1, + target_encoder=NumericalTargetEncoder(0, 1), ) loader = _worker_pool_loader( dm._worker_pool_registry, @@ -2614,6 +2654,7 @@ def test_setup_does_not_duplicate_explicit_worker_lifecycle_callback() -> None: sampling_plan=SamplingPlan(), train_batch_size=2, eval_batch_size=1, + target_encoder=NumericalTargetEncoder(0, 1), ) callback = dm.worker_pool_lifecycle_callback() dm.trainer = types.SimpleNamespace(callbacks=[callback]) @@ -2636,6 +2677,7 @@ def test_prefetch_factor_is_not_set_without_workers( eval_batch_size=1, num_workers=0, prefetch_factor=4, + target_encoder=NumericalTargetEncoder(0, 1), ) assert dm.train_dataloader().prefetch_factor is None @@ -2653,6 +2695,7 @@ def test_prefetch_factor_below_one_is_rejected_early(bad: int) -> None: eval_batch_size=1, num_workers=2, prefetch_factor=bad, + target_encoder=NumericalTargetEncoder(0, 1), ) @@ -2843,6 +2886,7 @@ def _rhs_dm( train_batch_size=2, eval_batch_size=eval_batch_size, task_type="temporal_link_prediction", + target_encoder=NumericalTargetEncoder(0, 1), ) @@ -3291,6 +3335,7 @@ def test_temporal_lp_train_loader_enables_grouping( eval_batch_size=10, task_type=_TEMPORAL_LP, use_lhs_node_loader=True, + target_encoder=NumericalTargetEncoder(0, 1), ) list(dm.train_dataloader()) @@ -3325,6 +3370,7 @@ def test_static_lp_with_lhs_loader_and_temporal_rhs_groups( eval_batch_size=10, task_type="static_link_prediction", use_lhs_node_loader=True, + target_encoder=NumericalTargetEncoder(0, 1), ) list(dm.train_dataloader()) assert calls["history"] @@ -3346,6 +3392,7 @@ def test_non_lp_task_never_groups( eval_batch_size=10, task_type="regression", use_lhs_node_loader=True, + target_encoder=NumericalTargetEncoder(0, 1), ) list(dm.train_dataloader()) assert calls["history"] @@ -3369,6 +3416,7 @@ def test_two_tower_no_lhs_loader_does_not_group( task_type=_TEMPORAL_LP, rhs_node_type="products", use_lhs_node_loader=False, + target_encoder=NumericalTargetEncoder(0, 1), ) list(dm.train_dataloader()) assert calls["history"] @@ -3439,6 +3487,7 @@ def test_atemporal_rhs_temporal_lp_train_loader_does_not_group( eval_batch_size=10, task_type=_TEMPORAL_LP, rhs_node_type="products", + target_encoder=NumericalTargetEncoder(0, 1), ) # Fake manifest has no index metadata -> time_col_dict empty -> # _rhs_is_temporal is False. @@ -3468,6 +3517,7 @@ def test_temporal_rhs_temporal_lp_train_loader_groups( task_type=_TEMPORAL_LP, rhs_node_type="products", use_lhs_node_loader=True, + target_encoder=NumericalTargetEncoder(0, 1), ) # Simulate a temporal RHS: products has a create-time column. monkeypatch.setattr(type(dm), "time_col_dict", @@ -3492,6 +3542,7 @@ def test_rhs_is_temporal_end_time_only( eval_batch_size=10, task_type=_TEMPORAL_LP, rhs_node_type="products", + target_encoder=NumericalTargetEncoder(0, 1), ) # No create-time column, but an end-time column is present. monkeypatch.setattr(type(dm), "time_col_dict", property(lambda self: {})) @@ -3509,6 +3560,7 @@ def test_rhs_is_temporal_false_without_rhs_node_type(tmp_path, ) -> None: train_batch_size=10, eval_batch_size=10, task_type=_TEMPORAL_LP, + target_encoder=NumericalTargetEncoder(0, 1), ) assert dm._rhs_is_temporal is False @@ -3534,6 +3586,7 @@ def test_grouped_train_len_uses_true_batch_count_not_ceil( eval_batch_size=10, task_type=_TEMPORAL_LP, use_lhs_node_loader=True, + target_encoder=NumericalTargetEncoder(0, 1), ) loader = dm.train_dataloader() # __len__ is the true grouped batch count (5), strictly greater than the @@ -3549,6 +3602,7 @@ def test_grouped_train_len_uses_true_batch_count_not_ceil( train_batch_size=10, eval_batch_size=10, task_type="static_link_prediction", + target_encoder=NumericalTargetEncoder(0, 1), ) assert len(flat_dm.train_dataloader()) == 2 @@ -3572,6 +3626,7 @@ def test_grouped_train_iter_does_not_truncate( eval_batch_size=10, task_type=_TEMPORAL_LP, use_lhs_node_loader=True, + target_encoder=NumericalTargetEncoder(0, 1), ) loader = dm.train_dataloader() advertised = len(loader) @@ -3602,6 +3657,7 @@ def test_grouped_train_len_honors_step_caps( min_steps_per_epoch=2, task_type=_TEMPORAL_LP, use_lhs_node_loader=True, + target_encoder=NumericalTargetEncoder(0, 1), ) loader = dm.train_dataloader() assert len(loader) == 3 @@ -3628,6 +3684,7 @@ def test_grouped_num_samples_not_divided_by_batch_size( eval_batch_size=128, task_type=_TEMPORAL_LP, use_lhs_node_loader=True, + target_encoder=NumericalTargetEncoder(0, 1), ) # If counts were treated as a single row count it would be //128 -> 0/1. assert len(dm.train_dataloader()) == 7 @@ -3755,6 +3812,7 @@ def test_grouped_multistage_refit_spans_all_stages( train_stages=("train", "val"), task_type=_TEMPORAL_LP, use_lhs_node_loader=True, + target_encoder=NumericalTargetEncoder(0, 1), ) loader = dm.train_dataloader() # __len__ == capped(global train+val grouped count) = 3 + 5 = 8. @@ -3812,6 +3870,7 @@ def test_grouped_global_cap_distributed_across_workers( max_steps_per_epoch=6, task_type=_TEMPORAL_LP, use_lhs_node_loader=True, + target_encoder=NumericalTargetEncoder(0, 1), ) loader = dm.train_dataloader() # __len__ is the GLOBAL capped count (6), exactly as the flat path would @@ -3857,6 +3916,7 @@ def test_grouped_global_cap_min_steps_distributed( num_workers=2, min_steps_per_epoch=8, # bites: floors global 4 -> 8 task_type=_TEMPORAL_LP, + target_encoder=NumericalTargetEncoder(0, 1), ) loader = dm.train_dataloader() assert len(loader) == 8 # global floored to min, then advertised @@ -4011,6 +4071,7 @@ def test_train_dataloader_sets_fork_context_when_workers(tmp_path) -> None: train_batch_size=10, eval_batch_size=1, num_workers=4, + target_encoder=NumericalTargetEncoder(0, 1), ) loader = dm.train_dataloader() context = loader.multiprocessing_context @@ -4030,6 +4091,7 @@ def test_train_dataloader_no_context_when_single_process(tmp_path) -> None: train_batch_size=10, eval_batch_size=1, num_workers=0, + target_encoder=NumericalTargetEncoder(0, 1), ) loader = dm.train_dataloader() assert loader.multiprocessing_context is None @@ -4239,6 +4301,7 @@ def _projection_datamodule( sampling_plan=SamplingPlan([LayerSpec(fanouts={})]), train_batch_size=2, eval_batch_size=2, + target_encoder=NumericalTargetEncoder(0, 1), ) @@ -4521,6 +4584,7 @@ def test_feature_projection_is_empty_without_a_schema(tmp_path) -> None: sampling_plan=SamplingPlan(), train_batch_size=2, eval_batch_size=1, + target_encoder=NumericalTargetEncoder(0, 1), ) dm._feature_schema = {"node_types": {}} diff --git a/test/train/test_diskgraph_nested_trainer.py b/test/train/test_diskgraph_nested_trainer.py index 8e72a70231..a8f61ae08a 100644 --- a/test/train/test_diskgraph_nested_trainer.py +++ b/test/train/test_diskgraph_nested_trainer.py @@ -2072,6 +2072,7 @@ def test_eval_df_uses_adapter_normalized_seed_time() -> None: hetero, _, _ = runtime_batch_to_hetero( batch, train_table_name="train_table", + target_encoder=_reg_target_encoder(), index_np_time_unit="s", ) seed_time = hetero["train_table"].time From 41bf0be9076ca6c6f85b5f23dea8ffc72a512e26 Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Thu, 3 Dec 2026 19:50:12 +0000 Subject: [PATCH 3/7] Preserve target category types and reject unknown supervised labels --- .../src/custom_tt_chunk_processor.rs | 17 +- .../src/ttgen_executor.rs | 9 +- .../diskgraph-train-table/src/ttgen_stats.rs | 290 ++++++++++++------ .../tests/custom_tt_integration.rs | 50 +++ .../tests/ttgen_integration.rs | 34 ++ .../src/kumo_core/encoders/target/base.py | 3 +- .../src/kumo_core/encoders/tensor_mapper.py | 102 ++++-- .../encoders/test_strict_target_mapping.py | 146 +++++++++ 8 files changed, 515 insertions(+), 136 deletions(-) create mode 100644 packages/kumo-core/tests/encoders/test_strict_target_mapping.py diff --git a/packages/diskgraph/diskgraph-train-table/src/custom_tt_chunk_processor.rs b/packages/diskgraph/diskgraph-train-table/src/custom_tt_chunk_processor.rs index c6a1f7c8f2..eead79a870 100644 --- a/packages/diskgraph/diskgraph-train-table/src/custom_tt_chunk_processor.rs +++ b/packages/diskgraph/diskgraph-train-table/src/custom_tt_chunk_processor.rs @@ -645,16 +645,13 @@ pub(crate) fn custom_tt_chunk_processor + Clon // Read the actual target dtype the chunk processor will emit (resolved // from the customer parquet schema in `output_mode_for_custom_tt`), // not from `plan.primary_target_dtype()` — that helper falls through - // to `Float64` for empty-stages custom-TT plans, which would lose the - // Boolean signal needed for JSON-bool CATEGORY_COUNTS emission. - let actual_target_is_bool = match &mode { - OutputMode::Node { target_dtypes } => { - matches!(target_dtypes.first(), Some(DataType::Boolean)) + // to `Float64` for empty-stages custom-TT plans. CATEGORY_COUNTS must + // preserve the customer's physical label type. + let actual_target_dtype = match &mode { + OutputMode::Node { target_dtypes } | OutputMode::LinkArray { target_dtypes, .. } => { + target_dtypes.first().cloned() } - OutputMode::LinkArray { target_dtypes, .. } => { - matches!(target_dtypes.first(), Some(DataType::Boolean)) - } - OutputMode::PassThrough | OutputMode::Forecasting { .. } => false, + OutputMode::PassThrough | OutputMode::Forecasting { .. } => None, }; let time_col_name = plan .entity_table_spec @@ -714,7 +711,7 @@ pub(crate) fn custom_tt_chunk_processor + Clon } ); let mut stats: ChunkStats = ChunkStats { - target_is_bool_dtype: actual_target_is_bool, + target_dtype: actual_target_dtype, ..ChunkStats::default() }; if target_is_numerical { diff --git a/packages/diskgraph/diskgraph-train-table/src/ttgen_executor.rs b/packages/diskgraph/diskgraph-train-table/src/ttgen_executor.rs index 44fbefb706..198a75b5e8 100644 --- a/packages/diskgraph/diskgraph-train-table/src/ttgen_executor.rs +++ b/packages/diskgraph/diskgraph-train-table/src/ttgen_executor.rs @@ -1049,7 +1049,7 @@ where target_category_counts, target_stype_str.as_str(), entity_category_counts, - ); + )?; // ── Fused pass-B by mode → per-stage seed parts ────────────────────── // @@ -1739,13 +1739,8 @@ fn execute_chunk + Clone>( } ); - // Propagate the resolved target dtype into the stats accumulator so - // bool-target CATEGORY_COUNTS emits JSON booleans (matches the - // BooleanArray downcast in tt_executor.rs:compute_train_table_col_stats_payload - // for the rehydration path; without this the ttgen path silently - // emits lowercase "true"/"false" strings). let mut stats: ChunkStats = ChunkStats { - target_is_bool_dtype: matches!(plan.primary_target_dtype(), DataType::Boolean), + target_dtype: Some(plan.primary_target_dtype().clone()), ..ChunkStats::default() }; if target_is_numerical { diff --git a/packages/diskgraph/diskgraph-train-table/src/ttgen_stats.rs b/packages/diskgraph/diskgraph-train-table/src/ttgen_stats.rs index 489e49fa27..722c07b103 100644 --- a/packages/diskgraph/diskgraph-train-table/src/ttgen_stats.rs +++ b/packages/diskgraph/diskgraph-train-table/src/ttgen_stats.rs @@ -5,10 +5,12 @@ use std::collections::HashMap; use arrow_array::{Array, ListArray}; +use arrow_schema::DataType; use serde::{Deserialize, Serialize}; use serde_json::{json, Value as JsonValue}; use crate::custom_tt_row_errors::SourceRowStats; +use crate::errors::{TTGenError, TTGenResult}; #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct SequenceFeatureStats { @@ -191,11 +193,8 @@ pub(crate) struct ChunkStats { pub(crate) timestamp_welford: Option, pub(crate) timestamp_tdigest: Option, pub(crate) timestamp_hll: Option, - /// Mirrors the StatsMerger field. Set once per chunk from - /// ``plan.primary_target_dtype() == DataType::Boolean`` and OR'd into the - /// merger so CATEGORY_COUNTS emits JSON booleans (not lowercase - /// strings) for bool targets. - pub(crate) target_is_bool_dtype: bool, + /// Physical target type used to restore typed category values at publication. + pub(crate) target_dtype: Option, pub(crate) sequence_feature_stats: HashMap, /// Custom-TT row validation tally; untouched on the PQL path. pub(crate) source_rows: SourceRowStats, @@ -231,7 +230,7 @@ impl Default for ChunkStats { timestamp_welford: None, timestamp_tdigest: None, timestamp_hll: None, - target_is_bool_dtype: false, + target_dtype: None, sequence_feature_stats: HashMap::new(), source_rows: SourceRowStats::default(), } @@ -269,9 +268,7 @@ pub(crate) struct StatsMerger { timestamp_welford: Option, timestamp_tdigest: Option, timestamp_hll: Option, - /// True when the TARGET Arrow column was BooleanArray. Required so - /// CATEGORY_COUNTS gets emitted as JSON booleans (matching GE/Spark). - pub(crate) target_is_bool_dtype: bool, + pub(crate) target_dtype: Option, pub(crate) sequence_feature_stats: HashMap, pub(crate) source_rows: SourceRowStats, } @@ -305,7 +302,7 @@ impl Default for StatsMerger { timestamp_welford: None, timestamp_tdigest: None, timestamp_hll: None, - target_is_bool_dtype: false, + target_dtype: None, sequence_feature_stats: HashMap::new(), source_rows: SourceRowStats::default(), } @@ -406,9 +403,9 @@ impl StatsMerger { .get_or_insert_with(HyperLogLog::new) .merge(&chunk_h); } - // Sticky: any chunk that observed a bool target column flips the - // merger flag for the rest of the run. - self.target_is_bool_dtype |= chunk.target_is_bool_dtype; + if chunk.target_dtype.is_some() { + self.target_dtype = chunk.target_dtype; + } for (name, stats) in chunk.sequence_feature_stats { self.sequence_feature_stats @@ -428,7 +425,7 @@ impl StatsMerger { target_category_counts: Option>, target_stype: &str, entity_category_counts: Option>, - ) -> TrainTableStatsPayload { + ) -> TTGenResult { // Cardinality is HLL-only. For PassThrough or any path // that left the HLL as None, fall back to 0 — same defensive value // the prior empty-HashSet branch returned. @@ -573,7 +570,7 @@ impl StatsMerger { "v1", target_category_counts, target_stype, - self.target_is_bool_dtype, + self.target_dtype.as_ref(), &self.entity_hll, &self.entity_welford, &mut self.entity_tdigest, @@ -582,10 +579,10 @@ impl StatsMerger { &mut self.timestamp_tdigest, &self.timestamp_hll, self.sequence_feature_stats.clone(), - ) + )? }; - TrainTableStatsPayload { + Ok(TrainTableStatsPayload { version: 2, num_total_rows, num_train_rows: self.num_train_rows, @@ -605,7 +602,7 @@ impl StatsMerger { frequency: frequency_stats, entity_include_bit: include_bit_stats, }, - } + }) } } @@ -625,7 +622,7 @@ pub fn build_inline_col_stats( data_version: &str, target_category_counts: Option>, target_stype: &str, - target_is_bool_dtype: bool, + target_dtype: Option<&DataType>, entity_hll: &Option, entity_welford: &Option, entity_tdigest: &mut Option, @@ -634,7 +631,7 @@ pub fn build_inline_col_stats( timestamp_tdigest: &mut Option, timestamp_hll: &Option, sequence_feature_stats: HashMap, -) -> Option { +) -> TTGenResult> { let mut stats = serde_json::Map::new(); let dv = data_version; @@ -694,33 +691,15 @@ pub fn build_inline_col_stats( kumo_entry(json!(0.0), false, dv, count), ); - // CATEGORY_COUNTS: [[key, count], ...] - // - // For boolean targets we emit JSON booleans (true/false), not - // strings, so the kumo encoder builds its mapping with bool keys - // — matching pandas/GE behaviour. Otherwise pd.Series.map() over - // a bool column with string keys yields all-NaN -> all -1, and - // the trainer fails the val-imbalance check on the first batch. let mut pairs: Vec<(&String, &u64)> = cat_counts.iter().collect(); - pairs.sort_by(|a, b| b.1.cmp(a.1)); // descending by count - // target_stype "boolean" OR Arrow BooleanArray rehydration both - // signal that the kumo encoder will see a bool-dtype column. - let target_is_boolean = target_stype == "boolean" || target_is_bool_dtype; - let category_array: Vec = pairs + pairs.sort_by(|a, b| b.1.cmp(a.1)); + let category_array = pairs .iter() - .map(|(k, c)| { - let key_value = if target_is_boolean { - match k.as_str() { - "true" => json!(true), - "false" => json!(false), - _ => json!(k), - } - } else { - json!(k) - }; - json!([key_value, c]) + .map(|(key, count)| { + let value = typed_target_category(key, target_dtype)?; + Ok(json!([value, count])) }) - .collect(); + .collect::>>()?; stats.insert( kumo_key(name, stype, "CATEGORY_COUNTS", false), kumo_entry(json!(category_array), false, dv, count), @@ -767,7 +746,21 @@ pub fn build_inline_col_stats( Some("|"), // standard LIST_DISTINCT delimiter &sorted_cats, ); - for (key, value) in pairs { + let category_dtype = match target_dtype { + Some( + DataType::List(field) + | DataType::LargeList(field) + | DataType::FixedSizeList(field, _), + ) => Some(field.data_type()), + _ => None, + }; + let category_key = kumo_key(name, stype, "MULTI_CATEGORY_COUNTS", false); + for (key, mut value) in pairs { + if key == category_key && category_dtype.is_some() { + for (index, (label, _)) in sorted_cats.iter().enumerate() { + value["value"][index][0] = typed_target_category(label, category_dtype)?; + } + } stats.insert(key, value); } } @@ -1206,16 +1199,42 @@ pub fn build_inline_col_stats( } if stats.is_empty() { - None + Ok(None) } else { - Some(json!({ + Ok(Some(json!({ "version": 1, "kind": "tt_train_table_col_stats", "stats_format": "kumo_col_stats_v1", "row_count": num_total_rows, "stats": stats, "provided_fields": ["stats"] - })) + }))) + } +} + +/// Restore category values using the output column type, never by guessing +/// whether a string label happens to look numeric. +fn typed_target_category(key: &str, dtype: Option<&DataType>) -> TTGenResult { + let invalid = || { + TTGenError::SchemaError(format!( + "TARGET1 category {key:?} cannot be represented as {dtype:?}" + )) + }; + match dtype { + Some(DataType::Boolean) => key.parse::().map(|v| json!(v)).map_err(|_| invalid()), + Some(DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64) => { + key.parse::().map(|v| json!(v)).map_err(|_| invalid()) + } + Some(DataType::UInt8 | DataType::UInt16 | DataType::UInt32 | DataType::UInt64) => { + key.parse::().map(|v| json!(v)).map_err(|_| invalid()) + } + Some(DataType::Float32 | DataType::Float64) => { + let value = key.parse::().map_err(|_| invalid())?; + serde_json::Number::from_f64(value) + .map(JsonValue::Number) + .ok_or_else(invalid) + } + _ => Ok(json!(key)), } } @@ -1566,7 +1585,9 @@ fn merge_chunk_stats_into(dst: &mut ChunkStats, src: ChunkStat .merge(&s); } - dst.target_is_bool_dtype |= src.target_is_bool_dtype; + if src.target_dtype.is_some() { + dst.target_dtype = src.target_dtype; + } for (name, stats) in src.sequence_feature_stats { dst.sequence_feature_stats @@ -1613,7 +1634,9 @@ mod tests { chunk.include_false_count = 1; merger.merge(chunk); - let out = merger.finalize(4, true, true, true, None, "numerical", None); + let out = merger + .finalize(4, true, true, true, None, "numerical", None) + .unwrap(); assert_eq!(out.version, 2); assert_eq!(out.num_total_rows, 4); @@ -1626,54 +1649,117 @@ mod tests { assert_eq!(out.exact_stats.entity_include_bit.unwrap().false_count, 1); } #[test] - fn test_merge_propagates_target_is_bool_dtype_when_chunk_sets_it() { - // A single chunk that observed a bool target dtype must flip the - // merger flag. This is the regression guard for the ttgen path. + fn test_merge_propagates_target_dtype() { let mut merger: StatsMerger = StatsMerger::default(); - assert!(!merger.target_is_bool_dtype, "merger starts false"); + assert!( + merger.target_dtype.is_none(), + "merger starts without a target dtype" + ); let chunk: ChunkStats = ChunkStats { - target_is_bool_dtype: true, + target_dtype: Some(DataType::Boolean), ..Default::default() }; merger.merge(chunk); assert!( - merger.target_is_bool_dtype, - "merge must OR target_is_bool_dtype from chunk into merger" + merger.target_dtype == Some(DataType::Boolean), + "merge must retain the target dtype" ); } #[test] - fn test_merge_target_is_bool_dtype_is_sticky_across_chunks() { - // Once any chunk flips the flag, subsequent chunks (even with - // false) must not unset it. Defensive in case some chunks see - // an empty target column and default to false. + fn test_merge_retains_target_dtype_across_empty_chunks() { let mut merger: StatsMerger = StatsMerger::default(); merger.merge(ChunkStats:: { - target_is_bool_dtype: true, + target_dtype: Some(DataType::Boolean), ..Default::default() }); merger.merge(ChunkStats:: { - target_is_bool_dtype: false, + target_dtype: None, ..Default::default() }); assert!( - merger.target_is_bool_dtype, - "false-valued chunk must not clear the flag" + merger.target_dtype == Some(DataType::Boolean), + "an empty chunk must not clear the target dtype" + ); + } + + #[test] + fn typed_categories_round_trip_through_json() { + for (dtype, spelling, expected) in [ + (DataType::Int64, "9223372036854775807", json!(i64::MAX)), + (DataType::Int64, "-42", json!(-42)), + (DataType::UInt64, "18446744073709551615", json!(u64::MAX)), + (DataType::Float64, "2.5", json!(2.5)), + (DataType::Float32, "2", json!(2.0)), + (DataType::Boolean, "true", json!(true)), + (DataType::Utf8, "001", json!("001")), + (DataType::Utf8, "true", json!("true")), + ] { + let value = typed_target_category(spelling, Some(&dtype)).unwrap(); + let decoded: JsonValue = serde_json::from_str(&value.to_string()).unwrap(); + assert_eq!(decoded, expected, "dtype={dtype:?}"); + } + for spelling in ["invalid", "1.5"] { + assert!(typed_target_category(spelling, Some(&DataType::Int64)).is_err()); + } + assert!(typed_target_category("NaN", Some(&DataType::Float64)).is_err()); + } + + #[test] + fn finalize_preserves_integer_multilabel_categories() { + let mut merger: StatsMerger = StatsMerger::default(); + merger.merge(ChunkStats { + target_dtype: Some(DataType::List(std::sync::Arc::new( + arrow_schema::Field::new("item", DataType::Int64, true), + ))), + ..Default::default() + }); + let counts = HashMap::from([("42".to_string(), 7), ("0".to_string(), 3)]); + let payload = merger + .finalize( + 10, + false, + false, + false, + Some(counts), + "multicategorical", + None, + ) + .unwrap(); + let stats = payload.parsed_train_table_col_stats.unwrap(); + assert_eq!( + stats["stats"]["TARGET1__kumo.multicategorical__MULTI_CATEGORY_COUNTS__False"]["value"], + json!([[42, 7], [0, 3]]) + ); + } + + #[test] + fn finalize_preserves_integer_target_categories() { + let mut merger: StatsMerger = StatsMerger::default(); + merger.merge(ChunkStats { + target_dtype: Some(DataType::Int64), + ..Default::default() + }); + merger.merge(ChunkStats::default()); + let counts = HashMap::from([("9223372036854775807".to_string(), 7), ("0".to_string(), 3)]); + let payload = merger + .finalize(10, false, false, false, Some(counts), "categorical", None) + .unwrap(); + let stats = payload.parsed_train_table_col_stats.unwrap(); + assert_eq!( + stats["stats"]["TARGET1__kumo.categorical__CATEGORY_COUNTS__False"]["value"], + json!([[i64::MAX, 7], [0, 3]]) ); } #[test] fn test_finalize_emits_json_booleans_for_bool_target() { - // End-to-end: a categorical target with target_is_bool_dtype = true - // and string-keyed category counts ("true"/"false", as ttgen records - // them via Display for bool) must surface as JSON booleans in the - // emitted CATEGORY_COUNTS array. let mut merger: StatsMerger = StatsMerger::default(); merger.merge(ChunkStats:: { num_train_rows: 10, - target_is_bool_dtype: true, + target_dtype: Some(DataType::Boolean), ..Default::default() }); @@ -1681,7 +1767,9 @@ mod tests { counts.insert("false".to_string(), 7); counts.insert("true".to_string(), 3); - let payload = merger.finalize(10, false, false, false, Some(counts), "categorical", None); + let payload = merger + .finalize(10, false, false, false, Some(counts), "categorical", None) + .unwrap(); let outer = payload .parsed_train_table_col_stats @@ -1709,16 +1797,11 @@ mod tests { } #[test] - fn test_finalize_emits_string_keys_when_target_is_bool_dtype_is_false() { - // Mirror of the previous test: when the flag is NOT set and stype - // is "categorical" (kumo's convention for binary classification), - // emit must NOT promote string keys to JSON booleans. Asserts the - // fix is gated correctly and doesn't over-fire on plain string - // categoricals that happen to use "true"/"false" as labels. + fn test_finalize_keeps_string_categories_without_physical_dtype() { let mut merger: StatsMerger = StatsMerger::default(); merger.merge(ChunkStats:: { num_train_rows: 10, - target_is_bool_dtype: false, + target_dtype: None, ..Default::default() }); @@ -1726,7 +1809,9 @@ mod tests { counts.insert("false".to_string(), 7); counts.insert("true".to_string(), 3); - let payload = merger.finalize(10, false, false, false, Some(counts), "categorical", None); + let payload = merger + .finalize(10, false, false, false, Some(counts), "categorical", None) + .unwrap(); let outer = payload.parsed_train_table_col_stats.unwrap(); let stats = outer.get("stats").expect("outer must have 'stats' wrapper"); let key = stats @@ -1963,7 +2048,9 @@ mod tests { chunk.num_train_rows = 6; let mut merger: StatsMerger = StatsMerger::default(); merger.merge(chunk); - let out = merger.finalize(6, false, false, false, None, "numerical", None); + let out = merger + .finalize(6, false, false, false, None, "numerical", None) + .unwrap(); assert_eq!(out.num_entities, 5); assert_eq!(out.num_targets, 3); assert_eq!(out.exact_stats.timestamp.num_unique, Some(4)); @@ -2000,15 +2087,17 @@ mod tests { let mut merger: StatsMerger = StatsMerger::default(); let train_rows = chunk.num_train_rows; merger.merge(chunk); - merger.finalize( - num_total_rows.max(train_rows), - is_link_prediction, - false, - false, - target_category_counts, - target_stype, - None, - ) + merger + .finalize( + num_total_rows.max(train_rows), + is_link_prediction, + false, + false, + target_category_counts, + target_stype, + None, + ) + .unwrap() } /// The entity column is a foreign key resolved to graph node ids; it is @@ -2033,16 +2122,18 @@ mod tests { let mut merger: StatsMerger = StatsMerger::default(); merger.merge(chunk); - let payload = merger.finalize( - 5, - false, - false, - false, - Some(target_counts), - "categorical", - // What the executor hands over: entity counting is not done at all. - None, - ); + let payload = merger + .finalize( + 5, + false, + false, + false, + Some(target_counts), + "categorical", + // What the executor hands over: entity counting is not done at all. + None, + ) + .unwrap(); let stats = payload .parsed_train_table_col_stats @@ -2432,6 +2523,7 @@ mod sequence_feature_emission_tests { } merger .finalize(num_rows, false, false, false, None, "numerical", None) + .unwrap() .parsed_train_table_col_stats .expect("sequence statistics must emit the Kumo envelope") } diff --git a/packages/diskgraph/diskgraph-train-table/tests/custom_tt_integration.rs b/packages/diskgraph/diskgraph-train-table/tests/custom_tt_integration.rs index 7b6508055e..de01dd5c60 100644 --- a/packages/diskgraph/diskgraph-train-table/tests/custom_tt_integration.rs +++ b/packages/diskgraph/diskgraph-train-table/tests/custom_tt_integration.rs @@ -939,6 +939,56 @@ fn synth_static_custom_tt_parquet(out_path: &Path, entity_pks: &[i64], has_targe write_parquet(out_path, &batch); } +/// Imported/exported rows must build a vocabulary with the same physical type. +#[test] +fn test_custom_tt_categorical_stats_preserve_target_type() { + let dir = tempfile::tempdir().unwrap(); + let index = build_users_only_graph(dir.path(), 3); + let targets: Vec> = vec![ + Arc::new(Int64Array::from(vec![0, i64::MAX, 0])), + Arc::new(Float64Array::from(vec![0.5, 2.5, 0.5])), + Arc::new(arrow_array::StringArray::from(vec!["001", "2", "001"])), + Arc::new(arrow_array::BooleanArray::from(vec![false, true, false])), + ]; + let expected = [ + serde_json::json!([[0, 2], [i64::MAX, 1]]), + serde_json::json!([[0.5, 2], [2.5, 1]]), + serde_json::json!([["001", 2], ["2", 1]]), + serde_json::json!([[false, 2], [true, 1]]), + ]; + for (target, expected_counts) in targets.into_iter().zip(expected) { + let pq = dir.path().join("typed_custom_tt.parquet"); + let schema = Arc::new(Schema::new(vec![ + Field::new("ENTITY1", DataType::Int64, false), + Field::new("TARGET1", target.data_type().clone(), false), + ])); + let batch = RecordBatch::try_new( + schema, + vec![Arc::new(Int64Array::from(vec![0, 1, 2])), target], + ) + .unwrap(); + write_parquet(&pq, &batch); + let mut plan = make_custom_tt_target_only_node_plan(); + plan.target_stype = Some("categorical".to_string()); + let out_dir = tempfile::tempdir().unwrap(); + let custom = CustomTtSource { + target_window_end: None, + parquet_path: pq, + input_timestamp_unit: diskgraph_core::time::TimeUnit::Nanoseconds, + on_error: diskgraph_train_table::custom_tt_row_errors::IngestOnError::Abort, + allow_negative_weight: false, + timestamp_reference: None, + }; + let output = + execute_tt_pass_with_source(&plan, &index, out_dir.path(), Some(custom)).unwrap(); + let stats = output.stats.unwrap().parsed_train_table_col_stats.unwrap(); + assert_eq!( + stats["stats"]["TARGET1__kumo.categorical__CATEGORY_COUNTS__False"]["value"], + expected_counts + ); + } +} + /// STATIC custom TRAIN: a parquet with no TIMESTAMP column must NOT error; /// DG synthesizes the native-static sentinel (raw 0 → epoch 0) for every row. #[test] diff --git a/packages/diskgraph/diskgraph-train-table/tests/ttgen_integration.rs b/packages/diskgraph/diskgraph-train-table/tests/ttgen_integration.rs index 0e2f56b6df..391f35cf12 100644 --- a/packages/diskgraph/diskgraph-train-table/tests/ttgen_integration.rs +++ b/packages/diskgraph/diskgraph-train-table/tests/ttgen_integration.rs @@ -2191,6 +2191,40 @@ fn integ_entity_filter_and_stage_filter() { // ─── Tests: Entity features ───────────────────────────────────────────────── +#[test] +fn integ_generated_categorical_stats_preserve_integer_labels() { + let dir = tempfile::tempdir().unwrap(); + let index = build_graph1(dir.path()); + let mut plan = g1_plan(vec![Stage { + ops: vec![Op::Column { + alias: "TARGET".to_string(), + table: "users".to_string(), + column: "level".to_string(), + path: vec![], + }], + filter: None, + }]); + plan.target_stype = Some("categorical".to_string()); + let out_dir = tempfile::tempdir().unwrap(); + let output = diskgraph_train_table::ttgen_executor::execute_tt_pass_with_customizer( + &plan, + &index, + out_dir.path(), + None, + None::)>, + ) + .unwrap(); + let stats = output.stats.unwrap().parsed_train_table_col_stats.unwrap(); + let pairs = stats["stats"]["TARGET1__kumo.categorical__CATEGORY_COUNTS__False"]["value"] + .as_array() + .unwrap(); + let counts: HashMap = pairs + .iter() + .map(|pair| (pair[0].as_i64().unwrap(), pair[1].as_u64().unwrap())) + .collect(); + assert_eq!(counts, HashMap::from([(1, 2), (2, 1), (3, 1), (5, 1)])); +} + #[test] fn integ_entity_column() { // Non-temporal: Op::Column(users.score) diff --git a/packages/kumo-core/src/kumo_core/encoders/target/base.py b/packages/kumo-core/src/kumo_core/encoders/target/base.py index 4c5c037385..c1563f2929 100644 --- a/packages/kumo-core/src/kumo_core/encoders/target/base.py +++ b/packages/kumo-core/src/kumo_core/encoders/target/base.py @@ -58,7 +58,7 @@ def from_encoder( category_counts = encoder._stats[ColStatType.CATEGORY_COUNTS] return CategoricalTargetEncoder( task_type, - CategoricalTensorMapper(category_counts=category_counts), + CategoricalTensorMapper(category_counts=category_counts, strict=True), ) elif isinstance(encoder, MultiCategorical): @@ -67,6 +67,7 @@ def from_encoder( MultiCategoricalTensorMapper( category_counts=category_counts, sep=encoder._stats[ColStatType.MULTI_CATEGORIES_SEPARATOR], + strict=True, )) elif isinstance(encoder, Numerical): diff --git a/packages/kumo-core/src/kumo_core/encoders/tensor_mapper.py b/packages/kumo-core/src/kumo_core/encoders/tensor_mapper.py index f7ef0a6e3e..c96b218502 100644 --- a/packages/kumo-core/src/kumo_core/encoders/tensor_mapper.py +++ b/packages/kumo-core/src/kumo_core/encoders/tensor_mapper.py @@ -269,17 +269,33 @@ def post_forward( ) +def _validate_target_indices(indices: Tensor, values: pa.Array) -> None: + """Reject invalid target IDs and include at most five offending labels.""" + invalid = indices < 0 + if bool(invalid.any()): + positions = invalid.nonzero().view(-1)[:5].tolist() + labels = [values[position].as_py() for position in positions] + raise ValueError( + f"Target labels not present in target encoder mapping: {labels}" + ) + + class CategoricalTensorMapper(TensorMapper[Tensor]): r"""Handles the conversion from categorical values to consecutive indices. Args: category_counts: Category counts to create a mapping from categorical values to integers. + strict: Raise ValueError for unknown or null labels instead of encoding -1. """ stype: Stype = Stype.categorical - def __init__(self, category_counts: Sequence[Sequence[Any]]) -> None: + def __init__( + self, category_counts: Sequence[Sequence[Any]], *, strict: bool = False + ) -> None: + """Build the vocabulary; strict mode rejects unknown or null targets.""" + self.strict = strict category_counts = _sort_category_counts(category_counts) self.mapping = _create_mapping_from_category_counts(category_counts) self.mapper = Mapper(self.mapping) @@ -299,7 +315,25 @@ def forward( *, device: torch.device | None = None, ) -> Tensor: - """Map Arrow categories to cached vocabulary indices; unknowns become -1.""" + """Map Arrow categories to vocabulary indices. + + Args: + array: Categorical values to look up. + device: Destination device for the mapped indices. + + Returns: + A column tensor of vocabulary IDs, with -1 for unknowns in permissive mode. + + Raises: + ValueError: If strict mode encounters an unknown or null label. + """ + if array.null_count == len(array): # Avoid errors due to poor typing. + if len(array) > 0 and getattr(self, "strict", False): + raise ValueError("Categorical targets must not contain null labels") + return torch.full( + (len(array), 1), fill_value=-1, dtype=torch.long, device=device + ) + if pa.types.is_dictionary(array.type): # Dictionary columns store integer codes into a small dictionary of # unique values; hash only the K unique values, then gather. @@ -315,14 +349,13 @@ def forward( if null_mask is not None: codes[null_mask] = -1 index = torch.from_numpy(codes).to(torch.long) + if getattr(self, "strict", False): + _validate_target_indices(index, array) return index.to(device).view(-1, 1) - if array.null_count == len(array): # Avoid errors due to poor typing. - return torch.full( - (len(array), 1), fill_value=-1, dtype=torch.long, device=device - ) - index = self.mapper.map(array.to_numpy(zero_copy_only=False)) + if getattr(self, "strict", False): + _validate_target_indices(index, array) return index.to(device).view(-1, 1) def post_forward( @@ -346,6 +379,8 @@ class MultiCategoricalTensorMapper(TensorMapper[MultiNestedTensor]): category_counts: Category counts to create a mapping from categorical values to integers. sep: The separator. + strict: Raise ValueError for unknown labels. Null and empty labels produce + no supervision entries in this mode. """ stype: Stype = Stype.multicategorical @@ -354,7 +389,11 @@ def __init__( self, category_counts: Sequence[Sequence[Any]], sep: str | None, + *, + strict: bool = False, ) -> None: + """Build a vocabulary with optional strict target-label validation.""" + self.strict = strict category_counts = _sort_category_counts(category_counts) self.mapping = _create_mapping_from_category_counts(category_counts) self.mapper = Mapper(self.mapping) @@ -393,15 +432,32 @@ def forward( *, device: torch.device | None = None, ) -> MultiNestedTensor: - """Map Arrow categories to IDs, preserving empty and missing rows.""" + """Map Arrow categories to IDs, preserving empty and missing rows. + + Args: + array: Scalar or list-valued categorical rows. + device: Destination device for the mapped indices and offsets. + + Returns: + Nested vocabulary IDs. Strict mode omits null and empty labels; + permissive mode retains its -1 placeholders. + + Raises: + ValueError: If strict mode encounters an unknown non-null label. + """ is_list = isinstance( array, (pa.ListArray, pa.LargeListArray, pa.FixedSizeListArray) ) - if len(array) > 0 and self._is_string_dtype is None: - self._is_string_dtype = not is_list and array.null_count < len(array) + strict = getattr(self, "strict", False) + is_string_dtype = not is_list + has_values = array.null_count < len(array) + if not strict and len(array) > 0 and self._is_string_dtype is None: + self._is_string_dtype = is_string_dtype and has_values if not is_list and self.sep is not None and len(array) > 0: - strings = pc.fill_null(pc.cast(array, pa.string()), "__None__") + strings = pc.fill_null( + pc.cast(array, pa.string()), "" if strict else "__None__" + ) if len(self.sep) == 1: array = pc.split_pattern(strings, pattern=self.sep) else: @@ -424,14 +480,17 @@ def forward( if pa.types.is_dictionary(values.type): values = values.dictionary_decode() + keep = None if pa.types.is_string(values.type) or pa.types.is_large_string(values.type): - keep = pc.fill_null(pc.not_equal(values, ""), True) - if not pc.all(keep).as_py(): - retained = np.empty(len(values) + 1, dtype=np.int64) - retained[0] = 0 - np.cumsum(keep.to_numpy(zero_copy_only=False), out=retained[1:]) - offsets = retained[offsets] - values = pc.filter(values, keep) + keep = pc.fill_null(pc.not_equal(values, ""), not strict) + elif strict and values.null_count: + keep = values.is_valid() + if keep is not None and not pc.all(keep).as_py(): + retained = np.empty(len(values) + 1, dtype=np.int64) + retained[0] = 0 + np.cumsum(keep.to_numpy(zero_copy_only=False), out=retained[1:]) + offsets = retained[offsets] + values = pc.filter(values, keep) # Fill nullable integers before conversion to avoid rounding through float64. nulls = None @@ -443,7 +502,10 @@ def forward( if nulls is not None: index[torch.tensor(nulls)] = -1 - if missing.any(): + if strict: + _validate_target_indices(index, values) + + if not strict and missing.any(): offsets = offsets + np.concatenate(([0], np.cumsum(missing))) occupied = torch.ones(int(offsets[-1]), dtype=torch.bool) occupied[torch.from_numpy(offsets[:-1][missing])] = False @@ -451,6 +513,8 @@ def forward( expanded[occupied] = index index = expanded + if strict and has_values and self._is_string_dtype is None: + self._is_string_dtype = is_string_dtype return MultiNestedTensor( num_rows=len(array), num_cols=1, diff --git a/packages/kumo-core/tests/encoders/test_strict_target_mapping.py b/packages/kumo-core/tests/encoders/test_strict_target_mapping.py new file mode 100644 index 0000000000..bfa1cfe735 --- /dev/null +++ b/packages/kumo-core/tests/encoders/test_strict_target_mapping.py @@ -0,0 +1,146 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Strict supervised-label conversion through the shared Arrow mappers.""" + +import json + +import pyarrow as pa +import pytest +import torch +from kumo_core.encoders.target.base import TargetEncoder +from kumo_core.encoders.target.multicategorical import MultiCategoricalTargetEncoder +from kumo_core.encoders.tensor_mapper import ( + CategoricalTensorMapper, + MultiCategoricalTensorMapper, +) +from kumoapi.encoder import Index, MultiCategorical +from kumoapi.task import TaskType +from kumoapi.typing import ColStatType + + +@pytest.mark.parametrize("dictionary", [False, True]) +@pytest.mark.parametrize("labels", [["known", "unknown"], ["known", None], [None]]) +def test_strict_categorical_rejects_invalid_labels( + dictionary: bool, labels: list[str | None] +) -> None: + """Unknown and null supervised classes fail before reaching the loss.""" + mapper = CategoricalTensorMapper([["known", 10]], strict=True) + values = pa.array(labels, type=pa.string()) + if dictionary: + values = values.dictionary_encode() + + with pytest.raises(ValueError, match="Target labels|must not contain null"): + mapper(values) + + +def test_dictionary_unused_unknown_category_is_allowed() -> None: + """Validate referenced dictionary codes rather than unused dictionary values.""" + mapper = CategoricalTensorMapper([["known", 10]], strict=True) + values = pa.DictionaryArray.from_arrays([0, 0], ["known", "unused"]) + + result = mapper(values) + + torch.testing.assert_close(result, torch.zeros(2, 1, dtype=torch.long)) + + +@pytest.mark.parametrize("dtype", [pa.int64(), pa.uint64()]) +def test_typed_json_vocabulary_matches_integer_targets(dtype: pa.DataType) -> None: + """JSON category pairs preserve integer IDs without float precision loss.""" + category_counts = json.loads(f"[[{2**63 - 1}, 10], [0, 5]]") + mapper = CategoricalTensorMapper(category_counts, strict=True) + + result = mapper(pa.array([0, 2**63 - 1], type=dtype)) + + torch.testing.assert_close(result, torch.tensor([[1], [0]])) + + +@pytest.mark.parametrize( + "values", + [pa.array(["c1|c5"]), pa.array([["c1", "c5"]]), pa.array(["c1 | c4"])], +) +def test_strict_multilabel_rejects_unknown_labels(values: pa.Array) -> None: + """Unknown labels cannot silently select the final multi-hot class.""" + mapper = MultiCategoricalTensorMapper( + [["c1", 10], ["c2", 8], ["c3", 6], ["c4", 4]], sep="|", strict=True + ) + + with pytest.raises(ValueError, match="not present in target encoder mapping"): + mapper(values) + + assert mapper._is_string_dtype is None + + +@pytest.mark.parametrize( + "values", + [ + pa.array([["c1", None], [], None, ["c4"]]), + pa.array(["c1", "", None, "c4"]), + ], +) +def test_strict_multilabel_missing_rows_have_no_positive_labels( + values: pa.Array, +) -> None: + """Null and empty entries produce zero rows instead of the final class.""" + mapper = MultiCategoricalTensorMapper([["c1", 10], ["c4", 4]], sep="|", strict=True) + encoder = MultiCategoricalTargetEncoder(mapper) + + result = encoder.encode_tensor(mapper(values)) + + torch.testing.assert_close( + result, torch.tensor([[1.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 1.0]]) + ) + + +def test_all_null_batch_does_not_choose_multilabel_decode_format() -> None: + """A later valid string batch determines string prediction reconstruction.""" + mapper = MultiCategoricalTensorMapper([["c1", 10]], sep="|", strict=True) + missing = mapper(pa.nulls(2)) + assert missing.values.numel() == 0 + assert mapper._is_string_dtype is None + + mapper(pa.array(["c1"])) + + assert mapper._is_string_dtype is True + + +@pytest.mark.parametrize("multilabel", [False, True]) +def test_only_target_mapper_construction_enables_strictness(multilabel: bool) -> None: + """Target factories enable validation while feature mappers stay permissive.""" + config: Index | MultiCategorical + feature_mapper: CategoricalTensorMapper | MultiCategoricalTensorMapper + if multilabel: + config = MultiCategorical() + config._stats = { + ColStatType.MULTI_CATEGORY_COUNTS: [["known", 10]], + ColStatType.MULTI_CATEGORIES_SEPARATOR: "|", + } + task_type = TaskType.MULTILABEL_CLASSIFICATION + feature_mapper = MultiCategoricalTensorMapper([["known", 10]], sep="|") + else: + config = Index() + config._stats = {ColStatType.CATEGORY_COUNTS: [["known", 10]]} + task_type = TaskType.MULTICLASS_CLASSIFICATION + feature_mapper = CategoricalTensorMapper([["known", 10]]) + encoder = TargetEncoder.from_encoder(task_type, config) + values = pa.array(["unknown"]) + + with pytest.raises(ValueError, match="not present in target encoder mapping"): + encoder.tensor_mapper(values) + result = feature_mapper(values) + + indices = result if isinstance(result, torch.Tensor) else result.values + assert indices.view(-1).tolist() == [-1] + + +def test_strict_integer_multilabel_preserves_precision_with_null_children() -> None: + """Dropping null children must not round large integer labels through floats.""" + mapper = MultiCategoricalTensorMapper( + [[2**63 - 1, 10], [0, 5]], sep="|", strict=True + ) + values = pa.array([[2**63 - 1, None], [], [0]], type=pa.list_(pa.int64())) + + result = mapper(values) + + torch.testing.assert_close(result.values, torch.tensor([0, 1])) + torch.testing.assert_close(result.offset, torch.tensor([0, 1, 1, 2])) From 735cb3e3b72fe9e410fe7dc724066815d840fcf1 Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Thu, 3 Dec 2026 23:13:47 +0000 Subject: [PATCH 4/7] Normalize target vocabularies from persisted dtype metadata --- .github/workflows/kumo-engine-pr.yml | 12 +- .../src/custom_tt_chunk_processor.rs | 17 +- .../src/ttgen_executor.rs | 9 +- .../diskgraph-train-table/src/ttgen_stats.rs | 290 ++++++------------ .../tests/custom_tt_integration.rs | 50 --- .../tests/ttgen_integration.rs | 34 -- .../src/kumo_core/automl/auto_trainer.py | 34 +- .../src/kumo_core/encoders/config.py | 49 +++ .../src/kumo_core/encoders/target/base.py | 106 ++++++- .../src/kumo_core/encoders/tensor_mapper.py | 6 +- .../kumo-core/src/kumo_core/task_dataset.py | 27 ++ .../kumo-core/src/kumo_core/train/trainer.py | 22 +- .../encoders/test_target_dtype_metadata.py | 211 +++++++++++++ .../encoders/test_target_vocabulary_dtype.py | 202 ++++++++++++ .../test/test_integer_categorical_targets.py | 229 ++++++++++++++ 15 files changed, 982 insertions(+), 316 deletions(-) create mode 100644 packages/kumo-core/tests/encoders/test_target_dtype_metadata.py create mode 100644 packages/kumo-core/tests/encoders/test_target_vocabulary_dtype.py create mode 100644 packages/kumo-engine/test/test_integer_categorical_targets.py diff --git a/.github/workflows/kumo-engine-pr.yml b/.github/workflows/kumo-engine-pr.yml index 514dc52252..9d2b1f8598 100644 --- a/.github/workflows/kumo-engine-pr.yml +++ b/.github/workflows/kumo-engine-pr.yml @@ -211,13 +211,23 @@ jobs: mkdir -p "$work" python -m venv "$RUNNER_TEMP/lifecycle-env" uv --no-config pip install --python "$RUNNER_TEMP/lifecycle-env/bin/python" \ - --default-index https://pypi.org/simple --torch-backend cpu "$wheel[mlflow]" 'mlflow>=3.5,<4' 2>&1 | tee "$work/install.log" + --default-index https://pypi.org/simple --torch-backend cpu "$wheel[mlflow]" 'mlflow>=3.5,<4' 'pytest>=8,<10' 2>&1 | tee "$work/install.log" # uv omits archive hashes; pip records the selected wheel's identity. "$RUNNER_TEMP/lifecycle-env/bin/python" -I -m pip --isolated install --no-index --no-deps --force-reinstall "$wheel" cp "$GITHUB_WORKSPACE"/packages/kumo-engine/test/wheel_{mlops_lifecycle,gpu_smoke}.py "$work/" cd "$work" "$RUNNER_TEMP/lifecycle-env/bin/python" -I wheel_mlops_lifecycle.py \ --output-dir "$work/results" --wheel "$wheel" --expected-version "$version" --phase-timeout 300 2>&1 | tee "$work/run.log" + - name: Test integer categorical targets against the candidate wheel + run: | + set -euo pipefail + work="$RUNNER_TEMP/engine-cpu-lifecycle" + cp packages/kumo-engine/test/test_integer_categorical_targets.py "$work/" + cd "$work" + "$RUNNER_TEMP/lifecycle-env/bin/python" -I -m pytest \ + -q -c /dev/null --confcutdir="$work" \ + --basetemp="$work/integer-target-tests" \ + test_integer_categorical_targets.py 2>&1 | tee "$work/integer-target-tests.log" - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 if: always() with: diff --git a/packages/diskgraph/diskgraph-train-table/src/custom_tt_chunk_processor.rs b/packages/diskgraph/diskgraph-train-table/src/custom_tt_chunk_processor.rs index eead79a870..c6a1f7c8f2 100644 --- a/packages/diskgraph/diskgraph-train-table/src/custom_tt_chunk_processor.rs +++ b/packages/diskgraph/diskgraph-train-table/src/custom_tt_chunk_processor.rs @@ -645,13 +645,16 @@ pub(crate) fn custom_tt_chunk_processor + Clon // Read the actual target dtype the chunk processor will emit (resolved // from the customer parquet schema in `output_mode_for_custom_tt`), // not from `plan.primary_target_dtype()` — that helper falls through - // to `Float64` for empty-stages custom-TT plans. CATEGORY_COUNTS must - // preserve the customer's physical label type. - let actual_target_dtype = match &mode { - OutputMode::Node { target_dtypes } | OutputMode::LinkArray { target_dtypes, .. } => { - target_dtypes.first().cloned() + // to `Float64` for empty-stages custom-TT plans, which would lose the + // Boolean signal needed for JSON-bool CATEGORY_COUNTS emission. + let actual_target_is_bool = match &mode { + OutputMode::Node { target_dtypes } => { + matches!(target_dtypes.first(), Some(DataType::Boolean)) } - OutputMode::PassThrough | OutputMode::Forecasting { .. } => None, + OutputMode::LinkArray { target_dtypes, .. } => { + matches!(target_dtypes.first(), Some(DataType::Boolean)) + } + OutputMode::PassThrough | OutputMode::Forecasting { .. } => false, }; let time_col_name = plan .entity_table_spec @@ -711,7 +714,7 @@ pub(crate) fn custom_tt_chunk_processor + Clon } ); let mut stats: ChunkStats = ChunkStats { - target_dtype: actual_target_dtype, + target_is_bool_dtype: actual_target_is_bool, ..ChunkStats::default() }; if target_is_numerical { diff --git a/packages/diskgraph/diskgraph-train-table/src/ttgen_executor.rs b/packages/diskgraph/diskgraph-train-table/src/ttgen_executor.rs index 198a75b5e8..44fbefb706 100644 --- a/packages/diskgraph/diskgraph-train-table/src/ttgen_executor.rs +++ b/packages/diskgraph/diskgraph-train-table/src/ttgen_executor.rs @@ -1049,7 +1049,7 @@ where target_category_counts, target_stype_str.as_str(), entity_category_counts, - )?; + ); // ── Fused pass-B by mode → per-stage seed parts ────────────────────── // @@ -1739,8 +1739,13 @@ fn execute_chunk + Clone>( } ); + // Propagate the resolved target dtype into the stats accumulator so + // bool-target CATEGORY_COUNTS emits JSON booleans (matches the + // BooleanArray downcast in tt_executor.rs:compute_train_table_col_stats_payload + // for the rehydration path; without this the ttgen path silently + // emits lowercase "true"/"false" strings). let mut stats: ChunkStats = ChunkStats { - target_dtype: Some(plan.primary_target_dtype().clone()), + target_is_bool_dtype: matches!(plan.primary_target_dtype(), DataType::Boolean), ..ChunkStats::default() }; if target_is_numerical { diff --git a/packages/diskgraph/diskgraph-train-table/src/ttgen_stats.rs b/packages/diskgraph/diskgraph-train-table/src/ttgen_stats.rs index 722c07b103..489e49fa27 100644 --- a/packages/diskgraph/diskgraph-train-table/src/ttgen_stats.rs +++ b/packages/diskgraph/diskgraph-train-table/src/ttgen_stats.rs @@ -5,12 +5,10 @@ use std::collections::HashMap; use arrow_array::{Array, ListArray}; -use arrow_schema::DataType; use serde::{Deserialize, Serialize}; use serde_json::{json, Value as JsonValue}; use crate::custom_tt_row_errors::SourceRowStats; -use crate::errors::{TTGenError, TTGenResult}; #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct SequenceFeatureStats { @@ -193,8 +191,11 @@ pub(crate) struct ChunkStats { pub(crate) timestamp_welford: Option, pub(crate) timestamp_tdigest: Option, pub(crate) timestamp_hll: Option, - /// Physical target type used to restore typed category values at publication. - pub(crate) target_dtype: Option, + /// Mirrors the StatsMerger field. Set once per chunk from + /// ``plan.primary_target_dtype() == DataType::Boolean`` and OR'd into the + /// merger so CATEGORY_COUNTS emits JSON booleans (not lowercase + /// strings) for bool targets. + pub(crate) target_is_bool_dtype: bool, pub(crate) sequence_feature_stats: HashMap, /// Custom-TT row validation tally; untouched on the PQL path. pub(crate) source_rows: SourceRowStats, @@ -230,7 +231,7 @@ impl Default for ChunkStats { timestamp_welford: None, timestamp_tdigest: None, timestamp_hll: None, - target_dtype: None, + target_is_bool_dtype: false, sequence_feature_stats: HashMap::new(), source_rows: SourceRowStats::default(), } @@ -268,7 +269,9 @@ pub(crate) struct StatsMerger { timestamp_welford: Option, timestamp_tdigest: Option, timestamp_hll: Option, - pub(crate) target_dtype: Option, + /// True when the TARGET Arrow column was BooleanArray. Required so + /// CATEGORY_COUNTS gets emitted as JSON booleans (matching GE/Spark). + pub(crate) target_is_bool_dtype: bool, pub(crate) sequence_feature_stats: HashMap, pub(crate) source_rows: SourceRowStats, } @@ -302,7 +305,7 @@ impl Default for StatsMerger { timestamp_welford: None, timestamp_tdigest: None, timestamp_hll: None, - target_dtype: None, + target_is_bool_dtype: false, sequence_feature_stats: HashMap::new(), source_rows: SourceRowStats::default(), } @@ -403,9 +406,9 @@ impl StatsMerger { .get_or_insert_with(HyperLogLog::new) .merge(&chunk_h); } - if chunk.target_dtype.is_some() { - self.target_dtype = chunk.target_dtype; - } + // Sticky: any chunk that observed a bool target column flips the + // merger flag for the rest of the run. + self.target_is_bool_dtype |= chunk.target_is_bool_dtype; for (name, stats) in chunk.sequence_feature_stats { self.sequence_feature_stats @@ -425,7 +428,7 @@ impl StatsMerger { target_category_counts: Option>, target_stype: &str, entity_category_counts: Option>, - ) -> TTGenResult { + ) -> TrainTableStatsPayload { // Cardinality is HLL-only. For PassThrough or any path // that left the HLL as None, fall back to 0 — same defensive value // the prior empty-HashSet branch returned. @@ -570,7 +573,7 @@ impl StatsMerger { "v1", target_category_counts, target_stype, - self.target_dtype.as_ref(), + self.target_is_bool_dtype, &self.entity_hll, &self.entity_welford, &mut self.entity_tdigest, @@ -579,10 +582,10 @@ impl StatsMerger { &mut self.timestamp_tdigest, &self.timestamp_hll, self.sequence_feature_stats.clone(), - )? + ) }; - Ok(TrainTableStatsPayload { + TrainTableStatsPayload { version: 2, num_total_rows, num_train_rows: self.num_train_rows, @@ -602,7 +605,7 @@ impl StatsMerger { frequency: frequency_stats, entity_include_bit: include_bit_stats, }, - }) + } } } @@ -622,7 +625,7 @@ pub fn build_inline_col_stats( data_version: &str, target_category_counts: Option>, target_stype: &str, - target_dtype: Option<&DataType>, + target_is_bool_dtype: bool, entity_hll: &Option, entity_welford: &Option, entity_tdigest: &mut Option, @@ -631,7 +634,7 @@ pub fn build_inline_col_stats( timestamp_tdigest: &mut Option, timestamp_hll: &Option, sequence_feature_stats: HashMap, -) -> TTGenResult> { +) -> Option { let mut stats = serde_json::Map::new(); let dv = data_version; @@ -691,15 +694,33 @@ pub fn build_inline_col_stats( kumo_entry(json!(0.0), false, dv, count), ); + // CATEGORY_COUNTS: [[key, count], ...] + // + // For boolean targets we emit JSON booleans (true/false), not + // strings, so the kumo encoder builds its mapping with bool keys + // — matching pandas/GE behaviour. Otherwise pd.Series.map() over + // a bool column with string keys yields all-NaN -> all -1, and + // the trainer fails the val-imbalance check on the first batch. let mut pairs: Vec<(&String, &u64)> = cat_counts.iter().collect(); - pairs.sort_by(|a, b| b.1.cmp(a.1)); - let category_array = pairs + pairs.sort_by(|a, b| b.1.cmp(a.1)); // descending by count + // target_stype "boolean" OR Arrow BooleanArray rehydration both + // signal that the kumo encoder will see a bool-dtype column. + let target_is_boolean = target_stype == "boolean" || target_is_bool_dtype; + let category_array: Vec = pairs .iter() - .map(|(key, count)| { - let value = typed_target_category(key, target_dtype)?; - Ok(json!([value, count])) + .map(|(k, c)| { + let key_value = if target_is_boolean { + match k.as_str() { + "true" => json!(true), + "false" => json!(false), + _ => json!(k), + } + } else { + json!(k) + }; + json!([key_value, c]) }) - .collect::>>()?; + .collect(); stats.insert( kumo_key(name, stype, "CATEGORY_COUNTS", false), kumo_entry(json!(category_array), false, dv, count), @@ -746,21 +767,7 @@ pub fn build_inline_col_stats( Some("|"), // standard LIST_DISTINCT delimiter &sorted_cats, ); - let category_dtype = match target_dtype { - Some( - DataType::List(field) - | DataType::LargeList(field) - | DataType::FixedSizeList(field, _), - ) => Some(field.data_type()), - _ => None, - }; - let category_key = kumo_key(name, stype, "MULTI_CATEGORY_COUNTS", false); - for (key, mut value) in pairs { - if key == category_key && category_dtype.is_some() { - for (index, (label, _)) in sorted_cats.iter().enumerate() { - value["value"][index][0] = typed_target_category(label, category_dtype)?; - } - } + for (key, value) in pairs { stats.insert(key, value); } } @@ -1199,42 +1206,16 @@ pub fn build_inline_col_stats( } if stats.is_empty() { - Ok(None) + None } else { - Ok(Some(json!({ + Some(json!({ "version": 1, "kind": "tt_train_table_col_stats", "stats_format": "kumo_col_stats_v1", "row_count": num_total_rows, "stats": stats, "provided_fields": ["stats"] - }))) - } -} - -/// Restore category values using the output column type, never by guessing -/// whether a string label happens to look numeric. -fn typed_target_category(key: &str, dtype: Option<&DataType>) -> TTGenResult { - let invalid = || { - TTGenError::SchemaError(format!( - "TARGET1 category {key:?} cannot be represented as {dtype:?}" - )) - }; - match dtype { - Some(DataType::Boolean) => key.parse::().map(|v| json!(v)).map_err(|_| invalid()), - Some(DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64) => { - key.parse::().map(|v| json!(v)).map_err(|_| invalid()) - } - Some(DataType::UInt8 | DataType::UInt16 | DataType::UInt32 | DataType::UInt64) => { - key.parse::().map(|v| json!(v)).map_err(|_| invalid()) - } - Some(DataType::Float32 | DataType::Float64) => { - let value = key.parse::().map_err(|_| invalid())?; - serde_json::Number::from_f64(value) - .map(JsonValue::Number) - .ok_or_else(invalid) - } - _ => Ok(json!(key)), + })) } } @@ -1585,9 +1566,7 @@ fn merge_chunk_stats_into(dst: &mut ChunkStats, src: ChunkStat .merge(&s); } - if src.target_dtype.is_some() { - dst.target_dtype = src.target_dtype; - } + dst.target_is_bool_dtype |= src.target_is_bool_dtype; for (name, stats) in src.sequence_feature_stats { dst.sequence_feature_stats @@ -1634,9 +1613,7 @@ mod tests { chunk.include_false_count = 1; merger.merge(chunk); - let out = merger - .finalize(4, true, true, true, None, "numerical", None) - .unwrap(); + let out = merger.finalize(4, true, true, true, None, "numerical", None); assert_eq!(out.version, 2); assert_eq!(out.num_total_rows, 4); @@ -1649,117 +1626,54 @@ mod tests { assert_eq!(out.exact_stats.entity_include_bit.unwrap().false_count, 1); } #[test] - fn test_merge_propagates_target_dtype() { + fn test_merge_propagates_target_is_bool_dtype_when_chunk_sets_it() { + // A single chunk that observed a bool target dtype must flip the + // merger flag. This is the regression guard for the ttgen path. let mut merger: StatsMerger = StatsMerger::default(); - assert!( - merger.target_dtype.is_none(), - "merger starts without a target dtype" - ); + assert!(!merger.target_is_bool_dtype, "merger starts false"); let chunk: ChunkStats = ChunkStats { - target_dtype: Some(DataType::Boolean), + target_is_bool_dtype: true, ..Default::default() }; merger.merge(chunk); assert!( - merger.target_dtype == Some(DataType::Boolean), - "merge must retain the target dtype" + merger.target_is_bool_dtype, + "merge must OR target_is_bool_dtype from chunk into merger" ); } #[test] - fn test_merge_retains_target_dtype_across_empty_chunks() { + fn test_merge_target_is_bool_dtype_is_sticky_across_chunks() { + // Once any chunk flips the flag, subsequent chunks (even with + // false) must not unset it. Defensive in case some chunks see + // an empty target column and default to false. let mut merger: StatsMerger = StatsMerger::default(); merger.merge(ChunkStats:: { - target_dtype: Some(DataType::Boolean), + target_is_bool_dtype: true, ..Default::default() }); merger.merge(ChunkStats:: { - target_dtype: None, + target_is_bool_dtype: false, ..Default::default() }); assert!( - merger.target_dtype == Some(DataType::Boolean), - "an empty chunk must not clear the target dtype" - ); - } - - #[test] - fn typed_categories_round_trip_through_json() { - for (dtype, spelling, expected) in [ - (DataType::Int64, "9223372036854775807", json!(i64::MAX)), - (DataType::Int64, "-42", json!(-42)), - (DataType::UInt64, "18446744073709551615", json!(u64::MAX)), - (DataType::Float64, "2.5", json!(2.5)), - (DataType::Float32, "2", json!(2.0)), - (DataType::Boolean, "true", json!(true)), - (DataType::Utf8, "001", json!("001")), - (DataType::Utf8, "true", json!("true")), - ] { - let value = typed_target_category(spelling, Some(&dtype)).unwrap(); - let decoded: JsonValue = serde_json::from_str(&value.to_string()).unwrap(); - assert_eq!(decoded, expected, "dtype={dtype:?}"); - } - for spelling in ["invalid", "1.5"] { - assert!(typed_target_category(spelling, Some(&DataType::Int64)).is_err()); - } - assert!(typed_target_category("NaN", Some(&DataType::Float64)).is_err()); - } - - #[test] - fn finalize_preserves_integer_multilabel_categories() { - let mut merger: StatsMerger = StatsMerger::default(); - merger.merge(ChunkStats { - target_dtype: Some(DataType::List(std::sync::Arc::new( - arrow_schema::Field::new("item", DataType::Int64, true), - ))), - ..Default::default() - }); - let counts = HashMap::from([("42".to_string(), 7), ("0".to_string(), 3)]); - let payload = merger - .finalize( - 10, - false, - false, - false, - Some(counts), - "multicategorical", - None, - ) - .unwrap(); - let stats = payload.parsed_train_table_col_stats.unwrap(); - assert_eq!( - stats["stats"]["TARGET1__kumo.multicategorical__MULTI_CATEGORY_COUNTS__False"]["value"], - json!([[42, 7], [0, 3]]) - ); - } - - #[test] - fn finalize_preserves_integer_target_categories() { - let mut merger: StatsMerger = StatsMerger::default(); - merger.merge(ChunkStats { - target_dtype: Some(DataType::Int64), - ..Default::default() - }); - merger.merge(ChunkStats::default()); - let counts = HashMap::from([("9223372036854775807".to_string(), 7), ("0".to_string(), 3)]); - let payload = merger - .finalize(10, false, false, false, Some(counts), "categorical", None) - .unwrap(); - let stats = payload.parsed_train_table_col_stats.unwrap(); - assert_eq!( - stats["stats"]["TARGET1__kumo.categorical__CATEGORY_COUNTS__False"]["value"], - json!([[i64::MAX, 7], [0, 3]]) + merger.target_is_bool_dtype, + "false-valued chunk must not clear the flag" ); } #[test] fn test_finalize_emits_json_booleans_for_bool_target() { + // End-to-end: a categorical target with target_is_bool_dtype = true + // and string-keyed category counts ("true"/"false", as ttgen records + // them via Display for bool) must surface as JSON booleans in the + // emitted CATEGORY_COUNTS array. let mut merger: StatsMerger = StatsMerger::default(); merger.merge(ChunkStats:: { num_train_rows: 10, - target_dtype: Some(DataType::Boolean), + target_is_bool_dtype: true, ..Default::default() }); @@ -1767,9 +1681,7 @@ mod tests { counts.insert("false".to_string(), 7); counts.insert("true".to_string(), 3); - let payload = merger - .finalize(10, false, false, false, Some(counts), "categorical", None) - .unwrap(); + let payload = merger.finalize(10, false, false, false, Some(counts), "categorical", None); let outer = payload .parsed_train_table_col_stats @@ -1797,11 +1709,16 @@ mod tests { } #[test] - fn test_finalize_keeps_string_categories_without_physical_dtype() { + fn test_finalize_emits_string_keys_when_target_is_bool_dtype_is_false() { + // Mirror of the previous test: when the flag is NOT set and stype + // is "categorical" (kumo's convention for binary classification), + // emit must NOT promote string keys to JSON booleans. Asserts the + // fix is gated correctly and doesn't over-fire on plain string + // categoricals that happen to use "true"/"false" as labels. let mut merger: StatsMerger = StatsMerger::default(); merger.merge(ChunkStats:: { num_train_rows: 10, - target_dtype: None, + target_is_bool_dtype: false, ..Default::default() }); @@ -1809,9 +1726,7 @@ mod tests { counts.insert("false".to_string(), 7); counts.insert("true".to_string(), 3); - let payload = merger - .finalize(10, false, false, false, Some(counts), "categorical", None) - .unwrap(); + let payload = merger.finalize(10, false, false, false, Some(counts), "categorical", None); let outer = payload.parsed_train_table_col_stats.unwrap(); let stats = outer.get("stats").expect("outer must have 'stats' wrapper"); let key = stats @@ -2048,9 +1963,7 @@ mod tests { chunk.num_train_rows = 6; let mut merger: StatsMerger = StatsMerger::default(); merger.merge(chunk); - let out = merger - .finalize(6, false, false, false, None, "numerical", None) - .unwrap(); + let out = merger.finalize(6, false, false, false, None, "numerical", None); assert_eq!(out.num_entities, 5); assert_eq!(out.num_targets, 3); assert_eq!(out.exact_stats.timestamp.num_unique, Some(4)); @@ -2087,17 +2000,15 @@ mod tests { let mut merger: StatsMerger = StatsMerger::default(); let train_rows = chunk.num_train_rows; merger.merge(chunk); - merger - .finalize( - num_total_rows.max(train_rows), - is_link_prediction, - false, - false, - target_category_counts, - target_stype, - None, - ) - .unwrap() + merger.finalize( + num_total_rows.max(train_rows), + is_link_prediction, + false, + false, + target_category_counts, + target_stype, + None, + ) } /// The entity column is a foreign key resolved to graph node ids; it is @@ -2122,18 +2033,16 @@ mod tests { let mut merger: StatsMerger = StatsMerger::default(); merger.merge(chunk); - let payload = merger - .finalize( - 5, - false, - false, - false, - Some(target_counts), - "categorical", - // What the executor hands over: entity counting is not done at all. - None, - ) - .unwrap(); + let payload = merger.finalize( + 5, + false, + false, + false, + Some(target_counts), + "categorical", + // What the executor hands over: entity counting is not done at all. + None, + ); let stats = payload .parsed_train_table_col_stats @@ -2523,7 +2432,6 @@ mod sequence_feature_emission_tests { } merger .finalize(num_rows, false, false, false, None, "numerical", None) - .unwrap() .parsed_train_table_col_stats .expect("sequence statistics must emit the Kumo envelope") } diff --git a/packages/diskgraph/diskgraph-train-table/tests/custom_tt_integration.rs b/packages/diskgraph/diskgraph-train-table/tests/custom_tt_integration.rs index de01dd5c60..7b6508055e 100644 --- a/packages/diskgraph/diskgraph-train-table/tests/custom_tt_integration.rs +++ b/packages/diskgraph/diskgraph-train-table/tests/custom_tt_integration.rs @@ -939,56 +939,6 @@ fn synth_static_custom_tt_parquet(out_path: &Path, entity_pks: &[i64], has_targe write_parquet(out_path, &batch); } -/// Imported/exported rows must build a vocabulary with the same physical type. -#[test] -fn test_custom_tt_categorical_stats_preserve_target_type() { - let dir = tempfile::tempdir().unwrap(); - let index = build_users_only_graph(dir.path(), 3); - let targets: Vec> = vec![ - Arc::new(Int64Array::from(vec![0, i64::MAX, 0])), - Arc::new(Float64Array::from(vec![0.5, 2.5, 0.5])), - Arc::new(arrow_array::StringArray::from(vec!["001", "2", "001"])), - Arc::new(arrow_array::BooleanArray::from(vec![false, true, false])), - ]; - let expected = [ - serde_json::json!([[0, 2], [i64::MAX, 1]]), - serde_json::json!([[0.5, 2], [2.5, 1]]), - serde_json::json!([["001", 2], ["2", 1]]), - serde_json::json!([[false, 2], [true, 1]]), - ]; - for (target, expected_counts) in targets.into_iter().zip(expected) { - let pq = dir.path().join("typed_custom_tt.parquet"); - let schema = Arc::new(Schema::new(vec![ - Field::new("ENTITY1", DataType::Int64, false), - Field::new("TARGET1", target.data_type().clone(), false), - ])); - let batch = RecordBatch::try_new( - schema, - vec![Arc::new(Int64Array::from(vec![0, 1, 2])), target], - ) - .unwrap(); - write_parquet(&pq, &batch); - let mut plan = make_custom_tt_target_only_node_plan(); - plan.target_stype = Some("categorical".to_string()); - let out_dir = tempfile::tempdir().unwrap(); - let custom = CustomTtSource { - target_window_end: None, - parquet_path: pq, - input_timestamp_unit: diskgraph_core::time::TimeUnit::Nanoseconds, - on_error: diskgraph_train_table::custom_tt_row_errors::IngestOnError::Abort, - allow_negative_weight: false, - timestamp_reference: None, - }; - let output = - execute_tt_pass_with_source(&plan, &index, out_dir.path(), Some(custom)).unwrap(); - let stats = output.stats.unwrap().parsed_train_table_col_stats.unwrap(); - assert_eq!( - stats["stats"]["TARGET1__kumo.categorical__CATEGORY_COUNTS__False"]["value"], - expected_counts - ); - } -} - /// STATIC custom TRAIN: a parquet with no TIMESTAMP column must NOT error; /// DG synthesizes the native-static sentinel (raw 0 → epoch 0) for every row. #[test] diff --git a/packages/diskgraph/diskgraph-train-table/tests/ttgen_integration.rs b/packages/diskgraph/diskgraph-train-table/tests/ttgen_integration.rs index 391f35cf12..0e2f56b6df 100644 --- a/packages/diskgraph/diskgraph-train-table/tests/ttgen_integration.rs +++ b/packages/diskgraph/diskgraph-train-table/tests/ttgen_integration.rs @@ -2191,40 +2191,6 @@ fn integ_entity_filter_and_stage_filter() { // ─── Tests: Entity features ───────────────────────────────────────────────── -#[test] -fn integ_generated_categorical_stats_preserve_integer_labels() { - let dir = tempfile::tempdir().unwrap(); - let index = build_graph1(dir.path()); - let mut plan = g1_plan(vec![Stage { - ops: vec![Op::Column { - alias: "TARGET".to_string(), - table: "users".to_string(), - column: "level".to_string(), - path: vec![], - }], - filter: None, - }]); - plan.target_stype = Some("categorical".to_string()); - let out_dir = tempfile::tempdir().unwrap(); - let output = diskgraph_train_table::ttgen_executor::execute_tt_pass_with_customizer( - &plan, - &index, - out_dir.path(), - None, - None::)>, - ) - .unwrap(); - let stats = output.stats.unwrap().parsed_train_table_col_stats.unwrap(); - let pairs = stats["stats"]["TARGET1__kumo.categorical__CATEGORY_COUNTS__False"]["value"] - .as_array() - .unwrap(); - let counts: HashMap = pairs - .iter() - .map(|pair| (pair[0].as_i64().unwrap(), pair[1].as_u64().unwrap())) - .collect(); - assert_eq!(counts, HashMap::from([(1, 2), (2, 1), (3, 1), (5, 1)])); -} - #[test] fn integ_entity_column() { // Non-temporal: Op::Column(users.score) diff --git a/packages/kumo-core/src/kumo_core/automl/auto_trainer.py b/packages/kumo-core/src/kumo_core/automl/auto_trainer.py index 26bd13e027..afa027624e 100644 --- a/packages/kumo-core/src/kumo_core/automl/auto_trainer.py +++ b/packages/kumo-core/src/kumo_core/automl/auto_trainer.py @@ -47,6 +47,7 @@ from kumo_core.model_plan import ModelPlan, _is_inferred, _parse_hop_key from kumo_core.modeling.retrieval.mips import require_faiss from kumo_core.resolved_task import ResolvedNumericalTask, ResolvedTaskGraph +from kumo_core.task_dataset import DiskgraphTaskManifest from kumo_core.train.diskgraph_nested_trainer import DiskgraphNestedTrainer from kumo_core.train.shallow_rhs_link_gnn_module import MAX_RHS_SAMPLE_SIZE from kumo_core.train.trainer import Trainer, load_encoders, save_encoders @@ -1066,19 +1067,26 @@ def _resolve_encoders(self) -> EncodersConfig: f"But encoders not found in {automl_dir}") logger.info(f"Copying encoders.json from '{automl_dir}' " f"to '{self.log_dir}'.") - save_encoders(self.log_dir, encoders) - return encoders - - encoders = load_encoders(self.log_dir) - if encoders is None: - # collect_encoders is fairly expensive, so we only do it once. - encoders = self.runtime.collect_encoders(self.task) - processing = self.space.column_processing - overrides = processing.get_encoder_overrides( - processing.encoder_overrides) - apply_na_strategy(self.task, encoders, processing.na_strategy, - overridden=overrides.keys()) - apply_encoder_overrides(self.task, encoders, overrides) + else: + encoders = load_encoders(self.log_dir) + if encoders is None: + # Encoder fitting reads statistics only once per training run. + encoders = self.runtime.collect_encoders(self.task) + processing = self.space.column_processing + overrides = processing.get_encoder_overrides( + processing.encoder_overrides) + apply_na_strategy(self.task, encoders, processing.na_strategy, + overridden=overrides.keys()) + apply_encoder_overrides(self.task, encoders, overrides) + + target = encoders.target + if (target is not None and target.target_dtype is None + and self.diskgraph_task_dataset_bundle_dir is not None): + manifest = DiskgraphTaskManifest.load(osp.join( + self.diskgraph_task_dataset_bundle_dir, 'manifest.json')) + dtype = manifest.target_dtype + if dtype is not None: + target.record_dtype(dtype) save_encoders(self.log_dir, encoders) return encoders diff --git a/packages/kumo-core/src/kumo_core/encoders/config.py b/packages/kumo-core/src/kumo_core/encoders/config.py index d35de3c2e8..6b3d389f65 100644 --- a/packages/kumo-core/src/kumo_core/encoders/config.py +++ b/packages/kumo-core/src/kumo_core/encoders/config.py @@ -1,17 +1,57 @@ # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 +import base64 from collections.abc import Iterable from dataclasses import field +from typing import Literal +import pyarrow as pa from kumoapi.encoder import EncoderType +from pydantic import model_validator from pydantic.dataclasses import dataclass @dataclass class TargetEncoderConfig: + """Fitted target configuration with an optional persisted physical Arrow type. + + Args: + col_name: Logical target column name. + encoder: Fitted target encoder configuration and statistics. + target_dtype: Base64-encoded Arrow IPC schema containing the target field. + """ + col_name: str encoder: EncoderType + target_dtype: str | None = None + + @property + def arrow_dtype(self) -> pa.DataType | None: + """Return the saved Arrow target type, or None for legacy configurations. + + Raises: + ValueError: If the saved type is not a valid target-field schema. + """ + if self.target_dtype is None: + return None + try: + encoded = base64.b64decode(self.target_dtype, validate=True) + schema = pa.ipc.read_schema(pa.BufferReader(encoded)) + except (ValueError, pa.ArrowInvalid, OSError) as error: + raise ValueError("Invalid saved target dtype metadata") from error + if len(schema) != 1 or schema.names != ["target"]: + raise ValueError("Invalid saved target dtype metadata") + return schema.field(0).type + + def record_dtype(self, dtype: pa.DataType) -> None: + """Persist a target type using Arrow's lossless schema representation. + + Args: + dtype: Physical target type, including list element types. + """ + schema = pa.schema([pa.field("target", dtype)]) + self.target_dtype = base64.b64encode(schema.serialize()).decode("ascii") @dataclass(repr=False) @@ -21,6 +61,15 @@ class EncodersConfig: # The target encoder of the training table (optional): target: TargetEncoderConfig | None = None + schema_version: Literal[1, 2] = 2 + + @model_validator(mode="before") + @classmethod + def _legacy_schema_version(cls, value: object) -> object: + """Treat unversioned saved encoder metadata as version 1.""" + if isinstance(value, dict) and "schema_version" not in value: + return {**value, "schema_version": 1} + return value def __getitem__(self, table_name: str) -> dict[str, EncoderType]: if table_name not in self.encoders: diff --git a/packages/kumo-core/src/kumo_core/encoders/target/base.py b/packages/kumo-core/src/kumo_core/encoders/target/base.py index c1563f2929..2f7bccf115 100644 --- a/packages/kumo-core/src/kumo_core/encoders/target/base.py +++ b/packages/kumo-core/src/kumo_core/encoders/target/base.py @@ -2,9 +2,12 @@ # All rights reserved. # SPDX-License-Identifier: Apache-2.0 from abc import ABC, abstractmethod +from collections.abc import Sequence from typing import Generic, TypeVar import pandas as pd +import pyarrow as pa +import pyarrow.compute as pc from kumoapi.encoder import ( Index, MaxLogNumerical, @@ -18,16 +21,21 @@ from torch.nn import Module from torch_frame.data import MultiNestedTensor -from kumo_core.encoders.tensor_mapper import CategoricalTensorMapper, MultiCategoricalTensorMapper, TensorMapper from kumo_core.encoders.scaling import get_offset_and_scale +from kumo_core.encoders.tensor_mapper import ( + CategoricalTensorMapper, + MultiCategoricalTensorMapper, + TensorMapper, +) -T = TypeVar('T', Tensor, MultiNestedTensor) +T = TypeVar("T", Tensor, MultiNestedTensor) class TargetEncoder(Module, Generic[T], ABC): """Target encoder that instantiates the correct target encoder based on the encoder config and attaches the tensor mapper. """ + def __init__(self) -> None: super().__init__() self.tensor_mapper: TensorMapper @@ -47,28 +55,68 @@ def decode(self, tensor: Tensor) -> pd.Series: def from_encoder( cls, task_type: TaskType, - encoder: Index | MultiCategorical | Numerical | MaxLogNumerical + encoder: Index + | MultiCategorical + | Numerical + | MaxLogNumerical | MinLogNumerical, - ) -> 'TargetEncoder': + *, + target_dtype: pa.DataType | None = None, + ) -> "TargetEncoder": + """Build a target encoder using the physical target dtype for its vocabulary. + + Args: + task_type: Prediction task selecting the target transformation. + encoder: Fitted encoder configuration, including cached statistics. + target_dtype: Physical Arrow target type, when a labeled table is present. + + Returns: + A target encoder with a dtype-compatible vocabulary and strict lookup. + + Raises: + ValueError: If the encoder is unsupported or category values cannot be + converted losslessly to the physical target type. + """ from kumo_core.encoders.target.categorical import CategoricalTargetEncoder - from kumo_core.encoders.target.multicategorical import MultiCategoricalTargetEncoder + from kumo_core.encoders.target.multicategorical import ( + MultiCategoricalTargetEncoder, + ) from kumo_core.encoders.target.numerical import NumericalTargetEncoder if isinstance(encoder, Index): category_counts = encoder._stats[ColStatType.CATEGORY_COUNTS] - return CategoricalTargetEncoder( + typed_counts = _typed_target_counts(category_counts, target_dtype) + result = CategoricalTargetEncoder( task_type, - CategoricalTensorMapper(category_counts=category_counts, strict=True), + CategoricalTensorMapper(category_counts=typed_counts, strict=True), ) + if task_type == TaskType.BINARY_CLASSIFICATION: + # Checkpoint weights use the original vocabulary's binary orientation. + original_labels = pd.Index( + [ + label + for label, _ in sorted( + category_counts, key=lambda pair: pair[1], reverse=True + ) + ] + ) + result.reverse = not original_labels.is_monotonic_increasing + return result elif isinstance(encoder, MultiCategorical): category_counts = encoder._stats[ColStatType.MULTI_CATEGORY_COUNTS] - return MultiCategoricalTargetEncoder( - MultiCategoricalTensorMapper( - category_counts=category_counts, - sep=encoder._stats[ColStatType.MULTI_CATEGORIES_SEPARATOR], - strict=True, - )) + mapper = MultiCategoricalTensorMapper( + category_counts=_typed_target_counts(category_counts, target_dtype), + sep=encoder._stats[ColStatType.MULTI_CATEGORIES_SEPARATOR], + strict=True, + ) + if target_dtype is not None: + mapper._is_string_dtype = not ( + pa.types.is_list(target_dtype) + or pa.types.is_large_list(target_dtype) + or pa.types.is_fixed_size_list(target_dtype) + ) + return MultiCategoricalTargetEncoder(mapper) elif isinstance(encoder, Numerical): return NumericalTargetEncoder(*get_offset_and_scale(encoder)) @@ -85,5 +133,33 @@ def from_encoder( log_transform=True, ) - raise ValueError(f"Unsupported encoder provided to 'TargetEncoder'. " - f"Got '{encoder}'.") + raise ValueError( + f"Unsupported encoder provided to 'TargetEncoder'. Got '{encoder}'." + ) + + +def _typed_target_counts( + category_counts: Sequence[Sequence[object]], + target_dtype: pa.DataType | None, +) -> Sequence[Sequence[object]]: + """Cast vocabulary labels once, retaining their counts and original ordering.""" + if target_dtype is None: + return category_counts + if pa.types.is_dictionary(target_dtype): + target_dtype = target_dtype.value_type + if ( + pa.types.is_list(target_dtype) + or pa.types.is_large_list(target_dtype) + or pa.types.is_fixed_size_list(target_dtype) + ): + target_dtype = target_dtype.value_type + try: + labels = pa.array([pair[0] for pair in category_counts]) + labels = pc.cast(labels, target_dtype, safe=True) + except (pa.ArrowInvalid, pa.ArrowNotImplementedError, pa.ArrowTypeError) as error: + raise ValueError( + f"Target vocabulary cannot be converted to {target_dtype}: {error}" + ) from error + return [ + [label, pair[1]] for label, pair in zip(labels.to_pylist(), category_counts) + ] diff --git a/packages/kumo-core/src/kumo_core/encoders/tensor_mapper.py b/packages/kumo-core/src/kumo_core/encoders/tensor_mapper.py index c96b218502..9951d141a2 100644 --- a/packages/kumo-core/src/kumo_core/encoders/tensor_mapper.py +++ b/packages/kumo-core/src/kumo_core/encoders/tensor_mapper.py @@ -513,7 +513,11 @@ def forward( expanded[occupied] = index index = expanded - if strict and has_values and self._is_string_dtype is None: + if ( + strict + and (has_values or not is_string_dtype) + and self._is_string_dtype is None + ): self._is_string_dtype = is_string_dtype return MultiNestedTensor( num_rows=len(array), diff --git a/packages/kumo-core/src/kumo_core/task_dataset.py b/packages/kumo-core/src/kumo_core/task_dataset.py index 4cdcab6111..871db1dedd 100644 --- a/packages/kumo-core/src/kumo_core/task_dataset.py +++ b/packages/kumo-core/src/kumo_core/task_dataset.py @@ -14,6 +14,9 @@ from dataclasses import dataclass, field, replace from typing import Any, Mapping +import pyarrow as pa +import pyarrow.parquet as pq + from kumo_core.encoder_selection import _EncoderStat, select_target_encoder from kumoapi.encoder import EncoderType from kumoapi.typing import ColStatType, Stype @@ -148,6 +151,30 @@ def load_column_stats(self) -> dict[str, dict[str, Mapping[str, Any]]]: column["stats"]) return result + @property + def target_dtype(self) -> pa.DataType | None: + """Read the physical target type from a published seed part's schema. + + Returns: + The Arrow target type, or None for a table without target labels. + + Raises: + ValueError: If no seed stage is available. + OSError: If the published seed part cannot be read. + """ + runtime = _load_manifest_json(self.runtime_manifest_path) + target = runtime["table"]["columns"].get("primary_target") + if target is None: + return None + for stage in runtime["stages"].values(): + root = stage["index_path"] + if not os.path.isabs(root): + root = os.path.join(runtime["graph"]["index_path"], root) + part = os.path.join(root, stage["table_name"], "part-00000.parquet") + schema = pq.read_schema(part) + return schema.field(target).type if target in schema.names else None + raise ValueError("Task dataset has no seed stage to resolve the target dtype") + @property def train_table_name(self) -> str: name = self.metadata.get("train_table_name") diff --git a/packages/kumo-core/src/kumo_core/train/trainer.py b/packages/kumo-core/src/kumo_core/train/trainer.py index 079fdd7bca..b885867d18 100644 --- a/packages/kumo-core/src/kumo_core/train/trainer.py +++ b/packages/kumo-core/src/kumo_core/train/trainer.py @@ -1059,6 +1059,13 @@ def create_pl_model( logger.info(f"Initialized model from checkpoint {ckpt_path}." f" For task {self.task.name}") + @property + def target_dtype(self) -> pa.DataType | None: + """Return the saved target type, defaulting legacy target labels to strings.""" + encoders = self.encoders + target = encoders.target if encoders is not None else None + return (target.arrow_dtype or pa.string()) if target is not None else None + @property def target_encoder(self) -> TargetEncoder | None: if self.encoders.target is None or self.encoders.target.encoder is None: @@ -1066,7 +1073,8 @@ def target_encoder(self) -> TargetEncoder | None: if self._target_encoder is not None: return self._target_encoder self._target_encoder = TargetEncoder.from_encoder( - self.task.task_type, self.encoders.target.encoder) + self.task.task_type, self.encoders.target.encoder, + target_dtype=self.target_dtype) return self._target_encoder def create_pl_trainer(self): @@ -2589,7 +2597,17 @@ def _train_result_json_path(log_dir: str) -> str: return osp.join(log_dir, 'train_result.json') -def save_encoders(root_dir: str, encoders: EncodersConfig): +def save_encoders(root_dir: str, encoders: EncodersConfig) -> None: + """Write fitted encoder metadata using schema version 2. + + Args: + root_dir: Destination directory for encoders.json. + encoders: Fitted configurations, including the persisted target dtype. + + Raises: + OSError: If the encoder metadata cannot be written. + """ + encoders.schema_version = 2 save_json(encoders, osp.join(root_dir, 'encoders.json')) diff --git a/packages/kumo-core/tests/encoders/test_target_dtype_metadata.py b/packages/kumo-core/tests/encoders/test_target_dtype_metadata.py new file mode 100644 index 0000000000..228402e683 --- /dev/null +++ b/packages/kumo-core/tests/encoders/test_target_dtype_metadata.py @@ -0,0 +1,211 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Model encoder metadata preserves target types without prediction labels.""" + +from unittest.mock import Mock + +import pyarrow as pa +import pytest +import torch +from kumo_core.encoders.config import EncodersConfig, TargetEncoderConfig +from kumo_core.encoders.target.categorical import CategoricalTargetEncoder +from kumo_core.encoders.target.multicategorical import MultiCategoricalTargetEncoder +from kumoapi.encoder import Index, MultiCategorical +from kumoapi.task import TaskType +from kumoapi.typing import ColStatType +from pydantic import TypeAdapter, ValidationError + + +@pytest.mark.parametrize( + "dtype", + [ + pa.int64(), + pa.uint64(), + pa.float32(), + pa.bool_(), + pa.string(), + pa.binary(), + pa.duration("ns"), + pa.list_(pa.int64()), + pa.large_list(pa.string()), + pa.list_(pa.int64(), 2), + pa.dictionary(pa.int32(), pa.string()), + ], +) +def test_target_dtype_metadata_round_trip(dtype: pa.DataType) -> None: + """Arrow schema metadata preserves complete types across JSON serialization.""" + config = EncodersConfig(target=TargetEncoderConfig("TARGET", Index())) + assert config.target is not None + config.target.record_dtype(dtype) + serde = TypeAdapter(EncodersConfig) + + restored = serde.validate_json(serde.dump_json(config)) + + assert restored.schema_version == 2 + assert restored.target is not None + assert restored.target.arrow_dtype == dtype + + +def test_unversioned_metadata_loads_as_version_one() -> None: + """Old encoder files remain readable and explicitly lack target dtype metadata.""" + config = EncodersConfig(target=TargetEncoderConfig("TARGET", Index())) + serde = TypeAdapter(EncodersConfig) + legacy = serde.dump_python(config, mode="json") + legacy.pop("schema_version") + legacy["target"].pop("target_dtype") + + restored = serde.validate_python(legacy) + + assert restored.schema_version == 1 + assert restored.target is not None + assert restored.target.arrow_dtype is None + + +def test_future_encoder_metadata_version_is_rejected() -> None: + """A future metadata schema must not be silently interpreted as version two.""" + with pytest.raises(ValidationError, match="schema_version"): + TypeAdapter(EncodersConfig).validate_python({"schema_version": 3}) + + +@pytest.mark.parametrize("encoded", ["not base64", "aW52YWxpZA=="]) +def test_corrupt_target_dtype_metadata_is_rejected(encoded: str) -> None: + """Malformed dtype metadata fails explicitly rather than defaulting to strings.""" + config = TargetEncoderConfig("TARGET", Index(), target_dtype=encoded) + + with pytest.raises(ValueError, match="Invalid saved target dtype metadata"): + _ = config.arrow_dtype + + +@pytest.mark.parametrize("resumed", [False, True]) +@pytest.mark.parametrize("already_recorded", [False, True]) +def test_training_persists_dtype_before_saving_encoder_metadata( + monkeypatch: pytest.MonkeyPatch, resumed: bool, already_recorded: bool +) -> None: + """New fits and resumed checkpoints save a dtype for unlabeled prediction.""" + import kumo_core.automl.auto_trainer as automl + import kumo_core.train.trainer as trainer_module + + config = EncodersConfig( + target=TargetEncoderConfig( + "TARGET", Index(_stats={ColStatType.CATEGORY_COUNTS: [["2", 10], ["0", 5]]}) + ), + schema_version=1, + ) + assert config.target is not None + if already_recorded: + config.target.record_dtype(pa.int64()) + load_manifest = Mock(return_value=Mock(target_dtype=pa.int64())) + saved: list[bytes] = [] + + def capture_metadata(value: EncodersConfig, path: str) -> None: + """Capture serialized model metadata without writing to a filesystem.""" + assert path == "/runs/task/automl/encoders.json" + saved.append(TypeAdapter(EncodersConfig).dump_json(value)) + + monkeypatch.setattr(automl, "load_encoders", Mock(return_value=config)) + monkeypatch.setattr(automl.DiskgraphTaskManifest, "load", load_manifest) + monkeypatch.setattr(automl, "apply_na_strategy", Mock()) + monkeypatch.setattr(automl, "apply_encoder_overrides", Mock()) + monkeypatch.setattr(trainer_module, "save_json", capture_metadata) + trainer = object.__new__(automl.AutoTrainer) + trainer.checkpoint_path = "/old/checkpoint.ckpt" if resumed else None + trainer.checkpoint_encoder_dir = "/old" + trainer.root_dir = "/runs" + trainer.task = Mock() + trainer.task.name = "task" + trainer.diskgraph_task_dataset_bundle_dir = "/labeled-bundle" + trainer.space = Mock() + trainer.space.column_processing.get_encoder_overrides.return_value = {} + + trainer._resolve_encoders() + restored = TypeAdapter(EncodersConfig).validate_json(saved[0]) + + assert restored.schema_version == 2 + assert restored.target is not None + assert restored.target.arrow_dtype == pa.int64() + if already_recorded: + load_manifest.assert_not_called() + else: + load_manifest.assert_called_once_with("/labeled-bundle/manifest.json") + + +@pytest.mark.parametrize("multilabel", [False, True]) +@pytest.mark.parametrize("record_dtype", [False, True]) +def test_prediction_restores_label_types_without_reading_target_rows( + monkeypatch: pytest.MonkeyPatch, multilabel: bool, record_dtype: bool +) -> None: + """Reloaded models use saved types; legacy vocabularies decode to strings.""" + from kumo_core.task_dataset import DiskgraphTaskManifest + from kumo_core.train.diskgraph_nested_trainer import DiskgraphNestedTrainer + + config = ( + MultiCategorical( + _stats={ + ColStatType.MULTI_CATEGORY_COUNTS: [["2", 10], ["0", 5]], + ColStatType.MULTI_CATEGORIES_SEPARATOR: "|", + } + ) + if multilabel + else Index(_stats={ColStatType.CATEGORY_COUNTS: [["2", 10], ["0", 5]]}) + ) + encoders = EncodersConfig(target=TargetEncoderConfig("TARGET", config)) + assert encoders.target is not None + if record_dtype: + encoders.target.record_dtype(pa.list_(pa.int64()) if multilabel else pa.int64()) + serde = TypeAdapter(EncodersConfig) + payload = serde.dump_python(encoders, mode="json") + if not record_dtype: + payload.pop("schema_version") + payload["target"].pop("target_dtype") + trainer = object.__new__(DiskgraphNestedTrainer) + trainer.task = Mock( + task_type=( + TaskType.MULTILABEL_CLASSIFICATION + if multilabel + else TaskType.MULTICLASS_CLASSIFICATION + ) + ) + trainer.encoders = serde.validate_python(payload) + trainer._target_encoder = None + trainer.diskgraph_task_dataset_bundle_dir = "/unlabeled-prediction-bundle" + load = Mock(side_effect=AssertionError("Prediction must not read target rows")) + monkeypatch.setattr(DiskgraphTaskManifest, "load", load) + + encoder = trainer.target_encoder + assert encoder is not None + assert isinstance(encoder, CategoricalTargetEncoder | MultiCategoricalTargetEncoder) + if multilabel: + result = encoder.decode(torch.tensor([[1.0, 0.0]])) + if record_dtype: + assert result.iloc[0].tolist() == [2] + else: + assert result.iloc[0] == "2" + else: + result = encoder.decode(torch.tensor([[0]])) + assert result.tolist() == ([2] if record_dtype else ["2"]) + assert encoder.tensor_mapper.mapping.tolist() == ( + [2, 0] if record_dtype else ["2", "0"] + ) + load.assert_not_called() + + +def test_legacy_numeric_vocabulary_defaults_to_string_output() -> None: + """Missing dtype metadata explicitly selects strings even for JSON numbers.""" + from kumo_core.train.diskgraph_nested_trainer import DiskgraphNestedTrainer + + trainer = object.__new__(DiskgraphNestedTrainer) + trainer.task = Mock(task_type=TaskType.MULTICLASS_CLASSIFICATION) + trainer.encoders = EncodersConfig( + target=TargetEncoderConfig( + "TARGET", Index(_stats={ColStatType.CATEGORY_COUNTS: [[2, 10], [0, 5]]}) + ), + schema_version=1, + ) + trainer._target_encoder = None + + encoder = trainer.target_encoder + assert encoder is not None + result = encoder.decode(torch.tensor([[0], [1]])) + + assert result.tolist() == ["2", "0"] diff --git a/packages/kumo-core/tests/encoders/test_target_vocabulary_dtype.py b/packages/kumo-core/tests/encoders/test_target_vocabulary_dtype.py new file mode 100644 index 0000000000..f19b27adb5 --- /dev/null +++ b/packages/kumo-core/tests/encoders/test_target_vocabulary_dtype.py @@ -0,0 +1,202 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Normalize stored target vocabularies using physical training-table types.""" + +from unittest.mock import Mock + +import pyarrow as pa +import pytest +import torch +from kumo_core.encoders.config import EncodersConfig, TargetEncoderConfig +from kumo_core.encoders.target.base import TargetEncoder +from kumo_core.encoders.target.categorical import CategoricalTargetEncoder +from kumo_core.encoders.target.multicategorical import MultiCategoricalTargetEncoder +from kumo_core.task_dataset import DiskgraphTaskManifest +from kumoapi.encoder import Index, MultiCategorical +from kumoapi.task import TaskType +from kumoapi.typing import ColStatType +from pydantic import TypeAdapter + + +@pytest.mark.parametrize( + ("dtype", "stored_labels", "targets"), + [ + (pa.int64(), ["2", "0", "1"], [2, 0, 1]), + (pa.int64(), [2, 0, 1], [2, 0, 1]), + (pa.int64(), [str(2**63 - 1), "0", "-1"], [2**63 - 1, 0, -1]), + (pa.float64(), ["2.5", "0", "1"], [2.5, 0.0, 1.0]), + (pa.bool_(), ["true", "false"], [True, False]), + (pa.bool_(), [True, False], [True, False]), + (pa.string(), ["002", "0", "1"], ["002", "0", "1"]), + (pa.binary(), ["002", "0", "1"], [b"002", b"0", b"1"]), + ], +) +def test_restored_target_vocabulary_uses_physical_dtype( + dtype: pa.DataType, + stored_labels: list[str | int | float | bool], + targets: list[str | bytes | int | float | bool], +) -> None: + """Old and typed encoders.json retain class IDs when rebuilt for a table.""" + counts = [[label, 10 - index] for index, label in enumerate(stored_labels)] + config = EncodersConfig( + target=TargetEncoderConfig( + "TARGET", Index(_stats={ColStatType.CATEGORY_COUNTS: counts}) + ) + ) + serde = TypeAdapter(EncodersConfig) + restored = serde.validate_json(serde.dump_json(config)) + assert restored.target is not None + encoder = TargetEncoder.from_encoder( + TaskType.MULTICLASS_CLASSIFICATION, + restored.target.encoder, + target_dtype=dtype, + ) + assert isinstance(encoder, CategoricalTargetEncoder) + + result = encoder.tensor_mapper(pa.array(targets, type=dtype)) + + torch.testing.assert_close(result.view(-1), torch.arange(len(targets))) + assert encoder.tensor_mapper.mapping.tolist() == targets + assert restored.target.encoder._stats[ColStatType.CATEGORY_COUNTS] == counts + + +def test_binary_normalization_preserves_checkpoint_orientation() -> None: + """Converting vocabulary types must not reverse a saved binary model's head.""" + config = Index(_stats={ColStatType.CATEGORY_COUNTS: [["2", 10], ["10", 5]]}) + original = TargetEncoder.from_encoder(TaskType.BINARY_CLASSIFICATION, config) + normalized = TargetEncoder.from_encoder( + TaskType.BINARY_CLASSIFICATION, config, target_dtype=pa.int64() + ) + assert isinstance(normalized, CategoricalTargetEncoder) + assert isinstance(original, CategoricalTargetEncoder) + + result = normalized.encode_tensor(normalized.tensor_mapper(pa.array([2, 10]))) + expected = original.encode_tensor(original.tensor_mapper(pa.array(["2", "10"]))) + + torch.testing.assert_close(result, expected) + assert normalized.decode(torch.tensor([[0], [1]])).tolist() == [10, 2] + + +@pytest.mark.parametrize("dtype", [pa.int64(), pa.string()]) +def test_multilabel_vocabulary_uses_list_element_type(dtype: pa.DataType) -> None: + """List targets retain class order, missing rows, and unknown-label checks.""" + config = MultiCategorical( + _stats={ + ColStatType.MULTI_CATEGORY_COUNTS: [["2", 10], ["0", 5]], + ColStatType.MULTI_CATEGORIES_SEPARATOR: "|", + } + ) + encoder = TargetEncoder.from_encoder( + TaskType.MULTILABEL_CLASSIFICATION, config, target_dtype=pa.list_(dtype) + ) + assert isinstance(encoder, MultiCategoricalTargetEncoder) + labels = [2, 0] if pa.types.is_integer(dtype) else ["2", "0"] + + mapped = encoder.tensor_mapper(pa.array([labels, [], None], type=pa.list_(dtype))) + result = encoder.encode_tensor(mapped) + + torch.testing.assert_close( + result, torch.tensor([[1.0, 1.0], [0.0, 0.0], [0.0, 0.0]]) + ) + unknown = 5 if pa.types.is_integer(dtype) else "5" + with pytest.raises(ValueError, match="not present in target encoder mapping"): + encoder.tensor_mapper(pa.array([[unknown]], type=pa.list_(dtype))) + + +def test_invalid_vocabulary_fails_during_construction() -> None: + """Invalid persisted labels fail before a mapper can publish invalid IDs.""" + config = Index(_stats={ColStatType.CATEGORY_COUNTS: [["invalid", 10]]}) + + with pytest.raises(ValueError, match="Target vocabulary cannot be converted"): + TargetEncoder.from_encoder( + TaskType.MULTICLASS_CLASSIFICATION, config, target_dtype=pa.int64() + ) + + +@pytest.mark.parametrize("labeled", [False, True]) +def test_manifest_reads_actual_target_dtype( + monkeypatch: pytest.MonkeyPatch, labeled: bool +) -> None: + """Seed schemas override legacy string metadata without reading target rows.""" + runtime = { + "table": {"columns": {"primary_target": "TARGET1"}}, + "graph": {"index_path": "/graph"}, + "stages": { + "train": {"index_path": "train_tables/tt", "table_name": "train_seeds"} + }, + } + schema = pa.schema([("ENTITY1", pa.int64())]) + if labeled: + schema = schema.append(pa.field("TARGET1", pa.int64())) + read_schema = Mock(return_value=schema) + monkeypatch.setattr( + "kumo_core.task_dataset._load_manifest_json", Mock(return_value=runtime) + ) + monkeypatch.setattr("kumo_core.task_dataset.pq.read_schema", read_schema) + manifest = DiskgraphTaskManifest( + manifest_path="/bundle/manifest.json", + runtime_manifest_path="/bundle/runtime_manifest.json", + manifest={}, + metadata={}, + feature_schema={"target_encoder_input": {"dtype": "string"}}, + graph_runtime_metadata={}, + ) + + result = manifest.target_dtype + + assert result == (pa.int64() if labeled else None) + read_schema.assert_called_once_with( + "/graph/train_tables/tt/train_seeds/part-00000.parquet" + ) + + +def test_trainer_normalizes_a_restored_vocabulary_once( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Resume uses saved counts and the current table's schema, then caches the mapper.""" + from kumo_core.train.diskgraph_nested_trainer import DiskgraphNestedTrainer + + trainer = object.__new__(DiskgraphNestedTrainer) + trainer.task = Mock(task_type=TaskType.MULTICLASS_CLASSIFICATION) + trainer.encoders = EncodersConfig( + target=TargetEncoderConfig( + "TARGET", + Index(_stats={ColStatType.CATEGORY_COUNTS: [["2", 10], ["0", 5]]}), + ) + ) + assert trainer.encoders.target is not None + trainer.encoders.target.record_dtype(pa.int64()) + trainer._target_encoder = None + trainer.diskgraph_task_dataset_bundle_dir = "/bundle" + load = Mock(side_effect=AssertionError("Prediction must use persisted dtype")) + monkeypatch.setattr(DiskgraphTaskManifest, "load", load) + + encoder = trainer.target_encoder + + assert encoder is trainer.target_encoder + assert isinstance(encoder, CategoricalTargetEncoder) + torch.testing.assert_close( + encoder.tensor_mapper(pa.array([2, 0])), torch.tensor([[0], [1]]) + ) + load.assert_not_called() + + +def test_typed_null_multilabel_batch_selects_list_decoding() -> None: + """Typed all-null list inputs establish list decoding for numeric categories.""" + config = MultiCategorical( + _stats={ + ColStatType.MULTI_CATEGORY_COUNTS: [["42", 10]], + ColStatType.MULTI_CATEGORIES_SEPARATOR: "|", + } + ) + encoder = TargetEncoder.from_encoder( + TaskType.MULTILABEL_CLASSIFICATION, + config, + target_dtype=pa.list_(pa.int64()), + ) + encoder.tensor_mapper(pa.array([None], type=pa.list_(pa.int64()))) + + result = encoder.decode(torch.tensor([[1.0]])) + + assert result.iloc[0].tolist() == [42] diff --git a/packages/kumo-engine/test/test_integer_categorical_targets.py b/packages/kumo-engine/test/test_integer_categorical_targets.py new file mode 100644 index 0000000000..bd10b7ab7f --- /dev/null +++ b/packages/kumo-engine/test/test_integer_categorical_targets.py @@ -0,0 +1,229 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Exercise integer categorical targets through the installed public Engine API.""" + +from collections.abc import Iterator +from datetime import datetime, timedelta +from pathlib import Path + +import kumo.engine as kumo +import numpy as np +import pyarrow as pa +import pyarrow.compute as pc +import pyarrow.parquet as pq +import pytest +from kumo.engine._scratch import get_scratch_dir +from kumoapi.model_plan import ModelPlan, TrainingTableGenerationPlan +from kumoapi.train import TrainingTableSpec +from wheel_gpu_smoke import make_plan + + +@pytest.fixture(scope="module") +def integer_graph( + tmp_path_factory: pytest.TempPathFactory, +) -> Iterator[tuple[kumo.Graph, kumo.GraphSnapshot]]: + """Build a local graph with integer binary and multiclass target columns.""" + root = tmp_path_factory.mktemp("integer-categorical-targets") + previous = get_scratch_dir() + kumo.configure(scratch_dir=root / "scratch") + try: + data = root / "data" + data.mkdir() + users = pa.table( + { + "id": range(96), + "binary": [2 if index % 2 else 10 for index in range(96)], + "tier": [(11, 23, 47)[index % 3] for index in range(96)], + "feature": [float(index % 7) for index in range(96)], + } + ) + events = [(user, day) for user in range(96) for day in range(30)] + pq.write_table(users, data / "users.parquet") + pq.write_table( + pa.table( + { + "id": range(len(events)), + "user_id": [user for user, _ in events], + "time": pa.array( + [ + datetime(2024, 1, 1) + timedelta(days=day) + for _, day in events + ], + type=pa.timestamp("ns"), + ), + "tier": [(11, 23, 47)[user % 3] for user, _ in events], + } + ), + data / "events.parquet", + ) + connector = kumo.FileConnector(root_dir=str(data)) + graph = kumo.Graph( + { + "users": kumo.Table.from_source_table( + connector["users"], primary_key="id" + ) + .with_column("binary", stype="categorical") + .with_column("tier", stype="categorical"), + "events": kumo.Table.from_source_table( + connector["events"], primary_key="id", time_column="time" + ) + .with_column("user_id", stype="ID") + .with_column("tier", stype="categorical"), + }, + edges=[kumo.Edge("events", "user_id", "users")], + ) + yield graph, graph.snapshot() + finally: + kumo.configure(scratch_dir=previous) + + +def _small_plan(task_type: str) -> ModelPlan: + """Select a deterministic one-step CPU model without explanation work.""" + plan = make_plan("binary" if task_type == "binary_classification" else "multiclass") + plan.optimization.max_epochs = 1 + plan.optimization.min_steps_per_epoch = 1 + plan.optimization.max_steps_per_epoch = 1 + plan.optimization.max_val_steps = 2 + plan.optimization.max_test_steps = 2 + plan.optimization.batch_size = [32] + return plan + + +def _prediction_rows( + result: kumo.PredictionResult, task_type: str, labels: tuple[int, ...] +) -> pa.Table: + """Check bounded outputs: integer classes or boolean predicate predictions.""" + binary = task_type == "binary_classification" + assert result.num_rows == (3 if binary else 3 * len(labels)) + columns = ( + ["ENTITY", "TARGET_PRED", "True_PROB"] + if binary + else ["ENTITY", "CLASS", "SCORE"] + ) + tables = [] + for path in result.files: + with pq.ParquetFile(path) as source: + tables.append(source.read(columns=columns)) + rows = pa.concat_tables(tables) + label = "TARGET_PRED" if binary else "CLASS" + if binary: + assert pa.types.is_boolean(rows.schema.field(label).type) + assert rows[label].null_count == 0 + else: + assert pa.types.is_integer(rows.schema.field(label).type) + assert set(rows[label].to_pylist()) == set(labels) + score = "True_PROB" if binary else "SCORE" + assert np.isfinite(rows[score].to_numpy()).all() + keys = [("ENTITY", "ascending")] + if not binary: + keys.append(("CLASS", "ascending")) + return rows.take(pc.sort_indices(rows, sort_keys=keys)) + + +@pytest.mark.parametrize( + ("target", "task_type", "custom"), + [ + ("users.binary", "multiclass_classification", False), + ("users.tier", "multiclass_classification", False), + ("FIRST(events.tier, 0, 1, days)", "multiclass_classification", False), + ("users.binary = 2", "binary_classification", True), + ("users.tier", "multiclass_classification", True), + ], + ids=[ + "static-two-class", + "static-multiclass", + "temporal-first", + "custom-binary", + "custom-multiclass", + ], +) +def test_integer_categorical_fit_predict_and_reload( + integer_graph: tuple[kumo.Graph, kumo.GraphSnapshot], + tmp_path: Path, + target: str, + task_type: str, + custom: bool, +) -> None: + """Integer targets train and retain the query's output types after model reload.""" + graph, snapshot = integer_graph + query = kumo.PredictiveQuery(graph, f"PREDICT {target} FOR EACH users.id") + assert query.get_task_type().value == task_type + temporal = target.startswith("FIRST") + classes = (2, 10) if "binary" in target else (11, 23, 47) + connector = kumo.FileConnector(root_dir=str(tmp_path)) + if custom: + labels = ( + [2 if index % 2 else 10 for index in range(96)] + if task_type == "binary_classification" + else [(11, 23, 47)[index % 3] for index in range(96)] + ) + pq.write_table( + pa.table( + { + "ENTITY1": range(96), + "TARGET1": labels, + "SPLIT": [0] * 48 + [1] * 24 + [2] * 24, + } + ), + tmp_path / "training.parquet", + ) + table = kumo.TrainingTable.from_source_table( + connector["training"], + TrainingTableSpec(split_col="SPLIT"), + pq=query, + snapshot=snapshot, + ) + else: + generation = TrainingTableGenerationPlan( + split=( + "TimeRangeSplit([('2024-01-01', '2024-01-10'), " + "('2024-01-10', '2024-01-20'), ('2024-01-20', '2024-01-30')], " + "timeframe=1, flexible_boundaries=False)" + if temporal + else "RandomSplit([0.5, 0.25, 0.25])" + ), + ) + if temporal: + generation.timeframe_step = 3 + table = query.generate_training_table(snapshot, plan=generation) + trainer = kumo.Trainer(_small_plan(task_type), accelerator="cpu") + fitted = trainer.fit(table, snapshot=snapshot) + inputs = pa.table({"ENTITY1": [0, 1, 2]}) + if temporal: + inputs = inputs.append_column( + "TIMESTAMP", pa.array([datetime(2024, 1, 20)] * 3, type=pa.timestamp("ns")) + ) + pq.write_table(inputs, tmp_path / "prediction.parquet") + before = _prediction_rows( + trainer.predict( + snapshot=snapshot, + entities=connector["prediction"], + num_classes_to_return=None + if task_type == "binary_classification" + else len(classes), + binary_classification_threshold=0.5, + ), + task_type, + classes, + ) + restored = kumo.Trainer.load(fitted.bundle_dir, accelerator="cpu") + after = _prediction_rows( + restored.predict( + snapshot=snapshot, + entities=connector["prediction"], + num_classes_to_return=None + if task_type == "binary_classification" + else len(classes), + binary_classification_threshold=0.5, + ), + task_type, + classes, + ) + + label = "TARGET_PRED" if task_type == "binary_classification" else "CLASS" + score = "True_PROB" if task_type == "binary_classification" else "SCORE" + assert before[label].equals(after[label]) + np.testing.assert_allclose( + before[score].to_numpy(), after[score].to_numpy(), atol=0.005, rtol=0 + ) From 5d3a4ed7d89de2733ae5092455229bac606b6e68 Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Thu, 3 Dec 2026 23:18:57 +0000 Subject: [PATCH 5/7] Use default test discovery for integer target coverage --- .github/workflows/kumo-engine-pr.yml | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/.github/workflows/kumo-engine-pr.yml b/.github/workflows/kumo-engine-pr.yml index 9d2b1f8598..514dc52252 100644 --- a/.github/workflows/kumo-engine-pr.yml +++ b/.github/workflows/kumo-engine-pr.yml @@ -211,23 +211,13 @@ jobs: mkdir -p "$work" python -m venv "$RUNNER_TEMP/lifecycle-env" uv --no-config pip install --python "$RUNNER_TEMP/lifecycle-env/bin/python" \ - --default-index https://pypi.org/simple --torch-backend cpu "$wheel[mlflow]" 'mlflow>=3.5,<4' 'pytest>=8,<10' 2>&1 | tee "$work/install.log" + --default-index https://pypi.org/simple --torch-backend cpu "$wheel[mlflow]" 'mlflow>=3.5,<4' 2>&1 | tee "$work/install.log" # uv omits archive hashes; pip records the selected wheel's identity. "$RUNNER_TEMP/lifecycle-env/bin/python" -I -m pip --isolated install --no-index --no-deps --force-reinstall "$wheel" cp "$GITHUB_WORKSPACE"/packages/kumo-engine/test/wheel_{mlops_lifecycle,gpu_smoke}.py "$work/" cd "$work" "$RUNNER_TEMP/lifecycle-env/bin/python" -I wheel_mlops_lifecycle.py \ --output-dir "$work/results" --wheel "$wheel" --expected-version "$version" --phase-timeout 300 2>&1 | tee "$work/run.log" - - name: Test integer categorical targets against the candidate wheel - run: | - set -euo pipefail - work="$RUNNER_TEMP/engine-cpu-lifecycle" - cp packages/kumo-engine/test/test_integer_categorical_targets.py "$work/" - cd "$work" - "$RUNNER_TEMP/lifecycle-env/bin/python" -I -m pytest \ - -q -c /dev/null --confcutdir="$work" \ - --basetemp="$work/integer-target-tests" \ - test_integer_categorical_targets.py 2>&1 | tee "$work/integer-target-tests.log" - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 if: always() with: From ffc16ccb30c19113be9f1ac713bc7443a96ed5d7 Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Fri, 4 Dec 2026 00:06:08 +0000 Subject: [PATCH 6/7] Store compact target dtype metadata and preserve unsigned vocabularies --- .../src/kumo_core/encoders/config.py | 82 ++++++++++++++++--- .../src/kumo_core/encoders/target/base.py | 15 +++- .../encoders/test_target_dtype_metadata.py | 73 +++++++++++++---- .../encoders/test_target_vocabulary_dtype.py | 52 ++++++++++++ 4 files changed, 191 insertions(+), 31 deletions(-) diff --git a/packages/kumo-core/src/kumo_core/encoders/config.py b/packages/kumo-core/src/kumo_core/encoders/config.py index 6b3d389f65..110c128731 100644 --- a/packages/kumo-core/src/kumo_core/encoders/config.py +++ b/packages/kumo-core/src/kumo_core/encoders/config.py @@ -1,7 +1,6 @@ # SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. # All rights reserved. # SPDX-License-Identifier: Apache-2.0 -import base64 from collections.abc import Iterable from dataclasses import field from typing import Literal @@ -19,39 +18,96 @@ class TargetEncoderConfig: Args: col_name: Logical target column name. encoder: Fitted target encoder configuration and statistics. - target_dtype: Base64-encoded Arrow IPC schema containing the target field. + target_dtype: Arrow scalar alias or tagged JSON array for a container type. """ col_name: str encoder: EncoderType - target_dtype: str | None = None + target_dtype: str | list[str | int | bool] | None = None @property def arrow_dtype(self) -> pa.DataType | None: """Return the saved Arrow target type, or None for legacy configurations. Raises: - ValueError: If the saved type is not a valid target-field schema. + ValueError: If the saved type is not a valid alias or tagged container. """ if self.target_dtype is None: return None + encoded = self.target_dtype try: - encoded = base64.b64decode(self.target_dtype, validate=True) - schema = pa.ipc.read_schema(pa.BufferReader(encoded)) - except (ValueError, pa.ArrowInvalid, OSError) as error: + if isinstance(encoded, str): + return pa.type_for_alias(encoded) + if len(encoded) == 2 and isinstance(encoded[1], str): + item = pa.type_for_alias(encoded[1]) + if encoded[0] == "list": + return pa.list_(item) + if encoded[0] == "large_list": + return pa.large_list(item) + if ( + len(encoded) == 3 + and encoded[0] == "fixed_size_list" + and isinstance(encoded[1], str) + and type(encoded[2]) is int + and encoded[2] >= 0 + ): + return pa.list_(pa.type_for_alias(encoded[1]), encoded[2]) + if ( + len(encoded) == 4 + and encoded[0] == "dictionary" + and isinstance(encoded[1], str) + and isinstance(encoded[2], str) + and type(encoded[3]) is bool + ): + return pa.dictionary( + pa.type_for_alias(encoded[1]), + pa.type_for_alias(encoded[2]), + ordered=encoded[3], + ) + except (ValueError, TypeError) as error: raise ValueError("Invalid saved target dtype metadata") from error - if len(schema) != 1 or schema.names != ["target"]: - raise ValueError("Invalid saved target dtype metadata") - return schema.field(0).type + raise ValueError("Invalid saved target dtype metadata") def record_dtype(self, dtype: pa.DataType) -> None: - """Persist a target type using Arrow's lossless schema representation. + """Persist a target type as a scalar alias or compact tagged JSON array. Args: dtype: Physical target type, including list element types. + + Raises: + ValueError: If a component type has no round-trippable Arrow alias. """ - schema = pa.schema([pa.field("target", dtype)]) - self.target_dtype = base64.b64encode(schema.serialize()).decode("ascii") + if pa.types.is_dictionary(dtype): + self.target_dtype = [ + "dictionary", + _dtype_alias(dtype.index_type), + _dtype_alias(dtype.value_type), + dtype.ordered, + ] + elif pa.types.is_fixed_size_list(dtype): + self.target_dtype = [ + "fixed_size_list", + _dtype_alias(dtype.value_type), + dtype.list_size, + ] + elif pa.types.is_large_list(dtype): + self.target_dtype = ["large_list", _dtype_alias(dtype.value_type)] + elif pa.types.is_list(dtype): + self.target_dtype = ["list", _dtype_alias(dtype.value_type)] + else: + self.target_dtype = _dtype_alias(dtype) + + +def _dtype_alias(dtype: pa.DataType) -> str: + """Require a readable Arrow alias that reconstructs the exact component type.""" + alias = str(dtype) + try: + restored = pa.type_for_alias(alias) + except ValueError as error: + raise ValueError(f"Unsupported target dtype metadata: {dtype}") from error + if restored != dtype: + raise ValueError(f"Unsupported target dtype metadata: {dtype}") + return alias @dataclass(repr=False) diff --git a/packages/kumo-core/src/kumo_core/encoders/target/base.py b/packages/kumo-core/src/kumo_core/encoders/target/base.py index 2f7bccf115..3547242912 100644 --- a/packages/kumo-core/src/kumo_core/encoders/target/base.py +++ b/packages/kumo-core/src/kumo_core/encoders/target/base.py @@ -3,6 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 from abc import ABC, abstractmethod from collections.abc import Sequence +from numbers import Integral from typing import Generic, TypeVar import pandas as pd @@ -154,9 +155,19 @@ def _typed_target_counts( ): target_dtype = target_dtype.value_type try: - labels = pa.array([pair[0] for pair in category_counts]) + values = [pair[0] for pair in category_counts] + native_integers = pa.types.is_integer(target_dtype) and all( + isinstance(value, Integral) and not isinstance(value, bool) + for value in values + ) + labels = pa.array(values, type=target_dtype if native_integers else None) labels = pc.cast(labels, target_dtype, safe=True) - except (pa.ArrowInvalid, pa.ArrowNotImplementedError, pa.ArrowTypeError) as error: + except ( + pa.ArrowInvalid, + pa.ArrowNotImplementedError, + pa.ArrowTypeError, + OverflowError, + ) as error: raise ValueError( f"Target vocabulary cannot be converted to {target_dtype}: {error}" ) from error diff --git a/packages/kumo-core/tests/encoders/test_target_dtype_metadata.py b/packages/kumo-core/tests/encoders/test_target_dtype_metadata.py index 228402e683..7693e99e21 100644 --- a/packages/kumo-core/tests/encoders/test_target_dtype_metadata.py +++ b/packages/kumo-core/tests/encoders/test_target_dtype_metadata.py @@ -18,30 +18,41 @@ @pytest.mark.parametrize( - "dtype", + ("dtype", "encoded"), [ - pa.int64(), - pa.uint64(), - pa.float32(), - pa.bool_(), - pa.string(), - pa.binary(), - pa.duration("ns"), - pa.list_(pa.int64()), - pa.large_list(pa.string()), - pa.list_(pa.int64(), 2), - pa.dictionary(pa.int32(), pa.string()), + (pa.int64(), "int64"), + (pa.uint64(), "uint64"), + (pa.float32(), "float"), + (pa.bool_(), "bool"), + (pa.string(), "string"), + (pa.binary(), "binary"), + (pa.duration("ns"), "duration[ns]"), + (pa.list_(pa.int64()), ["list", "int64"]), + (pa.large_list(pa.string()), ["large_list", "string"]), + (pa.list_(pa.int64(), 2), ["fixed_size_list", "int64", 2]), + ( + pa.dictionary(pa.int32(), pa.string()), + ["dictionary", "int32", "string", False], + ), + ( + pa.dictionary(pa.int32(), pa.string(), ordered=True), + ["dictionary", "int32", "string", True], + ), ], ) -def test_target_dtype_metadata_round_trip(dtype: pa.DataType) -> None: - """Arrow schema metadata preserves complete types across JSON serialization.""" +def test_target_dtype_metadata_round_trip( + dtype: pa.DataType, encoded: str | list[str | int | bool] +) -> None: + """Readable scalar aliases and tagged arrays survive JSON serialization.""" config = EncodersConfig(target=TargetEncoderConfig("TARGET", Index())) assert config.target is not None config.target.record_dtype(dtype) serde = TypeAdapter(EncodersConfig) + payload = serde.dump_python(config, mode="json") restored = serde.validate_json(serde.dump_json(config)) + assert payload["target"]["target_dtype"] == encoded assert restored.schema_version == 2 assert restored.target is not None assert restored.target.arrow_dtype == dtype @@ -68,8 +79,24 @@ def test_future_encoder_metadata_version_is_rejected() -> None: TypeAdapter(EncodersConfig).validate_python({"schema_version": 3}) -@pytest.mark.parametrize("encoded", ["not base64", "aW52YWxpZA=="]) -def test_corrupt_target_dtype_metadata_is_rejected(encoded: str) -> None: +@pytest.mark.parametrize( + "encoded", + [ + "unknown_type", + [], + ["list"], + ["list", "unknown_type"], + ["unknown_container", "int64"], + ["list", "int64", 2], + ["fixed_size_list", "int64", -1], + ["fixed_size_list", "int64", True], + ["dictionary", "string", "string", False], + ["dictionary", "int32", "string", "false"], + ], +) +def test_corrupt_target_dtype_metadata_is_rejected( + encoded: str | list[str | int | bool], +) -> None: """Malformed dtype metadata fails explicitly rather than defaulting to strings.""" config = TargetEncoderConfig("TARGET", Index(), target_dtype=encoded) @@ -209,3 +236,17 @@ def test_legacy_numeric_vocabulary_defaults_to_string_output() -> None: result = encoder.decode(torch.tensor([[0], [1]])) assert result.tolist() == ["2", "0"] + + +@pytest.mark.parametrize( + "dtype", + [pa.timestamp("ns", tz="UTC"), pa.struct([("value", pa.int64())])], +) +def test_unsupported_dtype_is_rejected_before_recording(dtype: pa.DataType) -> None: + """Unsupported aliases fail without modifying an existing configuration.""" + config = TargetEncoderConfig("TARGET", Index(), target_dtype="int64") + + with pytest.raises(ValueError, match="Unsupported target dtype metadata"): + config.record_dtype(dtype) + + assert config.arrow_dtype == pa.int64() diff --git a/packages/kumo-core/tests/encoders/test_target_vocabulary_dtype.py b/packages/kumo-core/tests/encoders/test_target_vocabulary_dtype.py index f19b27adb5..2fd9d25355 100644 --- a/packages/kumo-core/tests/encoders/test_target_vocabulary_dtype.py +++ b/packages/kumo-core/tests/encoders/test_target_vocabulary_dtype.py @@ -25,6 +25,10 @@ (pa.int64(), ["2", "0", "1"], [2, 0, 1]), (pa.int64(), [2, 0, 1], [2, 0, 1]), (pa.int64(), [str(2**63 - 1), "0", "-1"], [2**63 - 1, 0, -1]), + (pa.uint64(), [2**63, 0], [2**63, 0]), + (pa.uint64(), [2**64 - 1, 0], [2**64 - 1, 0]), + (pa.uint64(), [str(2**63), "0"], [2**63, 0]), + (pa.uint64(), [str(2**64 - 1), "0"], [2**64 - 1, 0]), (pa.float64(), ["2.5", "0", "1"], [2.5, 0.0, 1.0]), (pa.bool_(), ["true", "false"], [True, False]), (pa.bool_(), [True, False], [True, False]), @@ -200,3 +204,51 @@ def test_typed_null_multilabel_batch_selects_list_decoding() -> None: result = encoder.decode(torch.tensor([[1.0]])) assert result.iloc[0].tolist() == [42] + + +@pytest.mark.parametrize("stored_as_strings", [False, True]) +def test_unsigned_multilabel_vocabulary_preserves_full_range( + stored_as_strings: bool, +) -> None: + """Native and saved unsigned classes retain exact IDs through multi-hot encoding.""" + labels = [2**64 - 1, 2**63, 0] + counts = [ + [str(label) if stored_as_strings else label, 10 - index] + for index, label in enumerate(labels) + ] + config = MultiCategorical( + _stats={ + ColStatType.MULTI_CATEGORY_COUNTS: counts, + ColStatType.MULTI_CATEGORIES_SEPARATOR: "|", + } + ) + encoder = TargetEncoder.from_encoder( + TaskType.MULTILABEL_CLASSIFICATION, + config, + target_dtype=pa.list_(pa.uint64()), + ) + assert isinstance(encoder, MultiCategoricalTargetEncoder) + targets = pa.array([[2**64 - 1, 2**63], [0], []], type=pa.list_(pa.uint64())) + + result = encoder.encode_tensor(encoder.tensor_mapper(targets)) + + assert encoder.tensor_mapper.mapping.tolist() == labels + torch.testing.assert_close( + result, torch.tensor([[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0]]) + ) + + +@pytest.mark.parametrize( + ("label", "dtype"), + [(-1, pa.uint64()), (2**64, pa.uint64()), (2**63, pa.int64()), (1.5, pa.int64())], +) +def test_target_vocabulary_rejects_overflow_and_fractional_integer_labels( + label: float, dtype: pa.DataType +) -> None: + """Explicit integer construction must preserve overflow and truncation checks.""" + config = Index(_stats={ColStatType.CATEGORY_COUNTS: [[label, 10], [0, 5]]}) + + with pytest.raises(ValueError, match="Target vocabulary cannot be converted"): + TargetEncoder.from_encoder( + TaskType.MULTICLASS_CLASSIFICATION, config, target_dtype=dtype + ) From 62ac7ed631427466fc473bcb1c199f30882e2c99 Mon Sep 17 00:00:00 2001 From: Haowei Yu Date: Fri, 4 Dec 2026 00:41:41 +0000 Subject: [PATCH 7/7] Fix integer target regression test import ordering --- .../kumo-engine/test/test_integer_categorical_targets.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/kumo-engine/test/test_integer_categorical_targets.py b/packages/kumo-engine/test/test_integer_categorical_targets.py index bd10b7ab7f..33facdf576 100644 --- a/packages/kumo-engine/test/test_integer_categorical_targets.py +++ b/packages/kumo-engine/test/test_integer_categorical_targets.py @@ -7,17 +7,18 @@ from datetime import datetime, timedelta from pathlib import Path -import kumo.engine as kumo import numpy as np import pyarrow as pa import pyarrow.compute as pc import pyarrow.parquet as pq import pytest -from kumo.engine._scratch import get_scratch_dir from kumoapi.model_plan import ModelPlan, TrainingTableGenerationPlan from kumoapi.train import TrainingTableSpec from wheel_gpu_smoke import make_plan +import kumo.engine as kumo +from kumo.engine._scratch import get_scratch_dir + @pytest.fixture(scope="module") def integer_graph(