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/diskgraph/runtime_adapter.py b/packages/kumo-core/src/kumo_core/diskgraph/runtime_adapter.py index 9f3c281e23..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,10 +14,8 @@ 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 torch from diskgraph.runtime_batch import ( @@ -29,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", @@ -480,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): @@ -802,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. @@ -968,165 +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) - values = _array_to_multilabel_lists(target, sep=sep or "|") - if target_encoder is None: - mapped = [[int(v) for v in row] for row in values] - 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)) - return MultiNestedTensor( - num_rows=len(mapped), - num_cols=1, - values=torch.tensor(flat, dtype=torch.long), - offset=torch.tensor(offsets, dtype=torch.long), - ) - - -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: list[Any], - 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) - - indices = mapping.get_indexer(values) - for candidate in candidates: - candidate_indices = mapping.get_indexer(candidate) - if (candidate_indices >= 0).all(): - return candidate, candidate_indices - return values, indices - - -def _categorical_indices( - target: pa.Array | pa.ChunkedArray, - target_encoder: TargetEncoder, -) -> torch.Tensor: - values = _arrow_array_to_pylist(target) - - mapping = cast(CategoricalTensorMapper, target_encoder.tensor_mapper).mapping - values, indices = _target_label_indices(values, mapping) - if (indices < 0).any(): - unknown = [values[i] for i, idx in enumerate(indices) if idx < 0] - 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 - - -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) - 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/src/kumo_core/encoders/config.py b/packages/kumo-core/src/kumo_core/encoders/config.py index d35de3c2e8..110c128731 100644 --- a/packages/kumo-core/src/kumo_core/encoders/config.py +++ b/packages/kumo-core/src/kumo_core/encoders/config.py @@ -3,15 +3,111 @@ # SPDX-License-Identifier: Apache-2.0 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: Arrow scalar alias or tagged JSON array for a container type. + """ + col_name: str encoder: EncoderType + 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 alias or tagged container. + """ + if self.target_dtype is None: + return None + encoded = self.target_dtype + try: + 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 + raise ValueError("Invalid saved target dtype metadata") + + def record_dtype(self, dtype: pa.DataType) -> None: + """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. + """ + 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) @@ -21,6 +117,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 4c5c037385..3547242912 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,13 @@ # All rights reserved. # 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 +import pyarrow as pa +import pyarrow.compute as pc from kumoapi.encoder import ( Index, MaxLogNumerical, @@ -18,16 +22,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,27 +56,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), + 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], - )) + 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)) @@ -84,5 +134,43 @@ 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: + 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, + OverflowError, + ) 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 f7ef0a6e3e..9951d141a2 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,12 @@ def forward( expanded[occupied] = index index = expanded + 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), num_cols=1, 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_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])) 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..7693e99e21 --- /dev/null +++ b/packages/kumo-core/tests/encoders/test_target_dtype_metadata.py @@ -0,0 +1,252 @@ +# 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", "encoded"), + [ + (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, 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 + + +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", + [ + "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) + + 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"] + + +@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 new file mode 100644 index 0000000000..2fd9d25355 --- /dev/null +++ b/packages/kumo-core/tests/encoders/test_target_vocabulary_dtype.py @@ -0,0 +1,254 @@ +# 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.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]), + (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] + + +@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 + ) 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..c33c8494a9 --- /dev/null +++ b/packages/kumo-core/tests/test_runtime_adapter_targets.py @@ -0,0 +1,144 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. +# All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""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 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( + ("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_seed_target_uses_tensor_mapper( + chunked: bool, + task_type: str | None, + target: pa.Array | pa.ChunkedArray, + encoder: TargetEncoder, +) -> None: + """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 + ) + + 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( + "task_type", ["static_link_prediction", "temporal_link_prediction"] +) +@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, 1), target.slice(1)]) + task = NormalizedTask(input_ids=None, seed_node_id=None, target=target) + hetero = HeteroData() + encoder = NumericalTargetEncoder(0, 1) + + with patch.object(encoder.tensor_mapper, "forward") as mapper: + _attach_seed_table( + hetero, task, "train_table", task_type=task_type, target_encoder=encoder + ) + + mapper.assert_not_called() + torch.testing.assert_close( + hetero["train_table"].y, torch.tensor([2**54 + 1, 2**54 + 3]) + ) + + +@pytest.mark.parametrize( + "task_type", + ["static_link_prediction", "temporal_link_prediction", "forecasting", "regression"], +) +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) + + assert "y" not in hetero["train_table"] + + +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]]) + ) + + _attach_seed_table(hetero, task, "train_table", task_type="forecasting") + + assert "y" not in hetero["train_table"] + + +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="target encoder is required"): + _attach_seed_table(HeteroData(), task, "train_table", task_type="regression") 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..33facdf576 --- /dev/null +++ b/packages/kumo-engine/test/test_integer_categorical_targets.py @@ -0,0 +1,230 @@ +# 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 numpy as np +import pyarrow as pa +import pyarrow.compute as pc +import pyarrow.parquet as pq +import pytest +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( + 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 + ) 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