Skip to content

The platform for continuously improving AI agents.

4.9 KB
Raw Blame
import hashlib
import json
import math

from modal_shared.decisions import DECISION_OBJECTIVE, DECISION_OBJECTIVES, TEXT_OBJECTIVE
from overbae.core.errors import InputValidationError


def dataset_objective(cell):
    report = (cell.intent_report.get("train") or {}) if cell else {}
    if report.get("format") == "decision":
        return report.get("objective", DECISION_OBJECTIVE)
    return TEXT_OBJECTIVE


def baseline_evaluation_enabled(hyperparameters):
    enabled = hyperparameters.get("pre_training_baseline", True)
    if type(enabled) is not bool:
        raise ValueError("pre_training_baseline must be a boolean.")
    if (
        "pre_training_baseline" in hyperparameters
        and hyperparameters.get("objective") not in DECISION_OBJECTIVES
    ):
        raise ValueError("pre_training_baseline applies only to native decision training.")
    return enabled


def validate_effective_batch(hyperparameters):
    unsupported = {
        "gradient_accumulation_steps",
        "per_device_train_batch_size",
    } & hyperparameters.keys()
    if unsupported:
        raise InputValidationError(
            f"Unsupported batch settings: {', '.join(sorted(unsupported))}. "
            "Set batch_size to the effective optimizer batch; the runtime derives "
            "micro-batches and gradient accumulation from the model and memory budget."
        )


# Each optimizer setting a client may send, with the smallest value it takes and whether
# that bound is open: a learning rate of 0 trains nothing.
_OPTIMIZER_RANGES = {
    "learning_rate": (0.0, True, None),
    "lr": (0.0, True, None),
    "warmup_ratio": (0.0, False, 1.0),
    "weight_decay": (0.0, False, None),
}


def validate_numbers(hyperparameters):
    """Optimizer settings are finite numbers in range: "NaN" parses as a float."""
    for key, (low, open_low, high) in _OPTIMIZER_RANGES.items():
        if key not in hyperparameters or hyperparameters[key] is None:
            continue
        raw = hyperparameters[key]
        try:
            value = float(raw) if not isinstance(raw, bool) else math.nan
        except (TypeError, ValueError, OverflowError):
            value = math.nan
        if (
            not math.isfinite(value)
            or value < low
            or (open_low and value == low)
            or (high is not None and value > high)
        ):
            raise InputValidationError(f"{key} must be a finite number in range.")


def contract(cell, hyperparameters=None):
    objective = (hyperparameters or {}).get("objective") or dataset_objective(cell)
    native = objective in DECISION_OBJECTIVES
    return {
        "objective": objective,
        "inference_contract": "decision" if native else "chat",
        "target": "declared_decision_supervision" if native else "assistant_tokens",
        "target_semantics": (
            (cell.intent_report.get("train") or {}).get("target_semantics", {}) if cell else {}
        ),
        "losses": {
            "distribution": "cross_entropy",
            "ordinal_mean": "squared_error_of_normalized_expectation",
        }
        if native
        else {"assistant_tokens": "cross_entropy"},
        "methods": ["lora"] if native else ["lora", "full"],
        "providers": ["modal"],
        "metrics": [
            "cross_entropy",
            "brier",
            "hard_label_accuracy",
            "expected_score_mae",
            "coverage",
        ]
        if native
        else ["cross_entropy", "token_accuracy"],
        "evaluation": "native_probabilities" if native else "chat_generation",
        "max_gpus": 1 if native else None,
        **(
            {"pre_training_baseline": (hyperparameters or {}).get("pre_training_baseline", True)}
            if native
            else {}
        ),
    }


def selection_record(
    cell,
    *,
    validation_cell=None,
    eval_cell=None,
    validation_enabled=True,
    validation_split_ratio=0.2,
    split_method="random",
    eval_set=None,
    evaluations=None,
):
    result = {}
    for name, selected in (("train", cell), ("validation", validation_cell), ("eval", eval_cell)):
        result[f"{name}_dataset"] = str(selected.dataset_id) if selected else None
        result[f"{name}_cell"] = str(selected.id) if selected else None
        result[f"{name}_fingerprint"] = selected.fingerprint if selected else None
        result[f"{name}_rows"] = selected.rows if selected else None
    result.update(
        validation_enabled=validation_enabled,
        validation_split_ratio=validation_split_ratio
        if validation_enabled and validation_cell is None
        else None,
        split_method=split_method if validation_enabled and validation_cell is None else None,
        eval_set=str(eval_set.id) if eval_set else None,
        evaluations=evaluations or {},
        grouping=["exact_input_content", "declared_case_group", "synthetic_seed"],
    )
    result["fingerprint"] = hashlib.sha256(json.dumps(result, sort_keys=True).encode()).hexdigest()
    return result