Skip to content

The platform for continuously improving AI agents.

3.7 KB
Raw Blame
import { useQuery } from "@tanstack/react-query";

import api from "@/client";
import { ExecutionTrend } from "@/components/ai-components/execution-trend";
import { buildTrainLossPoints } from "@/components/finetuning/loss-series";
import { Button } from "@/components/ui/button";
import { LoadingState } from "@/components/ui/spinner";
import type { LossCurveData } from "@/hooks/use-finetuning";
import { useFinetuningJobQuery } from "@/hooks/use-finetuning";
import { parseFinetuningProgress, progressPhaseLabel } from "@/lib/finetuning-progress";
import { ExecutionCard } from "./execution-card";

export function TrainingExecution({
  job,
  embedded = false,
  open,
  onOpenChange,
  onInspect,
}: {
  job: string;
  embedded?: boolean;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onInspect?: () => void;
}) {
  const jobQuery = useFinetuningJobQuery(job);
  const curves = useQuery({
    queryFn: () =>
      api.finetuningJobs.finetuningJobsLossCurvesRetrieve({
        id: job,
      }) as Promise<LossCurveData>,
    queryKey: ["finetuning-loss-curves", job],
    refetchInterval: ["succeeded", "failed", "cancelled"].includes(jobQuery.data?.status ?? "")
      ? false
      : 3000,
  });
  const points = buildTrainLossPoints(
    curves.data ?? { epochs: [], train_loss: [], valid_loss: [] }
  );
  const latest = points.filter((point) => point.train != null).at(-1);
  const progress = parseFinetuningProgress(jobQuery.data?.progress);
  return (
    <ExecutionCard
      embedded={embedded}
      onInspect={onInspect}
      onOpenChange={onOpenChange}
      open={open}
      status={jobQuery.data?.status}
      summary={
        <div className="flex items-baseline gap-2">
          <strong className="text-2xl font-medium tabular-nums">
            {latest?.train == null ? "—" : Number(latest.train.toPrecision(4))}
          </strong>
          <span className="text-xs text-muted-foreground">
            Train loss{latest ? ` · Step ${latest.step}` : " · Not measured"}
          </span>
        </div>
      }
      title="Training run"
    >
      <p className="mb-3 text-xs text-muted-foreground">
        {progressPhaseLabel(progress, jobQuery.data?.status)}
        {progress?.trained_steps != null
          ? ` · Step ${progress.trained_steps}${progress.total_steps != null ? ` / ${progress.total_steps}` : ""}`
          : ""}
      </p>
      {open && (
        <ExecutionTrend
          metrics={[
            {
              baseline: points.find((point) => point.train != null)?.train ?? undefined,
              baselineLabel: "first recorded loss",
              direction: "lower",
              id: "loss",
              label: "Train loss",
              points: points.map((point) => ({
                id: String(point.step),
                label: `Step ${point.step}`,
                value: point.train,
                x: point.step,
              })),
            },
            {
              direction: "lower",
              id: "validation",
              label: "Validation loss",
              points: points.map((point) => ({
                id: String(point.step),
                label: `Step ${point.step}`,
                value: point.eval,
                x: point.step,
              })),
            },
          ]}
        />
      )}
      {jobQuery.isError && (
        <Button onClick={() => void jobQuery.refetch()} size="xs" variant="outline">
          Retry training run
        </Button>
      )}
      {open && curves.isPending && <LoadingState label="Loading training metrics" />}
      {open && curves.isError && (
        <Button onClick={() => void curves.refetch()} size="xs" variant="outline">
          Retry training metrics
        </Button>
      )}
    </ExecutionCard>
  );
}