Skip to content

Data and ML reference

Secure loading and validation for discovered AGENT-K datasets.

(c) Mike Casale 2025. Licensed under the MIT License.

DatasetBundle dataclass

Validated training and unlabeled prediction frames.

Source code in agent_k/data.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@dataclass(frozen=True, slots=True)
class DatasetBundle:
    """Validated training and unlabeled prediction frames."""

    manifest: DatasetManifest
    train: pd.DataFrame
    predict: pd.DataFrame

    @property
    def train_features(self) -> pd.DataFrame:
        """Return training features in manifest order."""
        return self.train.loc[:, list(self.manifest.feature_columns)]

    @property
    def train_targets(self) -> pd.DataFrame:
        """Return training targets in manifest order."""
        return self.train.loc[:, list(self.manifest.target_columns)]

    @property
    def predict_features(self) -> pd.DataFrame:
        """Return prediction features in manifest order."""
        return self.predict.loc[:, list(self.manifest.feature_columns)]

    @property
    def predict_ids(self) -> pd.DataFrame:
        """Return prediction IDs in manifest order."""
        return self.predict.loc[:, list(self.manifest.id_columns)]

train_features property

train_features: DataFrame

Return training features in manifest order.

train_targets property

train_targets: DataFrame

Return training targets in manifest order.

predict_features property

predict_features: DataFrame

Return prediction features in manifest order.

predict_ids property

predict_ids: DataFrame

Return prediction IDs in manifest order.

load_dataset

load_dataset(
    manifest: DatasetManifest,
    input_root: Path,
    *,
    verify_hashes: bool = True,
) -> DatasetBundle

Load a manifest and enforce the train/predict trust boundary.

Parameters:

Name Type Description Default
manifest DatasetManifest

Discovered dataset contract.

required
input_root Path

Root containing manifest-relative assets.

required
verify_hashes bool

Whether to verify immutable asset digests.

True

Returns:

Type Description
DatasetBundle

Validated frames ready for candidate training and prediction.

Source code in agent_k/data.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def load_dataset(
    manifest: DatasetManifest,
    input_root: Path,
    *,
    verify_hashes: bool = True,
) -> DatasetBundle:
    """Load a manifest and enforce the train/predict trust boundary.

    Args:
        manifest: Discovered dataset contract.
        input_root: Root containing manifest-relative assets.
        verify_hashes: Whether to verify immutable asset digests.

    Returns:
        Validated frames ready for candidate training and prediction.
    """
    train_path = resolve_input_path(input_root, manifest.train.path)
    predict_path = resolve_input_path(input_root, manifest.predict.path)
    if verify_hashes:
        _verify_hash(train_path, manifest.train.sha256)
        _verify_hash(predict_path, manifest.predict.sha256)
    train = read_table(train_path)
    predict = read_table(predict_path)
    _validate_columns(manifest, train, predict)
    _validate_ids(manifest, train, predict)
    _validate_targets(manifest, train, predict)
    return DatasetBundle(manifest=manifest, train=train, predict=predict)

read_table

read_table(path: Path) -> DataFrame

Read a supported tabular asset without guessing its format.

Source code in agent_k/data.py
83
84
85
86
87
88
89
90
def read_table(path: Path) -> pd.DataFrame:
    """Read a supported tabular asset without guessing its format."""
    suffix = path.suffix.lower()
    if suffix == ".csv":
        return pd.read_csv(path, low_memory=False)
    if suffix == ".parquet":
        return pd.read_parquet(path)
    raise ValueError(f"unsupported table format: {suffix}")

resolve_input_path

resolve_input_path(root: Path, relative_path: str) -> Path

Resolve a relative asset path while preventing directory traversal.

Source code in agent_k/data.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
def resolve_input_path(root: Path, relative_path: str) -> Path:
    """Resolve a relative asset path while preventing directory traversal."""
    candidate = (root.resolve() / relative_path).resolve()
    try:
        candidate.relative_to(root.resolve())
    except ValueError as exc:
        raise ValueError(f"asset escapes input root: {relative_path}") from exc
    if not candidate.is_file():
        raise FileNotFoundError(f"input asset does not exist: {relative_path}")
    return candidate

Dataset discovery and immutable dataset contracts for AGENT-K.

(c) Mike Casale 2025. Licensed under the MIT License.

DataModality

Bases: StrEnum

Supported input modalities.

Source code in agent_k/datasets.py
53
54
55
56
57
58
class DataModality(StrEnum):
    """Supported input modalities."""

    TABULAR = "tabular"
    VISION = "vision"
    TEXT = "text"

TaskKind

Bases: StrEnum

Supported supervised-learning task kinds.

Source code in agent_k/datasets.py
61
62
63
64
65
class TaskKind(StrEnum):
    """Supported supervised-learning task kinds."""

    CLASSIFICATION = "classification"
    REGRESSION = "regression"

ProblemType

Bases: StrEnum

Complete supported problem taxonomy.

Source code in agent_k/datasets.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class ProblemType(StrEnum):
    """Complete supported problem taxonomy."""

    TABULAR_CLASSIFICATION = "tabular_classification"
    TABULAR_REGRESSION = "tabular_regression"
    VISION_CLASSIFICATION = "vision_classification"
    VISION_REGRESSION = "vision_regression"
    TEXT_CLASSIFICATION = "text_classification"
    TEXT_REGRESSION = "text_regression"

    @property
    def modality(self) -> DataModality:
        """Return the input modality encoded by the problem type."""
        return DataModality(self.value.split("_", maxsplit=1)[0])

    @property
    def task(self) -> TaskKind:
        """Return the task kind encoded by the problem type."""
        return TaskKind(self.value.rsplit("_", maxsplit=1)[1])

    @classmethod
    def from_parts(cls, modality: DataModality, task: TaskKind) -> ProblemType:
        """Build a problem type from its orthogonal dimensions."""
        return cls(f"{modality.value}_{task.value}")

modality property

modality: DataModality

Return the input modality encoded by the problem type.

task property

task: TaskKind

Return the task kind encoded by the problem type.

from_parts classmethod

from_parts(
    modality: DataModality, task: TaskKind
) -> ProblemType

Build a problem type from its orthogonal dimensions.

Source code in agent_k/datasets.py
88
89
90
91
@classmethod
def from_parts(cls, modality: DataModality, task: TaskKind) -> ProblemType:
    """Build a problem type from its orthogonal dimensions."""
    return cls(f"{modality.value}_{task.value}")

DataAsset

Bases: BaseModel

A discovered immutable input asset.

Source code in agent_k/datasets.py
 94
 95
 96
 97
 98
 99
100
101
102
103
class DataAsset(BaseModel):
    """A discovered immutable input asset."""

    model_config = ConfigDict(frozen=True, strict=True)

    path: str
    sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
    size_bytes: int = Field(ge=0)
    row_count: int | None = Field(default=None, ge=0)
    columns: tuple[str, ...] = ()

DatasetManifest

Bases: BaseModel

Authoritative description inferred from competition data.

Source code in agent_k/datasets.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
class DatasetManifest(BaseModel):
    """Authoritative description inferred from competition data."""

    model_config = ConfigDict(frozen=True, strict=True)

    schema_version: str = "1.0"
    problem_type: ProblemType
    train: DataAsset
    predict: DataAsset
    sample_submission: DataAsset | None = None
    id_columns: tuple[str, ...]
    target_columns: tuple[str, ...]
    feature_columns: tuple[str, ...]
    image_column: str | None = None
    train_image_root: str | None = None
    predict_image_root: str | None = None
    text_column: str | None = None
    class_labels: tuple[str, ...] = ()
    metric_id: str | None = None
    discovery_notes: tuple[str, ...] = ()

    @model_validator(mode="after")
    def validate_contract(self) -> DatasetManifest:
        """Reject ambiguous or internally inconsistent manifests."""
        if not self.id_columns:
            raise ValueError("at least one ID column is required")
        if not self.target_columns:
            raise ValueError("at least one target column is required")
        if not self.feature_columns:
            raise ValueError("at least one feature column is required")
        roles = [set(self.id_columns), set(self.target_columns), set(self.feature_columns)]
        if roles[0] & roles[1] or roles[0] & roles[2] or roles[1] & roles[2]:
            raise ValueError("ID, target, and feature columns must be disjoint")
        if self.problem_type.modality is DataModality.VISION and self.image_column is None:
            raise ValueError("vision manifests require image_column")
        image_roots = (self.train_image_root, self.predict_image_root)
        if any(root is not None and Path(root).is_absolute() for root in image_roots):
            raise ValueError("image roots must be relative to the dataset root")
        if self.problem_type.modality is DataModality.TEXT and self.text_column is None:
            raise ValueError("text manifests require text_column")
        if self.problem_type.task is TaskKind.CLASSIFICATION and not self.class_labels:
            raise ValueError("classification manifests require class_labels")
        return self

validate_contract

validate_contract() -> DatasetManifest

Reject ambiguous or internally inconsistent manifests.

Source code in agent_k/datasets.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
@model_validator(mode="after")
def validate_contract(self) -> DatasetManifest:
    """Reject ambiguous or internally inconsistent manifests."""
    if not self.id_columns:
        raise ValueError("at least one ID column is required")
    if not self.target_columns:
        raise ValueError("at least one target column is required")
    if not self.feature_columns:
        raise ValueError("at least one feature column is required")
    roles = [set(self.id_columns), set(self.target_columns), set(self.feature_columns)]
    if roles[0] & roles[1] or roles[0] & roles[2] or roles[1] & roles[2]:
        raise ValueError("ID, target, and feature columns must be disjoint")
    if self.problem_type.modality is DataModality.VISION and self.image_column is None:
        raise ValueError("vision manifests require image_column")
    image_roots = (self.train_image_root, self.predict_image_root)
    if any(root is not None and Path(root).is_absolute() for root in image_roots):
        raise ValueError("image roots must be relative to the dataset root")
    if self.problem_type.modality is DataModality.TEXT and self.text_column is None:
        raise ValueError("text manifests require text_column")
    if self.problem_type.task is TaskKind.CLASSIFICATION and not self.class_labels:
        raise ValueError("classification manifests require class_labels")
    return self

discover_dataset

discover_dataset(
    root: Path, *, metric_id: str | None = None
) -> DatasetManifest

Discover train, prediction, target, ID, modality, and task metadata.

Parameters:

Name Type Description Default
root Path

Directory containing downloaded competition data.

required
metric_id str | None

Optional trusted competition metric identifier.

None

Returns:

Type Description
DatasetManifest

A validated manifest with paths relative to root.

Raises:

Type Description
FileNotFoundError

If the root or required data files do not exist.

ValueError

If the data roles cannot be inferred without ambiguity.

Source code in agent_k/datasets.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def discover_dataset(root: Path, *, metric_id: str | None = None) -> DatasetManifest:
    """Discover train, prediction, target, ID, modality, and task metadata.

    Args:
        root: Directory containing downloaded competition data.
        metric_id: Optional trusted competition metric identifier.

    Returns:
        A validated manifest with paths relative to ``root``.

    Raises:
        FileNotFoundError: If the root or required data files do not exist.
        ValueError: If the data roles cannot be inferred without ambiguity.
    """
    dataset_root = root.resolve()
    if not dataset_root.is_dir():
        raise FileNotFoundError(f"dataset root does not exist: {root}")

    table_paths = sorted(
        path
        for path in dataset_root.rglob("*")
        if path.is_file() and path.suffix.lower() in _TABLE_SUFFIXES
    )
    if not table_paths:
        return _discover_image_directories(dataset_root, metric_id=metric_id)

    frames = {path: _read_table(path) for path in table_paths}
    train_path, predict_path, sample_path = _select_table_roles(frames)
    train = frames[train_path]
    predict = frames[predict_path]
    sample = frames[sample_path] if sample_path is not None else None

    target_columns = _infer_targets(train, predict, sample)
    id_columns = _infer_ids(train, predict, sample, target_columns)
    feature_columns = tuple(
        column for column in predict.columns if column not in {*id_columns, *target_columns}
    )
    if not feature_columns:
        raise ValueError("no feature columns remain after identifying IDs and targets")

    image_column, train_image_root, predict_image_root = _infer_image_layout(
        dataset_root,
        train,
        predict,
        feature_columns,
    )
    text_column = None if image_column is not None else _infer_text_column(train, feature_columns)
    modality = (
        DataModality.VISION
        if image_column is not None
        else DataModality.TEXT
        if text_column is not None
        else DataModality.TABULAR
    )
    task = _infer_task(train.loc[:, list(target_columns)], metric_id)
    labels = (
        _class_labels(train.loc[:, list(target_columns)]) if task is TaskKind.CLASSIFICATION else ()
    )
    problem_type = ProblemType.from_parts(modality, task)
    notes = (
        f"inferred train table from {train_path.name}",
        f"inferred prediction table from {predict_path.name}",
        f"inferred {problem_type.value} from data values",
    )
    return DatasetManifest(
        problem_type=problem_type,
        train=_asset(dataset_root, train_path, train),
        predict=_asset(dataset_root, predict_path, predict),
        sample_submission=(
            _asset(dataset_root, sample_path, sample)
            if sample_path is not None and sample is not None
            else None
        ),
        id_columns=id_columns,
        target_columns=target_columns,
        feature_columns=feature_columns,
        image_column=image_column,
        train_image_root=train_image_root,
        predict_image_root=predict_image_root,
        text_column=text_column,
        class_labels=labels,
        metric_id=metric_id,
        discovery_notes=notes,
    )

Pydantic Evals integration for reproducible trusted candidate scoring.

(c) Mike Casale 2025. Licensed under the MIT License.

build_evaluation_dataset

build_evaluation_dataset(
    requests: Sequence[EvaluationRequest],
    *,
    name: str = "trusted-candidate-evaluations",
) -> Dataset[
    EvaluationRequest, EvaluationResult, dict[str, str]
]

Build typed Pydantic Evals cases from trusted evaluation requests.

Source code in agent_k/evals.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def build_evaluation_dataset(
    requests: Sequence[EvaluationRequest],
    *,
    name: str = "trusted-candidate-evaluations",
) -> Dataset[EvaluationRequest, EvaluationResult, dict[str, str]]:
    """Build typed Pydantic Evals cases from trusted evaluation requests."""
    cases = [
        Case[EvaluationRequest, EvaluationResult, dict[str, str]](
            name=request.candidate_result.candidate_id,
            inputs=request,
            metadata={
                "metric_id": request.metric_id.value,
                "candidate_id": request.candidate_result.candidate_id,
            },
        )
        for request in requests
    ]
    return Dataset(name=name, cases=cases)

run_evaluation_dataset

run_evaluation_dataset(
    dataset: Dataset[
        EvaluationRequest, EvaluationResult, dict[str, str]
    ],
    *,
    max_concurrency: int = 1,
) -> EvaluationReport[
    EvaluationRequest, EvaluationResult, dict[str, str]
]

Run trusted host-side scoring through Pydantic Evals instrumentation.

Source code in agent_k/evals.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def run_evaluation_dataset(
    dataset: Dataset[EvaluationRequest, EvaluationResult, dict[str, str]],
    *,
    max_concurrency: int = 1,
) -> EvaluationReport[EvaluationRequest, EvaluationResult, dict[str, str]]:
    """Run trusted host-side scoring through Pydantic Evals instrumentation."""
    if max_concurrency < 1:
        raise ValueError("max_concurrency must be positive")
    return dataset.evaluate_sync(
        evaluate_candidate,
        max_concurrency=max_concurrency,
        progress=False,
        metadata={"trust_boundary": "host-only-hidden-labels"},
    )

Trusted split preparation and host-side candidate evaluation for AGENT-K.

(c) Mike Casale 2025. Licensed under the MIT License.

CandidateEngine

Bases: StrEnum

Supported concrete candidate implementations.

Source code in agent_k/evaluator.py
56
57
58
59
60
61
62
63
class CandidateEngine(StrEnum):
    """Supported concrete candidate implementations."""

    LIGHTGBM = "lightgbm"
    KUMO = "kumo"
    RESNET18 = "resnet18"
    TFIDF_LINEAR = "tfidf_linear"
    TRANSFORMER = "transformer"

CandidateStatus

Bases: StrEnum

Terminal candidate execution states.

Source code in agent_k/evaluator.py
66
67
68
69
70
class CandidateStatus(StrEnum):
    """Terminal candidate execution states."""

    SUCCEEDED = "succeeded"
    FAILED = "failed"

SplitRole

Bases: StrEnum

Trusted holdout purposes.

Source code in agent_k/evaluator.py
73
74
75
76
77
class SplitRole(StrEnum):
    """Trusted holdout purposes."""

    VALIDATION = "validation"
    ACCEPTANCE = "acceptance"

CandidateSpec

Bases: BaseModel

Complete sandbox input contract, intentionally excluding hidden labels.

Source code in agent_k/evaluator.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
class CandidateSpec(BaseModel):
    """Complete sandbox input contract, intentionally excluding hidden labels."""

    model_config = ConfigDict(frozen=True, strict=True)

    schema_version: str = "1.0"
    candidate_id: str = Field(min_length=1, max_length=200, pattern=r"^[A-Za-z0-9._-]+$")
    problem_type: ProblemType
    engine: CandidateEngine
    metric_id: MetricId
    seed: int = Field(default=42, ge=0, le=2**32 - 1)
    train_path: str
    predict_path: str
    train_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
    predict_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
    train_row_count: int = Field(gt=0)
    predict_row_count: int = Field(gt=0)
    id_columns: tuple[str, ...]
    target_columns: tuple[str, ...]
    feature_columns: tuple[str, ...]
    class_labels: tuple[str, ...] = ()
    image_column: str | None = None
    train_image_root: str | None = None
    predict_image_root: str | None = None
    text_column: str | None = None
    hyperparameters: dict[str, JsonValue] = Field(default_factory=dict)
    offline_assets: dict[str, str] = Field(default_factory=dict)

    @model_validator(mode="after")
    def validate_engine_and_problem(self) -> CandidateSpec:
        """Reject engine, modality, and task combinations that cannot execute."""
        engines = {
            DataModality.TABULAR: {CandidateEngine.LIGHTGBM, CandidateEngine.KUMO},
            DataModality.VISION: {CandidateEngine.RESNET18},
            DataModality.TEXT: {
                CandidateEngine.TFIDF_LINEAR,
                CandidateEngine.TRANSFORMER,
            },
        }
        if self.engine not in engines[self.problem_type.modality]:
            raise ValueError(
                f"engine {self.engine.value} does not support {self.problem_type.value}"
            )
        if self.problem_type.task is TaskKind.CLASSIFICATION and not self.class_labels:
            raise ValueError("classification candidates require class_labels")
        if self.engine is CandidateEngine.KUMO and len(self.target_columns) != 1:
            raise ValueError("Kumo supports exactly one target column")
        if Path(self.train_path).is_absolute() or Path(self.predict_path).is_absolute():
            raise ValueError("candidate data paths must be relative to the input root")
        image_roots = (self.train_image_root, self.predict_image_root)
        if any(root is not None and Path(root).is_absolute() for root in image_roots):
            raise ValueError("candidate image roots must be relative to the input root")
        if any(Path(path).is_absolute() for path in self.offline_assets.values()):
            raise ValueError("offline asset paths must be relative to the input root")
        return self

validate_engine_and_problem

validate_engine_and_problem() -> CandidateSpec

Reject engine, modality, and task combinations that cannot execute.

Source code in agent_k/evaluator.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
@model_validator(mode="after")
def validate_engine_and_problem(self) -> CandidateSpec:
    """Reject engine, modality, and task combinations that cannot execute."""
    engines = {
        DataModality.TABULAR: {CandidateEngine.LIGHTGBM, CandidateEngine.KUMO},
        DataModality.VISION: {CandidateEngine.RESNET18},
        DataModality.TEXT: {
            CandidateEngine.TFIDF_LINEAR,
            CandidateEngine.TRANSFORMER,
        },
    }
    if self.engine not in engines[self.problem_type.modality]:
        raise ValueError(
            f"engine {self.engine.value} does not support {self.problem_type.value}"
        )
    if self.problem_type.task is TaskKind.CLASSIFICATION and not self.class_labels:
        raise ValueError("classification candidates require class_labels")
    if self.engine is CandidateEngine.KUMO and len(self.target_columns) != 1:
        raise ValueError("Kumo supports exactly one target column")
    if Path(self.train_path).is_absolute() or Path(self.predict_path).is_absolute():
        raise ValueError("candidate data paths must be relative to the input root")
    image_roots = (self.train_image_root, self.predict_image_root)
    if any(root is not None and Path(root).is_absolute() for root in image_roots):
        raise ValueError("candidate image roots must be relative to the input root")
    if any(Path(path).is_absolute() for path in self.offline_assets.values()):
        raise ValueError("offline asset paths must be relative to the input root")
    return self

CandidateResult

Bases: BaseModel

Sandbox result metadata; prediction content remains a separate artifact.

Source code in agent_k/evaluator.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
class CandidateResult(BaseModel):
    """Sandbox result metadata; prediction content remains a separate artifact."""

    model_config = ConfigDict(frozen=True, strict=True)

    schema_version: str = "1.0"
    candidate_id: str
    status: CandidateStatus
    predictions_path: str | None = None
    predictions_sha256: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")
    row_count: int | None = Field(default=None, ge=0)
    prediction_columns: tuple[str, ...] = ()
    duration_seconds: float = Field(ge=0.0)
    diagnostics: dict[str, JsonValue] = Field(default_factory=dict)
    error: str | None = None

    @model_validator(mode="after")
    def validate_terminal_payload(self) -> CandidateResult:
        """Require complete artifacts on success and an explanation on failure."""
        artifacts = (
            self.predictions_path,
            self.predictions_sha256,
            self.row_count,
        )
        if self.status is CandidateStatus.SUCCEEDED and any(value is None for value in artifacts):
            raise ValueError("successful candidates require a complete prediction artifact")
        if self.status is CandidateStatus.FAILED and not self.error:
            raise ValueError("failed candidates require an error message")
        return self

validate_terminal_payload

validate_terminal_payload() -> CandidateResult

Require complete artifacts on success and an explanation on failure.

Source code in agent_k/evaluator.py
153
154
155
156
157
158
159
160
161
162
163
164
165
@model_validator(mode="after")
def validate_terminal_payload(self) -> CandidateResult:
    """Require complete artifacts on success and an explanation on failure."""
    artifacts = (
        self.predictions_path,
        self.predictions_sha256,
        self.row_count,
    )
    if self.status is CandidateStatus.SUCCEEDED and any(value is None for value in artifacts):
        raise ValueError("successful candidates require a complete prediction artifact")
    if self.status is CandidateStatus.FAILED and not self.error:
        raise ValueError("failed candidates require an error message")
    return self

EvaluationRequest

Bases: BaseModel

Host-only trusted evaluation request.

Source code in agent_k/evaluator.py
168
169
170
171
172
173
174
175
176
177
178
179
180
class EvaluationRequest(BaseModel):
    """Host-only trusted evaluation request."""

    model_config = ConfigDict(frozen=True, strict=True)

    schema_version: str = "1.0"
    candidate_result: CandidateResult
    metric_id: MetricId
    prediction_root: str
    trusted_labels_path: str
    id_columns: tuple[str, ...]
    target_columns: tuple[str, ...]
    class_labels: tuple[str, ...] = ()

EvaluationResult

Bases: BaseModel

Validated trusted score and its immutable evidence.

Source code in agent_k/evaluator.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
class EvaluationResult(BaseModel):
    """Validated trusted score and its immutable evidence."""

    model_config = ConfigDict(frozen=True, strict=True)

    schema_version: str = "1.0"
    candidate_id: str
    metric_id: MetricId
    direction: MetricDirection
    score: float
    row_count: int = Field(gt=0)
    predictions_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
    validated_columns: tuple[str, ...]
    duration_seconds: float = Field(ge=0.0)

PreparedSplit

Bases: BaseModel

Materialized candidate input paired with a host-only label location.

Source code in agent_k/evaluator.py
199
200
201
202
203
204
205
206
207
class PreparedSplit(BaseModel):
    """Materialized candidate input paired with a host-only label location."""

    model_config = ConfigDict(frozen=True, strict=True)

    role: SplitRole
    candidate_input_root: str
    trusted_labels_path: str
    manifest: DatasetManifest

PreparedSplitSet

Bases: BaseModel

Disjoint validation and acceptance split contracts.

Source code in agent_k/evaluator.py
210
211
212
213
214
215
216
class PreparedSplitSet(BaseModel):
    """Disjoint validation and acceptance split contracts."""

    model_config = ConfigDict(frozen=True, strict=True)

    validation: PreparedSplit
    acceptance: PreparedSplit

SubmissionArtifact

Bases: BaseModel

Immutable evidence for a sample-template-compatible submission.

Source code in agent_k/evaluator.py
219
220
221
222
223
224
225
226
227
class SubmissionArtifact(BaseModel):
    """Immutable evidence for a sample-template-compatible submission."""

    model_config = ConfigDict(frozen=True, strict=True)

    path: str
    sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
    row_count: int = Field(gt=0)
    columns: tuple[str, ...]

build_candidate_spec

build_candidate_spec(
    split: PreparedSplit,
    *,
    candidate_id: str,
    engine: CandidateEngine,
    metric_id: MetricId,
    seed: int = 42,
    hyperparameters: dict[str, JsonValue] | None = None,
    offline_assets: dict[str, str] | None = None,
) -> CandidateSpec

Build a sandbox candidate contract from one prepared split.

Source code in agent_k/evaluator.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def build_candidate_spec(
    split: PreparedSplit,
    *,
    candidate_id: str,
    engine: CandidateEngine,
    metric_id: MetricId,
    seed: int = 42,
    hyperparameters: dict[str, JsonValue] | None = None,
    offline_assets: dict[str, str] | None = None,
) -> CandidateSpec:
    """Build a sandbox candidate contract from one prepared split."""
    manifest = split.manifest
    return CandidateSpec(
        candidate_id=candidate_id,
        problem_type=manifest.problem_type,
        engine=engine,
        metric_id=metric_id,
        seed=seed,
        train_path=manifest.train.path,
        predict_path=manifest.predict.path,
        train_sha256=manifest.train.sha256,
        predict_sha256=manifest.predict.sha256,
        train_row_count=manifest.train.row_count or 0,
        predict_row_count=manifest.predict.row_count or 0,
        id_columns=manifest.id_columns,
        target_columns=manifest.target_columns,
        feature_columns=manifest.feature_columns,
        class_labels=manifest.class_labels,
        image_column=manifest.image_column,
        train_image_root=manifest.train_image_root,
        predict_image_root=manifest.predict_image_root,
        text_column=manifest.text_column,
        hyperparameters=hyperparameters or {},
        offline_assets=offline_assets or {},
    )

build_submission_spec

build_submission_spec(
    manifest: DatasetManifest,
    *,
    candidate_id: str,
    engine: CandidateEngine,
    metric_id: MetricId,
    seed: int = 42,
    hyperparameters: dict[str, JsonValue] | None = None,
    offline_assets: dict[str, str] | None = None,
) -> CandidateSpec

Build a final full-training/unlabeled-test candidate contract.

Source code in agent_k/evaluator.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def build_submission_spec(
    manifest: DatasetManifest,
    *,
    candidate_id: str,
    engine: CandidateEngine,
    metric_id: MetricId,
    seed: int = 42,
    hyperparameters: dict[str, JsonValue] | None = None,
    offline_assets: dict[str, str] | None = None,
) -> CandidateSpec:
    """Build a final full-training/unlabeled-test candidate contract."""
    if manifest.train.row_count is None or manifest.predict.row_count is None:
        raise ValueError("submission assets require known row counts")
    return CandidateSpec(
        candidate_id=candidate_id,
        problem_type=manifest.problem_type,
        engine=engine,
        metric_id=metric_id,
        seed=seed,
        train_path=manifest.train.path,
        predict_path=manifest.predict.path,
        train_sha256=manifest.train.sha256,
        predict_sha256=manifest.predict.sha256,
        train_row_count=manifest.train.row_count,
        predict_row_count=manifest.predict.row_count,
        id_columns=manifest.id_columns,
        target_columns=manifest.target_columns,
        feature_columns=manifest.feature_columns,
        class_labels=manifest.class_labels,
        image_column=manifest.image_column,
        train_image_root=manifest.train_image_root,
        predict_image_root=manifest.predict_image_root,
        text_column=manifest.text_column,
        hyperparameters=hyperparameters or {},
        offline_assets=offline_assets or {},
    )

hyperparameter_schema

hyperparameter_schema(model: type[BaseModel]) -> str

Render a validated configuration model as a compact prompt-ready JSON schema.

Parameters:

Name Type Description Default
model type[BaseModel]

Pydantic model that validates one engine's hyperparameters.

required

Returns:

Type Description
str

Sorted JSON of each field's type, default, and bounds, with enum members

str

listed under $defs.

Source code in agent_k/evaluator.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
def hyperparameter_schema(model: type[BaseModel]) -> str:
    """Render a validated configuration model as a compact prompt-ready JSON schema.

    Args:
        model: Pydantic model that validates one engine's hyperparameters.

    Returns:
        Sorted JSON of each field's type, default, and bounds, with enum members
        listed under ``$defs``.
    """
    schema = model.model_json_schema()
    properties: dict[str, Any] = {
        name: {key: value for key, value in field.items() if key != "title"}
        for name, field in schema["properties"].items()
    }
    if "$defs" in schema:
        properties["$defs"] = {
            name: definition.get("enum", definition) for name, definition in schema["$defs"].items()
        }
    return json.dumps(properties, separators=(",", ":"), sort_keys=True)

load_candidate_dataset

load_candidate_dataset(
    spec: CandidateSpec, input_root: Path
) -> DatasetBundle

Load candidate-visible data and verify it against the sandbox contract.

Source code in agent_k/evaluator.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
def load_candidate_dataset(spec: CandidateSpec, input_root: Path) -> DatasetBundle:
    """Load candidate-visible data and verify it against the sandbox contract."""
    train_path = _safe_artifact_path(input_root, spec.train_path)
    predict_path = _safe_artifact_path(input_root, spec.predict_path)
    manifest = DatasetManifest(
        problem_type=spec.problem_type,
        train=DataAsset(
            path=spec.train_path,
            sha256=spec.train_sha256,
            size_bytes=train_path.stat().st_size,
            row_count=spec.train_row_count,
            columns=(*spec.id_columns, *spec.feature_columns, *spec.target_columns),
        ),
        predict=DataAsset(
            path=spec.predict_path,
            sha256=spec.predict_sha256,
            size_bytes=predict_path.stat().st_size,
            row_count=spec.predict_row_count,
            columns=(*spec.id_columns, *spec.feature_columns),
        ),
        id_columns=spec.id_columns,
        target_columns=spec.target_columns,
        feature_columns=spec.feature_columns,
        image_column=spec.image_column,
        train_image_root=spec.train_image_root,
        predict_image_root=spec.predict_image_root,
        text_column=spec.text_column,
        class_labels=spec.class_labels,
        metric_id=spec.metric_id.value,
    )
    bundle = load_dataset(manifest, input_root)
    if len(bundle.train) != spec.train_row_count or len(bundle.predict) != spec.predict_row_count:
        raise ValueError("candidate data row counts do not match the signed specification")
    return bundle

materialize_trusted_splits

materialize_trusted_splits(
    manifest: DatasetManifest,
    dataset_root: Path,
    candidate_root: Path,
    trusted_root: Path,
    *,
    validation_fraction: float = 0.2,
    acceptance_fraction: float = 0.2,
    seed: int = 42,
) -> PreparedSplitSet

Create disjoint tuning and acceptance inputs with host-only labels.

The validation candidate trains on the fit partition. The acceptance candidate trains on all non-acceptance rows, including validation rows, but neither candidate input contains its own holdout labels.

Source code in agent_k/evaluator.py
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
def materialize_trusted_splits(
    manifest: DatasetManifest,
    dataset_root: Path,
    candidate_root: Path,
    trusted_root: Path,
    *,
    validation_fraction: float = 0.2,
    acceptance_fraction: float = 0.2,
    seed: int = 42,
) -> PreparedSplitSet:
    """Create disjoint tuning and acceptance inputs with host-only labels.

    The validation candidate trains on the fit partition. The acceptance
    candidate trains on all non-acceptance rows, including validation rows,
    but neither candidate input contains its own holdout labels.
    """
    if not 0.0 < validation_fraction < 1.0:
        raise ValueError("validation_fraction must be between zero and one")
    if not 0.0 < acceptance_fraction < 1.0:
        raise ValueError("acceptance_fraction must be between zero and one")
    if validation_fraction + acceptance_fraction >= 1.0:
        raise ValueError("validation and acceptance fractions must sum to less than one")
    _validate_separate_roots(candidate_root, trusted_root)
    source = read_table(_safe_artifact_path(dataset_root, manifest.train.path))
    row_indices = np.arange(len(source))
    stratify = _stratification_values(source, manifest)
    development, acceptance = train_test_split(
        row_indices,
        test_size=acceptance_fraction,
        random_state=seed,
        shuffle=True,
        stratify=stratify,
    )
    validation_share = validation_fraction / (1.0 - acceptance_fraction)
    development_stratify = stratify[development] if stratify is not None else None
    fit, validation = train_test_split(
        development,
        test_size=validation_share,
        random_state=seed + 1,
        shuffle=True,
        stratify=development_stratify,
    )
    candidate_root.mkdir(parents=True, exist_ok=True)
    trusted_root.mkdir(parents=True, exist_ok=True)
    validation_split = _materialize_split(
        SplitRole.VALIDATION,
        source.iloc[fit],
        source.iloc[validation],
        manifest,
        dataset_root,
        candidate_root,
        trusted_root,
    )
    acceptance_split = _materialize_split(
        SplitRole.ACCEPTANCE,
        source.iloc[development],
        source.iloc[acceptance],
        manifest,
        dataset_root,
        candidate_root,
        trusted_root,
    )
    return PreparedSplitSet(validation=validation_split, acceptance=acceptance_split)

evaluate_candidate

evaluate_candidate(
    request: EvaluationRequest,
) -> EvaluationResult

Validate and score a candidate artifact against inaccessible labels.

Source code in agent_k/evaluator.py
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
def evaluate_candidate(request: EvaluationRequest) -> EvaluationResult:
    """Validate and score a candidate artifact against inaccessible labels."""
    started = time.monotonic()
    result = request.candidate_result
    if result.status is not CandidateStatus.SUCCEEDED:
        raise ValueError(f"candidate did not succeed: {result.error}")
    assert result.predictions_path is not None
    assert result.predictions_sha256 is not None
    predictions_path = _safe_artifact_path(
        Path(request.prediction_root),
        result.predictions_path,
    )
    actual_digest = _sha256(predictions_path)
    if actual_digest != result.predictions_sha256:
        raise ValueError("prediction artifact digest does not match candidate result")

    expected_predictions = prediction_columns(
        request.metric_id,
        request.target_columns,
        request.class_labels,
    )
    expected_columns = (*request.id_columns, *expected_predictions)
    prediction_frame = _read_evaluation_csv(
        predictions_path,
        request.id_columns,
        expected_predictions,
        request.metric_id,
    )
    if result.row_count != len(prediction_frame):
        raise ValueError("prediction row count differs from candidate result metadata")
    if result.prediction_columns != expected_predictions:
        raise ValueError("prediction columns differ from candidate result metadata")
    trusted_frame = pd.read_csv(
        request.trusted_labels_path,
        dtype={column: str for column in request.id_columns},
    )
    trusted_columns = (*request.id_columns, *request.target_columns)
    _require_exact_columns(prediction_frame, expected_columns, "prediction")
    _require_exact_columns(trusted_frame, trusted_columns, "trusted label")
    if prediction_frame.loc[:, list(expected_predictions)].isna().any(axis=None):
        raise ValueError("prediction values contain missing values")
    if trusted_frame.loc[:, list(request.target_columns)].isna().any(axis=None):
        raise ValueError("trusted labels contain missing values")
    if request.class_labels:
        trusted_classes = set(trusted_frame.loc[:, request.target_columns[0]].astype(str))
        unknown_classes = trusted_classes - set(request.class_labels)
        if unknown_classes:
            raise ValueError(
                f"trusted labels are outside declared classes: {sorted(unknown_classes)}"
            )
    if metric_spec(request.metric_id).prediction_kind is PredictionKind.LABEL:
        observed = set(prediction_frame.loc[:, expected_predictions[0]].astype(str))
        unknown = observed - set(request.class_labels)
        if unknown:
            raise ValueError(f"prediction labels are outside declared classes: {sorted(unknown)}")
    _validate_evaluation_ids(prediction_frame, trusted_frame, request.id_columns)
    aligned = prediction_frame.set_index(list(request.id_columns)).loc[
        trusted_frame.set_index(list(request.id_columns)).index
    ]
    score = score_predictions(
        request.metric_id,
        trusted_frame.loc[:, list(request.target_columns)].to_numpy(),
        aligned.loc[:, list(expected_predictions)].to_numpy(),
        class_labels=request.class_labels,
    )
    if not np.isfinite(score):
        raise ValueError("trusted metric produced a non-finite score")
    return EvaluationResult(
        candidate_id=result.candidate_id,
        metric_id=request.metric_id,
        direction=metric_spec(request.metric_id).direction,
        score=score,
        row_count=len(trusted_frame),
        predictions_sha256=actual_digest,
        validated_columns=expected_columns,
        duration_seconds=time.monotonic() - started,
    )

write_candidate_predictions

write_candidate_predictions(
    spec: CandidateSpec,
    predict_ids: DataFrame,
    predictions: DataFrame,
    output_root: Path,
    *,
    started: float,
    diagnostics: dict[str, JsonValue] | None = None,
) -> CandidateResult

Validate and atomically describe a candidate prediction artifact.

Source code in agent_k/evaluator.py
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
def write_candidate_predictions(
    spec: CandidateSpec,
    predict_ids: pd.DataFrame,
    predictions: pd.DataFrame,
    output_root: Path,
    *,
    started: float,
    diagnostics: dict[str, JsonValue] | None = None,
) -> CandidateResult:
    """Validate and atomically describe a candidate prediction artifact."""
    expected_values = prediction_columns(
        spec.metric_id,
        spec.target_columns,
        spec.class_labels,
    )
    _require_exact_columns(predict_ids, spec.id_columns, "candidate ID")
    _require_exact_columns(predictions, expected_values, "candidate prediction")
    if len(predict_ids) != spec.predict_row_count or len(predictions) != len(predict_ids):
        raise ValueError("candidate prediction row count does not match the specification")
    if predict_ids.isna().any(axis=None) or predict_ids.duplicated().any():
        raise ValueError("candidate prediction IDs must be non-null and unique")
    values = predictions.to_numpy()
    validate_prediction_values(
        values,
        spec.metric_id,
        class_count=len(spec.class_labels) or None,
    )
    if metric_spec(spec.metric_id).prediction_kind is PredictionKind.LABEL:
        observed = set(predictions.iloc[:, 0].astype(str))
        unknown = observed - set(spec.class_labels)
        if unknown:
            raise ValueError(f"prediction labels are outside declared classes: {sorted(unknown)}")
    output_root.mkdir(parents=True, exist_ok=True)
    output_path = output_root / "predictions.csv"
    if output_path.exists():
        raise FileExistsError(f"prediction artifact already exists: {output_path}")
    artifact = pd.concat(
        (predict_ids.reset_index(drop=True), predictions.reset_index(drop=True)),
        axis=1,
    )
    temporary = output_root / ".predictions.csv.tmp"
    artifact.to_csv(temporary, index=False)
    temporary.replace(output_path)
    digest = _sha256(output_path)
    return CandidateResult(
        candidate_id=spec.candidate_id,
        status=CandidateStatus.SUCCEEDED,
        predictions_path=output_path.relative_to(output_root).as_posix(),
        predictions_sha256=digest,
        row_count=len(artifact),
        prediction_columns=expected_values,
        duration_seconds=time.monotonic() - started,
        diagnostics=diagnostics or {},
    )

write_submission

write_submission(
    prediction_path: Path,
    manifest: DatasetManifest,
    dataset_root: Path,
    destination: Path,
    *,
    metric_id: MetricId | None = None,
) -> SubmissionArtifact

Map internal predictions into the exact sample-submission schema.

IDs are aligned to the sample template rather than trusted by row position. Probability columns are mapped only when class semantics can be proven; ambiguous same-width schemas are rejected.

Source code in agent_k/evaluator.py
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
def write_submission(
    prediction_path: Path,
    manifest: DatasetManifest,
    dataset_root: Path,
    destination: Path,
    *,
    metric_id: MetricId | None = None,
) -> SubmissionArtifact:
    """Map internal predictions into the exact sample-submission schema.

    IDs are aligned to the sample template rather than trusted by row position.
    Probability columns are mapped only when class semantics can be proven;
    ambiguous same-width schemas are rejected.
    """
    if manifest.sample_submission is None:
        raise ValueError("a sample submission is required for unambiguous final mapping")
    if destination.exists():
        raise FileExistsError(f"submission destination already exists: {destination}")
    resolved_metric = metric_id or (
        MetricId(manifest.metric_id) if manifest.metric_id is not None else None
    )
    if resolved_metric is None:
        raise ValueError("metric_id is required when the dataset manifest does not define one")
    internal_columns = prediction_columns(
        resolved_metric,
        manifest.target_columns,
        manifest.class_labels,
    )
    predictions = _read_evaluation_csv(
        prediction_path,
        manifest.id_columns,
        internal_columns,
        resolved_metric,
    )
    _require_exact_columns(
        predictions,
        (*manifest.id_columns, *internal_columns),
        "final prediction",
    )
    validate_prediction_values(
        predictions.loc[:, list(internal_columns)].to_numpy(),
        resolved_metric,
        class_count=len(manifest.class_labels) or None,
    )
    if metric_spec(resolved_metric).prediction_kind is PredictionKind.LABEL:
        observed = set(predictions.loc[:, internal_columns[0]].astype(str))
        unknown = observed - set(manifest.class_labels)
        if unknown:
            raise ValueError(
                f"final prediction labels are outside declared classes: {sorted(unknown)}"
            )
    sample_path = _safe_artifact_path(dataset_root, manifest.sample_submission.path)
    if _sha256(sample_path) != manifest.sample_submission.sha256:
        raise ValueError("sample submission digest does not match the dataset manifest")
    sample = pd.read_csv(
        sample_path,
        dtype={column: str for column in manifest.id_columns},
    )
    sample_outputs = tuple(
        str(column) for column in sample.columns if column not in manifest.id_columns
    )
    if not sample_outputs:
        raise ValueError("sample submission has no output columns")
    _validate_evaluation_ids(predictions, sample, manifest.id_columns)
    aligned = predictions.set_index(list(manifest.id_columns)).loc[
        sample.set_index(list(manifest.id_columns)).index
    ]
    mapped = _map_submission_outputs(
        aligned,
        internal_columns,
        sample_outputs,
        manifest,
        resolved_metric,
    )
    submission = pd.concat(
        (sample.loc[:, list(manifest.id_columns)].reset_index(drop=True), mapped),
        axis=1,
    )
    _require_exact_columns(submission, tuple(map(str, sample.columns)), "submission")
    destination.parent.mkdir(parents=True, exist_ok=True)
    temporary = destination.with_name(f".{destination.name}.tmp")
    submission.to_csv(temporary, index=False)
    temporary.replace(destination)
    return SubmissionArtifact(
        path=str(destination.resolve()),
        sha256=_sha256(destination),
        row_count=len(submission),
        columns=tuple(map(str, submission.columns)),
    )

Training-only dataset summaries and actionable preprocessing guidance.

(c) Mike Casale 2026. Licensed under the MIT License.

ColumnProfile

Bases: BaseModel

Observable characteristics of one training column.

Source code in agent_k/hints.py
20
21
22
23
24
25
26
27
class ColumnProfile(BaseModel):
    """Observable characteristics of one training column."""

    model_config = ConfigDict(frozen=True)
    name: str
    dtype: str
    missing_fraction: float = Field(ge=0, le=1)
    unique_count: int = Field(ge=0)

DatasetProfile

Bases: BaseModel

A compact profile containing no row values or hidden labels.

Source code in agent_k/hints.py
30
31
32
33
34
35
36
class DatasetProfile(BaseModel):
    """A compact profile containing no row values or hidden labels."""

    model_config = ConfigDict(frozen=True)
    rows: int = Field(ge=1)
    columns: tuple[ColumnProfile, ...]
    recommendations: tuple[str, ...]

profile_training_data

profile_training_data(frame: DataFrame) -> DatasetProfile

Summarize training data without examining validation or acceptance rows.

Source code in agent_k/hints.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def profile_training_data(frame: pd.DataFrame) -> DatasetProfile:
    """Summarize training data without examining validation or acceptance rows."""
    if frame.empty:
        raise ValueError("Cannot profile an empty training table")
    columns = tuple(
        ColumnProfile(
            name=str(name),
            dtype=str(frame[name].dtype),
            missing_fraction=float(frame[name].isna().mean()),
            unique_count=int(frame[name].nunique()),
        )
        for name in frame.columns
    )
    hints: list[str] = []
    if any(column.missing_fraction for column in columns):
        hints.append("Fit imputation using training rows; retain missingness indicators.")
    if any(column.unique_count == 1 for column in columns):
        hints.append("Remove constant columns using a training-only variance check.")
    hints.append("Fit categorical vocabularies on training rows and handle unknown categories.")
    hints.append("Evaluate a LightGBM custom gradient and Hessian against the fixed baseline.")
    return DatasetProfile(rows=len(frame), columns=columns, recommendations=tuple(hints))

summarize_profile

summarize_profile(
    profile: DatasetProfile, *, max_columns: int = 60
) -> dict[str, Any]

Build a prompt-sized view of a profile that stays bounded for wide tables.

Parameters:

Name Type Description Default
profile DatasetProfile

Training-only profile of the candidate-visible table.

required
max_columns int

Largest number of individual columns to describe.

60

Returns:

Type Description
dict[str, Any]

Aggregate counts for every column and details for the columns most likely

dict[str, Any]

to need preprocessing: those with missing values first, then low cardinality.

Source code in agent_k/hints.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def summarize_profile(profile: DatasetProfile, *, max_columns: int = 60) -> dict[str, Any]:
    """Build a prompt-sized view of a profile that stays bounded for wide tables.

    Args:
        profile: Training-only profile of the candidate-visible table.
        max_columns: Largest number of individual columns to describe.

    Returns:
        Aggregate counts for every column and details for the columns most likely
        to need preprocessing: those with missing values first, then low cardinality.
    """
    ranked = sorted(
        profile.columns,
        key=lambda column: (-column.missing_fraction, column.unique_count, column.name),
    )
    return {
        "rows": profile.rows,
        "column_count": len(profile.columns),
        "dtype_counts": dict(Counter(column.dtype for column in profile.columns)),
        "columns_with_missing_values": sum(
            column.missing_fraction > 0 for column in profile.columns
        ),
        "constant_columns": sum(column.unique_count <= 1 for column in profile.columns),
        "columns": [column.model_dump() for column in ranked[:max_columns]],
        "columns_omitted": max(0, len(profile.columns) - max_columns),
        "recommendations": list(profile.recommendations),
    }

Differentiable custom LightGBM objectives for AGENT-K evolution.

(c) Mike Casale 2025. Licensed under the MIT License.

LossId

Bases: StrEnum

Evolvable objective families implemented by this module.

Source code in agent_k/losses.py
36
37
38
39
40
41
42
43
44
45
class LossId(StrEnum):
    """Evolvable objective families implemented by this module."""

    SQUARED_ERROR = "squared_error"
    ASYMMETRIC_SQUARED = "asymmetric_squared"
    PSEUDO_HUBER = "pseudo_huber"
    SMOOTH_L1 = "smooth_l1"
    SMOOTH_QUANTILE = "smooth_quantile"
    BINARY_LOG_LOSS = "binary_log_loss"
    MULTICLASS_LOG_LOSS = "multiclass_log_loss"

LossSpec

Bases: BaseModel

Validated parameters for a custom LightGBM objective.

Source code in agent_k/losses.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class LossSpec(BaseModel):
    """Validated parameters for a custom LightGBM objective."""

    model_config = ConfigDict(frozen=True, strict=True)

    loss_id: LossId
    underprediction_weight: float = Field(default=1.0, gt=0.0, le=100.0)
    overprediction_weight: float = Field(default=1.0, gt=0.0, le=100.0)
    delta: float = Field(default=1.0, gt=1e-9, le=1e6)
    squared_weight: float = Field(default=0.5, ge=0.0, le=1.0)
    epsilon: float = Field(default=1e-3, gt=1e-12, le=1.0)
    quantile: float = Field(default=0.5, gt=0.0, lt=1.0)
    smoothing: float = Field(default=0.05, gt=1e-9, le=100.0)
    min_hessian: float = Field(default=1e-6, gt=0.0, le=1.0)

    @model_validator(mode="after")
    def validate_relevant_parameters(self) -> LossSpec:
        """Ensure an objective cannot be configured with unusable curvature."""
        if self.loss_id is LossId.SMOOTH_L1 and self.squared_weight == 0.0:
            if self.epsilon < self.min_hessian:
                raise ValueError("smooth L1 epsilon must not be smaller than min_hessian")
        return self

validate_relevant_parameters

validate_relevant_parameters() -> LossSpec

Ensure an objective cannot be configured with unusable curvature.

Source code in agent_k/losses.py
63
64
65
66
67
68
69
@model_validator(mode="after")
def validate_relevant_parameters(self) -> LossSpec:
    """Ensure an objective cannot be configured with unusable curvature."""
    if self.loss_id is LossId.SMOOTH_L1 and self.squared_weight == 0.0:
        if self.epsilon < self.min_hessian:
            raise ValueError("smooth L1 epsilon must not be smaller than min_hessian")
    return self

squared_error_objective

squared_error_objective(
    labels: ArrayLike, raw_predictions: ArrayLike
) -> tuple[NDArray[float64], NDArray[float64]]

Return exact gradient and Hessian for half squared error.

Source code in agent_k/losses.py
72
73
74
75
76
77
78
79
def squared_error_objective(
    labels: npt.ArrayLike,
    raw_predictions: npt.ArrayLike,
) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
    """Return exact gradient and Hessian for half squared error."""
    truth, predictions = _coerce_pair(labels, raw_predictions)
    gradient = predictions - truth
    return gradient, np.ones_like(gradient)

asymmetric_squared_objective

asymmetric_squared_objective(
    labels: ArrayLike,
    raw_predictions: ArrayLike,
    *,
    underprediction_weight: float = 1.0,
    overprediction_weight: float = 1.0,
) -> tuple[NDArray[float64], NDArray[float64]]

Penalize under- and overprediction with independently evolvable weights.

Source code in agent_k/losses.py
82
83
84
85
86
87
88
89
90
91
92
93
def asymmetric_squared_objective(
    labels: npt.ArrayLike,
    raw_predictions: npt.ArrayLike,
    *,
    underprediction_weight: float = 1.0,
    overprediction_weight: float = 1.0,
) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
    """Penalize under- and overprediction with independently evolvable weights."""
    truth, predictions = _coerce_pair(labels, raw_predictions)
    residual = predictions - truth
    weights = np.where(residual < 0.0, underprediction_weight, overprediction_weight)
    return weights * residual, weights.astype(np.float64, copy=False)

pseudo_huber_objective

pseudo_huber_objective(
    labels: ArrayLike,
    raw_predictions: ArrayLike,
    *,
    delta: float = 1.0,
    min_hessian: float = 1e-06,
) -> tuple[NDArray[float64], NDArray[float64]]

Return robust pseudo-Huber derivatives with strictly positive curvature.

Source code in agent_k/losses.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def pseudo_huber_objective(
    labels: npt.ArrayLike,
    raw_predictions: npt.ArrayLike,
    *,
    delta: float = 1.0,
    min_hessian: float = 1e-6,
) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
    """Return robust pseudo-Huber derivatives with strictly positive curvature."""
    truth, predictions = _coerce_pair(labels, raw_predictions)
    scaled = (predictions - truth) / delta
    base = 1.0 + np.square(scaled)
    gradient = (predictions - truth) / np.sqrt(base)
    hessian = np.maximum(np.power(base, -1.5), min_hessian)
    return gradient, hessian

smooth_l1_objective

smooth_l1_objective(
    labels: ArrayLike,
    raw_predictions: ArrayLike,
    *,
    squared_weight: float = 0.5,
    epsilon: float = 0.001,
    min_hessian: float = 1e-06,
) -> tuple[NDArray[float64], NDArray[float64]]

Blend squared error with a differentiable absolute-error approximation.

Source code in agent_k/losses.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def smooth_l1_objective(
    labels: npt.ArrayLike,
    raw_predictions: npt.ArrayLike,
    *,
    squared_weight: float = 0.5,
    epsilon: float = 1e-3,
    min_hessian: float = 1e-6,
) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
    """Blend squared error with a differentiable absolute-error approximation."""
    truth, predictions = _coerce_pair(labels, raw_predictions)
    residual = predictions - truth
    smooth_radius = np.sqrt(np.square(residual) + epsilon**2)
    absolute_weight = 1.0 - squared_weight
    gradient = squared_weight * residual + absolute_weight * residual / smooth_radius
    hessian = squared_weight + absolute_weight * epsilon**2 / np.power(smooth_radius, 3)
    return gradient, np.maximum(hessian, min_hessian)

smooth_quantile_objective

smooth_quantile_objective(
    labels: ArrayLike,
    raw_predictions: ArrayLike,
    *,
    quantile: float = 0.5,
    smoothing: float = 0.05,
    min_hessian: float = 1e-06,
) -> tuple[NDArray[float64], NDArray[float64]]

Return derivatives for a smooth approximation to quantile pinball loss.

Source code in agent_k/losses.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def smooth_quantile_objective(
    labels: npt.ArrayLike,
    raw_predictions: npt.ArrayLike,
    *,
    quantile: float = 0.5,
    smoothing: float = 0.05,
    min_hessian: float = 1e-6,
) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
    """Return derivatives for a smooth approximation to quantile pinball loss."""
    truth, predictions = _coerce_pair(labels, raw_predictions)
    scaled = np.clip((predictions - truth) / smoothing, -40.0, 40.0)
    sigmoid = 1.0 / (1.0 + np.exp(-scaled))
    gradient = sigmoid - quantile
    hessian = np.maximum(sigmoid * (1.0 - sigmoid) / smoothing, min_hessian)
    return gradient, hessian

binary_log_loss_objective

binary_log_loss_objective(
    labels: ArrayLike,
    raw_predictions: ArrayLike,
    *,
    min_hessian: float = 1e-06,
) -> tuple[NDArray[float64], NDArray[float64]]

Return binary cross-entropy derivatives from raw LightGBM margins.

Source code in agent_k/losses.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def binary_log_loss_objective(
    labels: npt.ArrayLike,
    raw_predictions: npt.ArrayLike,
    *,
    min_hessian: float = 1e-6,
) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
    """Return binary cross-entropy derivatives from raw LightGBM margins."""
    truth, predictions = _coerce_pair(labels, raw_predictions)
    unique = np.unique(truth)
    if not set(unique).issubset({0.0, 1.0}):
        raise ValueError("binary log loss labels must be encoded as 0 or 1")
    margins = np.clip(predictions, -40.0, 40.0)
    probability = 1.0 / (1.0 + np.exp(-margins))
    gradient = probability - truth
    hessian = np.maximum(probability * (1.0 - probability), min_hessian)
    return gradient, hessian

multiclass_log_loss_objective

multiclass_log_loss_objective(
    labels: ArrayLike,
    raw_predictions: ArrayLike,
    *,
    min_hessian: float = 1e-06,
) -> tuple[NDArray[float64], NDArray[float64]]

Return softmax cross-entropy gradient and diagonal Hessian.

Source code in agent_k/losses.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
def multiclass_log_loss_objective(
    labels: npt.ArrayLike,
    raw_predictions: npt.ArrayLike,
    *,
    min_hessian: float = 1e-6,
) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
    """Return softmax cross-entropy gradient and diagonal Hessian."""
    truth = np.asarray(labels, dtype=np.int64).reshape(-1)
    predictions = np.asarray(raw_predictions, dtype=np.float64)
    if predictions.ndim != 2 or predictions.shape[0] != len(truth):
        raise ValueError("multiclass raw predictions must have shape (rows, classes)")
    if not np.isfinite(predictions).all():
        raise ValueError("multiclass predictions must be finite")
    class_count = predictions.shape[1]
    if class_count < 3:
        raise ValueError("multiclass log loss requires at least three classes")
    if (truth < 0).any() or (truth >= class_count).any():
        raise ValueError("multiclass labels are outside the prediction class range")
    shifted = predictions - predictions.max(axis=1, keepdims=True)
    exponentials = np.exp(shifted)
    probability = exponentials / exponentials.sum(axis=1, keepdims=True)
    gradient = probability.copy()
    gradient[np.arange(len(truth)), truth] -= 1.0
    hessian = np.maximum(probability * (1.0 - probability), min_hessian)
    return gradient, hessian

build_lightgbm_objective

build_lightgbm_objective(
    spec: LossSpec,
) -> LightGBMObjective

Build a top-level-compatible objective closure from a validated spec.

Source code in agent_k/losses.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def build_lightgbm_objective(spec: LossSpec) -> LightGBMObjective:
    """Build a top-level-compatible objective closure from a validated spec."""
    if spec.loss_id is LossId.SQUARED_ERROR:
        return squared_error_objective
    if spec.loss_id is LossId.ASYMMETRIC_SQUARED:
        return lambda labels, predictions: asymmetric_squared_objective(
            labels,
            predictions,
            underprediction_weight=spec.underprediction_weight,
            overprediction_weight=spec.overprediction_weight,
        )
    if spec.loss_id is LossId.PSEUDO_HUBER:
        return lambda labels, predictions: pseudo_huber_objective(
            labels,
            predictions,
            delta=spec.delta,
            min_hessian=spec.min_hessian,
        )
    if spec.loss_id is LossId.SMOOTH_L1:
        return lambda labels, predictions: smooth_l1_objective(
            labels,
            predictions,
            squared_weight=spec.squared_weight,
            epsilon=spec.epsilon,
            min_hessian=spec.min_hessian,
        )
    if spec.loss_id is LossId.SMOOTH_QUANTILE:
        return lambda labels, predictions: smooth_quantile_objective(
            labels,
            predictions,
            quantile=spec.quantile,
            smoothing=spec.smoothing,
            min_hessian=spec.min_hessian,
        )
    if spec.loss_id is LossId.BINARY_LOG_LOSS:
        return lambda labels, predictions: binary_log_loss_objective(
            labels,
            predictions,
            min_hessian=spec.min_hessian,
        )
    if spec.loss_id is LossId.MULTICLASS_LOG_LOSS:
        return lambda labels, predictions: multiclass_log_loss_objective(
            labels,
            predictions,
            min_hessian=spec.min_hessian,
        )
    raise AssertionError(f"unhandled loss: {spec.loss_id}")

Trusted metric definitions and prediction validation for AGENT-K.

(c) Mike Casale 2025. Licensed under the MIT License.

MetricId

Bases: StrEnum

Exact supported competition metric identifiers.

Source code in agent_k/metrics.py
40
41
42
43
44
45
46
47
48
49
50
51
class MetricId(StrEnum):
    """Exact supported competition metric identifiers."""

    ACCURACY = "accuracy"
    AUC = "auc"
    LOG_LOSS = "logLoss"
    F1 = "f1"
    RMSE = "rmse"
    MAE = "mae"
    RMSLE = "rmsle"
    MAP = "map"
    NDCG = "ndcg"

MetricDirection

Bases: StrEnum

Optimization direction for a trusted metric.

Source code in agent_k/metrics.py
54
55
56
57
58
class MetricDirection(StrEnum):
    """Optimization direction for a trusted metric."""

    MAXIMIZE = "maximize"
    MINIMIZE = "minimize"

PredictionKind

Bases: StrEnum

Semantic form required from a candidate.

Source code in agent_k/metrics.py
61
62
63
64
65
66
67
class PredictionKind(StrEnum):
    """Semantic form required from a candidate."""

    LABEL = "label"
    PROBABILITY = "probability"
    CONTINUOUS = "continuous"
    RANKING_SCORE = "ranking_score"

MetricSpec

Bases: BaseModel

Immutable trusted metric behavior.

Source code in agent_k/metrics.py
70
71
72
73
74
75
76
77
class MetricSpec(BaseModel):
    """Immutable trusted metric behavior."""

    model_config = ConfigDict(frozen=True, strict=True)

    metric_id: MetricId
    direction: MetricDirection
    prediction_kind: PredictionKind

metric_spec

metric_spec(metric_id: MetricId) -> MetricSpec

Return trusted behavior for an exact metric identifier.

Source code in agent_k/metrics.py
129
130
131
def metric_spec(metric_id: MetricId) -> MetricSpec:
    """Return trusted behavior for an exact metric identifier."""
    return _METRICS[metric_id]

prediction_columns

prediction_columns(
    metric_id: MetricId,
    target_columns: tuple[str, ...],
    class_labels: tuple[str, ...] = (),
) -> tuple[str, ...]

Return the exact candidate output columns for a metric.

Source code in agent_k/metrics.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def prediction_columns(
    metric_id: MetricId,
    target_columns: tuple[str, ...],
    class_labels: tuple[str, ...] = (),
) -> tuple[str, ...]:
    """Return the exact candidate output columns for a metric."""
    kind = metric_spec(metric_id).prediction_kind
    if kind is not PredictionKind.PROBABILITY:
        return target_columns
    if len(target_columns) != 1:
        raise ValueError("probability metrics require exactly one target column")
    target = target_columns[0]
    if len(class_labels) <= 2:
        return (f"{target}__probability",)
    return tuple(f"{target}__probability__{quote(label, safe='')}" for label in class_labels)

validate_prediction_values

validate_prediction_values(
    predictions: ArrayLike,
    metric_id: MetricId,
    *,
    class_count: int | None = None,
) -> NDArray[float64] | NDArray[object_]

Validate shape, finiteness, and probability invariants.

Label metrics intentionally permit string arrays. All other metrics require finite numeric values. Probability matrices must have one column per class and every row must sum to one.

Source code in agent_k/metrics.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def validate_prediction_values(
    predictions: npt.ArrayLike,
    metric_id: MetricId,
    *,
    class_count: int | None = None,
) -> npt.NDArray[np.float64] | npt.NDArray[np.object_]:
    """Validate shape, finiteness, and probability invariants.

    Label metrics intentionally permit string arrays. All other metrics require
    finite numeric values. Probability matrices must have one column per class
    and every row must sum to one.
    """
    kind = metric_spec(metric_id).prediction_kind
    raw = np.asarray(predictions)
    if raw.ndim not in {1, 2}:
        raise ValueError("predictions must be a one- or two-dimensional array")
    if raw.shape[0] == 0:
        raise ValueError("predictions cannot be empty")
    if kind is PredictionKind.LABEL:
        labels = np.asarray(raw, dtype=object).reshape(-1)
        if any(
            value is None
            or (isinstance(value, (float, np.floating)) and np.isnan(value))
            or (isinstance(value, str) and not value.strip())
            for value in labels
        ):
            raise ValueError("label predictions contain missing values")
        return np.asarray(raw, dtype=object)

    try:
        numeric = np.asarray(raw, dtype=np.float64)
    except (TypeError, ValueError) as exc:
        raise ValueError("predictions must be numeric") from exc
    if not np.isfinite(numeric).all():
        raise ValueError("predictions contain non-finite values")
    if kind is PredictionKind.PROBABILITY:
        if ((numeric < 0.0) | (numeric > 1.0)).any():
            raise ValueError("probabilities must be within [0, 1]")
        if class_count is not None and class_count > 2:
            if numeric.ndim != 2 or numeric.shape[1] != class_count:
                raise ValueError("multiclass probability column count does not match classes")
            if not np.allclose(numeric.sum(axis=1), 1.0, rtol=1e-6, atol=1e-8):
                raise ValueError("multiclass probabilities must sum to one per row")
        elif numeric.ndim == 2 and numeric.shape[1] != 1:
            raise ValueError("binary probabilities require exactly one column")
    return numeric

score_predictions

score_predictions(
    metric_id: MetricId,
    labels: ArrayLike,
    predictions: ArrayLike,
    *,
    class_labels: tuple[str, ...] = (),
) -> float

Score trusted hidden labels against already ID-aligned predictions.

Source code in agent_k/metrics.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def score_predictions(
    metric_id: MetricId,
    labels: npt.ArrayLike,
    predictions: npt.ArrayLike,
    *,
    class_labels: tuple[str, ...] = (),
) -> float:
    """Score trusted hidden labels against already ID-aligned predictions."""
    class_count = len(class_labels) or None
    checked = validate_prediction_values(
        predictions,
        metric_id,
        class_count=class_count,
    )
    truth = np.asarray(labels)
    if truth.ndim == 2 and truth.shape[1] == 1:
        truth = truth[:, 0]
    if len(truth) != checked.shape[0]:
        raise ValueError("label and prediction row counts differ")

    if metric_id is MetricId.ACCURACY:
        return float(accuracy_score(_label_strings(truth), _label_strings(checked)))
    if metric_id is MetricId.F1:
        average = "binary" if len(np.unique(truth)) == 2 else "macro"
        truth_strings = _label_strings(truth)
        prediction_strings = _label_strings(checked)
        positive = class_labels[-1] if class_labels else sorted(set(truth_strings))[-1]
        return float(
            f1_score(
                truth_strings,
                prediction_strings,
                average=average,
                pos_label=positive,
            )
        )
    if metric_id is MetricId.AUC:
        return _score_auc(truth, np.asarray(checked, dtype=np.float64), class_labels)
    if metric_id is MetricId.LOG_LOSS:
        return _score_log_loss(truth, np.asarray(checked, dtype=np.float64), class_labels)
    if metric_id is MetricId.RMSE:
        return float(mean_squared_error(truth, checked) ** 0.5)
    if metric_id is MetricId.MAE:
        return float(mean_absolute_error(truth, checked))
    if metric_id is MetricId.RMSLE:
        if (np.asarray(truth, dtype=np.float64) < 0.0).any() or (checked < 0.0).any():
            raise ValueError("RMSLE requires non-negative labels and predictions")
        return float(mean_squared_log_error(truth, checked) ** 0.5)
    if metric_id is MetricId.MAP:
        return _score_average_precision(truth, np.asarray(checked, dtype=np.float64), class_labels)
    if metric_id is MetricId.NDCG:
        return float(
            ndcg_score(
                np.asarray(truth, dtype=np.float64).reshape(1, -1),
                np.asarray(checked, dtype=np.float64).reshape(1, -1),
            )
        )
    raise AssertionError(f"unhandled metric: {metric_id}")

Production tabular candidates using LightGBM and NVIDIA Kumo Tabular.

(c) Mike Casale 2025. Licensed under the MIT License.

KumoFile

Bases: BaseModel

Digest evidence for one provisioned Kumo Hub file.

Source code in agent_k/tabular.py
74
75
76
77
78
79
80
81
class KumoFile(BaseModel):
    """Digest evidence for one provisioned Kumo Hub file."""

    model_config = ConfigDict(frozen=True, strict=True)

    filename: str
    sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
    size_bytes: int = Field(gt=0)

KumoAssetManifest

Bases: BaseModel

Pinned offline Kumo checkpoint set accepted by candidate workers.

Source code in agent_k/tabular.py
84
85
86
87
88
89
90
91
92
93
class KumoAssetManifest(BaseModel):
    """Pinned offline Kumo checkpoint set accepted by candidate workers."""

    model_config = ConfigDict(frozen=True, strict=True)

    schema_version: str = "1.0"
    repository: str = _KUMO_REPOSITORY
    revision: str = _KUMO_REVISION
    size: str
    files: tuple[KumoFile, ...]

run_candidate

run_candidate(
    spec: CandidateSpec, input_root: Path, output_root: Path
) -> CandidateResult

Run the selected tabular engine inside an offline candidate sandbox.

Source code in agent_k/tabular.py
127
128
129
130
131
132
133
134
135
136
137
def run_candidate(
    spec: CandidateSpec,
    input_root: Path,
    output_root: Path,
) -> CandidateResult:
    """Run the selected tabular engine inside an offline candidate sandbox."""
    if spec.engine is CandidateEngine.LIGHTGBM:
        return run_lightgbm_candidate(spec, input_root, output_root)
    if spec.engine is CandidateEngine.KUMO:
        return run_kumo_candidate(spec, input_root, output_root)
    raise ValueError(f"unsupported tabular engine: {spec.engine.value}")

describe_hyperparameters

describe_hyperparameters(engine: CandidateEngine) -> str

Describe the hyperparameters a tabular engine accepts, for evolution prompts.

Parameters:

Name Type Description Default
engine CandidateEngine

Tabular engine whose CandidateSpec.hyperparameters are described.

required

Returns:

Type Description
str

A compact contract listing accepted names; unknown names fail the candidate.

Source code in agent_k/tabular.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
def describe_hyperparameters(engine: CandidateEngine) -> str:
    """Describe the hyperparameters a tabular engine accepts, for evolution prompts.

    Args:
        engine: Tabular engine whose ``CandidateSpec.hyperparameters`` are described.

    Returns:
        A compact contract listing accepted names; unknown names fail the candidate.
    """
    if engine is CandidateEngine.KUMO:
        return f"Kumo hyperparameters (JSON schema): {hyperparameter_schema(_KumoConfig)}"
    if engine is not CandidateEngine.LIGHTGBM:
        raise ValueError(f"unsupported tabular engine: {engine.value}")
    estimator = sorted(_LIGHTGBM_PARAMETERS - set(_TrainingPlan.model_fields))
    return (
        f"LightGBM estimator hyperparameters: {', '.join(estimator)}. "
        f"Training-only resampling (JSON schema): {hyperparameter_schema(_TrainingPlan)}; "
        "folds >= 2 averages one model per fold, and early_stopping_rounds > 0 stops on "
        "held-out training rows. "
        f"Optional custom objective under the 'loss' key (JSON schema): "
        f"{hyperparameter_schema(LossSpec)}; classification requires binary_log_loss or "
        "multiclass_log_loss to match the class count. Regression objectives start from a "
        "training-target constant, and delta, epsilon, and smoothing are in target units."
    )

run_lightgbm_candidate

run_lightgbm_candidate(
    spec: CandidateSpec, input_root: Path, output_root: Path
) -> CandidateResult

Train LightGBM models and emit metric-appropriate predictions.

Source code in agent_k/tabular.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
def run_lightgbm_candidate(
    spec: CandidateSpec,
    input_root: Path,
    output_root: Path,
) -> CandidateResult:
    """Train LightGBM models and emit metric-appropriate predictions."""
    started = time.monotonic()
    bundle = load_candidate_dataset(spec, input_root)
    prediction_frame, categorical_count, loss, training = _lightgbm_prediction_frame(spec, bundle)
    diagnostics: dict[str, JsonValue] = {
        "engine": CandidateEngine.LIGHTGBM.value,
        "custom_loss": loss.loss_id.value if loss is not None else None,
        "categorical_feature_count": categorical_count,
        **training,
    }
    return write_candidate_predictions(
        spec,
        bundle.predict_ids,
        prediction_frame,
        output_root,
        started=started,
        diagnostics=diagnostics,
    )

run_kumo_candidate

run_kumo_candidate(
    spec: CandidateSpec, input_root: Path, output_root: Path
) -> CandidateResult

Run offline pretrained Kumo Tabular inference with eight estimators by default.

Source code in agent_k/tabular.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
def run_kumo_candidate(
    spec: CandidateSpec,
    input_root: Path,
    output_root: Path,
) -> CandidateResult:
    """Run offline pretrained Kumo Tabular inference with eight estimators by default."""
    started = time.monotonic()
    bundle = load_candidate_dataset(spec, input_root)
    if len(spec.target_columns) != 1:
        raise ValueError("Kumo Tabular supports exactly one target")
    config = _KumoConfig.model_validate(spec.hyperparameters)
    _configure_offline_huggingface(spec, input_root, config)
    if len(spec.feature_columns) > 500:
        raise ValueError("Kumo candidates support at most 500 feature columns")

    try:
        import sdm
        import torch
    except ImportError as exc:
        raise RuntimeError(
            "Kumo requires the 'kumo' worker dependencies structured-data-models and torch"
        ) from exc

    if config.device_policy == "cuda_required" and not torch.cuda.is_available():
        raise RuntimeError("Kumo production candidates require an available CUDA device")
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    if device.type == "cpu":
        torch.set_num_threads(config.cpu_threads)

    target = spec.target_columns[0]
    context = _sample_kumo_context(bundle.train, spec, config)
    context_frame = context.loc[:, [*spec.feature_columns, target]].copy()
    query_frame = bundle.predict.loc[:, list(spec.feature_columns)].copy()
    if spec.problem_type.task is TaskKind.CLASSIFICATION:
        context_frame[target] = context_frame[target].astype("string")
        query_frame[target] = pd.Series(
            pd.NA,
            index=query_frame.index,
            dtype="string",
        )
    else:
        query_frame[target] = np.nan
    combined = pd.concat(
        (context_frame, query_frame),
        ignore_index=True,
    )
    target_stype = (
        "categorical" if spec.problem_type.task is TaskKind.CLASSIFICATION else "numerical"
    )
    table = sdm.TableTensor.from_pandas(
        df=combined,
        stypes=sdm.infer_stypes(combined, overrides={target: target_stype}),
        device=device,
    )
    context_rows = len(context)
    model = sdm.models.KumoTabular(
        task=spec.problem_type.task.value,
        size=config.size,
        pretrained=True,
        device=device,
    )
    generator = torch.Generator(device=device).manual_seed(spec.seed)
    with torch.autocast(
        device.type,
        dtype=torch.float16,
        enabled=device.type == "cuda",
    ):
        result = model(
            x_context=table[:context_rows].drop_columns(target),
            y_context=table[:context_rows, target],
            x_query=table[context_rows:].drop_columns(target),
            num_estimators=config.num_estimators,
            generator=generator,
        )
    raw = result.to_pandas().reset_index(drop=True)
    inference_spec = spec
    if (
        config.lightgbm_weight > 0.0
        and spec.problem_type.task is TaskKind.CLASSIFICATION
        and metric_spec(spec.metric_id).prediction_kind is PredictionKind.LABEL
    ):
        inference_spec = spec.model_copy(update={"metric_id": MetricId.LOG_LOSS})
    prediction_frame, diagnostics = _kumo_predictions(inference_spec, raw, output_root)
    if config.lightgbm_weight > 0.0:
        lightgbm_spec = inference_spec.model_copy(
            update={
                "engine": CandidateEngine.LIGHTGBM,
                "hyperparameters": _kumo_lightgbm_parameters(spec, config),
            }
        )
        lightgbm_frame, _, _, _ = _lightgbm_prediction_frame(lightgbm_spec, bundle)
        prediction_frame = _blend_prediction_frames(
            prediction_frame,
            lightgbm_frame,
            lightgbm_weight=config.lightgbm_weight,
        )
    if inference_spec.metric_id is not spec.metric_id:
        prediction_frame = _probabilities_to_labels(prediction_frame, spec)
    diagnostics.update(
        {
            "engine": CandidateEngine.KUMO.value,
            "device": device.type,
            "model_size": config.size,
            "num_estimators": config.num_estimators,
            "context_rows": context_rows,
            "context_strategy": config.context_strategy,
            "lightgbm_weight": config.lightgbm_weight,
        }
    )
    return write_candidate_predictions(
        spec,
        bundle.predict_ids,
        prediction_frame,
        output_root,
        started=started,
        diagnostics=diagnostics,
    )

provision_kumo_assets

provision_kumo_assets(
    output: Path, *, size: str = "small"
) -> KumoAssetManifest

Download the pinned Kumo files for a manually approved offline worker gate.

This provisioning function is deliberately separate from candidate execution. Candidate sandboxes remain network-disabled and accept only the resulting cache plus its digest manifest.

Source code in agent_k/tabular.py
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
def provision_kumo_assets(output: Path, *, size: str = "small") -> KumoAssetManifest:
    """Download the pinned Kumo files for a manually approved offline worker gate.

    This provisioning function is deliberately separate from candidate execution.
    Candidate sandboxes remain network-disabled and accept only the resulting
    cache plus its digest manifest.
    """
    if size not in {"small", "medium", "large"}:
        raise ValueError("Kumo size must be small, medium, or large")
    try:
        from huggingface_hub import hf_hub_download
    except ImportError as exc:
        raise RuntimeError("huggingface-hub is required to provision Kumo assets") from exc
    destination = output.resolve()
    destination.mkdir(parents=True, exist_ok=True)
    cache = destination / "hf-cache"
    cache.mkdir(exist_ok=True)
    filenames = ("config.json", f"{size}/classifier.pt", f"{size}/regressor.pt")
    files: list[KumoFile] = []
    for filename in filenames:
        resolved = Path(
            hf_hub_download(
                repo_id=_KUMO_REPOSITORY,
                filename=filename,
                revision=_KUMO_REVISION,
                cache_dir=cache,
                local_files_only=False,
            )
        ).resolve()
        files.append(
            KumoFile(
                filename=filename,
                sha256=_sha256(resolved),
                size_bytes=resolved.stat().st_size,
            )
        )
    manifest = KumoAssetManifest(size=size, files=tuple(files))
    manifest_path = destination / "manifest.json"
    if manifest_path.exists():
        existing = KumoAssetManifest.model_validate_json(manifest_path.read_text(encoding="utf-8"))
        if existing != manifest:
            raise FileExistsError("existing Kumo manifest does not match provisioned files")
    else:
        temporary = destination / ".manifest.json.tmp"
        temporary.write_text(
            manifest.model_dump_json(indent=2) + "\n",
            encoding="utf-8",
        )
        temporary.replace(manifest_path)
    return manifest

main

main(argv: list[str] | None = None) -> int

Run explicit asset provisioning commands; candidate execution uses the runner.

Source code in agent_k/tabular.py
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
def main(argv: list[str] | None = None) -> int:
    """Run explicit asset provisioning commands; candidate execution uses the runner."""
    parser = argparse.ArgumentParser(description="AGENT-K tabular worker utilities")
    subparsers = parser.add_subparsers(dest="command", required=True)
    provision = subparsers.add_parser(
        "provision-kumo",
        help="download pinned Kumo assets for later offline candidate execution",
    )
    provision.add_argument("--output", type=Path, required=True)
    provision.add_argument(
        "--size",
        choices=("small", "medium", "large"),
        default="small",
    )
    arguments = parser.parse_args(argv)
    if arguments.command == "provision-kumo":
        manifest = provision_kumo_assets(arguments.output, size=arguments.size)
        print(json.dumps(manifest.model_dump(mode="json"), indent=2))
        return 0
    parser.error(f"unsupported command: {arguments.command}")
    return 2

TF-IDF linear and offline transformer candidates for AGENT-K text tasks.

(c) Mike Casale 2025. Licensed under the MIT License.

describe_hyperparameters

describe_hyperparameters(engine: CandidateEngine) -> str

Describe the hyperparameters a text engine accepts, for evolution prompts.

Parameters:

Name Type Description Default
engine CandidateEngine

Text engine whose CandidateSpec.hyperparameters are described.

required

Returns:

Type Description
str

A compact JSON-schema contract; unknown names fail the candidate.

Source code in agent_k/text.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def describe_hyperparameters(engine: CandidateEngine) -> str:
    """Describe the hyperparameters a text engine accepts, for evolution prompts.

    Args:
        engine: Text engine whose ``CandidateSpec.hyperparameters`` are described.

    Returns:
        A compact JSON-schema contract; unknown names fail the candidate.
    """
    if engine is CandidateEngine.TFIDF_LINEAR:
        config: type[BaseModel] = _TfidfConfig
    elif engine is CandidateEngine.TRANSFORMER:
        config = _TransformerConfig
    else:
        raise ValueError(f"unsupported text engine: {engine.value}")
    return f"{engine.value} hyperparameters (JSON schema): {hyperparameter_schema(config)}"

run_candidate

run_candidate(
    spec: CandidateSpec, input_root: Path, output_root: Path
) -> CandidateResult

Run the selected production text engine.

Source code in agent_k/text.py
109
110
111
112
113
114
115
116
117
118
119
def run_candidate(
    spec: CandidateSpec,
    input_root: Path,
    output_root: Path,
) -> CandidateResult:
    """Run the selected production text engine."""
    if spec.engine is CandidateEngine.TFIDF_LINEAR:
        return run_tfidf_candidate(spec, input_root, output_root)
    if spec.engine is CandidateEngine.TRANSFORMER:
        return run_transformer_candidate(spec, input_root, output_root)
    raise ValueError(f"unsupported text engine: {spec.engine.value}")

run_tfidf_candidate

run_tfidf_candidate(
    spec: CandidateSpec, input_root: Path, output_root: Path
) -> CandidateResult

Fit a word n-gram TF-IDF representation and a regularized linear model.

Source code in agent_k/text.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def run_tfidf_candidate(
    spec: CandidateSpec,
    input_root: Path,
    output_root: Path,
) -> CandidateResult:
    """Fit a word n-gram TF-IDF representation and a regularized linear model."""
    started = time.monotonic()
    _validate_text_spec(spec, _TFIDF_PARAMETERS)
    config = _TfidfConfig.model_validate(spec.hyperparameters)
    bundle = load_candidate_dataset(spec, input_root)
    assert spec.text_column is not None
    train_text = bundle.train[spec.text_column].fillna("").astype(str)
    predict_text = bundle.predict[spec.text_column].fillna("").astype(str)
    vectorizer = TfidfVectorizer(
        lowercase=True,
        strip_accents="unicode",
        ngram_range=(1, config.ngram_max),
        min_df=config.min_df,
        max_features=config.max_features,
        sublinear_tf=True,
        dtype=np.float64,
    )
    train_matrix = vectorizer.fit_transform(train_text)
    if train_matrix.shape[1] == 0:
        raise ValueError("TF-IDF produced no usable text features")
    predict_matrix = vectorizer.transform(predict_text)
    target = bundle.train_targets.iloc[:, 0]
    columns = prediction_columns(spec.metric_id, spec.target_columns, spec.class_labels)
    if spec.problem_type.task is TaskKind.CLASSIFICATION:
        labels = target.astype(str)
        if set(labels) != set(spec.class_labels):
            raise ValueError("text training classes differ from CandidateSpec.class_labels")
        model = LogisticRegression(
            C=config.c,
            max_iter=config.max_iter,
            class_weight=config.class_weight,
            random_state=spec.seed,
        )
        model.fit(train_matrix, labels)
        model_classes = tuple(str(label) for label in model.classes_)
        if model_classes != spec.class_labels:
            order = [model_classes.index(label) for label in spec.class_labels]
        else:
            order = list(range(len(model_classes)))
        probabilities = np.asarray(model.predict_proba(predict_matrix), dtype=np.float64)[:, order]
        predictions = _classification_frame(spec, columns, probabilities)
    else:
        values = pd.to_numeric(target, errors="raise").to_numpy(dtype=np.float64)
        model = Ridge(alpha=config.alpha)
        model.fit(train_matrix, values)
        prediction = np.asarray(model.predict(predict_matrix), dtype=np.float64)
        if spec.metric_id is MetricId.RMSLE:
            prediction = np.maximum(prediction, 0.0)
        predictions = pd.DataFrame({columns[0]: prediction})
    return write_candidate_predictions(
        spec,
        bundle.predict_ids,
        predictions,
        output_root,
        started=started,
        diagnostics={
            "engine": CandidateEngine.TFIDF_LINEAR.value,
            "vocabulary_size": len(vectorizer.vocabulary_),
        },
    )

run_transformer_candidate

run_transformer_candidate(
    spec: CandidateSpec, input_root: Path, output_root: Path
) -> CandidateResult

Fine-tune a locally mounted Hugging Face sequence model without network access.

Source code in agent_k/text.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
def run_transformer_candidate(
    spec: CandidateSpec,
    input_root: Path,
    output_root: Path,
) -> CandidateResult:
    """Fine-tune a locally mounted Hugging Face sequence model without network access."""
    started = time.monotonic()
    _validate_text_spec(spec, _TRANSFORMER_PARAMETERS)
    config = _TransformerConfig.model_validate(spec.hyperparameters)
    bundle = load_candidate_dataset(spec, input_root)
    model_relative = spec.offline_assets.get("transformer_model")
    if model_relative is None:
        raise ValueError("transformer candidates require offline_assets['transformer_model']")
    model_path = _safe_asset_directory(input_root, model_relative)
    os.environ["HF_HUB_OFFLINE"] = "1"
    os.environ["TRANSFORMERS_OFFLINE"] = "1"
    try:
        from transformers import AutoModelForSequenceClassification, AutoTokenizer
    except ImportError as exc:
        raise RuntimeError("transformer worker dependencies are not installed") from exc

    assert spec.text_column is not None
    train_text = bundle.train[spec.text_column].fillna("").astype(str).tolist()
    predict_text = bundle.predict[spec.text_column].fillna("").astype(str).tolist()
    device = _select_device(config.device_policy)
    if device.type == "cpu":
        torch.set_num_threads(config.cpu_threads)
    torch.manual_seed(spec.seed)
    np.random.seed(spec.seed)
    output_count = (
        len(spec.class_labels) if spec.problem_type.task is TaskKind.CLASSIFICATION else 1
    )
    tokenizer = AutoTokenizer.from_pretrained(  # type: ignore[no-untyped-call]
        model_path,
        local_files_only=True,
    )
    model = AutoModelForSequenceClassification.from_pretrained(
        model_path,
        local_files_only=True,
        num_labels=output_count,
        ignore_mismatched_sizes=True,
        problem_type=(
            "single_label_classification"
            if spec.problem_type.task is TaskKind.CLASSIFICATION
            else "regression"
        ),
    ).to(device)
    train_encoding = tokenizer(
        train_text,
        padding=True,
        truncation=True,
        max_length=config.max_length,
        return_tensors="pt",
    )
    predict_encoding = tokenizer(
        predict_text,
        padding=True,
        truncation=True,
        max_length=config.max_length,
        return_tensors="pt",
    )
    labels = _transformer_labels(spec, bundle.train_targets.iloc[:, 0])
    optimizer = torch.optim.AdamW(
        model.parameters(),
        lr=config.learning_rate,
        weight_decay=config.weight_decay,
    )
    order_generator = torch.Generator().manual_seed(spec.seed)
    model.train()
    for _ in range(config.epochs):
        order = torch.randperm(len(train_text), generator=order_generator)
        for start in range(0, len(order), config.batch_size):
            indices = order[start : start + config.batch_size]
            batch = {name: tensor[indices].to(device) for name, tensor in train_encoding.items()}
            batch["labels"] = labels[indices].to(device)
            optimizer.zero_grad(set_to_none=True)
            output = model(**batch)
            if output.loss is None or not torch.isfinite(output.loss):
                raise ValueError("transformer training produced a non-finite loss")
            output.loss.backward()
            optimizer.step()

    logits: list[np.ndarray[Any, Any]] = []
    model.eval()
    with torch.inference_mode():
        for start in range(0, len(predict_text), config.batch_size):
            stop = start + config.batch_size
            batch = {
                name: tensor[start:stop].to(device) for name, tensor in predict_encoding.items()
            }
            logits.append(model(**batch).logits.cpu().numpy())
    raw = np.concatenate(logits, axis=0)
    columns = prediction_columns(spec.metric_id, spec.target_columns, spec.class_labels)
    if spec.problem_type.task is TaskKind.CLASSIFICATION:
        shifted = raw - raw.max(axis=1, keepdims=True)
        exponentials = np.exp(shifted)
        probabilities = exponentials / exponentials.sum(axis=1, keepdims=True)
        predictions = _classification_frame(spec, columns, probabilities)
    else:
        prediction = raw.reshape(-1).astype(np.float64)
        if spec.metric_id is MetricId.RMSLE:
            prediction = np.maximum(prediction, 0.0)
        predictions = pd.DataFrame({columns[0]: prediction})
    return write_candidate_predictions(
        spec,
        bundle.predict_ids,
        predictions,
        output_root,
        started=started,
        diagnostics={
            "engine": CandidateEngine.TRANSFORMER.value,
            "device": device.type,
            "epochs": config.epochs,
            "max_length": config.max_length,
        },
    )

Offline ResNet18 training and inference for AGENT-K vision tasks.

(c) Mike Casale 2025. Licensed under the MIT License.

describe_hyperparameters

describe_hyperparameters() -> str

Describe the hyperparameters the ResNet18 engine accepts, for evolution prompts.

Source code in agent_k/vision.py
 98
 99
100
def describe_hyperparameters() -> str:
    """Describe the hyperparameters the ResNet18 engine accepts, for evolution prompts."""
    return f"resnet18 hyperparameters (JSON schema): {hyperparameter_schema(_VisionConfig)}"

run_candidate

run_candidate(
    spec: CandidateSpec, input_root: Path, output_root: Path
) -> CandidateResult

Fine-tune an actual ResNet18 and emit trusted-contract predictions.

Source code in agent_k/vision.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def run_candidate(
    spec: CandidateSpec,
    input_root: Path,
    output_root: Path,
) -> CandidateResult:
    """Fine-tune an actual ResNet18 and emit trusted-contract predictions."""
    started = time.monotonic()
    if spec.engine is not CandidateEngine.RESNET18:
        raise ValueError(f"unsupported vision engine: {spec.engine.value}")
    if spec.image_column is None:
        raise ValueError("vision candidates require image_column")
    if len(spec.target_columns) != 1:
        raise ValueError("vision candidates require exactly one target")
    unknown = set(spec.hyperparameters) - _VISION_PARAMETERS
    if unknown:
        raise ValueError(f"unsupported ResNet18 hyperparameters: {sorted(unknown)}")

    config = _VisionConfig.model_validate(spec.hyperparameters)
    bundle = load_candidate_dataset(spec, input_root)
    seed = spec.seed
    torch.manual_seed(seed)
    np.random.seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)
    device = _select_device(config.device_policy)
    if device.type == "cpu":
        torch.set_num_threads(config.cpu_threads)

    transform = transforms.Compose(
        (
            transforms.Resize((config.image_size, config.image_size)),
            transforms.ToTensor(),
            transforms.Normalize(
                mean=(0.485, 0.456, 0.406),
                std=(0.229, 0.224, 0.225),
            ),
        )
    )
    target, output_count = _vision_target(spec, bundle.train_targets.iloc[:, 0])
    train_dataset = _ImageDataset(
        bundle.train,
        image_column=spec.image_column,
        image_root=spec.train_image_root or "",
        input_root=input_root,
        transform=transform,
        target=target,
    )
    predict_dataset = _ImageDataset(
        bundle.predict,
        image_column=spec.image_column,
        image_root=spec.predict_image_root or "",
        input_root=input_root,
        transform=transform,
        target=None,
    )
    generator = torch.Generator().manual_seed(seed)
    train_loader = DataLoader(
        train_dataset,
        batch_size=config.batch_size,
        shuffle=True,
        num_workers=0,
        generator=generator,
    )
    predict_loader = DataLoader(
        predict_dataset,
        batch_size=config.batch_size,
        shuffle=False,
        num_workers=0,
    )
    model = resnet18(weights=None)
    _load_resnet_weights(model, spec, input_root)
    if config.freeze_backbone:
        for parameter in model.parameters():
            parameter.requires_grad = False
    model.fc = nn.Linear(model.fc.in_features, output_count)
    model.to(device)
    optimizer = torch.optim.AdamW(
        (parameter for parameter in model.parameters() if parameter.requires_grad),
        lr=config.learning_rate,
        weight_decay=config.weight_decay,
    )
    criterion: nn.Module = (
        nn.CrossEntropyLoss() if spec.problem_type.task is TaskKind.CLASSIFICATION else nn.MSELoss()
    )
    model.train()
    for _ in range(config.epochs):
        for images, labels in train_loader:
            images = images.to(device)
            labels = labels.to(device)
            optimizer.zero_grad(set_to_none=True)
            output = model(images)
            if spec.problem_type.task is TaskKind.REGRESSION:
                labels = labels.to(torch.float32).reshape(-1, 1)
            loss = criterion(output, labels)
            if not torch.isfinite(loss):
                raise ValueError("ResNet18 training produced a non-finite loss")
            loss.backward()
            optimizer.step()

    update_bn(train_loader, model, device=device)
    calibration_batches = int(model.bn1.num_batches_tracked.item())
    raw = _predict(model, predict_loader, device)
    predictions = _vision_predictions(spec, raw)
    return write_candidate_predictions(
        spec,
        bundle.predict_ids,
        predictions,
        output_root,
        started=started,
        diagnostics={
            "engine": CandidateEngine.RESNET18.value,
            "device": device.type,
            "epochs": config.epochs,
            "image_size": config.image_size,
            "batch_norm_calibrated": True,
            "batch_norm_calibration_batches": calibration_batches,
        },
    )