The platform for continuously improving AI agents.
"""Which models to fine-tune on a dataset, and the evidence behind the order.
The selected capability supplies the task; without one, the dataset does.
Capability classification is cached by codebase context. Benchmark ranking is pure.
"""
from __future__ import annotations
import logging
import math
from typing import Any
from modal_shared.decisions import DECISION_OBJECTIVES
from overbae.core.errors import InputValidationError
from overbae.services.serving_context import evaluation_budget, serving_plan
from overbae.services.training_contract import dataset_objective, validate_effective_batch
from .analysis import build_analysis, dataset_summary
from .candidates import build_candidate, dataset_total_tokens
from .catalog import active_backend, find_catalog_model, tier_models
logger = logging.getLogger(__name__)
_CLASSIFIER_INPUTS = ("output_kind", "modality", "has_tool_calls")
def get_recommendation(
dataset_id: str,
capability_id: str | None = None,
*,
eval_dataset_id: str | None = None,
cell=None,
eval_cell=None,
) -> dict[str, Any]:
"""Ranked fine-tuning candidates for a dataset, grounded in its capability's context.
Without ``capability_id`` classify the dataset, even if it has a capability mapping.
"""
from overbae.models import Capability, Dataset # noqa: PLC0415
from overbae.services.codebase.task_type import classify_capability_task # noqa: PLC0415
from overbae.services.datasets.rows import dataset_stats # noqa: PLC0415
from .capability_context import collect_capability_context # noqa: PLC0415
dataset = Dataset.objects.get(pk=dataset_id)
capability = None
if capability_id:
capability = Capability.objects.get(pk=capability_id, project_id=dataset.project_id)
stats = dataset_stats(dataset, cell)
native = dataset_objective(cell or dataset.active_cell) in DECISION_OBJECTIVES
if capability is not None:
task_type = classify_capability_task(capability)
source = "capability" if task_type != "unknown" else "unknown"
else:
task_type, source = _resolve_task_type(dataset, stats, native=native)
capability_context = collect_capability_context(capability) if capability is not None else None
if native:
return {
"task_type": task_type,
"task_type_source": source,
"dataset": dataset_summary(stats),
"candidates": [],
"excluded": [],
"shown": [],
"skill_weights": {},
"benchmark_snapshot": {"generated_at": None},
"capability_context": capability_context,
}
analysis = build_analysis(
stats,
task_type=task_type,
task_type_source=source,
capability_context=capability_context,
)
if eval_dataset_id:
evaluation = Dataset.objects.get(pk=eval_dataset_id, project_id=dataset.project_id)
cell = eval_cell or evaluation.active_cell
if cell is None:
raise InputValidationError("The evaluation dataset has no readable version.")
budget = evaluation_budget(cell, capability=capability)
accepted = []
for candidate in analysis["candidates"]:
try:
candidate["serving_context"] = serving_plan(candidate["model"], budget)
accepted.append(candidate)
except InputValidationError as exc:
analysis["excluded"].append({"model": candidate["model"], "reason": exc.detail})
analysis["candidates"] = accepted
remaining = {candidate["model"] for candidate in accepted}
analysis["shown"] = [model for model in analysis["shown"] if model in remaining]
if not analysis["shown"] and accepted:
analysis["shown"] = [accepted[0]["model"]]
accepted[0]["selected"] = True
return analysis
def estimate_for_hyperparams(
dataset_id: str,
*,
base_model: str,
n_epochs: int,
use_lora: bool,
cell: Any = None,
validation_cell=None,
validation_enabled=True,
validation_split_ratio=0.2,
split_method="random",
hyperparameters=None,
) -> dict[str, Any]:
"""Re-estimate cost and duration for user-edited hyperparameters."""
from overbae.modal.model_registry import context_headroom # noqa: PLC0415
from overbae.modal.training_type import ( # noqa: PLC0415
training_context_length,
training_enabled,
)
from overbae.models import Dataset # noqa: PLC0415
from overbae.services.datasets.rows import dataset_stats # noqa: PLC0415
from overbae.services.finetuning_pricing import estimate_training_run # noqa: PLC0415
dataset = Dataset.objects.get(pk=dataset_id)
if active_backend() == "modal":
validate_effective_batch(hyperparameters or {})
stats = dataset_stats(dataset, cell)
selected = cell or dataset.active_cell
native = selected is not None and dataset_objective(selected) in DECISION_OBJECTIVES
entry = find_catalog_model(base_model, decision=native)
if entry is None:
raise ValueError(f"Unknown base model: {base_model}")
params_b = entry.get("total_params_b")
if params_b is None:
raise ValueError(f"Model {base_model!r} is missing total_params_b")
kind = "lora" if use_lora else "full"
kind_label = "LoRA" if use_lora else "full"
if not training_enabled(entry, kind):
raise ValueError(f"Model {base_model} does not support {kind_label} fine-tuning")
requested_context = (hyperparameters or {}).get("context_length")
if active_backend() == "modal" and requested_context is not None:
from overbae.services.finetuning_policy import validate_requested_context_length
validate_requested_context_length(
requested_context, model_max=training_context_length(entry, kind)
)
max_tokens = int(stats.get("max_token_length") or 0)
if max_tokens:
model_max = training_context_length(entry, kind)
headroom = context_headroom(active_backend())
if model_max is not None and model_max < max_tokens + headroom:
raise ValueError(
f"Longest dataset row is ≈{max_tokens:,} tokens but {base_model}'s "
f"{kind_label} fine-tuning context is {model_max:,} tokens"
+ (f" (need {max_tokens + headroom:,} with headroom)" if headroom else "")
+ "."
)
from overbae.services.finetuning_validator import validate_dataset
checked = validate_dataset(
str(dataset.id),
cell_id=str(selected.id),
validation_cell_id=str(validation_cell.id) if validation_cell else None,
validation_dataset_id=str(validation_cell.dataset_id) if validation_cell else None,
validation_enabled=validation_enabled,
validation_split_ratio=validation_split_ratio,
split_method=split_method,
)
if not checked.valid:
raise ValueError("The selected training split is not technically compatible.")
count = checked.stats.get("train_examples", selected.rows)
selected_tokens = round(dataset_total_tokens(stats) * count / max(1, selected.rows))
if active_backend() == "modal" and native:
from overbae.services.training_forecast import forecast
recipe = {**(hyperparameters or {}), "objective": dataset_objective(selected)}
tokens = selected_tokens * int(recipe.get("n_epochs", n_epochs))
measured = forecast(dataset.project_id, base_model, recipe, tokens=tokens, stats=stats)
measured["token_estimate"] = "proportional_to_selected_rows"
measured["selected_training_rows"] = count
duration = measured["training_seconds"]
cost = measured["training_gpu_usd"]
return {
"forecast": measured,
"cost_estimate": {
"usd": cost[1],
"trained_tokens": tokens,
}
if cost
else None,
"time_estimate": {
"seconds": None,
"human": f"{math.floor(duration[0] / 60)}–{math.ceil(duration[1] / 60)} min"
if duration
else "Unmeasured recipe",
},
"trained_tokens": tokens,
}
return estimate_training_run(
dataset_tokens=selected_tokens,
n_epochs=n_epochs,
total_params_b=float(params_b),
use_lora=use_lora,
backend=active_backend(),
)
def recommend_hyperparams_for_model(
dataset_id: str, base_model: str, cell: Any = None
) -> dict[str, Any]:
"""A candidate row for an arbitrary catalog model, ungraded — the same derivation the
ranked rows use, for a model the user picked themselves.
"""
from overbae.models import Dataset # noqa: PLC0415
from overbae.services.datasets.rows import dataset_stats # noqa: PLC0415
dataset = Dataset.objects.get(pk=dataset_id)
stats = dataset_stats(dataset, cell)
selected = cell or dataset.active_cell
native = selected is not None and dataset_objective(selected) in DECISION_OBJECTIVES
entry = find_catalog_model(base_model, decision=native)
if entry is None:
raise ValueError(f"Unknown base model: {base_model}")
max_tokens = int(stats.get("max_token_length") or 0)
if max_tokens:
from overbae.modal.model_registry import context_headroom
from overbae.modal.training_type import training_context_length, usable_training_kinds
headroom = context_headroom(active_backend())
if not usable_training_kinds(entry, max_tokens=max_tokens, headroom=headroom):
model_max = max(training_context_length(entry, kind) or 0 for kind in ("lora", "full"))
raise ValueError(
f"Longest dataset row is ≈{max_tokens:,} tokens but {base_model} "
f"only supports {model_max:,} tokens for fine-tuning"
+ (f" (need {max_tokens + headroom:,} with headroom)" if headroom else "")
+ "."
)
tier = next(
(
t
for t, models in tier_models(backend="decision" if native else None).items()
if any(m.get("id") == base_model for m in models)
),
"small",
)
return build_candidate(stats, model_entry=entry, tier=tier)
def _resolve_task_type(dataset, stats: dict[str, Any], *, native: bool = False) -> tuple[str, str]:
"""The dataset's task type and where it came from.
A dataset that went straight to the wizard has no context, so it is classified inline
from its profile and the semantic value is left to arrive with the queued refresh.
"""
from overbae.models import DatasetContext # noqa: PLC0415
from overbae.services.benchmarks.classify import classify_task_type # noqa: PLC0415
from overbae.services.benchmarks.taxonomy import TaskType # noqa: PLC0415
from overbae.services.datasets.profiler import enqueue_refresh # noqa: PLC0415
context = DatasetContext.objects.filter(dataset=dataset).first()
# Chat-output shape cannot establish the semantic task of typed decision rows.
if native and (context is None or context.task_type_source != "semantic"):
return "unknown", "unknown"
if context is not None:
if context.task_type in set(TaskType.values):
return context.task_type, context.task_type_source or "heuristic"
if native:
return "unknown", "unknown"
profile = context.profile or {}
if not _carries_classifier_inputs(profile):
profile = _profile(dataset)
return classify_task_type(profile, stats), "heuristic"
enqueue_refresh(dataset.id)
return classify_task_type(_profile(dataset), stats), "heuristic"
def _carries_classifier_inputs(profile: dict[str, Any]) -> bool:
"""Stored profiles written before the classifier existed carry none of its fields, so
classifying them collapses every dataset onto the same fallback task type."""
return any(profile.get(key) is not None for key in _CLASSIFIER_INPUTS)
def _profile(dataset) -> dict[str, Any]:
"""Profiling reads datapoints and their spans; a failure degrades the task type rather
than the wizard."""
from overbae.services.datasets import profiler # noqa: PLC0415
try:
return profiler.profile_dataset(dataset)
except Exception as exc: # noqa: BLE001
logger.warning("Dataset profiling failed for dataset %s: %s", dataset.id, exc)
return {}
__all__ = [
"estimate_for_hyperparams",
"find_catalog_model",
"get_recommendation",
"recommend_hyperparams_for_model",
"tier_models",
]