Repository navigation
v0.2.0-alpha.10
Pre-releaseTrainers: an interactive training loop on grad's GPUs (docs/TRAINER_API.md). Migrations 0014_trainers.sql,
0016_trainer_lanes.sql, 0017_eval_env_and_gates.sql, 0019_trainer_ops_order_index.sql,
0020_checkpoint_ttl_and_metadata.sql, 0021_trainer_mode_and_sampled_usage.sql, and
0022_stream_media_hotswap.sql (expand-only). Before upgrading, note:
-
Breaking (API):
Checkpoint.run_idis nullable (a trainer's checkpoints havetrainer_id), and
ArtifactProvenancehastrainer_idand thesourcevaluetrainer. -
Breaking (API, SDKs, CLI, Web UI): released artifacts are now strictly immutable — removed
artifact deletion (DELETE /v1/artifacts/{id},artifacts.delete,grad artifacts delete, UI
Delete button) and artifact pinning (POST/DELETE /v1/artifacts/{id}/pins,
PUT/DELETE /internal/v1/workspaces/{ws}/artifacts/{id}/pins/{holder},Artifact.pins,
ArtifactPin), as well as the internal workspace-state push endpoints
(GET/PUT /internal/v1/workspaces/{ws}/state).GET /internal/v1/workspaces/{ws}/artifacts/{id}
continues to work and accepts bothartifacts:readand legacyartifacts:pinJWT scopes for
zero-downtime rolling upgrades; Postgres tables remain expand-only (no destructiveDROP TABLE),
and checkpoint expiration (ttl_s,PATCH /v1/checkpoints/{id},410 checkpoint_expired) is
unchanged. -
Upgrade grad-server before trainer workers: a worker of this release claims
trainerjobs by default
(GRAD_WORKER_KINDSnow defaults totrain,import,trainer; the Helm GPU pool'skindsare
[train, trainer]), and an older server refuses that kind in a claim. -
Trainers (
POST /v1/trainers,client.trainers.create(...)in all four SDKs,grad trainers list|show|close,
and a Trainers page in the console): a LoRA on one GPU worker that a client drives withforward_backward
(cross_entropyorlinear; Python'slosses.CustomLosscomputes any loss of the log-probs in local torch
and sends its gradient as alinearloss, withgrad-sdk[torch]),forward(current, base or starting
weights),optim_step(AdamW),sample,save_state,export(apeft_loraartifact) andrender. Every
op returns a future and carries a client-assignedseq, so retries are idempotent and ops run in order.
Per-token arrays are binary on the wire, and large requests and results live in storage, not in Postgres.
An idle trainer parks (state saved, GPU released, nothing billed) and resumes on the next op; a drain parks
it without losing the running op; a lost worker fails it loudly with the checkpoint to resume from.
max_cost_usdis a hard cap checked before every op, and usage flows through the Cloud usage export as
kind: trainer. -
Trainer futures compose with async code. Python:
await futwaits without blocking the event loop, and
fut.future()is the op as aconcurrent.futures.Future(as_completed,asyncio.wrap_future); one
background long-poll per trainer serves every awaited op. TypeScript: anOpFutureis aPromiseLike, so
await futandPromise.all([a, b])work without.result(). -
Multimodal Vision & Audio support across SFT, Trainer API, Evals, all 4 SDKs, and CLI:
- Added
modalities(["text"],["text", "image"],["text", "image", "audio"]) toTrainableModel,Trainer,JudgeModel, and catalog models (qwen/qwen3.5-*,qwen/qwen3.8-27b,qwen/qwen3.6-35b-a3b,google/gemma-4-{12b,26b-a4b,31b}-it→ vision;google/gemma-4-{e2b,e4b}-it→ vision + audio), surfaced ingrad models list. - Added strict API validation for OpenAI
image_url(inline PNG/JPEG/WebP base64 data URIs ≤ 5 MiB; zero SSRF: rejectshttp(s):///file://with422 invalid_media_uri) andinput_audio(RIFF/WAVE ≤ 10 MiB, rejected if non-WAV with422 invalid_media), role gating (422 invalid_media_role), modality gating (422 unsupported_modalityacross SFT, non-SFT recipes, Trainer ops, and Evals), bounded per-datum/per-op limits (≤ 8images,≤ 4audio clips,≤ 20 MiBdecoded media/op,32 MiBtrainer body limit), media-aware token bounding (4096/image,1024/audio), and eval scoring base64 stripping with multimodal judge passthrough. - Added pure-PIL (
pillow==13.0.0, zerotorchvision) + pure-Python RIFF/WAVE & NumPy FFT 16 kHz resampler multimodal pipeline ingrad_trainer(multimodal.py,templates.py,engine.py,session.py,recipes/sft.py,sampler.py,_vllm_worker.py) supportingQwen3_5ForConditionalGeneration/Qwen3_5MoeForConditionalGenerationandGemma4ForConditionalGenerationwith zero regression on text-only varlen fast paths,/dev/shmsha256-deduped vLLM media IPC withauto-mode fallback toHFSampler, and processor saving on merged exports. - Added zero-extra-dependency multimodal helpers (
image_part/audio_part/MediaItem/extract_media, plusImage/Audioin Python and*FromFilein TS/Go/Rust) and client-sideSampledPrompt.media/TokenSegment.mediapropagation (Datum.from_sample,Datum.from_trajectory,SnapshotProxy) across Python, TypeScript, Go, and Rust SDKs.
- Added
-
RL losses on trainers:
importance_sampling,ppo(clip_low,clip_high; recommended default for async/stale rollouts),cispo(clip_low,clip_high), anddro(beta, strictly masked byweights) read the datum fieldssampling_logprobsandadvantageswithweightsas the mask, and reportkl_sample_train,kl_sample_train_v2,sample_train_max_diff,ratio_mean,ratio_max, and (ppo/cispo)clip_fraction.forwardandforward_backwardtaketemperature(the soft-capped logits divided by it, as the sampler does). -
Calibrated
lr="auto"onoptim_step(all 4 SDKs):optim.AdamW(lr="auto", objective="sft"|"rl"|"dpo")resolves the model's calibrated LR server-side fromcatalog.ts(including calibratedrlLRs across trainable Qwen3/3.5/3.6/3.8 and Gemma 4 models), exposesTrainer.calibrated_lrs, returns the applied numericlronOptimStepResult, and refuses uncalibrated models/objectives with422 uncalibrated_model. -
top_k,top_logprobs, andprompt_logprobsonsample(bothHFSamplerand colocatedVLLMSampler, all 4 SDKs):sampleacceptstop_k(1..1000),top_logprobs(0..20, returning per-token[{token_id, logprob}]sorted descending from the processed sampling distribution), andprompt_logprobs(bool, returning per-prompt-tokenfloat32log-probs with index 0 =0.0matchingforward()). -
Checkpoint TTLs,
save_state(metadata=...), and410 checkpoint_expired(migration0020, all 4 SDKs, CLI, Web UI):POST /v1/trainersacceptscheckpoint_ttl_s(300..7776000s) for automaticautosave/parkcheckpoints;save_stateaccepts optionalttl_s(300..7776000, omitted/null = permanent) andmetadata(JSON object ≤ 16 KiB serialized UTF-8) returned onSaveStateResult.checkpoint.{expires_at, metadata}; finalclosecheckpoints stay permanent; maintenance sweeps expired trainer checkpoint S3 blobs outside DB locks while keeping tombstone rows so resuming returns410 checkpoint_expired. -
Expanded built-in verified HF benchmarks (4 → 13) +
math_equivalenceandifevalvalidators (all 4 SDKs, CLI): added pinned, public benchmarksarc_easy,hellaswag,winogrande,truthfulqa_mc1,boolq,openbookqa,commonsense_qa,math500(HuggingFaceH4/MATH-500, 500 rows, scored withmath_equivalencesupporting nested\boxed{...}, fractions, radicals,\pi/trig, intervals/tuples/sets, symbolic probing, and numeric tolerance), andifeval(google/IFEval, 541 rows, deterministic verifier for all 25 Google IFEval instruction IDs returning exactsatisfied / totalfraction). -
StableReinforceRL loss + per-stepentropyandclip_fractiondiagnostics (all 4 SDKs): addedstable_reinforce(clip_low=0.2,clip_high=0.28,kl_coef=0.0with non-negative k3 KL penalty; Pythongrad.StableReinforce/losses.StableReinforce, TSlosses.stableReinforce, Gograd.StableReinforce, RustLoss::StableReinforce) and surfaced Monte-Carloentropy(-mean(sampling_logprobs)) across all RL losses plusclip_fractionon clipped RL losses. -
32K Trainer context, Qwen3.5 vLLM default, true token-by-token
samplestreaming, content-addressed media uploads, and warm checkpoint/artifact hot-swap (migration0022, all 4 SDKs):- Raised
TRAINER_MAX_SEQ_LENfrom8192→32768(min(model.max_context_tokens, 32768)), enabled"Qwen3_5ForConditionalGeneration"inDEFAULT_VLLM_ALLOW_ARCHS, and capped colocatedVLLMSamplermax_model_lensafely tomin(model_max_pos, 32768)(respectingGRAD_VLLM_MAX_MODEL_LEN). - Added token-by-token SSE streaming on
sample(stream: true,GET /v1/trainers/{id}/ops/{op_id}/stream, workerPOST /v1/trainer-jobs/{id}/ops/{op_id}/chunks, backed by Valkey/Redis Streams via optionalREDIS_URLwithXADD MAXLEN ~ 2000, 5 min TTL, andXREAD BLOCK, falling back to a bounded in-memoryOpStreamBuswhenREDIS_URLis unset — zero Postgres chunk writes, never coalesced on the sample lane). Addedvalkey/valkey:8-alpineto Docker Compose and optionalredis.url/redis.existingSecret/networkPolicy.redisEgressto the Helm chart. Addedsample_stream/sampleStream/SampleStreamacross Python, TypeScript, Go, and Rust SDKs, and upgradedSnapshotProxy(OpenAI/v1/chat/completionsand Anthropic/v1/messages) to stream live token deltas while preserving exactTrajectoryandsampling_logprobscapture. - Added content-addressed, workspace-isolated media uploads (
POST /v1/mediaaccepting JSON or rawimage/png,image/jpeg,image/webp,audio/wav,GET /v1/media/{id}) deduplicated by(workspace_id, sha256)ingrad_media+ S3, usable viagrad://media/med_...,input_audio.media_id, orMediaItem.media_idwith a bounded worker LRUMediaCacheandclient.media.upload/gethelpers across all 4 SDKs. - Added instant checkpoint/artifact hot-swap on warm
mode: "sample"sessions viaweights: "checkpoint:<id>" | "artifact:<id>" | "base" | "initial"onsample, validated for workspace ownership (404), expiration (410 checkpoint_expired), base-model compatibility (422 incompatible_base_model), and sample-only mode (422 invalid_weights), backed by a bounded worker LRU_AdapterCache(vLLM externalLoRARequest+ HF PEFT/base swap). - Upgraded the Web Console
/playground(server/ui) with live token-by-token SSE streaming (stream: true+GET /v1/trainers/{id}/ops/{op_id}/streamwithAuthorizationheaders, live<think>folding, Stop/Cancel abort, and polling fallback), single-GPU warm checkpoint/artifact/base hot-swap (including shared single-GPU Compare A/B when targets sharebase_model), content-addressedPOST /v1/mediaattachment uploads (grad://media/<id>/media_idreuse across turns), and updated Phase 11 "Copy as Python" (sample_stream,weights,grad.Image.upload/grad.Audio.upload).
- Raised
-
Opt-in LoRA Multimodal Projector Adaptation & Multimodal DPO / Off-Policy Distill / Reward Recipes (all 4 SDKs, CLI):
- Added optional
adapter.train_multimodal_projector(defaultfalse) on LoRA runs and trainers (grad.Lora(..., train_multimodal_projector=True), TSadapters.lora({ trainMultimodalProjector: true }), GoLoRA{TrainMultimodalProjector: true}, RustAdapterSpec/TrainerOptions.train_multimodal_projector). Rejected synchronously with422 unsupported_modalityon text-only models; when enabled on multimodal models, targets only the vision/audio-to-language projector/merger linear layers (visual.merger.*on Qwen3.5/3.6/3.8,embed_vision.*/embed_audio.*on Gemma 4) alongside language decoder layers while keeping heavy vision/audio encoder backbones frozen, persists cleanly inadapter_config.jsonand trainerengine.json, and keepsGRAD_SAMPLER=autosafe by falling back toHFSampler(rejecting explicitGRAD_SAMPLER=vllmwithRecipeConfigError). - Enabled multimodal (
imageandaudio) datasets acrossDPORecipe(preference pairs preserving exact paddedsdpa+position_ids=Nonepolicy & disabled-adapter reference log-probs), off-policyDistillRecipe, andRewardRecipe(pairwise & pointwise multimodal scoring with left-truncation media-token protection), plus calibrateddistill/rewardLRs on all trainable multimodal catalog models. On-policydistill, incompatible recipes (embedding,classifier,router,cartridge,decision), and text-only models continue to reject multimodal datasets with422 unsupported_modality, and immutable dataset records/evals consistently reject Trainer-API-scopedgrad://media/med_.../input_audio.media_idreferences synchronously with422 invalid_media_uri.
- Added optional
-
Decoupled
SamplingClient(mode: "sample"on Trainers, migration0021, all 4 SDKs):POST /v1/trainersacceptsmode: "train" | "sample"(default"train"), allowing eval-only catalog LLMs (e.g.qwen/qwen3-32b) in sample mode, rejecting training/mutation ops (forward_backward,optim_step,save_state,export) with422 sample_only_trainer, skipping optimizer/gradient buffers and parking without a checkpoint while giving colocatedVLLMSamplerhigher VRAM headroom (up to0.75vs0.45). Addedclient.open_sampler(...)/SamplingClientacross Python, TypeScript, Go, and Rust. -
Mutable checkpoint TTL & metadata (
PATCH /v1/checkpoints/{id}, all 4 SDKs, CLI): updates an active checkpoint'sttl_s(300..7776000s from now, ornullfor permanent) and/or replacement usermetadatawhile preserving internal manifest keys; returns404 checkpoint_not_foundor410 checkpoint_expired. Exposed viacheckpoints.update(...)in all 4 SDKs andgrad checkpoints update <id> [--ttl-s <secs> | --permanent] [--metadata <json>]. -
console_urldeep-links & sampled-token usage accounting (migration0021, all 4 SDKs, CLI, Web UI): optionalGRAD_CONSOLE_URLaddsconsole_urlonTrainer,Run,EvalRun, andCheckpoint(/trainers/{id},/runs/{id},/evals/{id},/artifacts?checkpoint={id}), displayed in CLI detail views and copyable in the Web Console. Sample ops reportprompt_tokensandsampled_tokensonTrainerOp.usage,Trainer.usage,GET /v1/usage, andGET /v1/usage/summary(sampled_tokensbreakdown alongsidetokens). -
Interactive Checkpoint Chat Playground, Checkpoint TTL/Metadata Editor & Phase 9 Web Console (
server/ui): added/playgroundfor chatting with unexpired checkpoints, promotedpeft_loraartifacts, or catalog LLMs (including eval-only models) viamode: "sample"trainer sessions with side-by-side A/B compare, optional image (PNG/JPEG/WebP ≤ 5 MiB) and WAV audio (≤ 10 MiB) attachments, collapsible<think>blocks, and an interactive per-token logprob & top-5 alternative inspector. Added inlinePATCH /v1/checkpoints/{id}TTL/metadata editing (presets, custom seconds, permanentttl_s: null, 16 KiB JSON validation,410 checkpoint_expiredhandling),?checkpoint=<id>highlighting on/artifacts, "Chat in Playground" deep-links,mode/entropy/clip_fraction/sampled_tokensdisplays across Trainers and Usage, andMATH-500/IFEvalbenchmark & validator badges across Evals and Datasets. -
CLI diagnostics, credential hygiene & DevEx (
grad doctor,grad completions,grad local up): addedgrad doctor [--json](checks config/credentials0600permissions,/health/readylatency &/v1/modelsauth + multimodal count, Docker/Compose & local stack status, disk//dev/shm/GPU hardware, and Python SDK version parity), addedgrad completionsas an alias forgrad completion, tightened config directory permissions to0700on save with permissive-file warnings ingrad config showandgrad doctor, redactedapi_keyin CLIGlobalDebugoutput, added actionable CLI error hints for connection failures,401,410 checkpoint_expired,422 uncalibrated_model,422 unsupported_modality,422 sample_only_trainer, and422 recipe_not_supported_for_model, and surfaced the/playgroundURL andgrad doctorquickstart ingrad local up/grad local status. -
Environments run, on your machine (Python).
env.rollout_groups(policy, tasks, group_size=8)and
env.iter_rollout_groups(...)(groups as they finish) run multi-turn rollouts of anEnvironmentor
ToolsEnvironment(sync orasync def;setup=gives tools per-rolloutstate) against a policy: a
Trainer(snapshot, sample, release), atrainer.snapshot(), orpolicies.OpenAI(model, base_url=). Each
rollout runs on its own thread;timeout_scounts environment time only, and a timeout or an environment
error is a typederror/timeoutoutcome, dropped from training and reported (grad.rollout_metrics:
timeout_rate,error_rate,parse_fail_rate,reset_rate,truncation_rate). Teardown always runs;
abandoned hung calls count againstmax_concurrency(EnvironmentHungwhen they hold every slot). A
Trajectorycarries its exact tokensegments(TokenSegment) and runtime fields thatto_record()drops;
Datum.from_trajectory,grad.with_advantages(groups, advantages.GroupStd(min_std=) | GroupMean() | RLOO(), skip_zero_var=1e-6, kl=grad.KL(trainer, coef=, weights="base", discount=0.0))->Batch(with its sampling
temperature and, whenkl=is passed, zero-centered KL-to-reference advantage shaping via one
trainer.forward(..., weights=..., temperature=...)call pluskl_policy_ref/kl_policy_ref_v2in
batch.metrics),grad.recompute_logprobs,grad.mean_reward.grad.GroupScorer(fn, name=None, weight=1.0)
(sync orasync def,(trajectories,)or(task, trajectories)) scores a task's non-error rollout group
together insideRubric([...])acrossrollout_groups,iter_rollout_groups, andevals.create(env=...).
The reward isgrad.combine(rubric, scores), the server'scombineScoresexactly. Removed:
StepOutcomeandTrajectory.append_env_tokens(0.1 stubs);StatefulScorernow serialises as a local code
item. -
On-Policy Distillation (OPD), Prompt Distillation & Self-Distillation (SDFT) (Python,
grad.distillation):
addedTeacherScorerprotocol withTrainerTeacher(zero extra GPU memory withweights="base"|"initial"|"snapshot:<seq>"or a separate teacherTrainer),SnapshotTeacher(prompt_logprobs=True), andOpenAITeacher(/v1/completionsecho=True, max_tokens=0, logprobs=1);distillation_advantages/distillation_advantages_async(reverse_kl,forward_kl,jsd,clip_kl,discount,reward_weightblending, andteacher_tokens_fn/teacher_messages_fnprefix alignment across single- and multi-turn trajectories); and turnkeyOnPolicyDistiller,PromptDistiller, andSelfDistillerwrappers. -
Zero-dependency MCP tool binding (
grad.mcp, Python): added JSON-RPC 2.0MCP.stdio(...)(thread-safe subprocess transport with stderr draining and cleanterminate→killshutdown) andMCP.http(...)(Streamable HTTP withMcp-Session-Idnegotiation and JSON + SSE response parsing), withallow,deny,prefix,max_output_chars, structured error containment, and directToolsEnvironment(mcp=...)integration for rollouts and agent evals. -
Context compaction (
grad.compaction, Python): addedContextCompactor(truncate_tools,sliding_window, andsummarizestrategies with calibrated or custom token counting) wired intoEnvironment(..., compaction=...)andToolsEnvironment(..., compaction=...), cleanly opening a new token-alignedTokenSegment(incrementingcompactionsandresets) whenever compaction triggers mid-rollout. -
Curated, CI-tested runnable cookbook (
examples/): addedexamples/README.mdand 8 runnable recipes (rl_math.py,rl_tools_calculator.py,rl_mcp_agent.py,on_policy_distillation.py,preference_dpo.py,proxy_coding_agent.py,vlm_multimodal.py,rl_numerics_check.py), each supporting offline--dry-runsmoke verification in CI. -
External harness proxy & ecosystem integrations (Python):
- Live Snapshot OpenAI + Anthropic capturing proxy (
grad.proxy.SnapshotProxy):with snap.proxy() as p:
(andtrainer.proxy(), pluspython -m grad.cli proxy --trainer <id> [--snapshot <seq>]) runs a stdlib
loopback HTTP server exposingGET /v1/models,POST /v1/chat/completions(OpenAI JSON + SSE), and
POST /v1/messages(Anthropic JSON + SSE withsystem,thinking,tool_use, andtool_result
translation) atp.openai_urlandp.anthropic_url. Automatically detects multi-turn message extensions per
X-Grad-Session/X-Session-Idheader, sendscontinueprompts tosnap.sample(...), and captures
token-alignedTrajectoryobjects (p.trajectories(),p.reset_trajectories()) ready for
Datum.from_trajectory/with_advantages/PPO. inspect-aimodel provider (grad.integrations.inspect_ai, extragrad-sdk[inspect]):
GradInspectModel,grad_model(...), and@modelapi(name="grad")registration runinspect evalagainst a
liveSnapshot,Trainer, or OpenAI-compatiblegradendpoint without adding required dependencies.verifiersv1 environment adapter (grad.integrations.verifiers, extragrad-sdk[verifiers]):
from_verifiers(vf_env)wrapsverifiers.v1environments as nativegrad.Environmentinstances compatible
withrollout_groups,with_advantages,PPO, andclient.evals.create(env=...), automatically exposing
group-levelscore_groupmethods and plural-argument group rubric functions asgrad.GroupScoreritems on
env.rubric(andenv.group_scorer()). Addedrun_verifiers_via_proxy(...),VerifiersProxyRunner, and
VerifiersEnvironment.run_via_proxy(...)to run customvf_env.rollout()/a_rollout()loops through a
loopbackSnapshotProxy(usingopenai.AsyncOpenAI/openai.OpenAIwhen installed or a zero-dependency
httpxOpenAI-compatible shim otherwise) with automaticcontinuetoken alignment and full per-rollout +
group rubric scoring. Replaced the rigid<0.5.0hard crash with a forward-compatible structural
verifiers.v1guard (hard-rejecting legacy<0.4.0and missing/incompatibleverifiers.v1, warning and
proceeding on>=0.5.0whenverifiers.v1is compatible).
- Live Snapshot OpenAI + Anthropic capturing proxy (
-
Trainer phase 2 across all four SDKs (Python, TypeScript, Go, Rust):
losses.ImportanceSampling,
losses.PPO(clip_low, clip_high),Datumsampling_logprobs/advantages,temperatureon
forward/forward_backward,forward(weights="snapshot:<seq>"),trainer.snapshot()(Snapshotwith
sampleon the sample lane usingrequest_keyanddeadline_s, andrelease),trainer.snapshots(),
{"continue": {...}}prompts,Sample.message/parsed,SampledPrompt.reset, andops/waitfolded into
each SDK's poller. Pythonforward_backward(batch)also reportsstaleness_mean/staleness_max(optimizer
steps between each rollout's snapshot and the call). -
Agent evals (
mode: "env") and regression gates: run multi-turnEnvironment/ToolsEnvironment
evals on your own machine or CI (client.evals.create(env=..., models=[policies.OpenAI(...), trainer, snap], gate=grad.Gate(max_drop=0.02)),client.evals.resume(...), andgrad eval --env module:attr). Rollouts and
local scorers/validators run in your process, trajectories and scores post in batches
(POST /v1/evals/{id}/outputs+/complete), optionalJudgeitems run on the eval worker over the posted
trajectories, andgradaggregates with the same confidence intervals, pass@k and paired bootstrap. Gates
(rule="significant"default withmax_drop=0.0, or"delta", againstbaselineorbaseline_eval) work
on both agent and single-turn evals:grad evalexits8on regression (eval_regressed) and9when
rollout errors exceed--max-error-rate(eval_error_rate), writes$GITHUB_STEP_SUMMARY, and resumes
automatically on re-run viaIdempotency-Key=$GITHUB_RUN_ID. See docs/ENVIRONMENTS.md
andexamples/workflows/agent-eval.yml. -
Departure (
samplelogprobs at sampling temperature):samplenow returns log-probs under the sampling
distribution (log_softmax(softcap(logits) / temperature)renormalised overtop_p), matchingforward(..., temperature=...)attop_p=1for exact importance ratios, rather than rawtemperature=1log-probs. -
Multi-turn rollouts on trainers: a
continuesample prompt ({continue: {tokens, messages, ...}}) extends a
trajectory with exactly the tokens a deployment would render after it (text-equality rule;resetwhen the
template rewrote history), clampsmax_tokensto the room left (finish_reason: context_fullwith none), and
every sample carriesmessage(reasoning and OpenAI-style tool calls, parsed per template family from the
tokens with special tokens kept) andparsed. Gemma 4's<turn|>and<|tool_response>are always stop ids. -
Snapshots, sample lane, and dual-lane worker scheduling:
POST /v1/trainers/{id}/snapshotfreezes an adapter
copy byseq(max_snapshots,409 too_many_snapshots, no eviction,snapshot_ttl_sidle release).
POST /v1/trainers/{id}/snapshots/{seq}/sampleruns on the sample lane withrequest_keyidempotency, 1024 queue
cap (429 Retry-After: 1), deadline sweeps (expired samples never unpark), andPOST /v1/trainers/{id}/ops/wait.
The worker alternates train ops and just-in-time batched sample claims (grouped by snapshot and generation config;
seeded ops run alone), preserves live snapshots across park and drain, reports per-lanecompute_msand
utilization {train_s, sample_s, ready_s}, renders chats off the GPU critical path in the prefetch thread
(TokenizerRenderer), and isolates HTTP 413 result errors toresult_too_largeon the single op. -
Agent evals (
mode: env), judges over trajectories, and regression gates:POST /v1/evalswith
env: {name, max_turns, fingerprint?}starts inawaiting_outputs(unclaimed, 24 h sweep). Clients post rollout
outputs and trajectories toPOST /v1/evals/{id}/outputs(≤ 16 KiB inline, larger in S3 via presigned
trajectory_url;cost_usd: 0on the server), resume viaGET /v1/evals/{id}/outputs?fields=key, and finish
withPOST /v1/evals/{id}/complete. Rubrics with judge items queue for the eval worker to score stored
trajectories using a canonical 16 KiB capped transcript (preserving the final assistant turn) and bill judge tokens
throughbillAttempt.baseline_evalpairing (422 baseline_mismatchon dataset, version, rubric, fingerprint,
samples, max_turns or temperature mismatch) andgate {max_drop, rule: significant|delta}(minimum 30 paired
tasks, reportingpaired_tasksandmin_detectable_drop) work for both single-turn and env evals. Shared golden
reward fixturetests/fixtures/wire/combine-scores.jsonpins exacttoFixed(4)half-up parity between TypeScript
and Python. -
Web console for Trainer phase 2 and Agent Evals (
server/ui): Evals now showawaiting_outputsstatus,
environment metadata (env.name,max_turns,fingerprint),baseline_evallinks and deltas, regression gate
banners (passed,regressed,rule,max_drop,paired_tasks,min_detectable_drop), and a paginated
Outputs panel with an expandable trajectory viewer (inline or lazily fetched from S3trajectory_urlwith
formatted tool calls/responses, reasoning toggle, finish reason, and error banners). Trainers now show GPU
utilization ((train_s + sample_s) / ready_s), sample queue depth,closingstate, a Snapshots panel with
confirmed release (DELETE /v1/trainers/{id}/snapshots/{seq}), and op lane /snapshot_seq/compute_ms
columns. -
One engine for recipes and trainers (
grad_trainer/engine.py): SFTRecipe's forward, backward and
optimizer steps moved onto it, and a parity test checks a hand-written loop gives SFTRecipe's losses. -
Fixed: batched generation on CUDA attended padding. A model loaded for packed (varlen) training generated
left-padded batches without an attention mask, so distillation's student samples for short prompts saw the
padding. Generation now switches to padded SDPA.