Skip to content

The platform for continuously improving AI agents.

27.4 KB
Raw Blame
from __future__ import annotations

import gzip
import hashlib
import io
import json
import logging
import math
import tempfile
import uuid
from datetime import timedelta
from pathlib import Path

import modal
from django.conf import settings
from django.db import transaction
from django.utils import timezone
from modal.exception import ConnectionError as ModalConnectionError
from modal.exception import InternalError, NotFoundError, ServiceError

from modal_shared.decisions import DECISION_OBJECTIVES
from modal_shared.modelfam import resolve
from modal_shared.preparation import processor_fingerprint as asset_fingerprint
from modal_shared.preparation import validate_preparation_report
from modal_shared.stacks import TRAIN_DECISION, TRAIN_KEV, train_function_name
from modal_shared.training_data import file_digest
from overbae.core.errors import InputValidationError
from overbae.modal.decision_catalog import get as decision_catalog_model
from overbae.modal.decision_catalog import training_refusal
from overbae.modal.model_registry import (
    get_hf_base,
    get_model_config_any_backend,
    get_unsloth_image,
)
from overbae.modal.training_type import training_context_length, training_enabled
from overbae.models import DecisionJob, FinetuningJob, Project, TrainingPreparation
from overbae.services import operational_progress, training_release
from overbae.services.datasets import heartbeat
from overbae.services.datasets import rows as row_store
from overbae.services.datasets import use as dataset_use
from overbae.services.finetuning_policy import (
    estimated_training_context_length,
    snap_context_length,
    validate_requested_context_length,
)
from overbae.services.finetuning_validator import row_to_finetuning_line
from overbae.services.training_contract import dataset_objective

logger = logging.getLogger(__name__)

FINISHED_JOBS = (
    FinetuningJob.Status.SUCCEEDED,
    FinetuningJob.Status.FAILED,
    FinetuningJob.Status.CANCELLED,
)


def processor_fingerprint():
    return asset_fingerprint(Path(__file__).parent / "sft_assets")


def training_stack(model: str, objective: str) -> str:
    """The image a job prepares and trains on. A decision objective needs the qualified
    decision encoder, so it runs on the decision runtime unless its family brings its own
    (Kev); a foundation's chat image does not carry that encoder."""
    if objective not in DECISION_OBJECTIVES:
        return get_unsloth_image(model)
    family = resolve(get_hf_base(model) or model).train_image
    return family if family in {TRAIN_DECISION, TRAIN_KEV} else TRAIN_DECISION


def request_preparation(
    cell,
    model: str,
    context_length: int,
    *,
    validation_cell=None,
    training_type="lora",
    runtime=None,
):
    if runtime is None and settings.FINETUNING_BACKEND != "modal":
        raise InputValidationError(
            "Exact preprocessing is available for the Modal training backend."
        )
    model_config = get_model_config_any_backend(model)
    if not model_config:
        raise InputValidationError("Choose a catalog training model.")
    decision_model = decision_catalog_model(model)
    if decision_model and not decision_model["training_available"]:
        raise InputValidationError(training_refusal(decision_model))
    if training_type not in {"lora", "full"} or not training_enabled(model_config, training_type):
        raise InputValidationError("This model does not support the selected training type.")
    maximum = training_context_length(model_config, training_type)
    validate_requested_context_length(context_length, model_max=maximum)
    for target in (cell, validation_cell):
        if target is not None:
            if target.dataset.project_id != cell.dataset.project_id:
                raise InputValidationError("Both datasets must belong to the same project.")
            dataset_use.check(target.dataset, "train", cell=target)
    objective = dataset_objective(cell)
    if objective in DECISION_OBJECTIVES and training_type != "lora":
        raise InputValidationError("Native decision training currently supports LoRA only.")
    if validation_cell is not None:
        validation_objective = dataset_objective(validation_cell)
        if (
            objective != validation_objective
            and not {objective, validation_objective} <= DECISION_OBJECTIVES
        ):
            raise InputValidationError(
                "Training and validation must use the same inference contract."
            )
    runtime = runtime or training_release.current()
    config = {
        "runtime": runtime,
        "objective": objective,
        "model": model,
        "tokenizer_model": get_hf_base(model),
        "context_length": context_length,
        "training_type": training_type,
        "cell": str(cell.id),
        "fingerprint": cell.fingerprint,
        "validation_cell": str(validation_cell.id) if validation_cell else None,
        "validation_fingerprint": validation_cell.fingerprint if validation_cell else None,
        "processor": runtime["processor"] if runtime else processor_fingerprint(),
        "data_format": runtime["data_format"],
        "stack": training_stack(model, objective),
    }
    signature = hashlib.sha256(json.dumps(config, sort_keys=True).encode()).hexdigest()
    preparation, _ = TrainingPreparation.objects.get_or_create(
        signature=signature,
        defaults={
            "cell": cell,
            "validation_cell": validation_cell,
            "config": config,
            "deadline": timezone.now() + timedelta(hours=24),
        },
    )
    if preparation.state == "cancelled":
        if preparation.remote_id and not stop_remote(preparation):
            raise InputValidationError(
                "The cancelled preprocessing call has not stopped yet. Try again shortly."
            )
        # A cancelled preparation stopped its remote call; a new request starts it again.
        TrainingPreparation.objects.filter(pk=preparation.pk, state="cancelled").update(
            state="queued",
            remote_id="",
            report={},
            error="",
            deadline=timezone.now() + timedelta(hours=24),
            touched_at=timezone.now(),
        )
        preparation.refresh_from_db()
    return preparation


def cancel_for_job(job) -> TrainingPreparation | None:
    """Stops the job's preparation and its remote call, unless another live job waits on it."""
    if not job.preparation_id:
        return None
    with transaction.atomic():
        prep = TrainingPreparation.objects.select_for_update().get(pk=job.preparation_id)
        waiting = prep.training_jobs.exclude(pk=job.pk).exclude(status__in=FINISHED_JOBS).exists()
        if prep.state not in {"queued", "starting", "running"} or waiting:
            return None
        prep.state = "cancelled"
        prep.save(update_fields=["state", "touched_at"])
    if prep.remote_id:
        stop_remote(prep)
    operational_progress.preparation(prep)
    return prep


def stop_remote(prep) -> bool:
    """Cancels a cancelled preparation's remote call and forgets it once Modal acknowledges.
    An unacknowledged cancel keeps the call id, so the reconciler tries again."""
    try:
        modal.FunctionCall.from_id(prep.remote_id).cancel()
    except NotFoundError:
        pass
    except Exception:
        logger.warning("Preparation %s remote cancel was not acknowledged", prep.pk)
        return False
    TrainingPreparation.objects.filter(
        pk=prep.pk, state="cancelled", remote_id=prep.remote_id
    ).update(remote_id="")
    prep.remote_id = ""
    return True


def retry_preparation(preparation):
    if preparation.state != "failed" or not preparation.report.get("retryable"):
        raise InputValidationError("This preprocessing operation cannot be retried safely.")
    if preparation.remote_id:
        modal.FunctionCall.from_id(preparation.remote_id).cancel()
    TrainingPreparation.objects.filter(
        pk=preparation.pk, state="failed", touched_at=preparation.touched_at
    ).update(
        state="queued",
        remote_id="",
        report={},
        error="",
        deadline=timezone.now() + timedelta(hours=24),
        touched_at=timezone.now(),
    )
    preparation.refresh_from_db()
    sync_setup_jobs(preparation)
    return preparation


@transaction.atomic
def begin_preparation(cell, model, context_length, *, user, **kwargs):
    Project.objects.select_for_update().get(pk=cell.dataset.project_id)
    prep = request_preparation(cell, model, context_length, **kwargs)
    if not prep.training_jobs.exclude(status=FinetuningJob.Status.CANCELLED).exists():
        FinetuningJob.objects.create(
            project_id=prep.cell.dataset.project_id,
            dataset=prep.cell.dataset,
            cell=prep.cell,
            validation_cell=prep.validation_cell,
            validation_dataset=prep.validation_cell.dataset if prep.validation_cell_id else None,
            triggered_by=user,
            preparation=prep,
            base_model=prep.config["model"],
            provider=FinetuningJob.Provider.MODAL,
            name=f"{prep.cell.dataset.name} · {prep.config['model'].split('/')[-1]}",
            hyperparameters={
                "context_length": prep.config["context_length"],
                "objective": prep.config["objective"],
                "training_type": {
                    "type": "Full" if prep.config["training_type"] == "full" else "Lora"
                },
            },
            status=FinetuningJob.Status.PREPROCESSING,
            eval_model_before=False,
            eval_model_after=False,
        )
    if decision_catalog_model(model):
        for training_job in prep.training_jobs.all():
            DecisionJob.objects.get_or_create(finetuning_job=training_job)
    sync_setup_jobs(prep)
    return prep


def _estimated_tokens(*cells) -> int:
    return max(
        (
            int((cell.stats or {}).get("max_token_length") or 0)
            for cell in cells
            if cell is not None
        ),
        default=0,
    )


def _matches_estimate(context, estimated_tokens, maximum) -> bool:
    # The row-length bucket is the first preprocessing pass, not a chosen context.
    return int(context) == estimated_training_context_length(estimated_tokens, model_max=maximum)


def _adopt_measured_context(prep):
    if prep.state != "incompatible":
        return prep
    exact = int((prep.report or {}).get("max_tokens") or 0)
    context = int(prep.config["context_length"])
    if exact <= context:
        return prep
    maximum = training_context_length(
        get_model_config_any_backend(prep.config["model"]), prep.config["training_type"]
    )
    if maximum is not None and exact > maximum:
        return prep
    raised = snap_context_length(model_max=maximum, requested=exact)
    if raised == context:
        return prep
    measured = request_preparation(
        prep.cell,
        prep.config["model"],
        raised,
        validation_cell=prep.validation_cell,
        training_type=prep.config["training_type"],
        runtime=prep.config.get("runtime"),
    )
    moved = (
        FinetuningJob.objects.filter(preparation=prep, requested_configuration={})
        .exclude(status="cancelled")
        .update(preparation=measured)
    )
    if not moved:
        return prep
    if measured.state == "queued":
        from overbae.tasks.training_preparation import inspect_preparation

        inspect_preparation.delay(str(measured.id))
    return measured


def sync_setup_jobs(prep):
    prep = _adopt_measured_context(prep)
    failed = prep.state in {"failed", "incompatible"}
    status = (
        FinetuningJob.Status.FAILED
        if failed
        else FinetuningJob.Status.AWAITING_LAUNCH
        if prep.state == "ready"
        else FinetuningJob.Status.PREPROCESSING
    )
    progress = {
        "phase": "awaiting_launch" if prep.state == "ready" else "preprocessing",
        "preparation": {
            "id": str(prep.pk),
            "state": prep.state,
            "report": prep.report,
            **(prep.report.get("progress") or {}),
        },
    }
    # Only setup jobs follow the tokenization receipt; launched and cancelled jobs own their state.
    prep.training_jobs.filter(requested_configuration={}).exclude(status="cancelled").update(
        status=status,
        progress=progress,
        error_message=preparation_error(prep) if failed else "",
        completed_at=prep.touched_at if failed else None,
        updated_at=timezone.now(),
    )


def setup_job_for_launch(values, runtime):
    hp = values.get("hyperparameters") or {}
    return (
        FinetuningJob.objects.filter(
            project=values["project"],
            cell=values["cell"],
            validation_cell=values.get("validation_cell")
            if values.get("validation_enabled", True)
            else None,
            base_model=values["base_model"],
            status__in=[FinetuningJob.Status.PREPROCESSING, FinetuningJob.Status.AWAITING_LAUNCH],
            requested_configuration={},
            preparation__config__runtime=runtime,
            preparation__config__context_length=hp.get("context_length"),
            preparation__config__training_type="full"
            if (hp.get("training_type") or {}).get("type") == "Full"
            else "lora",
        )
        .select_for_update()
        .first()
    )


def observe_progress(prep):
    try:
        volume = modal.Volume.from_name(
            "overmind-sft", environment_name=prep.config["runtime"]["environment"]
        )
        content = bytearray()
        for chunk in volume.read_file(f"/preparations/{prep.id}/progress.json"):
            content.extend(chunk)
            if len(content) > 65536:
                return
        raw = json.loads(content)
        progress = {
            key: raw[key]
            for key in ("completed_rows", "reused_rows", "committed_shards", "updated_at")
            if isinstance(raw.get(key), (int, float)) and math.isfinite(raw[key]) and raw[key] >= 0
        }
        progress["stage"] = str(raw.get("stage", "tokenizing"))[:80]
        progress["total_rows"] = prep.cell.rows + (
            prep.validation_cell.rows if prep.validation_cell_id else 0
        )
        TrainingPreparation.objects.filter(
            pk=prep.pk, state="running", remote_id=prep.remote_id
        ).update(report={"progress": progress}, touched_at=timezone.now())
        operational_progress.preparation(prep, progress)
    except (
        OSError,
        ValueError,
        TypeError,
        ModalConnectionError,
        InternalError,
        ServiceError,
        NotFoundError,
    ):
        return


def live_progress_for_job(job):
    progress = dict(job.progress) if isinstance(job.progress, dict) else {}
    binding = progress.get("preparation")
    if (
        job.status not in {"preparing", "preprocessing", "awaiting_launch"}
        or not isinstance(binding, dict)
        or not binding.get("id")
    ):
        return progress
    current = (
        TrainingPreparation.objects.filter(
            pk=binding["id"], cell__dataset__project_id=job.project_id
        )
        .values("state", "report")
        .first()
    )
    if current:
        report = current["report"] or {}
        progress["preparation"] = {
            **binding,
            "state": current["state"],
            "report": report,
            **(report.get("progress") or {}),
        }
    return progress


def advance(preparation_id):
    now = timezone.now()
    with transaction.atomic():
        prep = (
            TrainingPreparation.objects.select_for_update(of=("self",))
            .select_related("cell", "validation_cell")
            .get(pk=preparation_id)
        )
        if prep.state in {"ready", "incompatible", "failed", "cancelled"}:
            if prep.state == "cancelled" and prep.remote_id:
                stop_remote(prep)
            return
        if prep.deadline <= now:
            prep.report = {"retryable": prep.state == "queued" or bool(prep.remote_id)}
            prep.state, prep.error = "failed", "Preprocessing exceeded its 24-hour deadline."
            prep.save(update_fields=["state", "error", "report", "touched_at"])
            return
        if prep.state == "starting":
            if prep.touched_at >= now - timedelta(seconds=heartbeat.STALE_SECONDS):
                return
            if prep.report.get("submitting"):
                prep.state, prep.error = (
                    "failed",
                    "Preprocessing submission was interrupted before acknowledgement.",
                )
                prep.save(update_fields=["state", "error", "touched_at"])
                return
            # The worker stopped before it asked Modal for anything, so it starts again.
            prep.state = "queued"
        starting = prep.state == "queued"
        if starting:
            prep.state, prep.attempt = "starting", uuid.uuid4()
            prep.save(update_fields=["state", "attempt", "touched_at"])
    # The export, the volume slot and the upload can each take minutes.
    beat = heartbeat.start(
        lambda: TrainingPreparation.objects.filter(
            pk=prep.pk, state="starting", attempt=prep.attempt
        ).update(touched_at=timezone.now()),
        owner=f"training preparation {prep.pk}",
    )
    try:
        if starting:
            training_release.verify(prep.config["runtime"])
            for cell in (prep.cell, prep.validation_cell):
                if cell is None:
                    continue
                row_store.verify(cell)
                expected = prep.config[
                    "fingerprint" if cell.id == prep.cell_id else "validation_fingerprint"
                ]
                if cell.fingerprint != expected:
                    raise ValueError("Dataset version changed before preprocessing.")
            total_rows = prep.cell.rows + (prep.validation_cell.rows if prep.validation_cell else 0)
            report_interval = max(1, min(1000, total_rows // 10))

            def report_export(stage, completed_rows, **marks):
                held = TrainingPreparation.objects.filter(
                    pk=prep.pk, state="starting", attempt=prep.attempt
                ).update(
                    report={
                        "progress": {
                            "stage": stage,
                            "completed_rows": completed_rows,
                            "total_rows": total_rows,
                        },
                        **marks,
                    },
                    touched_at=timezone.now(),
                )
                if held:
                    operational_progress.preparation(
                        prep,
                        {
                            "stage": stage,
                            "completed_rows": completed_rows,
                            "total_rows": total_rows,
                        },
                    )
                return held

            completed_rows = 0
            report_export("exporting", completed_rows)
            with tempfile.TemporaryDirectory(prefix="training-preparation-") as directory:
                source = Path(directory) / "rows.jsonl.gz"
                with (
                    source.open("wb") as raw,
                    gzip.GzipFile(
                        filename="", fileobj=raw, mode="wb", compresslevel=1, mtime=0
                    ) as compressed,
                    io.TextIOWrapper(compressed, encoding="utf-8") as stream,
                ):
                    for cell in (prep.cell, prep.validation_cell):
                        if cell is None:
                            continue
                        for row in row_store.iter_rows(cell):
                            stream.write(
                                json.dumps(
                                    {
                                        **row_to_finetuning_line(row),
                                        "source_row": row.extra.get("source_row", row.index),
                                        "cell": str(cell.id),
                                    }
                                )
                                + "\n"
                            )
                            completed_rows += 1
                            if (
                                completed_rows % report_interval == 0
                                or completed_rows == total_rows
                            ):
                                report_export("exporting", completed_rows)
                digest = file_digest(source)
                report_export("uploading", completed_rows)
                remote = f"/preparations/{prep.id}/rows.jsonl.gz"
                volume = modal.Volume.from_name(
                    "overmind-sft", environment_name=prep.config["runtime"]["environment"]
                )
                # Same cap as training-file commits. A launch wave otherwise stacks layers
                # until Modal refuses every writer on this volume.
                from overbae.services.training_transfer import VOLUME_WRITERS
                from overbae.tasks.utils.task_lock import hold_one_slot

                with (
                    hold_one_slot("sft-volume", VOLUME_WRITERS, timeout=3600),
                    volume.batch_upload(force=True) as batch,
                ):
                    batch.put_file(source, remote)
            function = modal.Function.from_name(
                prep.config["runtime"]["app"],
                "prepare_" + train_function_name(prep.config["stack"]),
                environment_name=prep.config["runtime"]["environment"],
            )
            # From here a lost worker may have started a paid call it never recorded. A worker
            # whose start was handed to another attempt stops before it calls Modal.
            if not report_export("uploading", completed_rows, submitting=True):
                return
            call = function.spawn(
                str(prep.id), {**prep.config, "rows_path": "/data" + remote, "rows_sha256": digest}
            )
            if not TrainingPreparation.objects.filter(
                pk=prep.pk, state="starting", attempt=prep.attempt
            ).update(state="running", remote_id=call.object_id, touched_at=timezone.now()):
                # Cancelled during submission: nothing else holds this call's ID.
                call.cancel()
        else:
            report = validate_preparation_report(
                modal.FunctionCall.from_id(prep.remote_id).get(timeout=0)
            )
            state = (
                "failed" if report.get("error") else "ready" if report["ready"] else "incompatible"
            )
            TrainingPreparation.objects.filter(
                pk=prep.pk, state="running", remote_id=prep.remote_id
            ).update(
                state=state,
                report=report,
                error=report.get("error", ""),
                touched_at=timezone.now(),
            )
    except TimeoutError:
        if not starting:
            observe_progress(prep)
        return
    except (ModalConnectionError, InternalError, ServiceError):
        # An observer failure is not a remote failure. Keep its handle until the deadline.
        return
    except Exception as exc:
        # Modal squashes volume layers in the background and asks the caller to wait.
        # Leaving the shared preparation failed makes every later job for this signature fail too.
        volume_busy = starting and "too many layers" in str(exc).lower()
        TrainingPreparation.objects.filter(
            pk=prep.pk, state__in=["starting", "running"], attempt=prep.attempt
        ).update(
            state="queued" if volume_busy else "failed",
            error="" if volume_busy else str(exc)[:1000],
            report={}
            if volume_busy
            else {"retryable": not starting or isinstance(exc, NotFoundError)},
            touched_at=timezone.now(),
        )
    finally:
        beat.set()


def ready_for_job(job, context_length):
    prep = request_preparation(
        job.cell,
        job.base_model,
        context_length,
        runtime=training_release.for_job(job),
        validation_cell=job.validation_cell if job.validation_enabled else None,
        training_type="full"
        if (job.hyperparameters or {}).get("training_type", {}).get("type") == "Full"
        else "lora",
    )
    if prep.state != "ready":
        raise ValueError(
            prep.error or "Exact preprocessing is not ready for this training configuration."
        )
    FinetuningJob.objects.filter(pk=job.pk).update(preparation=prep)
    return prep


def for_job(job):
    hp = job.hyperparameters or {}
    kind = "full" if hp.get("training_type", {}).get("type") == "Full" else "lora"
    config = get_model_config_any_backend(job.base_model) or {}
    maximum = training_context_length(config, kind)
    validation = job.validation_cell if job.validation_enabled else None
    estimated_tokens = _estimated_tokens(job.cell, validation)
    explicit_context = (
        (getattr(job, "requested_configuration", {}) or {})
        .get("configuration", {})
        .get("hyperparameters", {})
        or {}
    ).get("context_length")
    pinned = int(explicit_context) if explicit_context else None
    # A pin that is not the estimate still starts there. Measured rows that do not fit raise it.
    frozen = pinned is not None and not _matches_estimate(pinned, estimated_tokens, maximum)
    context = (
        pinned
        if frozen
        else estimated_training_context_length(
            estimated_tokens,
            model_max=maximum,
            requested=pinned or (int(hp.get("context_length") or 0) or None),
        )
    )
    prep = request_preparation(
        job.cell,
        job.base_model,
        context,
        validation_cell=validation,
        runtime=training_release.for_job(job),
        training_type=kind,
    )
    exact_tokens = int(prep.report.get("max_tokens") or 0)
    if (
        prep.state == "incompatible"
        and exact_tokens > context
        and (maximum is None or exact_tokens <= maximum)
    ):
        # Recheck every row at the measured size; length can coexist with other errors.
        context = snap_context_length(model_max=maximum, requested=exact_tokens)
        prep = request_preparation(
            job.cell,
            job.base_model,
            context,
            validation_cell=validation,
            runtime=training_release.for_job(job),
            training_type=kind,
        )
    FinetuningJob.objects.filter(pk=job.pk).update(preparation=prep)
    return prep


def preparation_error(prep):
    if prep.error:
        return prep.error
    longest = int(prep.report.get("max_tokens") or 0)
    context = int(prep.config["context_length"])
    if longest > context:
        return (
            f"The longest training or validation row needs {longest:,} tokens; "
            f"the selected training context is {context:,}. "
            "Choose a model with a larger training context or restructure the affected rows "
            "in the data workshop. No rows were truncated or dropped."
        )
    return (
        f"{prep.report.get('incompatible_rows', 0)} rows are incompatible with this "
        "training configuration. Inspect the preprocessing report for the affected rows."
    )


def retry_for_job(job):
    if settings.FINETUNING_BACKEND != "modal" or job.remote_job_id:
        return
    prep = for_job(job)
    if prep.state == "failed":
        retry_preparation(prep)
    elif prep.state == "incompatible":
        raise InputValidationError(
            "Training data is incompatible with this configuration. Inspect the preprocessing report."
            if prep.error
            else preparation_error(prep)
        )