Skip to content

The platform for continuously improving AI agents.

faster training models deployment (#232)

Rohit Guptaee6c0bc7e84a
diff --git a/.agents/skills/backend-architecture/SKILL.md b/.agents/skills/backend-architecture/SKILL.md
index 04d8ea14..ec16a476 100644
--- a/.agents/skills/backend-architecture/SKILL.md
+++ b/.agents/skills/backend-architecture/SKILL.md
@@ -162,8 +162,10 @@ Training handoff separates selection construction, acknowledged selection-file u
provider artifact verification, indexing, row selection and publication. Only successful
Modal batch completion increments acknowledged bytes/files; live network-byte progress
is unavailable. The pinned worker publishes bounded transfer measurements to the run's
-`transfer-progress.json`; the existing 15-second reconciler collects them even while the
-submission task is active. Console and MCP read persisted, attempt-fenced diagnostics
+`transfer-progress.json` and commits that volume when a stage finishes. Modal's
+background commit publishes step files; a timer commit is not used, and at most
+five launches upload at once. The existing 15-second reconciler collects transfer
+facts even while the submission task is active. Console and MCP read persisted, attempt-fenced diagnostics
and operational events, never invoking a worker to read status. Stage start, source
observation and last forward progress remain separate; absent measurements show no
percentage. Worker instrumentation requires deployment of a new immutable release and
@@ -379,9 +381,10 @@ The Console projects selected evaluations into waiting rows immediately and repl
each by kind when its run arrives. Loss-curve polling continues after deployment while
evaluations remain pending. `services.deployment` persists each deployment's stage,
remote call handle, generation, retry budget, deadline, and evaluation waiters.
-The single 15-second deployment controller covers training outputs and baselines;
-short IO tasks claim a row for 45 seconds, spawn or observe one remote call, then exit.
-Worker death reconnects to the saved call rather than restarting GPU work. Each
+The single 15-second deployment controller covers training outputs and baselines.
+A finished stage starts the next remote call before the claim is released. The S3
+checkpoint archive is spawned beside that sequence and does not gate readiness.
+Short IO tasks claim a row for 45 seconds. Worker death reconnects to the saved call rather than restarting GPU work. Each
attempt has a four-hour deadline and at most three confirmed-failure attempts with
30/60-second backoff. Transport errors retain the handle. Submission without a saved
acknowledgement fails closed; never launch another call until remote state is resolved.
diff --git a/AGENTS.md b/AGENTS.md
index c01df1f3..e90546a6 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -107,7 +107,7 @@ Each line is the invariant; the named skill section carries the mechanics.
- Explicit REST/MCP training preparation creates the dashboard FinetuningJob atomically before dispatching preprocessing. Setup jobs show preparing data, awaiting launch or preparation failure; they never enter GPU dispatch or pass launch admission. A matching launch promotes that same job and pins the full recipe; preparation retries only retry preprocessing.
-- Training launch receipts pin the runtime release/environment, exact cells and requested recipe. Stall detection counts native validation and checkpoint-stage progress independently of optimizer steps; a committer heartbeat alone does not establish forward progress. Reusing a project request key returns the same job; a changed recipe conflicts. Provider intent is persisted before dispatch; an unknown acknowledgement is reconciled against that job's provider metadata, never resubmitted. Explicit settings that require a clamp are rejected. Native paired evaluation uses its own frozen calibration/final plan, retains incompatible rows, keeps references local and fits calibration before final predictions. Downloadable run records distinguish recorded GPU spend from unreported components. Detail: backend-architecture § Reproducible training experiments.
+- Training launch receipts pin the runtime release/environment, exact cells and requested recipe. The training volume commits when a stage finishes, not on a timer, and at most five launches upload to it at once. Stall detection counts native validation and checkpoint-stage progress independently of optimizer steps; a committer heartbeat alone does not establish forward progress. Reusing a project request key returns the same job; a changed recipe conflicts. Provider intent is persisted before dispatch; an unknown acknowledgement is reconciled against that job's provider metadata, never resubmitted. Explicit settings that require a clamp are rejected. Native paired evaluation uses its own frozen calibration/final plan, retains incompatible rows, keeps references local and fits calibration before final predictions. Downloadable run records distinguish recorded GPU spend from unreported components. Detail: backend-architecture § Reproducible training experiments.
- Development monitoring freezes `hyperparameters.monitoring` across readiness,
estimates and launch. Modal freezes loss/reference/generation samples before GPU
diff --git a/frontend/src/components/finetuning/train/model-config.ts b/frontend/src/components/finetuning/train/model-config.ts
index 62fde589..0e586b5c 100644
--- a/frontend/src/components/finetuning/train/model-config.ts
+++ b/frontend/src/components/finetuning/train/model-config.ts
@@ -50,13 +50,20 @@ export const TIER_META: Record<string, { label: string; color: string; descripti
export const TIER_ORDER = ["compact", "small", "mid", "large"] as const;
export const MAX_MODELS = 4;
-const TIER_DEFAULTS: Record<string, { learning_rate: number; lora_r: number; lora_alpha: number }> =
- {
- compact: { learning_rate: 2e-4, lora_alpha: 32, lora_r: 16 },
- large: { learning_rate: 2e-5, lora_alpha: 16, lora_r: 8 },
- mid: { learning_rate: 5e-5, lora_alpha: 32, lora_r: 16 },
- small: { learning_rate: 1e-4, lora_alpha: 16, lora_r: 8 },
- };
+// Keep aligned with modal_shared/serving/args.py TRAINING_LORA_RANKS.
+export const LORA_RANKS = [8, 16, 32, 64, 128, 256, 320, 512] as const;
+
+export function loraRank(value: unknown, fallback: number): number {
+ const rank = typeof value === "number" ? value : Number(value);
+ return LORA_RANKS.some((step) => step === rank) ? rank : fallback;
+}
+
+const TIER_DEFAULTS: Record<string, { learning_rate: number; lora_r: number }> = {
+ compact: { learning_rate: 2e-4, lora_r: 16 },
+ large: { learning_rate: 2e-5, lora_r: 8 },
+ mid: { learning_rate: 5e-5, lora_r: 16 },
+ small: { learning_rate: 1e-4, lora_r: 8 },
+};
export function clampBatchSize(
value: number | string | undefined,
@@ -205,7 +212,7 @@ export function draftFromRecommendation(
const useLora = supportsLora && (!supportsFull || r.useLora || tt.type === "Lora");
const minBs = catalogModel?.minBatchSize ?? r.minBatchSize ?? 1;
const maxBs = catalogModel?.maxBatchSize ?? r.maxBatchSize ?? 64;
- const rank = Number(tt.lora_r) || TIER_DEFAULTS[r.tier]?.lora_r || 16;
+ const rank = loraRank(tt.lora_r, TIER_DEFAULTS[r.tier]?.lora_r || 16);
const contextLength =
typeof hp.context_length === "number" && hp.context_length > 0 ? hp.context_length : undefined;
const batch = clampBatchSize(hp.batch_size as number | string | undefined, minBs, maxBs);
@@ -226,7 +233,7 @@ export function draftFromRecommendation(
learningRateFull: r.learningRateFull,
learningRateLora: r.learningRateLora,
loraParams: {
- lora_alpha: Number(tt.lora_alpha) || rank * 2,
+ lora_alpha: rank * 2,
lora_dropout: Number(tt.lora_dropout) || 0,
lora_r: rank,
},
@@ -251,7 +258,7 @@ export function draftFromCatalogModel(tier: string, m: ModelEntry): ModelDraft {
const supportsLora = catalogTrainingEnabled(m, "lora");
const supportsFull = catalogTrainingEnabled(m, "full");
const td = TIER_DEFAULTS[tier];
- const loraR = td?.lora_r ?? 16;
+ const loraR = loraRank(td?.lora_r, 16);
return {
...ungraded(),
contextLengthSft: m.contextLengthSft,
@@ -267,7 +274,7 @@ export function draftFromCatalogModel(tier: string, m: ModelEntry): ModelDraft {
id: crypto.randomUUID(),
learningRateFull: td?.learning_rate ? td.learning_rate / 10 : 1e-5,
learningRateLora: td?.learning_rate ?? 1e-4,
- loraParams: { lora_alpha: td?.lora_alpha ?? loraR * 2, lora_dropout: 0, lora_r: loraR },
+ loraParams: { lora_alpha: loraR * 2, lora_dropout: 0, lora_r: loraR },
maxBatchSize: m.maxBatchSize ?? 64,
minBatchSize: m.minBatchSize ?? 1,
model: m.id,
@@ -310,9 +317,9 @@ export function draftWithModel(draft: ModelDraft, tier: string, m: ModelEntry):
learningRateFull: td?.learning_rate ? td.learning_rate / 10 : draft.learningRateFull,
learningRateLora: td?.learning_rate ?? draft.learningRateLora,
loraParams: {
- lora_alpha: td?.lora_alpha ?? draft.loraParams.lora_alpha,
+ lora_alpha: loraRank(td?.lora_r, draft.loraParams.lora_r) * 2,
lora_dropout: draft.loraParams.lora_dropout,
- lora_r: td?.lora_r ?? draft.loraParams.lora_r,
+ lora_r: loraRank(td?.lora_r, draft.loraParams.lora_r),
},
maxBatchSize: maxBs,
minBatchSize: minBs,
diff --git a/frontend/src/components/finetuning/train/models-panel.tsx b/frontend/src/components/finetuning/train/models-panel.tsx
index c80a0d72..079a80f1 100644
--- a/frontend/src/components/finetuning/train/models-panel.tsx
+++ b/frontend/src/components/finetuning/train/models-panel.tsx
@@ -5,6 +5,7 @@ import { Column, FactLine, type Segment, SplitBar } from "@/components/finetunin
import {
clampBatchSize,
draftWithModel,
+ LORA_RANKS,
MAX_MODELS,
type ModelDraft,
TIER_META,
@@ -313,38 +314,21 @@ function TuneFields({
<TuningField
id={`lora-r-${draft.id}`}
label="Rank"
- min={1}
onCommit={(v) => {
- const r = Number.parseInt(v, 10) || 1;
+ const r = Number.parseInt(v, 10);
onChange({
...draft,
loraParams: {
...draft.loraParams,
- lora_alpha: Math.max(draft.loraParams.lora_alpha, r),
+ lora_alpha: r * 2,
lora_r: r,
},
});
}}
- parse="int"
+ options={LORA_RANKS}
recommended={draft.recommendedValues?.lora_r}
value={String(draft.loraParams.lora_r)}
/>
- <TuningField
- id={`lora-alpha-${draft.id}`}
- label="Alpha"
- min={1}
- onCommit={(v) =>
- onChange({
- ...draft,
- loraParams: {
- ...draft.loraParams,
- lora_alpha: Number.parseInt(v, 10) || 1,
- },
- })
- }
- parse="int"
- value={String(draft.loraParams.lora_alpha)}
- />
<TuningField
id={`lora-dropout-${draft.id}`}
label="Dropout"
diff --git a/frontend/src/components/finetuning/train/tuning.tsx b/frontend/src/components/finetuning/train/tuning.tsx
index f47d22d6..9cbee089 100644
--- a/frontend/src/components/finetuning/train/tuning.tsx
+++ b/frontend/src/components/finetuning/train/tuning.tsx
@@ -4,6 +4,13 @@ import { formatLr } from "@/components/finetuning/train/model-config";
import { Icon } from "@/components/ui/icons";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
export function TuningField({
@@ -17,6 +24,7 @@ export function TuningField({
step,
hint,
recommended,
+ options,
}: {
id: string;
label: string;
@@ -28,6 +36,7 @@ export function TuningField({
step?: number;
hint?: string;
recommended?: number;
+ options?: readonly number[];
}) {
const [draft, setDraft] = useState(value);
const focused = useRef(false);
@@ -77,28 +86,43 @@ export function TuningField({
</Tooltip>
)}
</div>
- <Input
- className="font-mono"
- id={id}
- max={max}
- min={min}
- onBlur={() => {
- focused.current = false;
- commit();
- }}
- onChange={(e) => setDraft(e.target.value)}
- onFocus={() => {
- focused.current = true;
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter") e.currentTarget.blur();
- }}
- placeholder={value === "" ? "auto" : undefined}
- size="sm"
- step={step}
- type="number"
- value={draft}
- />
+ {options ? (
+ <Select onValueChange={onCommit} value={value}>
+ <SelectTrigger className="w-full font-mono" id={id} size="sm">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((option) => (
+ <SelectItem key={option} value={String(option)}>
+ {option}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : (
+ <Input
+ className="font-mono"
+ id={id}
+ max={max}
+ min={min}
+ onBlur={() => {
+ focused.current = false;
+ commit();
+ }}
+ onChange={(e) => setDraft(e.target.value)}
+ onFocus={() => {
+ focused.current = true;
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") e.currentTarget.blur();
+ }}
+ placeholder={value === "" ? "auto" : undefined}
+ size="sm"
+ step={step}
+ type="number"
+ value={draft}
+ />
+ )}
</div>
);
}
diff --git a/modal_shared/serving/args.py b/modal_shared/serving/args.py
index 53baa3da..24454e3b 100644
--- a/modal_shared/serving/args.py
+++ b/modal_shared/serving/args.py
@@ -24,8 +24,24 @@ CUDAGRAPH_CAPTURE_SIZES: tuple[int, ...] = (1, 2, 4, 8, 16, 32)
# batching win.
MAX_LORA_SLOTS = 8
-# vLLM only accepts these values for --max-lora-rank; anything else is rejected at startup.
-_LORA_RANK_STEPS: tuple[int, ...] = (1, 8, 16, 32, 64, 128, 256, 320, 512)
+# vLLM rejects any other --max-lora-rank at startup. Rank 1 is a kernel size,
+# not a training choice.
+LORA_RANK_STEPS: tuple[int, ...] = (1, 8, 16, 32, 64, 128, 256, 320, 512)
+TRAINING_LORA_RANKS: tuple[int, ...] = (8, 16, 32, 64, 128, 256, 320, 512)
+
+
+def require_lora_rank(rank: object) -> int:
+ if type(rank) is not int or rank not in TRAINING_LORA_RANKS:
+ allowed = ", ".join(str(step) for step in TRAINING_LORA_RANKS)
+ raise ValueError(f"lora_r must be one of {allowed}.")
+ return rank
+
+
+def require_lora_alpha(rank: int, alpha: object) -> int:
+ expected = rank * 2
+ if type(alpha) is not int or alpha != expected:
+ raise ValueError(f"lora_alpha must be {expected}, twice lora_r.")
+ return alpha
def snap_lora_rank(rank: int) -> int:
@@ -35,10 +51,10 @@ def snap_lora_rank(rank: int) -> int:
measured 59% slower and 15.9x larger — so this rounds up to the next step, never to a
blanket maximum.
"""
- for step in _LORA_RANK_STEPS:
+ for step in LORA_RANK_STEPS:
if rank <= step:
return step
- return _LORA_RANK_STEPS[-1]
+ return LORA_RANK_STEPS[-1]
def lora_load_request(name: str, path: str) -> dict:
diff --git a/overbae/api/serializers.py b/overbae/api/serializers.py
index 2c978661..0880e9c4 100644
--- a/overbae/api/serializers.py
+++ b/overbae/api/serializers.py
@@ -12,6 +12,7 @@ from rest_framework.validators import UniqueTogetherValidator
from modal_shared.decision_checkpoint_policy import validate_policy
from modal_shared.decisions import DECISION_OBJECTIVES
+from modal_shared.serving.args import require_lora_alpha, require_lora_rank
from overbae.api.model_activation import ModelActivationSerializer
from overbae.api.native_evaluation import NativeEvaluationSerializer
from overbae.api.scoping import project_ids_for
@@ -1293,6 +1294,33 @@ class FinetuningJobSerializer(serializers.ModelSerializer):
)
if training_type.get("type", "Lora") not in ("Lora", "Full"):
raise serializers.ValidationError('training_type.type must be "Lora" or "Full".')
+ full = isinstance(training_type, dict) and training_type.get("type") == "Full"
+ if full:
+ rank = None
+ elif isinstance(training_type, dict) and "lora_r" in training_type:
+ rank = training_type["lora_r"]
+ elif "lora_r" in value:
+ rank = value["lora_r"]
+ else:
+ rank = None
+ if rank is not None:
+ try:
+ require_lora_rank(rank)
+ except ValueError as exc:
+ raise serializers.ValidationError(str(exc)) from exc
+ if isinstance(training_type, dict) and "lora_alpha" in training_type:
+ alpha = training_type["lora_alpha"]
+ elif "lora_alpha" in value:
+ alpha = value["lora_alpha"]
+ else:
+ alpha = None
+ if alpha is not None and not full:
+ if not isinstance(rank, int):
+ raise serializers.ValidationError("lora_alpha is twice lora_r.")
+ try:
+ require_lora_alpha(rank, alpha)
+ except ValueError as exc:
+ raise serializers.ValidationError(str(exc)) from exc
return value
def validate_eval_judge_model(self, value):
diff --git a/overbae/modal/modal_sft_worker.py b/overbae/modal/modal_sft_worker.py
index 29d01e3f..04f8e57d 100644
--- a/overbae/modal/modal_sft_worker.py
+++ b/overbae/modal/modal_sft_worker.py
@@ -30,7 +30,6 @@ import shutil
import subprocess
import sys
import tempfile
-import threading
import time
from collections import deque
from pathlib import Path
@@ -60,7 +59,6 @@ DATA_MOUNT = "/data"
WEIGHTS_MOUNT = "/weights"
RUNS_DIR = f"{DATA_MOUNT}/runs"
TRAIN_TIMEOUT_S = 24 * 60 * 60 # Modal's per-attempt ceiling
-_VOLUME_COMMIT_INTERVAL_S = 5.0
_ASSETS_REMOTE_DIR = "/root/sft_assets"
# modal_shared lives outside overbae on purpose: overbae/__init__.py imports
@@ -171,23 +169,10 @@ def _run_training(run_id: str, env: dict[str, str], *, gpu_type="H100", gpu_coun
child_env["HF_TOKEN"] = hf_token
child_env["HUGGING_FACE_HUB_TOKEN"] = hf_token
- # ProgressCallback writes to run_dir on every logged step but has no Modal
- # awareness, so commit the Volume on a timer instead of coupling the training
- # script to Modal internals.
- stop_commit = threading.Event()
-
- def _commit_loop() -> None:
- while not stop_commit.wait(_VOLUME_COMMIT_INTERVAL_S):
- try:
- record_heartbeat(run_dir)
- atomic_json(usage_path, [*previous_usage, meter.snapshot()])
- sft_vol.commit()
- except Exception as exc: # noqa: BLE001 — best-effort background commit
- print(f"[modal_sft_worker] volume commit skipped: {exc!r}")
-
- committer = threading.Thread(target=_commit_loop, daemon=True)
- committer.start()
-
+ # A timer commit stacks a layer per job every few seconds, and Modal then
+ # rejects new writers. Step files publish through Modal's background commit.
+ # The durable transcript stays local until a stage boundary.
+ local_log = work_dir / "train_stdout.log"
_write_meta(run_dir, status="running")
sft_vol.commit()
@@ -197,14 +182,11 @@ def _run_training(run_id: str, env: dict[str, str], *, gpu_type="H100", gpu_coun
# constants, pretok.py's sys.path/sys.modules swap, transformers'/unsloth's
# one-time patching) do not reset between calls — a second job inherits a
# corrupted `trl` import. One training process per job, no shared Python state.
- # stdout is tee'd to the Volume as well as the container: the live log stream
- # keeps only a short rolling window, and intermittent failures need a durable
- # per-run transcript (`modal volume get overmind-sft runs/<run_id>/train_stdout.log`).
log_path = run_dir / "train_stdout.log"
for verify in [False, True] if native else [False]:
phase_env = {**child_env, "DECISION_VERIFY_CHECKPOINT": "1" if verify else "0"}
with (
- open(log_path, "ab") as log_f,
+ open(local_log, "ab") as log_f,
subprocess.Popen( # noqa: S603
[sys.executable, f"{_ASSETS_REMOTE_DIR}/train.py"],
cwd=work_dir,
@@ -220,6 +202,8 @@ def _run_training(run_id: str, env: dict[str, str], *, gpu_type="H100", gpu_coun
log_f.write(line)
log_f.flush()
proc.wait()
+ if local_log.exists():
+ shutil.copy2(local_log, log_path)
sft_vol.commit()
if proc.returncode != 0:
raise RuntimeError(f"train.py exited with code {proc.returncode}")
@@ -229,13 +213,13 @@ def _run_training(run_id: str, env: dict[str, str], *, gpu_type="H100", gpu_coun
candidate_dir.rename(final_dir)
status = "succeeded"
except Exception:
- failure = failure_receipt(log_path)
+ if local_log.exists():
+ shutil.copy2(local_log, run_dir / "train_stdout.log")
+ failure = failure_receipt(run_dir / "train_stdout.log")
_write_meta(run_dir, status="failed", error=failure["message"], failure=failure)
sft_vol.commit()
raise
finally:
- stop_commit.set()
- committer.join(timeout=10)
atomic_json(usage_path, [*previous_usage, meter.snapshot()])
sft_vol.commit()
@@ -437,23 +421,14 @@ def upload_dataset(
for name, selection in selections.items()
]
- next_publication = 0.0
-
def report_progress(values):
- nonlocal next_publication
- publish = time.monotonic() >= next_publication
try:
atomic_json(run_dir / "transfer-progress.json", {"source_at": time.time(), **values})
- if publish:
- sft_vol.commit()
except Exception as exc:
# Telemetry delivery must not invalidate the selected training rows.
logging.getLogger(__name__).warning(
"Transfer telemetry unavailable (%s)", type(exc).__name__
)
- finally:
- if publish:
- next_publication = time.monotonic() + _VOLUME_COMMIT_INTERVAL_S
materialize_files(
preparation / "tokens.jsonl", artifact_sha256, files, progress=report_progress
diff --git a/overbae/services/deployment.py b/overbae/services/deployment.py
index 94ae4b45..b95a68fb 100644
--- a/overbae/services/deployment.py
+++ b/overbae/services/deployment.py
@@ -18,6 +18,7 @@ from modal.call_graph import InputStatus
from modal_shared.decision_artifact import verify_report
from modal_shared.decisions import DECISION_OBJECTIVES
+from modal_shared.serving.args import snap_lora_rank
from overbae.core.errors import InputValidationError
from overbae.modal.gpu_selector import gpu_vram_gb, select_gpu
from overbae.modal.model_registry import get_hf_base, get_model_config_any_backend
@@ -338,6 +339,74 @@ def retry_deployment(deployment_id) -> DeployedModel:
return deployed
+def _launch_archive(deployed: DeployedModel) -> None:
+ runtime = dict(deployed.serving_runtime or {})
+ if runtime.get("archive_call_id"):
+ return
+ job = deployed.finetuning_job
+ if not job or job.provider != "modal":
+ return
+ env = (
+ deployed.serving_runtime["environment"]
+ if deployed.inference_contract == "decision"
+ else modal_environment()
+ )
+ try:
+ call_id = _bounded(
+ modal.Function.from_name(
+ "overmind-register", "sync_modal_checkpoint_to_s3", environment_name=env
+ ).spawn.aio,
+ remote_id=job.remote_job_id,
+ user_id=str(job.triggered_by_id) if job.triggered_by_id else "",
+ job_id=str(job.id),
+ job_result=job.result if isinstance(job.result, dict) else {},
+ ).object_id
+ except Exception:
+ logger.exception("Checkpoint archive did not start for deployment %s", deployed.pk)
+ return
+ runtime["archive_call_id"] = call_id
+ DeployedModel.objects.filter(pk=deployed.pk).update(serving_runtime=runtime)
+ deployed.serving_runtime = runtime
+
+
+def start_serving_snapshot(job, *, base: dict, rank: int) -> None:
+ """Boot the shared-base pool while training runs.
+
+ The snapshot holds the base engine only. A pool that already matches this
+ base, GPU, context and rank is reused; a failure leaves the post-training
+ boot to capture it.
+ """
+ if not serves_as_adapter(job) or not isinstance(base, dict):
+ return
+ try:
+ from modal_shared.shared import base_pool_name
+ from modal_shared.stacks import worker_cls_name
+
+ length = int(job_serving_plan(job)["max_model_len"])
+ snapped = snap_lora_rank(int(rank or 16))
+ cfg = dict(get_model_config_any_backend(job.base_model) or {})
+ cfg["fp8_supported"] = False
+ gpu, _ = select_gpu(cfg, length)
+ rel = str(base.get("base_model_path") or "").removeprefix("/weights/").lstrip("/")
+ identity = str(base.get("base_identity") or "")
+ if not rel or not identity:
+ return
+ modal.Cls.from_name(
+ "overmind-inference",
+ worker_cls_name(gpu, "vllm", enable_lora=True),
+ environment_name=modal_environment(),
+ )(
+ model_path=rel,
+ model_name=base_pool_name(rel),
+ max_model_len=length,
+ enable_lora=True,
+ max_lora_rank=snapped,
+ base_identity=identity,
+ ).startup_info.spawn()
+ except Exception:
+ logger.exception("Serving snapshot did not start for job %s", job.pk)
+
+
def _remote_operation(deployed: DeployedModel):
env = (
deployed.serving_runtime["environment"]
@@ -718,11 +787,11 @@ def _complete_stage(deployed: DeployedModel, result) -> None:
values = {"deployment_call_id": "", "deployment_dispatching": False, "error_message": ""}
stage = deployed.deployment_stage
if stage == "base":
- values["deployment_stage"] = (
- "archive"
- if deployed.finetuning_job and deployed.finetuning_job.provider == "modal"
- else "weights"
- )
+ # The zip is the download and rebuild copy. Serving reads final/ on the
+ # training volume, so the archive runs beside the rest of the deploy.
+ if deployed.finetuning_job and deployed.finetuning_job.provider == "modal":
+ _launch_archive(deployed)
+ values["deployment_stage"] = "weights"
elif stage == "archive":
values["deployment_stage"] = "weights"
elif stage == "weights":
@@ -742,7 +811,7 @@ def _complete_stage(deployed: DeployedModel, result) -> None:
values.update(
weights_path="/weights/" + result["base_path"].removeprefix("/weights/"),
adapter_path="/weights/.adapters/" + deployed.model_id,
- lora_rank=int(result.get("lora_rank") or 16),
+ lora_rank=snap_lora_rank(int(result.get("lora_rank") or 16)),
is_lora=True,
quantization="bf16",
)
@@ -840,6 +909,8 @@ def advance_deployment(deployment_id) -> None:
logger.exception("Invalid result for deployment %s", deployed.pk)
state = "failed"
result = "Remote operation returned an invalid result."
+ else:
+ deployed.refresh_from_db()
if state == "failed":
message = f"{STAGE_LABELS[deployed.deployment_stage]} failed."
if isinstance(result, str):
@@ -868,7 +939,9 @@ def advance_deployment(deployment_id) -> None:
error_message=message,
deployment_next_poll_at=next_poll,
)
- return
+ return
+ if state != "complete" or deployed.status not in ACTIVE_STATUSES:
+ return
if deployed.deployment_dispatching:
_finish(
deployed,
diff --git a/overbae/services/finetuning_policy.py b/overbae/services/finetuning_policy.py
index 8acdfc28..3336cf6f 100644
--- a/overbae/services/finetuning_policy.py
+++ b/overbae/services/finetuning_policy.py
@@ -13,6 +13,7 @@ from typing import Any
from modal_shared.decisions import DECISION_OBJECTIVES
from modal_shared.modelfam import resolve
+from modal_shared.serving.args import require_lora_alpha, require_lora_rank
from overbae.core.errors import InputValidationError
from overbae.modal.model_registry import context_headroom, get_training_context_policy
from overbae.services.training_contract import baseline_evaluation_enabled, validate_effective_batch
@@ -509,8 +510,31 @@ def derive_baseten_training_plan(
)
qlora = qlora_lora_params(params_b or 7.0, num_train_examples)
- lora_r = int(training_type.get("lora_r") or hp.get("lora_r") or qlora["lora_r"])
- lora_alpha = int(training_type.get("lora_alpha") or hp.get("lora_alpha") or lora_r * 2)
+ if "lora_r" in training_type:
+ supplied_rank = training_type["lora_r"]
+ elif "lora_r" in hp:
+ supplied_rank = hp["lora_r"]
+ else:
+ supplied_rank = None
+ if use_lora and supplied_rank is not None:
+ try:
+ supplied_rank = require_lora_rank(supplied_rank)
+ except ValueError as exc:
+ raise TrainingPlanError(str(exc)) from exc
+ lora_r = int(supplied_rank or qlora["lora_r"])
+ if "lora_alpha" in training_type:
+ supplied_alpha = training_type["lora_alpha"]
+ elif "lora_alpha" in hp:
+ supplied_alpha = hp["lora_alpha"]
+ else:
+ supplied_alpha = None
+ if use_lora and supplied_alpha is not None:
+ try:
+ lora_alpha = require_lora_alpha(lora_r, supplied_alpha)
+ except ValueError as exc:
+ raise TrainingPlanError(str(exc)) from exc
+ else:
+ lora_alpha = lora_r * 2
if "lora_dropout" in training_type:
lora_dropout = float(training_type["lora_dropout"])
elif "lora_dropout" in hp:
diff --git a/overbae/services/finetuning_runner.py b/overbae/services/finetuning_runner.py
index 0f48b052..a056f082 100644
--- a/overbae/services/finetuning_runner.py
+++ b/overbae/services/finetuning_runner.py
@@ -1698,11 +1698,11 @@ class ModalRunner(BaseFinetuningRunner):
raise ValueError("Training observer requires a pinned worker environment.")
return self.release["environment"]
- def _await_base_model(self, hf_base: str) -> None:
+ def _await_base_model(self, hf_base: str) -> dict:
"""Block until ``.base_models/`` has this repo. Concurrent jobs share the mutex."""
import modal # noqa: PLC0415
- modal.Function.from_name(
+ return modal.Function.from_name(
"overmind-register", "fetch_base_model", environment_name=self._modal_env()
).remote(base_model=hf_base)
@@ -1828,6 +1828,8 @@ class ModalRunner(BaseFinetuningRunner):
env["LOAD_IN_4BIT"] = "1"
if is_gpt_oss:
env["UNSLOTH_COMPILE_DISABLE"] = "1"
+ if family_key(str(model_id)) in {"qwen35", "qwen38"}:
+ env["UNSLOTH_BLOCK_COMPILE"] = "0"
if max_steps > 0:
# Probe-run cap only: the wizard and recommender never set max_steps.
env["MAX_STEPS"] = str(max_steps)
@@ -1989,7 +1991,13 @@ class ModalRunner(BaseFinetuningRunner):
"preparing_base_model",
"Checking base model weights and downloading missing files",
)
- self._await_base_model(env["MODEL_ID"])
+ base = self._await_base_model(env["MODEL_ID"])
+ if training_kind == "lora":
+ from overbae.services.deployment import start_serving_snapshot # noqa: PLC0415
+
+ start_serving_snapshot(
+ job, base=base if isinstance(base, dict) else {}, rank=int(env.get("LORA_R") or 16)
+ )
training_submission.record_pre_dispatch_stage(
job, "starting_training_worker", "Base model weights ready; starting training worker"
)
diff --git a/overbae/services/mcp/contracts/finetuning.py b/overbae/services/mcp/contracts/finetuning.py
index 91164fd9..23052fbf 100644
--- a/overbae/services/mcp/contracts/finetuning.py
+++ b/overbae/services/mcp/contracts/finetuning.py
@@ -153,7 +153,7 @@ class CheckFinetuneReadinessOutput(MCPModel):
class EstimateFinetuneInput(FinetuneSelectionInput):
hyperparameters: dict[str, Any] = Field(
default_factory=dict,
- description="Model recipe. batch_size is the effective optimizer batch; do not supply gradient_accumulation_steps or per_device_train_batch_size.",
+ description="Model recipe. batch_size is the effective optimizer batch; do not supply gradient_accumulation_steps or per_device_train_batch_size. lora_r must be 8, 16, 32, 64, 128, 256, 320, or 512. lora_alpha is twice lora_r.",
)
dataset: str = Field(min_length=1, max_length=255)
base_model: str = Field(min_length=1, max_length=255)
@@ -258,7 +258,7 @@ class StartFinetuneInput(MCPModel):
use_case: str = Field(default="", max_length=10_000)
hyperparameters: dict[str, Any] | None = Field(
default=None,
- description="Model recipe. batch_size is the effective optimizer batch; do not supply gradient_accumulation_steps or per_device_train_batch_size. Native decisions accept pre_training_baseline (boolean, default true); false skips only the initial development evaluation.",
+ description="Model recipe. batch_size is the effective optimizer batch; do not supply gradient_accumulation_steps or per_device_train_batch_size. lora_r must be 8, 16, 32, 64, 128, 256, 320, or 512. lora_alpha is twice lora_r. Native decisions accept pre_training_baseline (boolean, default true); false skips only the initial development evaluation.",
)
group_id: UUID | None = None
diff --git a/overbae/services/mcp/contracts/model_workflows.py b/overbae/services/mcp/contracts/model_workflows.py
index 8a9b6a61..97749509 100644
--- a/overbae/services/mcp/contracts/model_workflows.py
+++ b/overbae/services/mcp/contracts/model_workflows.py
@@ -112,7 +112,7 @@ class CandidateInput(MCPModel):
cell: UUID
development_cell: UUID | None = None
hyperparameters: dict[str, Any] = Field(
- description='Model recipe; for LoRA use training_type={"type":"Lora"}. Common fields include n_epochs, learning_rate, lora_r and seed. Native pre_training_baseline=false skips only the initial development evaluation; defaults true.'
+ description='Model recipe; for LoRA use training_type={"type":"Lora"}. Common fields include n_epochs, learning_rate, lora_r and seed. lora_r must be 8, 16, 32, 64, 128, 256, 320, or 512. lora_alpha is twice lora_r. Native pre_training_baseline=false skips only the initial development evaluation; defaults true.'
)
diff --git a/overbae/services/mcp/prompts.py b/overbae/services/mcp/prompts.py
index 9fa38be1..d38210b0 100644
--- a/overbae/services/mcp/prompts.py
+++ b/overbae/services/mcp/prompts.py
@@ -146,7 +146,7 @@ PROMPTS = (
"coverage, overlap and identity evidence through get_job(kind=native_evaluation). "
"Use create_training_experiment to save purpose, explicit variants (base_model, cell, optional "
"development_cell, hyperparameters) and optional evaluation protocol. Hyperparameters use n_epochs, "
- 'learning_rate, lora_r and seed; LoRA uses training_type={{"type":"Lora"}}. checkpoint_policy has fractions ending at 1 and selection last '
+ 'learning_rate, lora_r and seed; lora_r must be 8, 16, 32, 64, 128, 256, 320, or 512. lora_alpha is twice lora_r. LoRA uses training_type={{"type":"Lora"}}. checkpoint_policy has fractions ending at 1 and selection last '
"or development_loss; final scores never select checkpoints. Inspect requested/effective settings "
"and authorization after prepare_training_experiment returns a configuration-bound forecast. Pass its quote_id to launch_training_experiment where saved constraints require it. Novel recipes can use create_training_profile for explicitly authorized bounded measurement. Reuse completed compatible predictions only through reuse_evaluation_predictions or an explicit experiment reuse_existing_predictions choice. Poll existing jobs without duplicate starts. "
"Transient evaluation interruptions recover automatically; poll get_job while running. Use resume_native_evaluation only for stopped work. Saved call IDs and completed responses are reused; missing external predictions have bounded retries with uncertain prior costs retained. "
diff --git a/overbae/services/sft_assets/families/qwen35.py b/overbae/services/sft_assets/families/qwen35.py
index 5bb5f66a..9548266e 100644
--- a/overbae/services/sft_assets/families/qwen35.py
+++ b/overbae/services/sft_assets/families/qwen35.py
@@ -23,8 +23,9 @@ def _seq_len_from_mask_kwargs(*args: Any, **kwargs: Any) -> int | None:
class Qwen35Hooks(DefaultHooks):
def env_overrides(self, *, use_lora: bool) -> dict[str, str]:
- # Unsloth flex patch falls through to eager_attention_forward on this family.
- return {"UNSLOTH_ENABLE_FLEX_ATTENTION": "0"}
+ # Flex falls through to eager attention. Block compile then reads
+ # __closure__ on a string and fails once per Qwen3_5DecoderLayer.
+ return {"UNSLOTH_ENABLE_FLEX_ATTENTION": "0", "UNSLOTH_BLOCK_COMPILE": "0"}
def load_kwargs(self, *, use_lora: bool) -> dict[str, Any]:
# Image has no FA2. SDPA + is_causal still uses Hopper flash; Unsloth's
diff --git a/overbae/services/training_transfer.py b/overbae/services/training_transfer.py
index db2f3701..5c2c74a3 100644
--- a/overbae/services/training_transfer.py
+++ b/overbae/services/training_transfer.py
@@ -10,6 +10,9 @@ from modal.exception import InternalError, NotFoundError, ServiceError
from modal_shared.training_data import write_selection
from overbae.services import training_monitoring, training_release, training_submission
+# Modal's published v1 guidance: a handful of concurrent small commits.
+_VOLUME_WRITERS = 5
+
STAGES = {
"building_selections": "Building row selections",
"uploading_selections": "Uploading row selections",
@@ -51,40 +54,47 @@ def stage_data(job, paths, run_id, preparation, volume, upload_fn, *, num_exampl
if num_examples is not None and selections["data"]["rows"] != num_examples:
raise ValueError("The training selection does not match the selected row count.")
total_bytes = sum(spec["rows"] * 32 for spec in selections.values())
- for name in paths:
+ # Lazy: task_lock imports the Celery app, which imports this module.
+ from overbae.tasks.utils.task_lock import hold_one_slot
+
+ # One commit for every selection file, and at most five launches at once.
+ # A commit per file across a sweep stacks volume layers until Modal refuses.
+ with hold_one_slot("sft-volume", _VOLUME_WRITERS, timeout=3600):
+ with volume.batch_upload() as batch:
+ for name in paths:
+ report(
+ {
+ "stage": "uploading_selections",
+ "completed": details["acknowledged_bytes"],
+ "total": total_bytes,
+ "unit": "bytes",
+ "measurement": "provider_acknowledged_files",
+ }
+ )
+ # put_file only queues bytes; successful context exit acknowledges the file.
+ batch.put_file(
+ Path(directory) / f"{name}.keys", f"/runs/{run_id}/selected-{name}.keys"
+ )
+ for name in paths:
+ details["files_completed"] += 1
+ details["acknowledged_bytes"] += selections[name]["rows"] * 32
report(
{
"stage": "uploading_selections",
- "completed": details["acknowledged_bytes"],
+ "completed": total_bytes,
"total": total_bytes,
"unit": "bytes",
"measurement": "provider_acknowledged_files",
}
)
- # put_file only queues bytes; successful context exit acknowledges the file.
- with volume.batch_upload() as batch:
- batch.put_file(
- Path(directory) / f"{name}.keys", f"/runs/{run_id}/selected-{name}.keys"
- )
- details["files_completed"] += 1
- details["acknowledged_bytes"] += selections[name]["rows"] * 32
- report(
- {
- "stage": "uploading_selections",
- "completed": total_bytes,
- "total": total_bytes,
- "unit": "bytes",
- "measurement": "provider_acknowledged_files",
- }
- )
- report({"stage": "waiting_for_materialization"})
- result = upload_fn.remote(
- run_id=run_id,
- preparation_id=str(preparation.id),
- artifact_sha256=preparation.report["artifact_sha256"],
- selections=selections,
- monitoring=(job.hyperparameters or {}).get("monitoring"),
- )
+ report({"stage": "waiting_for_materialization"})
+ result = upload_fn.remote(
+ run_id=run_id,
+ preparation_id=str(preparation.id),
+ artifact_sha256=preparation.report["artifact_sha256"],
+ selections=selections,
+ monitoring=(job.hyperparameters or {}).get("monitoring"),
+ )
if isinstance(result, dict) and result.get("monitoring_plan"):
training_monitoring.save_plan(job, result["monitoring_plan"])
diff --git a/overbae/tasks/utils/task_lock.py b/overbae/tasks/utils/task_lock.py
index eb7648c2..3112cd76 100644
--- a/overbae/tasks/utils/task_lock.py
+++ b/overbae/tasks/utils/task_lock.py
@@ -1,5 +1,6 @@
import logging
import threading
+import time
from collections.abc import Callable
from contextlib import contextmanager
from functools import wraps
@@ -38,6 +39,48 @@ def _renew(lock, timeout: int, stop: threading.Event) -> None:
logger.warning("Could not renew lock %s", lock.name, exc_info=True)
+@contextmanager
+def hold_one_slot(lock_name: str, slots: int, *, timeout: int):
+ """Hold one of ``slots`` locks until the block exits.
+
+ Modal's v1 volume rejects small commits once more than a handful of writers
+ commit at once, so training uploads share five slots.
+ """
+ if slots < 1:
+ raise ValueError("slots must be positive")
+ if not _is_redis_broker(_broker_url()):
+ yield
+ return
+ client = _get_redis_client()
+ while True:
+ for slot in range(slots):
+ lock = client.lock(
+ f"celery:lock:{lock_name}:{slot}",
+ timeout=timeout,
+ blocking_timeout=0,
+ thread_local=False,
+ )
+ if not lock.acquire(blocking=False):
+ continue
+ stop = threading.Event()
+ threading.Thread(
+ target=_renew,
+ args=(lock, timeout, stop),
+ name=f"lock {lock_name}:{slot}",
+ daemon=True,
+ ).start()
+ try:
+ yield
+ finally:
+ stop.set()
+ try:
+ lock.release()
+ except LockNotOwnedError:
+ logger.error("Lock %s:%s lapsed while its holder still runs", lock_name, slot)
+ return
+ time.sleep(0.5)
+
+
@contextmanager
def acquire_task_lock(lock_name: str, *, timeout: int, blocking: bool = False, renew: bool = False):
"""Redis lock that a holder killed mid-task keeps for ``timeout`` seconds.
diff --git a/tests/test_finetuning_baseten_plan.py b/tests/test_finetuning_baseten_plan.py
index ca436106..607406f3 100644
--- a/tests/test_finetuning_baseten_plan.py
+++ b/tests/test_finetuning_baseten_plan.py
@@ -2,7 +2,9 @@ from __future__ import annotations
import pytest
from django.test import override_settings
+from rest_framework.exceptions import ValidationError
+from overbae.api.serializers import FinetuningJobSerializer
from overbae.services.finetuning_policy import (
TrainingPlanError,
default_epochs,
@@ -80,6 +82,7 @@ class TestExplicitValuesWin:
assert plan.token_budget == 32768
env = ModalRunner._training_env(plan, "Qwen/Qwen3.5-4B")
assert env["PADDED_TOKEN_BUDGET"] == "32768"
+ assert env["UNSLOTH_BLOCK_COMPILE"] == "0"
@pytest.mark.parametrize("enabled", [True, False])
def test_native_baseline_choice_reaches_worker_environment(self, enabled):
@@ -122,6 +125,28 @@ class TestExplicitValuesWin:
assert (plan.lora_r, plan.lora_alpha, plan.lora_dropout) == (8, 16, 0.0)
assert plan.lora_target_modules == "q_proj,v_proj"
+ def test_lora_rank_must_be_a_serving_step(self):
+ with pytest.raises(TrainingPlanError, match="lora_r must be one of"):
+ _plan(hyperparameters={"training_type": {"type": "Lora", "lora_r": 4}})
+ high = _plan(hyperparameters={"training_type": {"type": "Lora", "lora_r": 512}})
+ assert high.lora_r == 512
+ assert high.lora_alpha == 1024
+ with pytest.raises(TrainingPlanError, match="twice lora_r"):
+ _plan(hyperparameters={"training_type": {"type": "Lora", "lora_r": 8, "lora_alpha": 8}})
+ full = _plan(hyperparameters={"training_type": {"type": "Full", "lora_r": 4}})
+ assert full.lora_r == 4
+ serializer = FinetuningJobSerializer()
+ with pytest.raises(ValidationError, match="twice lora_r"):
+ serializer.validate_hyperparameters(
+ {"training_type": {"type": "Lora", "lora_r": 16, "lora_alpha": 16}}
+ )
+ with pytest.raises(ValidationError, match="lora_r must be one of"):
+ serializer.validate_hyperparameters({"training_type": {"type": "Lora", "lora_r": 12}})
+ accepted = serializer.validate_hyperparameters(
+ {"training_type": {"type": "Lora", "lora_r": 32}}
+ )
+ assert accepted["training_type"]["lora_r"] == 32
+
@override_settings(FINETUNING_BACKEND="baseten")
def test_recommender_output_is_reproduced_exactly(self):
entry = {
diff --git a/tests/test_model_deployment_resume.py b/tests/test_model_deployment_resume.py
index 51ccdb48..35b597ba 100644
--- a/tests/test_model_deployment_resume.py
+++ b/tests/test_model_deployment_resume.py
@@ -193,16 +193,17 @@ def test_deadline_stops_remote_operation_without_losing_weights(deployed, fake_m
def test_complete_adapter_pipeline_persists_every_stage(deployed, fake_modal):
- stages = ["base", "archive", "weights", "register", "warm"]
with patch("overbae.services.finetuning_eval.tick_job_evals") as tick:
- for stage in stages:
- assert deployed.deployment_stage == stage
- advance(deployed)
- assert fake_modal.calls[deployed.deployment_call_id].state == "done"
+ seen = []
+ for _ in range(8):
+ if deployed.status == "ready":
+ break
+ seen.append(deployed.deployment_stage)
advance(deployed)
assert deployed.status == "ready"
advance(deployed)
+ assert seen == ["base", "base", "weights", "register", "warm"]
assert fake_modal.spawns() == [
"fetch_base_model",
"sync_modal_checkpoint_to_s3",
@@ -255,11 +256,13 @@ def test_decision_checkpoint_deploys_and_verifies_without_chat_registration(
fake_modal.deploy(
runtime, "pre_warm", lambda **_: {"verified": True, "artifact_identity": "a" * 64}
)
- for stage in ["base", "archive", "weights", "warm"]:
- assert row.deployment_stage == stage
- advance(row)
- assert row.status != "ready"
+ seen = []
+ for _ in range(8):
+ if row.status == "ready":
+ break
+ seen.append(row.deployment_stage)
advance(row)
+ assert seen == ["base", "base", "weights", "warm"]
assert row.status == "ready"
assert row.quantization == "bf16"
assert row.gpu_type == "H100"
diff --git a/tests/test_sft_qwen35_hooks.py b/tests/test_sft_qwen35_hooks.py
index ed88ec5c..46156b16 100644
--- a/tests/test_sft_qwen35_hooks.py
+++ b/tests/test_sft_qwen35_hooks.py
@@ -10,7 +10,10 @@ from families.qwen35 import _seq_len_from_mask_kwargs, hooks
def test_qwen35_sdpa_and_flex_off():
- assert hooks.env_overrides(use_lora=True)["UNSLOTH_ENABLE_FLEX_ATTENTION"] == "0"
+ overrides = hooks.env_overrides(use_lora=True)
+ assert overrides["UNSLOTH_ENABLE_FLEX_ATTENTION"] == "0"
+ assert overrides["UNSLOTH_BLOCK_COMPILE"] == "0"
+ assert hooks.env_overrides(use_lora=False)["UNSLOTH_BLOCK_COMPILE"] == "0"
assert hooks.load_kwargs(use_lora=True)["attn_implementation"] == "sdpa"