Training API reference
Every public endpoint of grad-server, generated from grad's
spec/openapi.yaml: its fields, an example request and response, and the
complete SDK call or CLI command that sends it, in the language you picked
above.
The same API runs on grad local up, the Helm chart and, soon, Gradiated Cloud. Set GRADIATED_BASE_URL to your server (http://127.0.0.1:18787 for grad local up) and GRADIATED_API_KEY to a key; every /v1/* call sends it as Authorization: Bearer <key>. Authentication, scopes, idempotency, pagination and the error format are on the API overview; every error code is explained in Errors. A running server also serves this spec at /openapi.json.
Every sample sends the same values as its curl request, and grad's scripts/check-docs-snippets.py --compile type-checks each one against the SDK sources on grad 0.2.0-alpha.12, the current release (see 0.2.0-alpha.12; earlier Go and Rust signature changes are under 0.2.0-alpha.8).
Auth#
Identify the authenticated caller, workspace, and server mode#
GET/v1/whoami
Returns
200 WhoamiResponse Authenticated identity and server capabilities.
6 fields
workspace_idstringrequiredAuthenticated workspace id.
workspace_namestringrequiredWorkspace display name when available, else null.
auth_kindstringrequiredHow the request authenticated (e.g.
"api_key","session","dev","worker").deployment_modeDeploymentModerequiredWhether this server is Gradiated Cloud (
cloud) or a self-hosted deployment (self-hosted)."cloud""self-hosted"capabilitiesWhoamiCapabilitiesrequired1 child fields
inference_evalsbooleanrequiredWhether server-side evals, LLM judges, and prompt-labeling evals are enabled on this server.
console_urlstringThe web console's runs page for this workspace when GRAD_CONSOLE_URL is configured; null otherwise.
grad uiopens it on Gradiated Cloud.
from grad import Grad
client = Grad()
me = client.whoami()
print(me.workspace_id, me.auth_kind, me.deployment_mode){
"workspace_id": "ws_e2e",
"workspace_name": null,
"auth_kind": "api_key",
"deployment_mode": "self-hosted",
"capabilities": {
"inference_evals": true
}
}Datasets#
List datasets#
GET/v1/datasets
Newest first.
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstringqstringOnly items whose name contains this text (any case), or whose id is exactly this.
Returns
200 object Datasets.
2 fields
dataarray of Datasetrequired9 child fields
idstringrequiredDataset id (
ds_and 24 hex characters).workspace_idstringrequirednamestringrequiredDataset name, unique in the workspace.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionintegerrequiredCurrent version. Every push, import, score or sync that changes records adds one; runs and evals pin a version.
record_countintegerrequiredRecords in the current version after merging: score updates fold into their records, and a full source sync restarts the count. A record pushed again with an id it already has counts again.
metadatamap of anyrequiredFree-form metadata you set at creation.
created_atstring (date-time)requiredupdated_atstring (date-time)requiredconsole_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
for dataset in client.datasets.list(search="support"):
print(dataset.name, dataset.version, dataset.record_count){
"data": [
{
"id": "ds_933362777156d207844b5d12",
"workspace_id": "ws_e2e",
"name": "support-good",
"version": 1,
"record_count": 1,
"metadata": {
"view": {
"filter": {
"scores": {
"resolved": ">=0.8"
}
},
"source": "support-prod",
"version": 1
}
},
"created_at": "2026-12-02T15:48:59.845Z",
"updated_at": "2026-12-02T15:48:59.847Z"
},
{
"id": "ds_c66d7ad841f251049ca0e550",
"workspace_id": "ws_e2e",
"name": "support-prod",
"version": 2,
"record_count": 1,
"metadata": {},
"created_at": "2026-12-02T15:48:59.567Z",
"updated_at": "2026-12-02T15:49:00.345Z"
}
],
"next_cursor": null
}Create an empty dataset#
POST/v1/datasets
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body CreateDatasetRequest
namestringrequiredDataset name: lowercase letters, digits,
.,_and-, unique in the workspace.Matches
^[a-z0-9][a-z0-9._-]{0,63}$metadatamap of anyFree-form metadata stored on the dataset.
Returns
201 Dataset Created dataset (version 0).
9 fields
idstringrequiredDataset id (
ds_and 24 hex characters).workspace_idstringrequirednamestringrequiredDataset name, unique in the workspace.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionintegerrequiredCurrent version. Every push, import, score or sync that changes records adds one; runs and evals pin a version.
record_countintegerrequiredRecords in the current version after merging: score updates fold into their records, and a full source sync restarts the count. A record pushed again with an id it already has counts again.
metadatamap of anyrequiredFree-form metadata you set at creation.
created_atstring (date-time)requiredupdated_atstring (date-time)requiredconsole_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
dataset = client.datasets.create("support-prod"){
"id": "ds_c66d7ad841f251049ca0e550",
"workspace_id": "ws_e2e",
"name": "support-prod",
"version": 0,
"record_count": 0,
"metadata": {},
"created_at": "2026-12-02T15:48:59.567Z",
"updated_at": "2026-12-02T15:48:59.567Z"
}Get a dataset by name#
GET/v1/datasets/{name}
Path parameters
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$
Returns
200 Dataset Dataset metadata.
9 fields
idstringrequiredDataset id (
ds_and 24 hex characters).workspace_idstringrequirednamestringrequiredDataset name, unique in the workspace.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionintegerrequiredCurrent version. Every push, import, score or sync that changes records adds one; runs and evals pin a version.
record_countintegerrequiredRecords in the current version after merging: score updates fold into their records, and a full source sync restarts the count. A record pushed again with an id it already has counts again.
metadatamap of anyrequiredFree-form metadata you set at creation.
created_atstring (date-time)requiredupdated_atstring (date-time)requiredconsole_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
dataset = client.datasets.get("support-prod")
print(dataset.version, dataset.record_count){
"id": "ds_c66d7ad841f251049ca0e550",
"workspace_id": "ws_e2e",
"name": "support-prod",
"version": 2,
"record_count": 1,
"metadata": {},
"created_at": "2026-12-02T15:48:59.567Z",
"updated_at": "2026-12-02T15:49:00.345Z"
}Delete a dataset and its versions#
DELETE/v1/datasets/{name}
409 while referenced by runs, evals, sources, or active imports.
Path parameters
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$
Returns
204 Deleted.
from grad import Grad
client = Grad()
client.datasets.delete("support-prod")Deleted.
Append records as a new dataset version#
POST/v1/datasets/{name}/records
Creates the dataset if needed.
Path parameters
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body PushDatasetRequest
recordsarray of DatasetRecordRecords to append inline; together they become the next dataset version. Mutually exclusive with
upload_id.24 child fields
schema"grad.trajectory/1""grad.trajectory/1"idstringsession_idstringgroup_idstringroleenum"chosen""rejected""anchor""positive""negative""desirable""undesirable""rollout"nullsourcestringtimestampstringmessagesarray of ChatMessage7 child fields
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
toolsarray of map of anyinputTrajectoryInput5 child fields
messagesarray of ChatMessage7 child fields
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
toolsarray of map of anymediaarray of map of anyfeaturesmap of anypayloadany
outputTrajectoryOutputpromptstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
completionstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
chosenstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
rejectedstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
querystringpositivestringnegativesarray of stringstateanyquestionsmap of anyexpected_outputanyscoresmap of numbermetricsmap of numbermetadatamap of any
upload_idstringStaged JSONL or gzipped JSONL uploaded via
POST /v1/uploads(purpose: "dataset_import"). Commits all records atomically as one dataset version; mutually exclusive withrecords.Matches
^[0-9a-f]{64}$formatPushDatasetFormatFormat of the staged upload (
jsonlorjsonl.gz); only valid withupload_id. Defaults to auto-detection via gzip magic bytes."jsonl""jsonl.gz"metadatamap of anyKeys merged into the dataset's metadata.
Returns
200 Dataset Updated dataset.
9 fields
idstringrequiredDataset id (
ds_and 24 hex characters).workspace_idstringrequirednamestringrequiredDataset name, unique in the workspace.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionintegerrequiredCurrent version. Every push, import, score or sync that changes records adds one; runs and evals pin a version.
record_countintegerrequiredRecords in the current version after merging: score updates fold into their records, and a full source sync restarts the count. A record pushed again with an id it already has counts again.
metadatamap of anyrequiredFree-form metadata you set at creation.
created_atstring (date-time)requiredupdated_atstring (date-time)requiredconsole_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
dataset = client.datasets.push("support-prod", [
{
"messages": [
{"role": "user", "content": "Where is my order #4512?"},
{"role": "assistant", "content": "It shipped this morning; here is the tracking link."},
],
"scores": {"resolved": 1},
"metadata": {"route": "support"},
},
]){
"id": "ds_c66d7ad841f251049ca0e550",
"workspace_id": "ws_e2e",
"name": "support-prod",
"version": 1,
"record_count": 1,
"metadata": {},
"created_at": "2026-12-02T15:48:59.567Z",
"updated_at": "2026-12-02T15:48:59.803Z"
}Read records of a dataset version#
GET/v1/datasets/{name}/records
Path parameters
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$
Query parameters
versionintegerlimitintegerPage size (default 100). Values above 1000 are clamped to 1000.
cursorstring
Returns
200 DatasetRecordsPage Dataset records page.
5 fields
datasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$versionintegerrequiredtotalintegerrequireddataarray of DatasetRecordrequired24 child fields
schema"grad.trajectory/1""grad.trajectory/1"idstringsession_idstringgroup_idstringroleenum"chosen""rejected""anchor""positive""negative""desirable""undesirable""rollout"nullsourcestringtimestampstringmessagesarray of ChatMessage7 child fields
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
toolsarray of map of anyinputTrajectoryInput5 child fields
messagesarray of ChatMessage7 child fields
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
toolsarray of map of anymediaarray of map of anyfeaturesmap of anypayloadany
outputTrajectoryOutputpromptstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
completionstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
chosenstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
rejectedstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
querystringpositivestringnegativesarray of stringstateanyquestionsmap of anyexpected_outputanyscoresmap of numbermetricsmap of numbermetadatamap of any
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
for record in client.datasets.records("support-prod", limit=100):
print(record["messages"][-1]["content"]){
"dataset": "support-prod",
"version": 2,
"total": 1,
"data": [
{
"messages": [
{
"role": "user",
"content": "Where is my order #4512?"
},
{
"role": "assistant",
"content": "It shipped this morning; here is the tracking link."
}
],
"scores": {
"resolved": 1,
"polite": 0
},
"metadata": {
"route": "support"
},
"id": "rec_0918892977163ffc"
}
],
"next_cursor": null
}Score a dataset's records with a rubric#
POST/v1/datasets/{name}/score
Async; the scores become the next version.
Runs the rubric (judges, validators, regexes, code scorers) on each record's own answer, skipping records that already have every score. It is an eval with mode: "score": poll it at /v1/evals/{id}, and it is billed like one. On completion the scores are appended as a score-update part, so the dataset's next version (scored_dataset_version) carries them in record.scores.
Path parameters
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body ScoreDatasetRequest
rubricarray of EvalRubricItemrequired9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
versionintegerDataset version to score (default: the current version).
namestringName of the scoring job (default
<dataset>-score).Matches
^[a-z0-9][a-z0-9._-]{0,63}$limitinteger
Returns
202 EvalRun Queued scoring job.
29 fields
idstringrequiredEval id (
eval_and 24 hex characters).workspace_idstringrequirednamestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$statusEvalStatusrequired"queued""running""awaiting_outputs""awaiting_scores""completed""failed""cancelled"modeEvalModerequiredevalgenerates outputs frommodels;score(dataset.score()) grades each record's own output (modelrecord) and writes the scores to the dataset's next version;envis a client-driven agent evaluation whose rollouts post outputs via/outputsand/complete."eval""score""env"modelsarray of stringrequiredThe models evaluated: catalog ids, artifacts (
name@version), models the inference endpoint serves, or policy labels inenvmode.baselinestringrequiredThe model the summary compares the others with (
vs_baseline); null for none.baseline_evalEvalBaselineRefrequiredenvEvalEnvConfigrequiredgateEvalGateResultrequiredtask_sourceobjectrequired3 child fields
kind"dataset"required"dataset"datasetstringrequiredversionintegerrequired
rubricarray of EvalRubricItemrequired9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
samplesintegerrequiredAnswers generated per task and model.
temperaturenumberrequiredSampling temperature of the model calls.
max_tokensintegerrequiredThe most tokens each answer may have.
pass_thresholdnumberrequiredScore at or above which a task passes.
judge_modelsarray of stringrequiredThe judge models the rubric calls.
local_scorersarray of stringrequiredCode scorers that run in the SDK process; the eval waits in
awaiting_scoresuntil they post their scores.progressobjectrequired3 child fields
total_outputsintegerrequiredgeneratedintegerrequiredpending_local_scoresintegerrequired
summaryarray of EvalModelSummaryrequired12 child fields
modelstringrequiredThe model this summary is for.
overallnumberrequiredMean task score (each task's score averages its samples).
ci_lownumberrequiredLower bound of the bootstrap 95% confidence interval on
overall.ci_highnumberrequiredUpper bound of the bootstrap 95% confidence interval on
overall.pass_at_kmap of numberrequiredUnbiased pass@k per k (
pass@1, ...): the chance that one of k samples scores at leastpass_threshold.vs_baselineobjectrequiredThe mean paired difference from the baseline over the tasks both answered, with a bootstrap 95% interval; null for the baseline itself or without one.
3 child fields
deltanumberrequiredci_lownumberrequiredci_highnumberrequired
tasksintegerrequiredTasks this model answered.
errorsintegerrequiredModel or judge calls that failed.
tokens_per_tasknumberrequiredMean tokens per task.
cost_per_1k_tasks_usdnumberrequiredCost per 1,000 tasks in USD; null when the model has no price.
by_scorermap of numberMean score per rubric scorer over outputs carrying that scorer.
mean_turnsnumberMean agent turns per rollout (present when outputs include trajectories with turns).
total_cost_usdnumberrequiredCost of the model and judge calls so far, in USD.
scored_dataset_versionintegerrequiredScoring jobs: the dataset version holding the new scores (the source version when every record was already scored); null until completed.
errorstringrequiredWhy the eval failed; null otherwise.
waiting_reasonenumrequiredWhile running: the eval's model calls are waiting for capacity (a serving pool at zero that has not woken yet), for a rate limit (a full eval lane), or for an inference endpoint that is down. The worker keeps its lease and retries; this is not counted as a failed attempt. null otherwise.
"capacity_unavailable""rate_limited""inference_unavailable"nulllast_output_atstring (date-time)requiredWhen the last client output was received in
envmode; null otherwise.created_atstring (date-time)requiredupdated_atstring (date-time)requiredcompleted_atstring (date-time)requiredWhen the eval reached a final status; null until then.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad, Scorer
from grad.validators import Regex
client = Grad()
polite = Scorer("polite", fn=Regex("thank", flags="i")) # runs on the server
scoring = client.datasets.score("support-prod", [polite])
scored = scoring.wait() # the version with the scores{
"id": "eval_c13bd1724f656bf328ba0115",
"workspace_id": "ws_e2e",
"name": "support-prod-score",
"status": "queued",
"mode": "score",
"models": [
"record"
],
"baseline": null,
"baseline_eval": null,
"env": null,
"gate": null,
"task_source": {
"kind": "dataset",
"dataset": "support-prod",
"version": 1
},
"rubric": [
{
"kind": "regex",
"name": "polite",
"flags": "i",
"weight": 1,
"pattern": "thank"
}
],
"samples": 1,
"temperature": 0,
"max_tokens": 1,
"pass_threshold": 1,
"judge_models": [],
"local_scorers": [],
"progress": {
"total_outputs": 1,
"generated": 0,
"pending_local_scores": 0
},
"summary": [],
"total_cost_usd": 0,
"scored_dataset_version": null,
"error": null,
"waiting_reason": null,
"last_output_at": null,
"created_at": "2026-12-02T15:48:59.828Z",
"updated_at": "2026-12-02T15:48:59.828Z",
"completed_at": null
}Save a filtered view of a dataset version#
POST/v1/datasets/{name}/filter
Keeps the records whose stored scores, metadata, timestamp or id match, and saves them as a dataset named <dataset>-f-<hash> (or name). The same filter on the same version returns the same view (200) without recomputing; a new threshold is a new view (201). Filtering calls no model and costs nothing.
Path parameters
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body FilterDatasetRequest
scoresmap of string or numberConditions on stored scores,
{name: "<op><number>"}with op one of >=, <=, >, <, ==, != (a bare number means ==). A record without the score does not match.metadatamap of string or number or booleanExact matches on
metadatafields.created_afterstring (date-time) or string (date)Records whose
timestampis at or after this time (a timestamp with offset, or a UTC dateYYYY-MM-DD).One of 2 shapes
- string (date-time)
- string (date)
created_beforestring (date-time) or string (date)Records whose
timestampis before this time.One of 2 shapes
- string (date-time)
- string (date)
idsarray of stringKeep only these record ids (what the SDKs send for a filter function they ran locally).
versionintegerSource version to filter (default: the current version).
namestringName of the view. Default:
<dataset>-f-<hash of source, version and filter>, so the same filter returns the same view.Matches
^[a-z0-9][a-z0-9._-]{0,63}$
Returns
200 Dataset The existing view.
201 Dataset Created view.
9 fields
idstringrequiredDataset id (
ds_and 24 hex characters).workspace_idstringrequirednamestringrequiredDataset name, unique in the workspace.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionintegerrequiredCurrent version. Every push, import, score or sync that changes records adds one; runs and evals pin a version.
record_countintegerrequiredRecords in the current version after merging: score updates fold into their records, and a full source sync restarts the count. A record pushed again with an id it already has counts again.
metadatamap of anyrequiredFree-form metadata you set at creation.
created_atstring (date-time)requiredupdated_atstring (date-time)requiredconsole_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
view = client.datasets.filter("support-prod", scores={"resolved": ">=0.8"}, name="support-good")
print(view.name, view.record_count){
"id": "ds_933362777156d207844b5d12",
"workspace_id": "ws_e2e",
"name": "support-good",
"version": 1,
"record_count": 1,
"metadata": {
"view": {
"filter": {
"scores": {
"resolved": ">=0.8"
}
},
"source": "support-prod",
"version": 1
}
},
"created_at": "2026-12-02T15:48:59.845Z",
"updated_at": "2026-12-02T15:48:59.847Z"
}Preview chat-template rendering and loss masks#
POST/v1/datasets/{name}/render
Estimated token counts.
Path parameters
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body RenderDatasetRequest
modelstringtrain_onenum"last""all_assistant"thinkingenum"auto""on""off"preserve_thinkingbooleanlimitinteger
Returns
200 RenderDatasetResponse Rendered examples.
5 fields
datasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$modelstringrequiredtemplate_revisionstringrequiredtoken_counts"estimated"requiredToken counts (total, trained and per span) are estimates (about 4 characters per token); the trainer tokenizes with the model's pinned tokenizer, and the run's metrics report the exact tokens.
"estimated"examplesarray of objectrequired6 child fields
record_idstringrequiredtemplate_revisionstringrequiredtotal_tokensintegerrequiredtrained_tokensintegerrequiredtrained_fractionnumberrequiredspansarray of objectrequired3 child fields
textstringrequiredtrainedbooleanrequiredtokensintegerrequired
from grad import Grad
client = Grad()
preview = client.datasets.render("support-prod", model="qwen/qwen3-8b", limit=1)
print(preview){
"dataset": "support-prod",
"model": "qwen/qwen3-8b",
"template_revision": "qwen3@3",
"token_counts": "estimated",
"examples": [
{
"record_id": "rec_0918892977163ffc",
"template_revision": "qwen3@3",
"total_tokens": 33,
"trained_tokens": 14,
"trained_fraction": 0.42424242424242425,
"spans": [
{
"text": "<|im_start|>user\nWhere is my order #4512?<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
"trained": false,
"tokens": 18
},
{
"text": "It shipped this morning; here is the tracking link.<|im_end|>",
"trained": true,
"tokens": 14
}
]
}
]
}Get an upload URL for a file to import#
POST/v1/uploads
PUT the bytes, then create a dataset import, artifact import, or environment.
The staged file expires after 7 days unless an import or environment uses it.
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body CreateUploadRequest
purposeenumrequireddataset_import (needs datasets:write), artifact_import (artifacts:write), or environment_bundle (runs:write).
"dataset_import""artifact_import""environment_bundle"filenamestringrequiredsize_bytesintegerrequiredsha256stringrequiredMatches
^[0-9a-f]{64}$
Returns
201 UploadTicket Upload ticket.
5 fields
upload_idstringrequiredThe file's sha256: uploads are content-addressed, so re-uploading the same bytes is harmless.
method"PUT"required"PUT"urlstringrequiredPresigned S3 PUT URL; send exactly
headers(they bind the length and sha256).headersmap of stringrequiredexpires_atstring (date-time)required
from grad import Grad
client = Grad()
# Uploads the file (POST /v1/uploads, then a PUT to the returned URL) and imports it.
job = client.datasets.import_file("support-prod", "./traces.jsonl")
print(job.wait().status){
"upload_id": "9f2c4e1ab0d3c5e7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c9d1e3f5a7b9c1d3e5",
"method": "PUT",
"url": "https://storage.example.com/grad-test/uploads/ws_e2e/9f2c4e1ab0d3c5e7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c9d1e3f5a7b9c1d3e5?X-Amz-Algorithm=…&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=…&X-Amz-Date=…&X-Amz-Expires=…&X-Amz-Signature=…&X-Amz-SignedHeaders=…&x-id=PutObject",
"headers": {
"content-length": "52431",
"x-amz-checksum-sha256": "nyxOGrDTxef5obPF1+nxo7XH2eHzpbfJ0eP1p7nB0+U="
},
"expires_at": "2026-12-02T21:48:59.857Z"
}Import an uploaded file or a Hugging Face dataset into a dataset#
POST/v1/datasets/{name}/imports
Async job.
Path parameters
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body CreateImportRequest
sourceImportSourcerequiredOne of 3 shapes
- object
kind"upload"required"upload"upload_idstringrequiredformatenum"auto""jsonl""json""parquet"
- object
kind"hf"required"hf"repostringrequiredMatches
^[A-Za-z0-9](?:[\w-]|\.(?!\.))*(\/[A-Za-z0-9](?:[\w-]|\.(?!\.))*)?$splitstringconfigstringrevisionstringMatches
^(?!.*\.\.)[A-Za-z0-9][A-Za-z0-9._/-]*$columnsHfColumnMapping19 child fields
messagesstringMatches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$systemstringSystem prompt column; prepended to messages or combined with prompt/completion into messages.
Matches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$promptstringMatches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$completionstringMatches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$inputstringAlpaca-style secondary input (appended to prompt when both are strings, or mapped to prompt/record input).
Matches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$outputstringOutput column (mapped to completion unless completion is also set, or preserved as structured record output).
Matches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$chosenstringMatches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$rejectedstringMatches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$answerstringMatches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$expected_outputstringMatches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$toolsstringMatches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$querystringMatches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$positivestringMatches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$negativesstringMatches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$scoresstringMatches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$labelstringNumeric or boolean label column mapped into scores.label when scores is not explicitly set.
Matches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$idstringMatches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$group_idstringMatches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$session_idstringMatches
^[^\x00-\x1f\x7f.]+(?:\.[^\x00-\x1f\x7f.]+)*$
metadata_columnsmap of stringMap of metadata key to Hugging Face column name (or dotted nested path) to preserve in each record's
metadataobject.keep_extra_metadatabooleanPreserve all unmapped Hugging Face columns in each record's
metadataobject.limitintegerintegrationstringA huggingface integration whose token reads gated or private datasets. Default: the workspace's only huggingface integration; with none, public access.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$
- object
kind"benchmark"required"benchmark"benchmarkenumrequiredA built-in benchmark, imported from Hugging Face at a pinned revision with fixed prompts; evals on the dataset default to its answer check.
"gsm8k""mmlu""mmlu_pro""arc_challenge""arc_easy""hellaswag""winogrande""truthfulqa_mc1""boolq""openbookqa""commonsense_qa""math500""ifeval"limitintegerImport the first N problems (the same ones every time).
- object
connectorenum"auto""grad_trajectories""openai_chat""gradiated""otel""langfuse""posthog""braintrust""langsmith"
Returns
202 ImportJob Queued import job.
15 fields
idstringrequiredImport job id (
imp_and 24 hex characters).workspace_idstringrequireddatasetstringrequiredThe dataset the records go into.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$statusImportStatusrequired"queued""running""completed""failed"sourcemap of anyrequiredWhere the records come from: an upload, a Hugging Face dataset, a benchmark, or a source sync.
connectorenumrequiredThe parser requested for the records (
autodetects it from the file)."auto""grad_trajectories""openai_chat""gradiated""otel""langfuse""posthog""braintrust""langsmith"attemptintegerrequiredAttempts started so far.
imported_countintegerrequiredRecords this import added to the dataset (score updates for existing records add none).
dropped_countintegerrequiredRows that couldn't be imported;
drop_reasonssays why.detected_scoresarray of stringrequiredScore names found on the imported records.
drop_reasonsarray of stringrequiredWhy rows were dropped, one line per row (
line 12: invalid JSON), capped at 100 entries.dataset_versionintegerrequiredThe dataset version this import produced; null until then.
errorstringrequiredWhy the import failed; null otherwise.
created_atstring (date-time)requiredupdated_atstring (date-time)required
from grad import Grad
client = Grad()
dataset = client.datasets.from_hf(
"HuggingFaceH4/ultrachat_200k", split="train_sft", limit=1000, name="support-prod"
){
"id": "imp_235ef2625ab31d7d988bab19",
"workspace_id": "ws_e2e",
"dataset": "support-prod",
"status": "queued",
"source": {
"kind": "hf",
"repo": "HuggingFaceH4/ultrachat_200k",
"limit": 1000,
"split": "train_sft",
"columns": {}
},
"connector": "auto",
"attempt": 0,
"imported_count": 0,
"dropped_count": 0,
"detected_scores": [],
"drop_reasons": [],
"dataset_version": null,
"error": null,
"created_at": "2026-12-02T15:48:59.865Z",
"updated_at": "2026-12-02T15:48:59.865Z"
}List dataset import jobs#
GET/v1/imports
Newest first.
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstringstatusstringOnly these statuses, comma-separated: queued, running, completed, failed.
datasetstringOnly imports into this dataset.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$
Returns
200 object Import jobs.
2 fields
dataarray of ImportJobrequired15 child fields
idstringrequiredImport job id (
imp_and 24 hex characters).workspace_idstringrequireddatasetstringrequiredThe dataset the records go into.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$statusImportStatusrequired"queued""running""completed""failed"sourcemap of anyrequiredWhere the records come from: an upload, a Hugging Face dataset, a benchmark, or a source sync.
connectorenumrequiredThe parser requested for the records (
autodetects it from the file)."auto""grad_trajectories""openai_chat""gradiated""otel""langfuse""posthog""braintrust""langsmith"attemptintegerrequiredAttempts started so far.
imported_countintegerrequiredRecords this import added to the dataset (score updates for existing records add none).
dropped_countintegerrequiredRows that couldn't be imported;
drop_reasonssays why.detected_scoresarray of stringrequiredScore names found on the imported records.
drop_reasonsarray of stringrequiredWhy rows were dropped, one line per row (
line 12: invalid JSON), capped at 100 entries.dataset_versionintegerrequiredThe dataset version this import produced; null until then.
errorstringrequiredWhy the import failed; null otherwise.
created_atstring (date-time)requiredupdated_atstring (date-time)required
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
for job in client.imports.list(status="failed", dataset="support-prod"):
print(job.id, job.error){
"data": [
{
"id": "imp_3f9c0a1b2c3d4e5f60718293",
"workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
"dataset": "support-prod",
"status": "queued",
"source": {},
"connector": "auto",
"attempt": 0,
"imported_count": 0,
"dropped_count": 0,
"detected_scores": [
"string"
],
"drop_reasons": [
"string"
],
"dataset_version": 0,
"error": "…",
"created_at": "2026-11-28T09:30:00.000Z",
"updated_at": "2026-11-28T09:30:00.000Z"
}
],
"next_cursor": "string"
}Get a dataset import job#
GET/v1/imports/{id}
Path parameters
idstringrequired
Returns
200 ImportJob Import job.
15 fields
idstringrequiredImport job id (
imp_and 24 hex characters).workspace_idstringrequireddatasetstringrequiredThe dataset the records go into.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$statusImportStatusrequired"queued""running""completed""failed"sourcemap of anyrequiredWhere the records come from: an upload, a Hugging Face dataset, a benchmark, or a source sync.
connectorenumrequiredThe parser requested for the records (
autodetects it from the file)."auto""grad_trajectories""openai_chat""gradiated""otel""langfuse""posthog""braintrust""langsmith"attemptintegerrequiredAttempts started so far.
imported_countintegerrequiredRecords this import added to the dataset (score updates for existing records add none).
dropped_countintegerrequiredRows that couldn't be imported;
drop_reasonssays why.detected_scoresarray of stringrequiredScore names found on the imported records.
drop_reasonsarray of stringrequiredWhy rows were dropped, one line per row (
line 12: invalid JSON), capped at 100 entries.dataset_versionintegerrequiredThe dataset version this import produced; null until then.
errorstringrequiredWhy the import failed; null otherwise.
created_atstring (date-time)requiredupdated_atstring (date-time)required
from grad import Grad
client = Grad()
job = client.imports.get("imp_3f9c0a1b2c3d4e5f60718293")
print(job.status, job.imported_count){
"id": "imp_3f9c0a1b2c3d4e5f60718293",
"workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
"dataset": "support-prod",
"status": "queued",
"source": {},
"connector": "auto",
"attempt": 0,
"imported_count": 0,
"dropped_count": 0,
"detected_scores": [
"string"
],
"drop_reasons": [
"string"
],
"dataset_version": 0,
"error": "…",
"created_at": "2026-11-28T09:30:00.000Z",
"updated_at": "2026-11-28T09:30:00.000Z"
}Runs#
Dry-run a training recipe at zero cost#
POST/v1/runs/plan
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body PlanRunRequest
datasetstringrequiredDataset to train on. The run pins its current version.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$namestringrequiredRun name; the artifact it produces is released as
name@version.Matches
^[a-z0-9][a-z0-9._-]{0,63}$recipeRecipeSpecrequired50 child fields
kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"modelstringadapterAdapterSpecOne of 3 shapes
- object
kind"lora"required"lora"rankintegeralphaintegermerge_on_exportbooleantrain_multimodal_projectorbooleanAlso attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).
- object
kind"prefix_kv"required"prefix_kv"num_tokensinteger
- object
kind"frozen_head"required"frozen_head"
- object
lr"auto" or numberOne of 2 shapes
- "auto"
- number
lr_scalenumberbatch_sizeintegerepochsintegerscheduleenum"linear""cosine""constant"warmupnumbertrain_onenumWhich assistant turns are trained (default 'last'; LLM recipes only).
"last""all_assistant"thinkingenumThinking mode for chat rendering (default 'auto'; LLM recipes only).
"auto""on""off"preserve_thinkingbooleanWhether earlier assistant turns keep their reasoning in the prompt (default false; LLM recipes only).
reductionenumDefault per_example (LLM recipes only).
"per_example""per_token"selectenum"best""last"checkpoint_ttl_daysintegerbetanumbermodelsarray of stringmax_quality_dropnumbercontext_textstringnum_tokensintegertempnumberteacherstringCartridgeRecipe and DistillRecipe: the model to learn from. DistillRecipe also takes an artifact (name@version) with rollout off_policy.
rolloutRolloutSpecDistillRecipe: on_policy (default) samples answers from the student and the trainer scores them with the teacher's top-k logits; off_policy has the teacher answer each prompt once through the inference endpoint and trains the student on those answers.
One of 2 shapes
- object
kind"on_policy"required"on_policy"max_new_tokens"auto" or integerLength of each student answer; auto (default) sizes it from the assistant turns in your records (256 without any).
One of 2 shapes
- "auto"
- integer
- object
kind"off_policy"required"off_policy"max_new_tokensinteger
- object
optimizerOptimizerSpec4 child fields
kind"adamw""adamw"betasarray of anyweight_decaynumbergrad_clipnumberMax global gradient norm; 0 disables clipping.
eval_every"auto" or integerOptimizer steps between held-out evaluations; auto = every 25% of the run, at most every 20 steps; each eval step is also a checkpoint.
One of 2 shapes
- "auto"
- integer
lossLossSpecOne of 5 shapes
- object
kind"cross_entropy"required"cross_entropy"reductionenum"per_example""per_token"
- object
kind"dpo"required"dpo"betanumber
- object
kind"infonce"required"infonce"tempnumber
- object
kind"top_k_kl_distill"required"top_k_kl_distill"top_kinteger
- object
kind"grpo"required"grpo"clip_lownumberclip_highnumber
- object
poolPoolingSpec1 child fields
kindenumrequired"mean""cls""last_token"
matryoshka_dimsarray of integerEmbeddingRecipe: Matryoshka Representation Learning truncation dimensions (e.g. [64, 128, 256, 512]).
query_prefixstringEmbeddingRecipe: text prepended to every query before tokenization.
doc_prefixstringEmbeddingRecipe: text prepended to every positive and negative document before tokenization.
max_seq_lenintegerEmbeddingRecipe: maximum token length per text (capped at the encoder's context window).
rubricstring or array of EvalRubricItemRouterRecipe: a score name on your records (scores[rubric]), or Judge/validator items: the server then replays each prompt against recipe.models and scores the answers in a labeling eval before training. RewardModelRecipe: a score name in [0, 1] on records ending in an assistant turn, trained pointwise next to the chosen/rejected pairs.
One of 2 shapes
- string
- array of EvalRubricItem
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
pricingmap of numberRouterRecipe: USD per request for each candidate; overrides metrics.cost_usd on your records.
fallbackstringRouterRecipe: the candidate that gets every request the router does not offload (default: the best-scoring candidate).
max_new_tokensintegerCartridgeRecipe: teacher answer length per prompt during distillation (default 256).
slot_tokenstringCartridgeRecipe: a reserved token that marks where the cartridge goes (default: the first reserved token that tokenizes atomically).
validatorenumGRPORecipe: built-in deterministic reward validator (default 'exact_match'; 'math' aliases 'math_equivalence', 'json_valid' aliases 'json').
"exact_match""contains""math""math_equivalence""final_number""choice""json""json_valid""non_empty""regex"validator_patternstringGRPORecipe: regular expression pattern used when validator is 'regex'.
system_promptstringGRPORecipe: optional system prompt prepended to every prompt before rollout generation.
group_sizeintegerGRPORecipe: completions sampled per prompt in each rollout group (default 8, min 2).
max_tokensintegerGRPORecipe: maximum generated tokens per sampled completion (default 1024).
temperaturenumberGRPORecipe: rollout sampling temperature in (0, 2] (default 1.0; top_p is fixed at 1.0 for exact importance sampling).
advantageenumGRPORecipe: group advantage estimator: 'group_std' (GRPO, default), 'dr_grpo' (mean-centered without std division), or 'rloo' (leave-one-out).
"group_std""dr_grpo""rloo"kl_coefnumberGRPORecipe: Schulman k3 KL penalty coefficient against initial/base weights (default 0.04; 0 disables KL).
clip_lownumberGRPORecipe: lower PPO/GRPO importance-ratio clip epsilon (default 0.2).
clip_highnumberGRPORecipe: upper PPO/GRPO importance-ratio clip epsilon (default 0.2; e.g. 0.28 for DAPO Clip-Higher).
skip_zero_varbooleanGRPORecipe: skip prompt groups whose rollout rewards have near-zero variance (default true).
max_stepsintegerGRPORecipe: optional maximum number of optimizer steps (caps epochs * steps_per_epoch).
evalsarray of RecipeEvalExtra evals on each checkpoint during training (the eval executor, billed like any eval). Results are in run.checkpoint_evals, the run's checkpoint_eval events and eval_report.checkpoint_evals.
5 child fields
datasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$versionintegerDataset version (default: the current one, pinned at plan time).
rubricarray of EvalRubricItemJudges, regexes and validators (default: the dataset's own rubric, such as a benchmark's answer check). Code scorers can't run during training.
9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
limitintegerEvaluate the first N tasks at each checkpoint.
namestringName of this eval in the report (default: the dataset name).
Matches
^[a-z0-9][a-z0-9._-]{0,63}$
loggersarray of LoggerSpecExperiment trackers that receive the run's metrics. A tracker that fails is reported and dropped; it never fails the run.
splitSplitSpec3 child fields
strategyenum"by_session""by_group""random"eval_fractionnumberseedinteger
max_cost_usdnumberHard spend cap in USD. The run stops with
stopped_budgetand keeps its checkpoint when it reaches the cap, and is never billed past it. Default: no cap.
Returns
200 PlanRunResponse Resolved defaults and cost estimate.
16 fields
resolved_configResolvedRunConfigrequired29 child fields
rule_versionstringrequiredThe version of the rules that resolved the
autodefaults (auto@2); a config keeps resolving the same way.datasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredThe pinned dataset version.
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"modelstringrequiredThe base model trained.
template_revisionstringrequiredThe pinned chat template (
qwen3@3); evals of the run's checkpoints use it too.adapterobject or object or object or objectrequiredOne of 4 shapes
- object
kind"lora"required"lora"rankintegeralphaintegermerge_on_exportbooleantrain_multimodal_projectorbooleanAlso attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).
- object
kind"prefix_kv"required"prefix_kv"num_tokensinteger
- object
kind"frozen_head"required"frozen_head"
- object
kind"encoder_full"required"encoder_full"
- object
lrnumberrequiredThe resolved learning rate.
lr_sourcestringrequiredWhere
lrcame from: the calibrated rule (auto@2: calibrated for ... at batch 128, sqrt batch scaling) or the value you passed.batch_sizeintegerrequiredTraining examples per optimizer step.
epochsintegerrequiredPasses over the training split.
scheduleenumrequiredLearning-rate schedule after warmup.
"linear""cosine""constant"warmupnumberrequiredThe fraction of steps spent warming up the learning rate.
train_onenumrequiredWhich assistant turns are trained: the last one, or every one.
"last""all_assistant"thinkingenumrequiredThinking mode the records are rendered with.
"auto""on""off"preserve_thinkingbooleanrequiredWhether earlier assistant turns keep their reasoning in the prompt.
reductionenumrequiredHow the loss averages: per example, then across the batch, or per token.
"per_example""per_token"selectenumrequiredWhich checkpoint becomes the artifact: the best by the held-out metric, or the last.
"best""last"checkpoint_every_stepsintegerrequiredSteps between checkpoints.
eval_every_stepsintegerrequiredSteps between held-out evaluations.
optimizerOptimizerSpecrequired4 child fields
kind"adamw""adamw"betasarray of anyweight_decaynumbergrad_clipnumberMax global gradient norm; 0 disables clipping.
checkpoint_ttl_daysintegerrequiredDays an intermediate checkpoint is kept; the best and final never expire.
splitobjectrequired5 child fields
strategyenumrequired"by_session""by_group""random"eval_fractionnumberrequiredseedintegerrequiredtrain_recordsintegerrequiredeval_recordsintegerrequired
label_eval_idstringrequiredThe labeling eval whose answers the run trains on: router runs with a Judge/validator rubric, and off-policy distill runs (the teacher's answers).
base_artifactBaseArtifactrequiredContinued training: the artifact whose adapter the run starts from (recipe.model was an artifact reference).
recipe_paramsmap of anyrequiredThe recipe's own settings (router candidates, DPO
beta, a cartridge's context, ...).checkpoint_evalsarray of objectrecipe.evals, with the dataset version and rubric pinned.
5 child fields
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$datasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredrubricarray of EvalRubricItemrequired9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
limitintegerrequired
loggersarray of LoggerSpec
dataset_versionintegerrequiredThe dataset version the run would pin.
usable_recordsintegerrequiredRecords the recipe can train on (the rest are skipped; a warning says why).
total_recordsintegerrequiredRecords in the dataset version.
estimated_stepsintegerrequiredOptimizer steps the run would take.
estimated_tokensintegerrequiredTokens the run would process (billed tokens).
estimated_cost_usdnumberrequiredEverything the run is expected to bill: training (and teacher) tokens, plus the evals it starts (labeling, recipe.evals). See cost_breakdown.
estimated_duration_sintegerrequiredWall-clock estimate in seconds on one H100 80 GB: model load and export, training at the measured tokens/s for this base and recipe, evaluations and checkpoints. Excludes queueing and any labeling eval.
min_gpu_memory_gbnumberrequiredGPU memory (GB) this run needs: the base's min_gpu_memory_gb plus a teacher loaded beside it. Null when the base's requirement is unknown.
price_per_million_tokensnumberrequiredThe base model's price, USD per million tokens.
trained_token_fractionnumberrequiredThe share of tokens that are trained on (the loss mask), the rest being prompt context.
labelingobjectrequiredThe labeling eval that runs before training (billed as an eval, included in estimated_cost_usd): router runs with a Judge/validator rubric replay prompts against the candidates; off-policy distill runs have the teacher answer each prompt.
3 child fields
estimated_model_callsintegerrequiredestimated_judge_callsintegerrequiredestimated_cost_usdnumberrequired
teacherobjectrequiredOn-policy distill runs: the teacher's scoring tokens at the teacher's price (included in estimated_tokens as student-price tokens, and in estimated_cost_usd).
4 child fields
modelstringrequiredprice_per_million_tokensnumberrequiredestimated_tokensintegerrequiredestimated_cost_usdnumberrequired
cost_breakdownPlanCostBreakdownrequiredestimated_cost_usd split by what bills it; the parts sum to it (to rounding).
3 child fields
train_usdnumberrequiredThe base model's tokens on every training step: each record (or both sides of a preference pair) once per epoch, at price_per_million_tokens. Held-out evaluation during training is not billed.
teacher_usdnumberrequiredThe teacher's tokens (on-policy distill), at its price.
eval_usdnumberrequiredEvals the run starts, billed as evals: the labeling eval before training and recipe.evals on every checkpoint.
router_summaryRouterPlanSummaryPre-flight router data health summary (populated for router recipes; null otherwise).
warningsarray of stringrequired
from grad import Grad
from grad.recipes import SFTRecipe
client = Grad()
plan = client.runs.plan(
dataset="support-prod",
name="support-sft",
recipe=SFTRecipe(model="qwen/qwen3-8b"),
max_cost_usd=5,
)
print(plan) # steps, tokens, cost and warnings; nothing is billed{
"resolved_config": {
"rule_version": "auto@2",
"dataset": "support-prod",
"dataset_version": 1,
"name": "support-sft",
"recipe_kind": "sft",
"model": "qwen/qwen3-8b",
"template_revision": "qwen3@3",
"adapter": {
"kind": "lora",
"rank": 32,
"alpha": 32,
"merge_on_export": false,
"train_multimodal_projector": false
},
"lr": 0.000125,
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"batch_size": 8,
"epochs": 1,
"schedule": "linear",
"warmup": 0.03,
"train_on": "last",
"thinking": "auto",
"preserve_thinking": false,
"reduction": "per_example",
"select": "best",
"checkpoint_every_steps": 1,
"eval_every_steps": 1,
"optimizer": {
"kind": "adamw",
"betas": [
0.9,
0.95
],
"weight_decay": 0,
"grad_clip": 1
},
"checkpoint_ttl_days": 30,
"split": {
"strategy": "by_session",
"eval_fraction": 0.1,
"seed": 42,
"train_records": 1,
"eval_records": 0
},
"label_eval_id": null,
"base_artifact": null,
"recipe_params": {}
},
"dataset_version": 1,
"usable_records": 1,
"total_records": 1,
"estimated_steps": 1,
"estimated_tokens": 33,
"estimated_cost_usd": 0,
"estimated_duration_s": 97,
"min_gpu_memory_gb": 36,
"price_per_million_tokens": 0.4,
"trained_token_fraction": 0.4242,
"labeling": null,
"teacher": null,
"cost_breakdown": {
"train_usd": 0,
"teacher_usd": 0,
"eval_usd": 0
},
"router_summary": null,
"warnings": [
"The eval split is empty; eval metrics will be unavailable. Add records or raise split.eval_fraction.",
"Training thinking model 'qwen/qwen3-8b' with thinking='auto', but 0% of assistant turns contain <think> reasoning. Pass thinking='off' if non-thinking answers are intended, or verify your traces include <think>...</think> reasoning."
]
}Create and enqueue a training run#
POST/v1/runs
Pins the dataset version.
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body PlanRunRequest
datasetstringrequiredDataset to train on. The run pins its current version.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$namestringrequiredRun name; the artifact it produces is released as
name@version.Matches
^[a-z0-9][a-z0-9._-]{0,63}$recipeRecipeSpecrequired50 child fields
kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"modelstringadapterAdapterSpecOne of 3 shapes
- object
kind"lora"required"lora"rankintegeralphaintegermerge_on_exportbooleantrain_multimodal_projectorbooleanAlso attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).
- object
kind"prefix_kv"required"prefix_kv"num_tokensinteger
- object
kind"frozen_head"required"frozen_head"
- object
lr"auto" or numberOne of 2 shapes
- "auto"
- number
lr_scalenumberbatch_sizeintegerepochsintegerscheduleenum"linear""cosine""constant"warmupnumbertrain_onenumWhich assistant turns are trained (default 'last'; LLM recipes only).
"last""all_assistant"thinkingenumThinking mode for chat rendering (default 'auto'; LLM recipes only).
"auto""on""off"preserve_thinkingbooleanWhether earlier assistant turns keep their reasoning in the prompt (default false; LLM recipes only).
reductionenumDefault per_example (LLM recipes only).
"per_example""per_token"selectenum"best""last"checkpoint_ttl_daysintegerbetanumbermodelsarray of stringmax_quality_dropnumbercontext_textstringnum_tokensintegertempnumberteacherstringCartridgeRecipe and DistillRecipe: the model to learn from. DistillRecipe also takes an artifact (name@version) with rollout off_policy.
rolloutRolloutSpecDistillRecipe: on_policy (default) samples answers from the student and the trainer scores them with the teacher's top-k logits; off_policy has the teacher answer each prompt once through the inference endpoint and trains the student on those answers.
One of 2 shapes
- object
kind"on_policy"required"on_policy"max_new_tokens"auto" or integerLength of each student answer; auto (default) sizes it from the assistant turns in your records (256 without any).
One of 2 shapes
- "auto"
- integer
- object
kind"off_policy"required"off_policy"max_new_tokensinteger
- object
optimizerOptimizerSpec4 child fields
kind"adamw""adamw"betasarray of anyweight_decaynumbergrad_clipnumberMax global gradient norm; 0 disables clipping.
eval_every"auto" or integerOptimizer steps between held-out evaluations; auto = every 25% of the run, at most every 20 steps; each eval step is also a checkpoint.
One of 2 shapes
- "auto"
- integer
lossLossSpecOne of 5 shapes
- object
kind"cross_entropy"required"cross_entropy"reductionenum"per_example""per_token"
- object
kind"dpo"required"dpo"betanumber
- object
kind"infonce"required"infonce"tempnumber
- object
kind"top_k_kl_distill"required"top_k_kl_distill"top_kinteger
- object
kind"grpo"required"grpo"clip_lownumberclip_highnumber
- object
poolPoolingSpec1 child fields
kindenumrequired"mean""cls""last_token"
matryoshka_dimsarray of integerEmbeddingRecipe: Matryoshka Representation Learning truncation dimensions (e.g. [64, 128, 256, 512]).
query_prefixstringEmbeddingRecipe: text prepended to every query before tokenization.
doc_prefixstringEmbeddingRecipe: text prepended to every positive and negative document before tokenization.
max_seq_lenintegerEmbeddingRecipe: maximum token length per text (capped at the encoder's context window).
rubricstring or array of EvalRubricItemRouterRecipe: a score name on your records (scores[rubric]), or Judge/validator items: the server then replays each prompt against recipe.models and scores the answers in a labeling eval before training. RewardModelRecipe: a score name in [0, 1] on records ending in an assistant turn, trained pointwise next to the chosen/rejected pairs.
One of 2 shapes
- string
- array of EvalRubricItem
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
pricingmap of numberRouterRecipe: USD per request for each candidate; overrides metrics.cost_usd on your records.
fallbackstringRouterRecipe: the candidate that gets every request the router does not offload (default: the best-scoring candidate).
max_new_tokensintegerCartridgeRecipe: teacher answer length per prompt during distillation (default 256).
slot_tokenstringCartridgeRecipe: a reserved token that marks where the cartridge goes (default: the first reserved token that tokenizes atomically).
validatorenumGRPORecipe: built-in deterministic reward validator (default 'exact_match'; 'math' aliases 'math_equivalence', 'json_valid' aliases 'json').
"exact_match""contains""math""math_equivalence""final_number""choice""json""json_valid""non_empty""regex"validator_patternstringGRPORecipe: regular expression pattern used when validator is 'regex'.
system_promptstringGRPORecipe: optional system prompt prepended to every prompt before rollout generation.
group_sizeintegerGRPORecipe: completions sampled per prompt in each rollout group (default 8, min 2).
max_tokensintegerGRPORecipe: maximum generated tokens per sampled completion (default 1024).
temperaturenumberGRPORecipe: rollout sampling temperature in (0, 2] (default 1.0; top_p is fixed at 1.0 for exact importance sampling).
advantageenumGRPORecipe: group advantage estimator: 'group_std' (GRPO, default), 'dr_grpo' (mean-centered without std division), or 'rloo' (leave-one-out).
"group_std""dr_grpo""rloo"kl_coefnumberGRPORecipe: Schulman k3 KL penalty coefficient against initial/base weights (default 0.04; 0 disables KL).
clip_lownumberGRPORecipe: lower PPO/GRPO importance-ratio clip epsilon (default 0.2).
clip_highnumberGRPORecipe: upper PPO/GRPO importance-ratio clip epsilon (default 0.2; e.g. 0.28 for DAPO Clip-Higher).
skip_zero_varbooleanGRPORecipe: skip prompt groups whose rollout rewards have near-zero variance (default true).
max_stepsintegerGRPORecipe: optional maximum number of optimizer steps (caps epochs * steps_per_epoch).
evalsarray of RecipeEvalExtra evals on each checkpoint during training (the eval executor, billed like any eval). Results are in run.checkpoint_evals, the run's checkpoint_eval events and eval_report.checkpoint_evals.
5 child fields
datasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$versionintegerDataset version (default: the current one, pinned at plan time).
rubricarray of EvalRubricItemJudges, regexes and validators (default: the dataset's own rubric, such as a benchmark's answer check). Code scorers can't run during training.
9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
limitintegerEvaluate the first N tasks at each checkpoint.
namestringName of this eval in the report (default: the dataset name).
Matches
^[a-z0-9][a-z0-9._-]{0,63}$
loggersarray of LoggerSpecExperiment trackers that receive the run's metrics. A tracker that fails is reported and dropped; it never fails the run.
splitSplitSpec3 child fields
strategyenum"by_session""by_group""random"eval_fractionnumberseedinteger
max_cost_usdnumberHard spend cap in USD. The run stops with
stopped_budgetand keeps its checkpoint when it reaches the cap, and is never billed past it. Default: no cap.
Returns
202 Run Enqueued training run.
35 fields
idstringrequiredRun id (
run_and 24 hex characters).workspace_idstringrequirednamestringrequiredRun name; its artifact is released as
name@version.Matches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_idstringrequiredId of the dataset trained on.
dataset_namestringrequiredName of the dataset trained on.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredThe dataset version the run pinned when it was created.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"statusRunStatusrequiredstopped_budget: the run reached its max_cost_usd (resume with a higher cap). stopped_balance: the workspace ran out of balance on Cloud (top up, then resume; the cap is unchanged). Both keep their checkpoints.
"queued""running""completed""failed""cancelled""stopped_budget""stopped_balance"resolved_configResolvedRunConfigrequired29 child fields
rule_versionstringrequiredThe version of the rules that resolved the
autodefaults (auto@2); a config keeps resolving the same way.datasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredThe pinned dataset version.
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"modelstringrequiredThe base model trained.
template_revisionstringrequiredThe pinned chat template (
qwen3@3); evals of the run's checkpoints use it too.adapterobject or object or object or objectrequiredOne of 4 shapes
- object
kind"lora"required"lora"rankintegeralphaintegermerge_on_exportbooleantrain_multimodal_projectorbooleanAlso attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).
- object
kind"prefix_kv"required"prefix_kv"num_tokensinteger
- object
kind"frozen_head"required"frozen_head"
- object
kind"encoder_full"required"encoder_full"
- object
lrnumberrequiredThe resolved learning rate.
lr_sourcestringrequiredWhere
lrcame from: the calibrated rule (auto@2: calibrated for ... at batch 128, sqrt batch scaling) or the value you passed.batch_sizeintegerrequiredTraining examples per optimizer step.
epochsintegerrequiredPasses over the training split.
scheduleenumrequiredLearning-rate schedule after warmup.
"linear""cosine""constant"warmupnumberrequiredThe fraction of steps spent warming up the learning rate.
train_onenumrequiredWhich assistant turns are trained: the last one, or every one.
"last""all_assistant"thinkingenumrequiredThinking mode the records are rendered with.
"auto""on""off"preserve_thinkingbooleanrequiredWhether earlier assistant turns keep their reasoning in the prompt.
reductionenumrequiredHow the loss averages: per example, then across the batch, or per token.
"per_example""per_token"selectenumrequiredWhich checkpoint becomes the artifact: the best by the held-out metric, or the last.
"best""last"checkpoint_every_stepsintegerrequiredSteps between checkpoints.
eval_every_stepsintegerrequiredSteps between held-out evaluations.
optimizerOptimizerSpecrequired4 child fields
kind"adamw""adamw"betasarray of anyweight_decaynumbergrad_clipnumberMax global gradient norm; 0 disables clipping.
checkpoint_ttl_daysintegerrequiredDays an intermediate checkpoint is kept; the best and final never expire.
splitobjectrequired5 child fields
strategyenumrequired"by_session""by_group""random"eval_fractionnumberrequiredseedintegerrequiredtrain_recordsintegerrequiredeval_recordsintegerrequired
label_eval_idstringrequiredThe labeling eval whose answers the run trains on: router runs with a Judge/validator rubric, and off-policy distill runs (the teacher's answers).
base_artifactBaseArtifactrequiredContinued training: the artifact whose adapter the run starts from (recipe.model was an artifact reference).
recipe_paramsmap of anyrequiredThe recipe's own settings (router candidates, DPO
beta, a cartridge's context, ...).checkpoint_evalsarray of objectrecipe.evals, with the dataset version and rubric pinned.
5 child fields
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$datasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredrubricarray of EvalRubricItemrequired9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
limitintegerrequired
loggersarray of LoggerSpec
max_cost_usdnumberrequiredHard spend cap in USD (null: none). The run is never billed past it.
price_per_million_tokensnumberrequiredUSD per million tokens processed, fixed when the run was created.
tokens_processedintegerrequiredTraining tokens processed so far, over every attempt.
cost_usdnumberrequiredCost of the tokens processed so far, in USD. It counts the whole step that crossed max_cost_usd; billing stops at the cap.
current_stepintegerrequiredLast optimizer step reported.
total_stepsintegerrequiredPlanned optimizer steps.
attemptintegerrequiredAttempts started so far (every start on a worker counts, including ones whose GPU was reclaimed).
max_attemptsintegerrequiredThe run fails once this many attempts end without a result (lost worker, worker error, OOM). Attempts whose GPU was reclaimed don't count toward it.
phaseenumrequiredWhat the run is doing now; null once it has finished (finished_at is set). A cancelled run whose worker hasn't stopped yet reads stopping. The run's events keep every phase it went through.
"queued""waiting_for_compute""starting""loading_model""training""evaluating""checkpointing""uploading""completing""stopping"nullphase_sincestring (date-time)requiredWhen the run entered its phase; null with phase.
last_interruptionRunInterruptionrequiredworkers_onlineintegerrequiredWhile queued: workers of this kind holding a lease (all busy). Null otherwise.
autoscalingbooleanrequiredWhile queued: true when workers scale from zero (KEDA), so a worker is starting. Null otherwise.
queue_positionintegerrequiredWhile queued for a worker: about how many runs start before this one. Claims are fair across workspaces (the workspace with the fewest running runs goes next), so this counts other workspaces' runs too. Approximate; null otherwise.
queue_messagestringrequiredWhile queued for a worker: why it waits, ready to show: "Queued behind 3 runs", "Queued: workspace concurrency limit (8 running)" (the workspace runs as many as it may at once), or "Waiting for a GPU with ≥46 GB; online workers have 24 GB". Null when it is next in line, and once it is claimed.
min_gpu_memory_gbnumberrequiredGPU memory (GB) the run needs (its plan's min_gpu_memory_gb): only workers with at least this much claim it. Null when unknown.
latest_metricMetricPointrequiredeval_reportEvalReportrequiredcheckpoint_evalsarray of CheckpointEvalResultrequiredrecipe.evals results, one per finished eval: a checkpoint (step) on a dataset.
10 child fields
namestringrequiredstepintegerrequiredcheckpoint_idstringrequiredeval_idstringrequireddatasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredstatusenumrequired"completed""failed""cancelled"scorenumberrequiredThe checkpoint's overall rubric score (null unless completed).
cost_usdnumberrequirederrorstringrequired
artifact_idstringrequiredThe released artifact (
name@version) once the run completes; null before.errorstringrequiredWhy the run failed or stopped; null otherwise.
created_atstring (date-time)requiredWhen the run was created.
updated_atstring (date-time)requiredWhen the run last changed.
finished_atstring (date-time)requiredWhen the run reached a final status; null while it is queued or running.
warningsarray of stringOnly on the response that created the run (POST /v1/runs): the plan's warnings, such as another queued or running run with the same name. They're also the run's first warning events.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
from grad.recipes import SFTRecipe
client = Grad()
run = client.runs.create(
dataset="support-prod",
name="support-sft",
recipe=SFTRecipe(model="qwen/qwen3-8b"),
max_cost_usd=5,
)
run.wait() # streams progress; raises if the run fails{
"id": "run_ed1c235f0c631d8f209e22a5",
"workspace_id": "ws_e2e",
"name": "support-sft",
"dataset_id": "ds_c66d7ad841f251049ca0e550",
"dataset_name": "support-prod",
"dataset_version": 1,
"recipe_kind": "sft",
"status": "queued",
"resolved_config": {
"lr": 0.000125,
"name": "support-sft",
"model": "qwen/qwen3-8b",
"split": {
"seed": 42,
"strategy": "by_session",
"eval_records": 0,
"eval_fraction": 0.1,
"train_records": 1
},
"epochs": 1,
"select": "best",
"warmup": 0.03,
"adapter": {
"kind": "lora",
"rank": 32,
"alpha": 32,
"merge_on_export": false,
"train_multimodal_projector": false
},
"dataset": "support-prod",
"schedule": "linear",
"thinking": "auto",
"train_on": "last",
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"optimizer": {
"kind": "adamw",
"betas": [
0.9,
0.95
],
"grad_clip": 1,
"weight_decay": 0
},
"reduction": "per_example",
"batch_size": 8,
"recipe_kind": "sft",
"rule_version": "auto@2",
"base_artifact": null,
"label_eval_id": null,
"recipe_params": {},
"dataset_version": 1,
"eval_every_steps": 1,
"preserve_thinking": false,
"template_revision": "qwen3@3",
"checkpoint_ttl_days": 30,
"checkpoint_every_steps": 1
},
"max_cost_usd": 5,
"price_per_million_tokens": 0.4,
"tokens_processed": 0,
"cost_usd": 0,
"current_step": 0,
"total_steps": 1,
"attempt": 0,
"max_attempts": 10,
"phase": "queued",
"phase_since": "2026-12-02T15:48:59.895Z",
"last_interruption": null,
"workers_online": 0,
"autoscaling": false,
"queue_position": 0,
"queue_message": null,
"min_gpu_memory_gb": 36,
"latest_metric": null,
"eval_report": null,
"checkpoint_evals": [],
"artifact_id": null,
"error": null,
"created_at": "2026-12-02T15:48:59.888Z",
"updated_at": "2026-12-02T15:48:59.888Z",
"finished_at": null,
"warnings": [
"The eval split is empty; eval metrics will be unavailable. Add records or raise split.eval_fraction.",
"Training thinking model 'qwen/qwen3-8b' with thinking='auto', but 0% of assistant turns contain <think> reasoning. Pass thinking='off' if non-thinking answers are intended, or verify your traces include <think>...</think> reasoning."
]
}List training runs#
GET/v1/runs
Newest first.
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstringstatusstringOnly these statuses, comma-separated: queued, running, completed, failed, cancelled, stopped_budget, stopped_balance.
qstringOnly items whose name contains this text (any case), or whose id is exactly this.
Returns
200 object Training runs.
2 fields
dataarray of Runrequired35 child fields
idstringrequiredRun id (
run_and 24 hex characters).workspace_idstringrequirednamestringrequiredRun name; its artifact is released as
name@version.Matches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_idstringrequiredId of the dataset trained on.
dataset_namestringrequiredName of the dataset trained on.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredThe dataset version the run pinned when it was created.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"statusRunStatusrequiredstopped_budget: the run reached its max_cost_usd (resume with a higher cap). stopped_balance: the workspace ran out of balance on Cloud (top up, then resume; the cap is unchanged). Both keep their checkpoints.
"queued""running""completed""failed""cancelled""stopped_budget""stopped_balance"resolved_configResolvedRunConfigrequired29 child fields
rule_versionstringrequiredThe version of the rules that resolved the
autodefaults (auto@2); a config keeps resolving the same way.datasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredThe pinned dataset version.
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"modelstringrequiredThe base model trained.
template_revisionstringrequiredThe pinned chat template (
qwen3@3); evals of the run's checkpoints use it too.adapterobject or object or object or objectrequiredOne of 4 shapes
- object
kind"lora"required"lora"rankintegeralphaintegermerge_on_exportbooleantrain_multimodal_projectorbooleanAlso attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).
- object
kind"prefix_kv"required"prefix_kv"num_tokensinteger
- object
kind"frozen_head"required"frozen_head"
- object
kind"encoder_full"required"encoder_full"
- object
lrnumberrequiredThe resolved learning rate.
lr_sourcestringrequiredWhere
lrcame from: the calibrated rule (auto@2: calibrated for ... at batch 128, sqrt batch scaling) or the value you passed.batch_sizeintegerrequiredTraining examples per optimizer step.
epochsintegerrequiredPasses over the training split.
scheduleenumrequiredLearning-rate schedule after warmup.
"linear""cosine""constant"warmupnumberrequiredThe fraction of steps spent warming up the learning rate.
train_onenumrequiredWhich assistant turns are trained: the last one, or every one.
"last""all_assistant"thinkingenumrequiredThinking mode the records are rendered with.
"auto""on""off"preserve_thinkingbooleanrequiredWhether earlier assistant turns keep their reasoning in the prompt.
reductionenumrequiredHow the loss averages: per example, then across the batch, or per token.
"per_example""per_token"selectenumrequiredWhich checkpoint becomes the artifact: the best by the held-out metric, or the last.
"best""last"checkpoint_every_stepsintegerrequiredSteps between checkpoints.
eval_every_stepsintegerrequiredSteps between held-out evaluations.
optimizerOptimizerSpecrequired4 child fields
kind"adamw""adamw"betasarray of anyweight_decaynumbergrad_clipnumberMax global gradient norm; 0 disables clipping.
checkpoint_ttl_daysintegerrequiredDays an intermediate checkpoint is kept; the best and final never expire.
splitobjectrequired5 child fields
strategyenumrequired"by_session""by_group""random"eval_fractionnumberrequiredseedintegerrequiredtrain_recordsintegerrequiredeval_recordsintegerrequired
label_eval_idstringrequiredThe labeling eval whose answers the run trains on: router runs with a Judge/validator rubric, and off-policy distill runs (the teacher's answers).
base_artifactBaseArtifactrequiredContinued training: the artifact whose adapter the run starts from (recipe.model was an artifact reference).
recipe_paramsmap of anyrequiredThe recipe's own settings (router candidates, DPO
beta, a cartridge's context, ...).checkpoint_evalsarray of objectrecipe.evals, with the dataset version and rubric pinned.
5 child fields
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$datasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredrubricarray of EvalRubricItemrequired9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
limitintegerrequired
loggersarray of LoggerSpec
max_cost_usdnumberrequiredHard spend cap in USD (null: none). The run is never billed past it.
price_per_million_tokensnumberrequiredUSD per million tokens processed, fixed when the run was created.
tokens_processedintegerrequiredTraining tokens processed so far, over every attempt.
cost_usdnumberrequiredCost of the tokens processed so far, in USD. It counts the whole step that crossed max_cost_usd; billing stops at the cap.
current_stepintegerrequiredLast optimizer step reported.
total_stepsintegerrequiredPlanned optimizer steps.
attemptintegerrequiredAttempts started so far (every start on a worker counts, including ones whose GPU was reclaimed).
max_attemptsintegerrequiredThe run fails once this many attempts end without a result (lost worker, worker error, OOM). Attempts whose GPU was reclaimed don't count toward it.
phaseenumrequiredWhat the run is doing now; null once it has finished (finished_at is set). A cancelled run whose worker hasn't stopped yet reads stopping. The run's events keep every phase it went through.
"queued""waiting_for_compute""starting""loading_model""training""evaluating""checkpointing""uploading""completing""stopping"nullphase_sincestring (date-time)requiredWhen the run entered its phase; null with phase.
last_interruptionRunInterruptionrequiredworkers_onlineintegerrequiredWhile queued: workers of this kind holding a lease (all busy). Null otherwise.
autoscalingbooleanrequiredWhile queued: true when workers scale from zero (KEDA), so a worker is starting. Null otherwise.
queue_positionintegerrequiredWhile queued for a worker: about how many runs start before this one. Claims are fair across workspaces (the workspace with the fewest running runs goes next), so this counts other workspaces' runs too. Approximate; null otherwise.
queue_messagestringrequiredWhile queued for a worker: why it waits, ready to show: "Queued behind 3 runs", "Queued: workspace concurrency limit (8 running)" (the workspace runs as many as it may at once), or "Waiting for a GPU with ≥46 GB; online workers have 24 GB". Null when it is next in line, and once it is claimed.
min_gpu_memory_gbnumberrequiredGPU memory (GB) the run needs (its plan's min_gpu_memory_gb): only workers with at least this much claim it. Null when unknown.
latest_metricMetricPointrequiredeval_reportEvalReportrequiredcheckpoint_evalsarray of CheckpointEvalResultrequiredrecipe.evals results, one per finished eval: a checkpoint (step) on a dataset.
10 child fields
namestringrequiredstepintegerrequiredcheckpoint_idstringrequiredeval_idstringrequireddatasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredstatusenumrequired"completed""failed""cancelled"scorenumberrequiredThe checkpoint's overall rubric score (null unless completed).
cost_usdnumberrequirederrorstringrequired
artifact_idstringrequiredThe released artifact (
name@version) once the run completes; null before.errorstringrequiredWhy the run failed or stopped; null otherwise.
created_atstring (date-time)requiredWhen the run was created.
updated_atstring (date-time)requiredWhen the run last changed.
finished_atstring (date-time)requiredWhen the run reached a final status; null while it is queued or running.
warningsarray of stringOnly on the response that created the run (POST /v1/runs): the plan's warnings, such as another queued or running run with the same name. They're also the run's first warning events.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
for run in client.runs.list(status=["failed", "cancelled"], search="support"):
print(run.id, run.name, run.status){
"data": [
{
"id": "run_ed1c235f0c631d8f209e22a5",
"workspace_id": "ws_e2e",
"name": "support-sft",
"dataset_id": "ds_c66d7ad841f251049ca0e550",
"dataset_name": "support-prod",
"dataset_version": 1,
"recipe_kind": "sft",
"status": "completed",
"resolved_config": {
"lr": 0.000125,
"name": "support-sft",
"model": "qwen/qwen3-8b",
"split": {
"seed": 42,
"strategy": "by_session",
"eval_records": 0,
"eval_fraction": 0.1,
"train_records": 1
},
"epochs": 1,
"select": "best",
"warmup": 0.03,
"adapter": {
"kind": "lora",
"rank": 32,
"alpha": 32,
"merge_on_export": false,
"train_multimodal_projector": false
},
"dataset": "support-prod",
"schedule": "linear",
"thinking": "auto",
"train_on": "last",
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"optimizer": {
"kind": "adamw",
"betas": [
0.9,
0.95
],
"grad_clip": 1,
"weight_decay": 0
},
"reduction": "per_example",
"batch_size": 8,
"recipe_kind": "sft",
"rule_version": "auto@2",
"base_artifact": null,
"label_eval_id": null,
"recipe_params": {},
"dataset_version": 1,
"eval_every_steps": 1,
"preserve_thinking": false,
"template_revision": "qwen3@3",
"checkpoint_ttl_days": 30,
"checkpoint_every_steps": 1
},
"max_cost_usd": 5,
"price_per_million_tokens": 0.4,
"tokens_processed": 21,
"cost_usd": 0.000008,
"current_step": 1,
"total_steps": 1,
"attempt": 1,
"max_attempts": 10,
"phase": null,
"phase_since": null,
"last_interruption": null,
"workers_online": null,
"autoscaling": null,
"queue_position": null,
"queue_message": null,
"min_gpu_memory_gb": 36,
"latest_metric": {
"lr": 0.000125,
"seq": 13,
"loss": 0.6931471805599453,
"step": 1,
"epoch": 0,
"tokens": 21,
"attempt": 1,
"cost_usd": 0.000008,
"grad_norm": 0.7071067811865476,
"timestamp": "2026-12-02T15:49:00.078009Z",
"tokens_per_sec": 254684.0341332008
},
"eval_report": {
"warnings": [
"Reference test backend: the base model was not trained; the artifact is not deployable.",
"No held-out examples: eval metrics are null and select='last' was used."
],
"best_step": null,
"eval_loss": null,
"final_step": 1,
"metric_mode": "min",
"metric_name": "eval_loss",
"eval_records": 0,
"eval_examples": 0,
"selected_step": 1,
"train_records": 1,
"train_examples": 1,
"reference_backend": true
},
"checkpoint_evals": [],
"artifact_id": "support-sft@2026-12-02-1",
"error": null,
"created_at": "2026-12-02T15:48:59.888Z",
"updated_at": "2026-12-02T15:49:00.207Z",
"finished_at": "2026-12-02T15:49:00.191Z"
}
],
"next_cursor": null
}Count the workspace's runs per status#
GET/v1/runs/counts
One count per status (the web console's status tabs), narrowed by q like GET /v1/runs.
Query parameters
qstringOnly items whose name contains this text (any case), or whose id is exactly this.
Returns
200 RunCounts Runs per status.
2 fields
totalintegerrequiredby_statusobjectrequiredRuns per status (0 when none).
7 child fields
queuedintegerrequiredrunningintegerrequiredcompletedintegerrequiredfailedintegerrequiredcancelledintegerrequiredstopped_budgetintegerrequiredstopped_balanceintegerrequired
from grad import Grad
client = Grad()
counts = client.runs.counts(search="support")
print(counts["total"], counts["by_status"]["running"]){
"total": 1,
"by_status": {
"queued": 0,
"running": 0,
"completed": 1,
"failed": 0,
"cancelled": 0,
"stopped_budget": 0,
"stopped_balance": 0
}
}Get a training run#
GET/v1/runs/{id}
Path parameters
idstringrequired
Returns
200 Run Training run.
35 fields
idstringrequiredRun id (
run_and 24 hex characters).workspace_idstringrequirednamestringrequiredRun name; its artifact is released as
name@version.Matches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_idstringrequiredId of the dataset trained on.
dataset_namestringrequiredName of the dataset trained on.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredThe dataset version the run pinned when it was created.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"statusRunStatusrequiredstopped_budget: the run reached its max_cost_usd (resume with a higher cap). stopped_balance: the workspace ran out of balance on Cloud (top up, then resume; the cap is unchanged). Both keep their checkpoints.
"queued""running""completed""failed""cancelled""stopped_budget""stopped_balance"resolved_configResolvedRunConfigrequired29 child fields
rule_versionstringrequiredThe version of the rules that resolved the
autodefaults (auto@2); a config keeps resolving the same way.datasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredThe pinned dataset version.
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"modelstringrequiredThe base model trained.
template_revisionstringrequiredThe pinned chat template (
qwen3@3); evals of the run's checkpoints use it too.adapterobject or object or object or objectrequiredOne of 4 shapes
- object
kind"lora"required"lora"rankintegeralphaintegermerge_on_exportbooleantrain_multimodal_projectorbooleanAlso attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).
- object
kind"prefix_kv"required"prefix_kv"num_tokensinteger
- object
kind"frozen_head"required"frozen_head"
- object
kind"encoder_full"required"encoder_full"
- object
lrnumberrequiredThe resolved learning rate.
lr_sourcestringrequiredWhere
lrcame from: the calibrated rule (auto@2: calibrated for ... at batch 128, sqrt batch scaling) or the value you passed.batch_sizeintegerrequiredTraining examples per optimizer step.
epochsintegerrequiredPasses over the training split.
scheduleenumrequiredLearning-rate schedule after warmup.
"linear""cosine""constant"warmupnumberrequiredThe fraction of steps spent warming up the learning rate.
train_onenumrequiredWhich assistant turns are trained: the last one, or every one.
"last""all_assistant"thinkingenumrequiredThinking mode the records are rendered with.
"auto""on""off"preserve_thinkingbooleanrequiredWhether earlier assistant turns keep their reasoning in the prompt.
reductionenumrequiredHow the loss averages: per example, then across the batch, or per token.
"per_example""per_token"selectenumrequiredWhich checkpoint becomes the artifact: the best by the held-out metric, or the last.
"best""last"checkpoint_every_stepsintegerrequiredSteps between checkpoints.
eval_every_stepsintegerrequiredSteps between held-out evaluations.
optimizerOptimizerSpecrequired4 child fields
kind"adamw""adamw"betasarray of anyweight_decaynumbergrad_clipnumberMax global gradient norm; 0 disables clipping.
checkpoint_ttl_daysintegerrequiredDays an intermediate checkpoint is kept; the best and final never expire.
splitobjectrequired5 child fields
strategyenumrequired"by_session""by_group""random"eval_fractionnumberrequiredseedintegerrequiredtrain_recordsintegerrequiredeval_recordsintegerrequired
label_eval_idstringrequiredThe labeling eval whose answers the run trains on: router runs with a Judge/validator rubric, and off-policy distill runs (the teacher's answers).
base_artifactBaseArtifactrequiredContinued training: the artifact whose adapter the run starts from (recipe.model was an artifact reference).
recipe_paramsmap of anyrequiredThe recipe's own settings (router candidates, DPO
beta, a cartridge's context, ...).checkpoint_evalsarray of objectrecipe.evals, with the dataset version and rubric pinned.
5 child fields
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$datasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredrubricarray of EvalRubricItemrequired9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
limitintegerrequired
loggersarray of LoggerSpec
max_cost_usdnumberrequiredHard spend cap in USD (null: none). The run is never billed past it.
price_per_million_tokensnumberrequiredUSD per million tokens processed, fixed when the run was created.
tokens_processedintegerrequiredTraining tokens processed so far, over every attempt.
cost_usdnumberrequiredCost of the tokens processed so far, in USD. It counts the whole step that crossed max_cost_usd; billing stops at the cap.
current_stepintegerrequiredLast optimizer step reported.
total_stepsintegerrequiredPlanned optimizer steps.
attemptintegerrequiredAttempts started so far (every start on a worker counts, including ones whose GPU was reclaimed).
max_attemptsintegerrequiredThe run fails once this many attempts end without a result (lost worker, worker error, OOM). Attempts whose GPU was reclaimed don't count toward it.
phaseenumrequiredWhat the run is doing now; null once it has finished (finished_at is set). A cancelled run whose worker hasn't stopped yet reads stopping. The run's events keep every phase it went through.
"queued""waiting_for_compute""starting""loading_model""training""evaluating""checkpointing""uploading""completing""stopping"nullphase_sincestring (date-time)requiredWhen the run entered its phase; null with phase.
last_interruptionRunInterruptionrequiredworkers_onlineintegerrequiredWhile queued: workers of this kind holding a lease (all busy). Null otherwise.
autoscalingbooleanrequiredWhile queued: true when workers scale from zero (KEDA), so a worker is starting. Null otherwise.
queue_positionintegerrequiredWhile queued for a worker: about how many runs start before this one. Claims are fair across workspaces (the workspace with the fewest running runs goes next), so this counts other workspaces' runs too. Approximate; null otherwise.
queue_messagestringrequiredWhile queued for a worker: why it waits, ready to show: "Queued behind 3 runs", "Queued: workspace concurrency limit (8 running)" (the workspace runs as many as it may at once), or "Waiting for a GPU with ≥46 GB; online workers have 24 GB". Null when it is next in line, and once it is claimed.
min_gpu_memory_gbnumberrequiredGPU memory (GB) the run needs (its plan's min_gpu_memory_gb): only workers with at least this much claim it. Null when unknown.
latest_metricMetricPointrequiredeval_reportEvalReportrequiredcheckpoint_evalsarray of CheckpointEvalResultrequiredrecipe.evals results, one per finished eval: a checkpoint (step) on a dataset.
10 child fields
namestringrequiredstepintegerrequiredcheckpoint_idstringrequiredeval_idstringrequireddatasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredstatusenumrequired"completed""failed""cancelled"scorenumberrequiredThe checkpoint's overall rubric score (null unless completed).
cost_usdnumberrequirederrorstringrequired
artifact_idstringrequiredThe released artifact (
name@version) once the run completes; null before.errorstringrequiredWhy the run failed or stopped; null otherwise.
created_atstring (date-time)requiredWhen the run was created.
updated_atstring (date-time)requiredWhen the run last changed.
finished_atstring (date-time)requiredWhen the run reached a final status; null while it is queued or running.
warningsarray of stringOnly on the response that created the run (POST /v1/runs): the plan's warnings, such as another queued or running run with the same name. They're also the run's first warning events.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
run = client.runs.get("run_3f9c0a1b2c3d4e5f60718293")
print(run.status, run.cost_usd){
"id": "run_ed1c235f0c631d8f209e22a5",
"workspace_id": "ws_e2e",
"name": "support-sft",
"dataset_id": "ds_c66d7ad841f251049ca0e550",
"dataset_name": "support-prod",
"dataset_version": 1,
"recipe_kind": "sft",
"status": "completed",
"resolved_config": {
"lr": 0.000125,
"name": "support-sft",
"model": "qwen/qwen3-8b",
"split": {
"seed": 42,
"strategy": "by_session",
"eval_records": 0,
"eval_fraction": 0.1,
"train_records": 1
},
"epochs": 1,
"select": "best",
"warmup": 0.03,
"adapter": {
"kind": "lora",
"rank": 32,
"alpha": 32,
"merge_on_export": false,
"train_multimodal_projector": false
},
"dataset": "support-prod",
"schedule": "linear",
"thinking": "auto",
"train_on": "last",
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"optimizer": {
"kind": "adamw",
"betas": [
0.9,
0.95
],
"grad_clip": 1,
"weight_decay": 0
},
"reduction": "per_example",
"batch_size": 8,
"recipe_kind": "sft",
"rule_version": "auto@2",
"base_artifact": null,
"label_eval_id": null,
"recipe_params": {},
"dataset_version": 1,
"eval_every_steps": 1,
"preserve_thinking": false,
"template_revision": "qwen3@3",
"checkpoint_ttl_days": 30,
"checkpoint_every_steps": 1
},
"max_cost_usd": 5,
"price_per_million_tokens": 0.4,
"tokens_processed": 21,
"cost_usd": 0.000008,
"current_step": 1,
"total_steps": 1,
"attempt": 1,
"max_attempts": 10,
"phase": null,
"phase_since": null,
"last_interruption": null,
"workers_online": null,
"autoscaling": null,
"queue_position": null,
"queue_message": null,
"min_gpu_memory_gb": 36,
"latest_metric": {
"lr": 0.000125,
"seq": 13,
"loss": 0.6931471805599453,
"step": 1,
"epoch": 0,
"tokens": 21,
"attempt": 1,
"cost_usd": 0.000008,
"grad_norm": 0.7071067811865476,
"timestamp": "2026-12-02T15:49:00.078009Z",
"tokens_per_sec": 254684.0341332008
},
"eval_report": {
"warnings": [
"Reference test backend: the base model was not trained; the artifact is not deployable.",
"No held-out examples: eval metrics are null and select='last' was used."
],
"best_step": null,
"eval_loss": null,
"final_step": 1,
"metric_mode": "min",
"metric_name": "eval_loss",
"eval_records": 0,
"eval_examples": 0,
"selected_step": 1,
"train_records": 1,
"train_examples": 1,
"reference_backend": true
},
"checkpoint_evals": [],
"artifact_id": "support-sft@2026-12-02-1",
"error": null,
"created_at": "2026-12-02T15:48:59.888Z",
"updated_at": "2026-12-02T15:49:00.207Z",
"finished_at": "2026-12-02T15:49:00.191Z"
}Training step metrics as JSON pages#
GET/v1/runs/{id}/metrics
next_cursor pages through the points written so far (null on the last page, like every list), and tail_cursor polls for points written later. To follow a run live, stream its events (GET /v1/runs/{id}/events, metric events).
Path parameters
idstringrequired
Query parameters
cursorstringafter_stepintegerlimitintegerPage size (default 1000). Values above 5000 are clamped to 5000.
max_pointsintegerReturn the whole curve after
cursoras one page, thinned to at most this many points spaced evenly from the newest (plus as many eval points, thinned the same way). Points a resumed attempt replayed are left out, so steps only increase.limitis ignored andnext_cursoris null. Compare runs or draw a long run without paging every point.
Returns
200 MetricsPage Metric points.
5 fields
run_idstringrequiredstatusRunStatusrequiredstopped_budget: the run reached its max_cost_usd (resume with a higher cap). stopped_balance: the workspace ran out of balance on Cloud (top up, then resume; the cap is unchanged). Both keep their checkpoints.
"queued""running""completed""failed""cancelled""stopped_budget""stopped_balance"dataarray of MetricPointrequired12 child fields
seqintegerrequiredattemptintegerrequiredstepintegerrequiredlossnumberrequiredeval_lossnumbereval_metricsmap of numberHeld-out metrics of an eval step by name (including the recipe's selection metric, eval_report.metric_name); absent on steps without an eval.
grad_normnumberlrnumbertokens_per_secnumbertokensintegerrequiredcost_usdnumberrequiredtimestampstring (date-time)required
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).tail_cursorstringrequiredCursor after the newest point returned so far; pass it back as
cursorto poll for points written later (tailing a running run).
from grad import Grad
client = Grad()
for point in client.runs.metrics("run_3f9c0a1b2c3d4e5f60718293"):
print(point.step, point.loss, point.eval_loss){
"run_id": "run_ed1c235f0c631d8f209e22a5",
"status": "completed",
"data": [
{
"lr": 0.000125,
"loss": 0.6931471805599453,
"step": 1,
"epoch": 0,
"tokens": 21,
"cost_usd": 0.000008,
"grad_norm": 0.7071067811865476,
"timestamp": "2026-12-02T15:49:00.078009Z",
"tokens_per_sec": 254684.0341332008,
"seq": 13,
"attempt": 1
}
],
"next_cursor": null,
"tail_cursor": "WzEzXQ"
}A run's lifecycle events#
GET/v1/runs/{id}/events
Phases, metrics, checkpoints, attempts, warnings, logs.
Every event is a RunEvent discriminated by type; a terminal run's stream ends with one completed event. With Accept: text/event-stream the response is a Server-Sent Events stream: the SSE event name is the event's type and its id is seq (none on completed); reconnect with Last-Event-ID to resume. Otherwise returns a JSON page: next_cursor pages through the events written so far, tail_cursor polls for later ones.
Path parameters
idstringrequired
Query parameters
cursorstringlimitintegerPage size (default 1000). Values above 5000 are clamped to 5000.
Returns
200 RunEventsPage Run events.
5 fields
run_idstringrequiredstatusRunStatusrequiredstopped_budget: the run reached its max_cost_usd (resume with a higher cap). stopped_balance: the workspace ran out of balance on Cloud (top up, then resume; the cap is unchanged). Both keep their checkpoints.
"queued""running""completed""failed""cancelled""stopped_budget""stopped_balance"dataarray of RunEventrequirednext_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).tail_cursorstringrequiredCursor after the newest event returned so far; pass it back as
cursorto poll for later events.
from grad import Grad
client = Grad()
for event in client.runs.events("run_3f9c0a1b2c3d4e5f60718293", follow=True):
print(event.type, event){
"run_id": "run_ed1c235f0c631d8f209e22a5",
"status": "completed",
"data": [
{
"type": "phase",
"run_id": "run_ed1c235f0c631d8f209e22a5",
"seq": 1,
"attempt": 1,
"timestamp": "2026-12-02T15:48:59.895Z",
"phase": "queued",
"step": 0,
"workers_online": 0,
"autoscaling": false,
"queue_position": 0,
"message": null,
"gpu": null
},
{
"type": "warning",
"run_id": "run_ed1c235f0c631d8f209e22a5",
"seq": 2,
"attempt": 1,
"timestamp": "2026-12-02T15:48:59.896Z",
"step": null,
"message": "The eval split is empty; eval metrics will be unavailable. Add records or raise split.eval_fraction."
}
],
"next_cursor": null,
"tail_cursor": "WzIxXQ"
}Cancel a training run#
POST/v1/runs/{id}/cancel
A running attempt is stopped and billed.
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Returns
200 Run Cancelled training run.
35 fields
idstringrequiredRun id (
run_and 24 hex characters).workspace_idstringrequirednamestringrequiredRun name; its artifact is released as
name@version.Matches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_idstringrequiredId of the dataset trained on.
dataset_namestringrequiredName of the dataset trained on.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredThe dataset version the run pinned when it was created.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"statusRunStatusrequiredstopped_budget: the run reached its max_cost_usd (resume with a higher cap). stopped_balance: the workspace ran out of balance on Cloud (top up, then resume; the cap is unchanged). Both keep their checkpoints.
"queued""running""completed""failed""cancelled""stopped_budget""stopped_balance"resolved_configResolvedRunConfigrequired29 child fields
rule_versionstringrequiredThe version of the rules that resolved the
autodefaults (auto@2); a config keeps resolving the same way.datasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredThe pinned dataset version.
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"modelstringrequiredThe base model trained.
template_revisionstringrequiredThe pinned chat template (
qwen3@3); evals of the run's checkpoints use it too.adapterobject or object or object or objectrequiredOne of 4 shapes
- object
kind"lora"required"lora"rankintegeralphaintegermerge_on_exportbooleantrain_multimodal_projectorbooleanAlso attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).
- object
kind"prefix_kv"required"prefix_kv"num_tokensinteger
- object
kind"frozen_head"required"frozen_head"
- object
kind"encoder_full"required"encoder_full"
- object
lrnumberrequiredThe resolved learning rate.
lr_sourcestringrequiredWhere
lrcame from: the calibrated rule (auto@2: calibrated for ... at batch 128, sqrt batch scaling) or the value you passed.batch_sizeintegerrequiredTraining examples per optimizer step.
epochsintegerrequiredPasses over the training split.
scheduleenumrequiredLearning-rate schedule after warmup.
"linear""cosine""constant"warmupnumberrequiredThe fraction of steps spent warming up the learning rate.
train_onenumrequiredWhich assistant turns are trained: the last one, or every one.
"last""all_assistant"thinkingenumrequiredThinking mode the records are rendered with.
"auto""on""off"preserve_thinkingbooleanrequiredWhether earlier assistant turns keep their reasoning in the prompt.
reductionenumrequiredHow the loss averages: per example, then across the batch, or per token.
"per_example""per_token"selectenumrequiredWhich checkpoint becomes the artifact: the best by the held-out metric, or the last.
"best""last"checkpoint_every_stepsintegerrequiredSteps between checkpoints.
eval_every_stepsintegerrequiredSteps between held-out evaluations.
optimizerOptimizerSpecrequired4 child fields
kind"adamw""adamw"betasarray of anyweight_decaynumbergrad_clipnumberMax global gradient norm; 0 disables clipping.
checkpoint_ttl_daysintegerrequiredDays an intermediate checkpoint is kept; the best and final never expire.
splitobjectrequired5 child fields
strategyenumrequired"by_session""by_group""random"eval_fractionnumberrequiredseedintegerrequiredtrain_recordsintegerrequiredeval_recordsintegerrequired
label_eval_idstringrequiredThe labeling eval whose answers the run trains on: router runs with a Judge/validator rubric, and off-policy distill runs (the teacher's answers).
base_artifactBaseArtifactrequiredContinued training: the artifact whose adapter the run starts from (recipe.model was an artifact reference).
recipe_paramsmap of anyrequiredThe recipe's own settings (router candidates, DPO
beta, a cartridge's context, ...).checkpoint_evalsarray of objectrecipe.evals, with the dataset version and rubric pinned.
5 child fields
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$datasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredrubricarray of EvalRubricItemrequired9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
limitintegerrequired
loggersarray of LoggerSpec
max_cost_usdnumberrequiredHard spend cap in USD (null: none). The run is never billed past it.
price_per_million_tokensnumberrequiredUSD per million tokens processed, fixed when the run was created.
tokens_processedintegerrequiredTraining tokens processed so far, over every attempt.
cost_usdnumberrequiredCost of the tokens processed so far, in USD. It counts the whole step that crossed max_cost_usd; billing stops at the cap.
current_stepintegerrequiredLast optimizer step reported.
total_stepsintegerrequiredPlanned optimizer steps.
attemptintegerrequiredAttempts started so far (every start on a worker counts, including ones whose GPU was reclaimed).
max_attemptsintegerrequiredThe run fails once this many attempts end without a result (lost worker, worker error, OOM). Attempts whose GPU was reclaimed don't count toward it.
phaseenumrequiredWhat the run is doing now; null once it has finished (finished_at is set). A cancelled run whose worker hasn't stopped yet reads stopping. The run's events keep every phase it went through.
"queued""waiting_for_compute""starting""loading_model""training""evaluating""checkpointing""uploading""completing""stopping"nullphase_sincestring (date-time)requiredWhen the run entered its phase; null with phase.
last_interruptionRunInterruptionrequiredworkers_onlineintegerrequiredWhile queued: workers of this kind holding a lease (all busy). Null otherwise.
autoscalingbooleanrequiredWhile queued: true when workers scale from zero (KEDA), so a worker is starting. Null otherwise.
queue_positionintegerrequiredWhile queued for a worker: about how many runs start before this one. Claims are fair across workspaces (the workspace with the fewest running runs goes next), so this counts other workspaces' runs too. Approximate; null otherwise.
queue_messagestringrequiredWhile queued for a worker: why it waits, ready to show: "Queued behind 3 runs", "Queued: workspace concurrency limit (8 running)" (the workspace runs as many as it may at once), or "Waiting for a GPU with ≥46 GB; online workers have 24 GB". Null when it is next in line, and once it is claimed.
min_gpu_memory_gbnumberrequiredGPU memory (GB) the run needs (its plan's min_gpu_memory_gb): only workers with at least this much claim it. Null when unknown.
latest_metricMetricPointrequiredeval_reportEvalReportrequiredcheckpoint_evalsarray of CheckpointEvalResultrequiredrecipe.evals results, one per finished eval: a checkpoint (step) on a dataset.
10 child fields
namestringrequiredstepintegerrequiredcheckpoint_idstringrequiredeval_idstringrequireddatasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredstatusenumrequired"completed""failed""cancelled"scorenumberrequiredThe checkpoint's overall rubric score (null unless completed).
cost_usdnumberrequirederrorstringrequired
artifact_idstringrequiredThe released artifact (
name@version) once the run completes; null before.errorstringrequiredWhy the run failed or stopped; null otherwise.
created_atstring (date-time)requiredWhen the run was created.
updated_atstring (date-time)requiredWhen the run last changed.
finished_atstring (date-time)requiredWhen the run reached a final status; null while it is queued or running.
warningsarray of stringOnly on the response that created the run (POST /v1/runs): the plan's warnings, such as another queued or running run with the same name. They're also the run's first warning events.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
run = client.runs.cancel("run_3f9c0a1b2c3d4e5f60718293"){
"id": "run_3f9c0a1b2c3d4e5f60718293",
"workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
"name": "support-prod",
"dataset_id": "ds_3f9c0a1b2c3d4e5f60718293",
"dataset_name": "support-prod",
"dataset_version": 0,
"recipe_kind": "sft",
"status": "queued",
"resolved_config": {
"rule_version": "string",
"dataset": "support-prod",
"dataset_version": 0,
"name": "support-prod",
"recipe_kind": "sft",
"model": "qwen/qwen3-8b",
"template_revision": "string",
"adapter": {
"kind": "lora",
"rank": 32,
"alpha": 32,
"merge_on_export": false,
"train_multimodal_projector": false
},
"lr": 1,
"lr_source": "string",
"batch_size": 1,
"epochs": 1,
"schedule": "linear",
"warmup": 0,
"train_on": "last",
"thinking": "auto",
"preserve_thinking": false,
"reduction": "per_example",
"select": "best",
"checkpoint_every_steps": 1,
"eval_every_steps": 1,
"optimizer": {
"kind": "adamw",
"betas": [
0.9,
0.95
],
"weight_decay": 0,
"grad_clip": 1
},
"checkpoint_ttl_days": 1,
"split": {
"strategy": "by_session",
"eval_fraction": 0,
"seed": 0,
"train_records": 0,
"eval_records": 0
},
"label_eval_id": "obj_3f9c0a1b2c3d4e5f60718293",
"base_artifact": {
"id": "obj_3f9c0a1b2c3d4e5f60718293",
"recipe_kind": "sft",
"format": "peft_lora",
"sha256": "9f2c4e1ab0d3c5e7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c9d1e3f5a7b9c1d3e5"
},
"recipe_params": {},
"checkpoint_evals": [
{
"name": "support-prod",
"dataset": "support-prod",
"dataset_version": 1,
"rubric": [
{}
],
"limit": 1
}
],
"loggers": [
{
"kind": "wandb",
"project": "string",
"entity": "string",
"integration": "string",
"run_name": "support-prod"
}
]
},
"max_cost_usd": 1,
"price_per_million_tokens": 1,
"tokens_processed": 0,
"cost_usd": 0,
"current_step": 0,
"total_steps": 0,
"attempt": 0,
"max_attempts": 1,
"phase": "queued",
"phase_since": "2026-11-28T09:30:00.000Z",
"last_interruption": {
"attempt": 1,
"reason": "lease_lost",
"step": 0,
"resume_step": 0,
"at": "2026-11-28T09:30:00.000Z",
"message": "…"
},
"workers_online": 0,
"autoscaling": false,
"queue_position": 0,
"queue_message": "string",
"min_gpu_memory_gb": 1,
"latest_metric": {
"seq": 1,
"attempt": 1,
"step": 0,
"loss": 0,
"eval_loss": 0,
"eval_metrics": {},
"grad_norm": 0,
"lr": 0,
"tokens_per_sec": 0,
"tokens": 0,
"cost_usd": 0,
"timestamp": "2026-11-28T09:30:00.000Z"
},
"eval_report": {
"metric_name": "support-prod",
"metric_mode": "min",
"selected_step": 0,
"best_step": 0,
"final_step": 0,
"train_records": 0,
"eval_records": 0,
"warnings": [
"string"
],
"eval_loss": 0,
"eval_token_accuracy": 0,
"trained_token_fraction": 0,
"train_examples": 0,
"eval_examples": 0,
"selection_examples": 0,
"truncated": 0,
"preference_accuracy": 0,
"reward_margin": 0,
"beta": 0,
"train_pairs": 0,
"eval_pairs": 0,
"dropped_records": 0,
"train_points": 0,
"eval_points": 0,
"pointwise_brier": 0,
"eval_kl": 0,
"base_kl": 0,
"no_context_kl": 0,
"kl_reduction": 0,
"num_tokens": 0,
"teacher": "string",
"rollout": "on_policy",
"candidates": [
"string"
],
"fallback_model": "string",
"fallback_quality": 0,
"routes_any_traffic": false,
"pareto_summary": {
"target_max_drop": 0,
"routed_quality": 0,
"quality_drop": 0,
"quality_drop_ci95": [
0
],
"offload_rate": 0,
"cost_savings_pct": 0,
"ece": 0,
"threshold": 0,
"temperature": 0
},
"ece": 0,
"heads": {},
"recall_at_1": 0,
"recall_at_5": 0,
"recall_at_10": 0,
"ndcg_at_10": 0,
"mrr": 0,
"corpus_size": 0,
"baseline": {
"recall_at_1": 0,
"recall_at_5": 0,
"recall_at_10": 0,
"ndcg_at_10": 0,
"mrr": 0
},
"eval_reward": 0,
"eval_pass_at_1": 0,
"baseline_reward": 0,
"baseline_pass_at_1": 0,
"final_train_reward": 0,
"mean_train_reward": 0,
"zero_var_skip_rate": 0,
"mean_completion_tokens": 0,
"mean_kl_ref": 0,
"validator": "string",
"advantage": "string",
"group_size": 0,
"kl_coef": 0,
"clip_low": 0,
"clip_high": 0
},
"checkpoint_evals": [
{
"name": "support-prod",
"step": 0,
"checkpoint_id": "ckpt_3f9c0a1b2c3d4e5f60718293",
"eval_id": "obj_3f9c0a1b2c3d4e5f60718293",
"dataset": "support-prod",
"dataset_version": 1,
"status": "completed",
"score": 0,
"cost_usd": 0,
"error": "…"
}
],
"artifact_id": "support-sft@2026-11-28-1",
"error": "…",
"created_at": "2026-11-28T09:30:00.000Z",
"updated_at": "2026-11-28T09:30:00.000Z",
"finished_at": "2026-11-28T09:30:00.000Z",
"warnings": [
"string"
],
"console_url": "string"
}Resume a stopped, failed or cancelled run from its latest checkpoint#
POST/v1/runs/{id}/resume
A run that is already queued or running is returned as it is, so a retried resume is a no-op. A resume queues the run again, so it counts toward the workspace's queued cap (429 queue_limit) like a new run.
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body ResumeRunRequest
max_cost_usdnumber
Returns
200 Run Re-queued training run.
35 fields
idstringrequiredRun id (
run_and 24 hex characters).workspace_idstringrequirednamestringrequiredRun name; its artifact is released as
name@version.Matches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_idstringrequiredId of the dataset trained on.
dataset_namestringrequiredName of the dataset trained on.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredThe dataset version the run pinned when it was created.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"statusRunStatusrequiredstopped_budget: the run reached its max_cost_usd (resume with a higher cap). stopped_balance: the workspace ran out of balance on Cloud (top up, then resume; the cap is unchanged). Both keep their checkpoints.
"queued""running""completed""failed""cancelled""stopped_budget""stopped_balance"resolved_configResolvedRunConfigrequired29 child fields
rule_versionstringrequiredThe version of the rules that resolved the
autodefaults (auto@2); a config keeps resolving the same way.datasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredThe pinned dataset version.
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"modelstringrequiredThe base model trained.
template_revisionstringrequiredThe pinned chat template (
qwen3@3); evals of the run's checkpoints use it too.adapterobject or object or object or objectrequiredOne of 4 shapes
- object
kind"lora"required"lora"rankintegeralphaintegermerge_on_exportbooleantrain_multimodal_projectorbooleanAlso attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).
- object
kind"prefix_kv"required"prefix_kv"num_tokensinteger
- object
kind"frozen_head"required"frozen_head"
- object
kind"encoder_full"required"encoder_full"
- object
lrnumberrequiredThe resolved learning rate.
lr_sourcestringrequiredWhere
lrcame from: the calibrated rule (auto@2: calibrated for ... at batch 128, sqrt batch scaling) or the value you passed.batch_sizeintegerrequiredTraining examples per optimizer step.
epochsintegerrequiredPasses over the training split.
scheduleenumrequiredLearning-rate schedule after warmup.
"linear""cosine""constant"warmupnumberrequiredThe fraction of steps spent warming up the learning rate.
train_onenumrequiredWhich assistant turns are trained: the last one, or every one.
"last""all_assistant"thinkingenumrequiredThinking mode the records are rendered with.
"auto""on""off"preserve_thinkingbooleanrequiredWhether earlier assistant turns keep their reasoning in the prompt.
reductionenumrequiredHow the loss averages: per example, then across the batch, or per token.
"per_example""per_token"selectenumrequiredWhich checkpoint becomes the artifact: the best by the held-out metric, or the last.
"best""last"checkpoint_every_stepsintegerrequiredSteps between checkpoints.
eval_every_stepsintegerrequiredSteps between held-out evaluations.
optimizerOptimizerSpecrequired4 child fields
kind"adamw""adamw"betasarray of anyweight_decaynumbergrad_clipnumberMax global gradient norm; 0 disables clipping.
checkpoint_ttl_daysintegerrequiredDays an intermediate checkpoint is kept; the best and final never expire.
splitobjectrequired5 child fields
strategyenumrequired"by_session""by_group""random"eval_fractionnumberrequiredseedintegerrequiredtrain_recordsintegerrequiredeval_recordsintegerrequired
label_eval_idstringrequiredThe labeling eval whose answers the run trains on: router runs with a Judge/validator rubric, and off-policy distill runs (the teacher's answers).
base_artifactBaseArtifactrequiredContinued training: the artifact whose adapter the run starts from (recipe.model was an artifact reference).
recipe_paramsmap of anyrequiredThe recipe's own settings (router candidates, DPO
beta, a cartridge's context, ...).checkpoint_evalsarray of objectrecipe.evals, with the dataset version and rubric pinned.
5 child fields
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$datasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredrubricarray of EvalRubricItemrequired9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
limitintegerrequired
loggersarray of LoggerSpec
max_cost_usdnumberrequiredHard spend cap in USD (null: none). The run is never billed past it.
price_per_million_tokensnumberrequiredUSD per million tokens processed, fixed when the run was created.
tokens_processedintegerrequiredTraining tokens processed so far, over every attempt.
cost_usdnumberrequiredCost of the tokens processed so far, in USD. It counts the whole step that crossed max_cost_usd; billing stops at the cap.
current_stepintegerrequiredLast optimizer step reported.
total_stepsintegerrequiredPlanned optimizer steps.
attemptintegerrequiredAttempts started so far (every start on a worker counts, including ones whose GPU was reclaimed).
max_attemptsintegerrequiredThe run fails once this many attempts end without a result (lost worker, worker error, OOM). Attempts whose GPU was reclaimed don't count toward it.
phaseenumrequiredWhat the run is doing now; null once it has finished (finished_at is set). A cancelled run whose worker hasn't stopped yet reads stopping. The run's events keep every phase it went through.
"queued""waiting_for_compute""starting""loading_model""training""evaluating""checkpointing""uploading""completing""stopping"nullphase_sincestring (date-time)requiredWhen the run entered its phase; null with phase.
last_interruptionRunInterruptionrequiredworkers_onlineintegerrequiredWhile queued: workers of this kind holding a lease (all busy). Null otherwise.
autoscalingbooleanrequiredWhile queued: true when workers scale from zero (KEDA), so a worker is starting. Null otherwise.
queue_positionintegerrequiredWhile queued for a worker: about how many runs start before this one. Claims are fair across workspaces (the workspace with the fewest running runs goes next), so this counts other workspaces' runs too. Approximate; null otherwise.
queue_messagestringrequiredWhile queued for a worker: why it waits, ready to show: "Queued behind 3 runs", "Queued: workspace concurrency limit (8 running)" (the workspace runs as many as it may at once), or "Waiting for a GPU with ≥46 GB; online workers have 24 GB". Null when it is next in line, and once it is claimed.
min_gpu_memory_gbnumberrequiredGPU memory (GB) the run needs (its plan's min_gpu_memory_gb): only workers with at least this much claim it. Null when unknown.
latest_metricMetricPointrequiredeval_reportEvalReportrequiredcheckpoint_evalsarray of CheckpointEvalResultrequiredrecipe.evals results, one per finished eval: a checkpoint (step) on a dataset.
10 child fields
namestringrequiredstepintegerrequiredcheckpoint_idstringrequiredeval_idstringrequireddatasetstringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerrequiredstatusenumrequired"completed""failed""cancelled"scorenumberrequiredThe checkpoint's overall rubric score (null unless completed).
cost_usdnumberrequirederrorstringrequired
artifact_idstringrequiredThe released artifact (
name@version) once the run completes; null before.errorstringrequiredWhy the run failed or stopped; null otherwise.
created_atstring (date-time)requiredWhen the run was created.
updated_atstring (date-time)requiredWhen the run last changed.
finished_atstring (date-time)requiredWhen the run reached a final status; null while it is queued or running.
warningsarray of stringOnly on the response that created the run (POST /v1/runs): the plan's warnings, such as another queued or running run with the same name. They're also the run's first warning events.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
run = client.runs.resume("run_3f9c0a1b2c3d4e5f60718293", max_cost_usd=10){
"id": "run_ed1c235f0c631d8f209e22a5",
"workspace_id": "ws_e2e",
"name": "support-sft",
"dataset_id": "ds_c66d7ad841f251049ca0e550",
"dataset_name": "support-prod",
"dataset_version": 1,
"recipe_kind": "sft",
"status": "queued",
"resolved_config": {
"lr": 0.000125,
"name": "support-sft",
"model": "qwen/qwen3-8b",
"split": {
"seed": 42,
"strategy": "by_session",
"eval_records": 0,
"eval_fraction": 0.1,
"train_records": 1
},
"epochs": 1,
"select": "best",
"warmup": 0.03,
"adapter": {
"kind": "lora",
"rank": 32,
"alpha": 32,
"merge_on_export": false,
"train_multimodal_projector": false
},
"dataset": "support-prod",
"schedule": "linear",
"thinking": "auto",
"train_on": "last",
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"optimizer": {
"kind": "adamw",
"betas": [
0.9,
0.95
],
"grad_clip": 1,
"weight_decay": 0
},
"reduction": "per_example",
"batch_size": 8,
"recipe_kind": "sft",
"rule_version": "auto@2",
"base_artifact": null,
"label_eval_id": null,
"recipe_params": {},
"dataset_version": 1,
"eval_every_steps": 1,
"preserve_thinking": false,
"template_revision": "qwen3@3",
"checkpoint_ttl_days": 30,
"checkpoint_every_steps": 1
},
"max_cost_usd": 5,
"price_per_million_tokens": 0.4,
"tokens_processed": 0,
"cost_usd": 0,
"current_step": 0,
"total_steps": 1,
"attempt": 0,
"max_attempts": 10,
"phase": "queued",
"phase_since": "2026-12-02T15:48:59.895Z",
"last_interruption": null,
"workers_online": 0,
"autoscaling": false,
"queue_position": 0,
"queue_message": null,
"min_gpu_memory_gb": 36,
"latest_metric": null,
"eval_report": null,
"checkpoint_evals": [],
"artifact_id": null,
"error": null,
"created_at": "2026-12-02T15:48:59.888Z",
"updated_at": "2026-12-02T15:48:59.888Z",
"finished_at": null
}Trainers#
Start a trainer: a LoRA on one GPU that you drive op by op#
POST/v1/trainers
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body CreateTrainerRequest
modelstringA trainable causal-LM catalog id (
qwen/qwen3-8b), or any catalog LLM whenmodeissample.modeTrainerModetrain(default): full LoRA training and sampling;sample: inference-only sampling session (no optimizer/gradients, higher vLLM KV-cache headroom, allows sampling any catalog LLM)."train""sample"from_artifactstringStart from a
peft_loraartifact's weights (id orname@version) with a fresh optimizer: a stage transition.from_checkpointstringResume a trainer's
save_statecheckpoint: its weights, optimizer, gradients and step.adapterTrainerAdapterThe LoRA a trainer trains (on every linear layer of the language model, plus multimodal projector/merger layers when
train_multimodal_projectoris true). A trainer from an artifact or checkpoint keeps that adapter's settings.4 child fields
kind"lora""lora"rankintegeralphaintegertrain_multimodal_projectorbooleanAlso attach LoRA adapters to multimodal-to-language projector/merger linear layers while keeping vision/audio encoder backbones frozen (multimodal models only; default false).
max_cost_usdnumberrequiredHard cap on what the trainer may spend. An op that could pass it is refused (
budget_exceeded) before it runs.idle_timeout_sintegerSeconds without an op after which the trainer parks: it saves its state and gives the GPU back (nothing is billed while parked). The next op resumes it.
namestringautosave_everyintegerSave the state every N optimizer steps (between ops), so a lost worker costs at most N steps.
max_snapshotsintegerSnapshots (frozen copies of the adapter to sample from) it may hold at once, pending or live; one more is
409 too_many_snapshots. Each is an adapter-sized copy in GPU memory (about 350 MB at 8B rank 32).snapshot_ttl_sintegerA snapshot with no sample queued or running for this long is released (a crashed client's snapshots don't hold the slots).
checkpoint_ttl_sintegerTTL in seconds (300 to 7776000) for automatic
autosaveandparkcheckpoints. Explicitsave_state(withoutttl_s) and finalclosecheckpoints stay permanent.total_stepsintegerOptional target optimizer step count used for progress indicators in the web console and
grad trainers watchTUI.
Returns
202 Trainer The trainer, queued for a GPU.
36 fields
idstringrequiredtrn_and 24 hex.namestringrequiredmodelstringrequiredThe base model.
modalitiesarray of ModalityrequiredInput modalities accepted by this trainer's base model (
text,image,audio).modeTrainerModerequiredtrain(default): full LoRA training and sampling;sample: inference-only sampling session (no optimizer/gradients, higher vLLM KV-cache headroom, allows sampling any catalog LLM)."train""sample"adapterobjectrequired4 child fields
kind"lora"required"lora"rankintegerrequiredalphaintegerrequiredtrain_multimodal_projectorboolean
statusTrainerStatusrequiredqueued (waiting for a GPU), loading (a worker is loading the base and adapter), ready (running ops), parked (idle: its state is saved and no GPU is held; the next op resumes it), closed, failed (see
error)."queued""loading""ready""parked""closed""failed"stepintegerrequiredOptimizer steps taken.
total_stepsintegerOptional target optimizer step count configured at creation (null if unset).
next_seqintegerrequiredThe
seqthe next op must carry.pending_opsintegerrequiredTrain-lane ops (the seq-ordered ones) submitted and not finished yet.
closingbooleanrequiredclosewas called: the ops already submitted run (with abort, the ones the worker has not taken fail), then it closes. It takes no new op.max_snapshotsintegerrequiredsnapshot_ttl_sintegerrequiredcheckpoint_ttl_sintegerConfigured TTL in seconds for automatic
autosave/parkcheckpoints (null: server default retention).sample_queueobjectrequiredSample-lane ops (snapshot samples) waiting and running. At most 1024 together (
429 sample_queue_full).2 child fields
queuedintegerrequiredrunningintegerrequired
utilizationobjectrequiredCumulative worker compute time per lane (
train_s: train-lane ops,sample_s: sample-lane batches) and wall time spent loaded (ready_s). The GPU's busy fraction over an interval is the change intrain_s + sample_sover the change inready_s.3 child fields
train_snumberrequiredsample_snumberrequiredready_snumberrequired
usageTrainerUsagerequired4 child fields
tokensintegerrequiredcost_usdnumberrequiredprompt_tokensintegersampled_tokensinteger
max_cost_usdnumberrequiredreserved_cost_usdnumberrequiredThe worst-case cost of the pending ops. An op is refused (
budget_exceeded) when spent + reserved + its worst case would passmax_cost_usd.price_per_million_tokensnumberrequiredcalibrated_lrsmap of numberrequiredCalibrated learning rates for this trainer's base model by objective (
sft,rl,dpo, ...); empty when uncalibrated.idle_timeout_sintegerrequiredmax_seq_lenintegerrequiredThe longest datum (and sample prompt + max_tokens) it takes.
tokenizerobjectrequiredThe base's tokenizer (Hugging Face repo and revision) for raw-token clients; null until a worker has loaded the trainer once.
template_revisionstringrequiredstop_token_idsarray of integerrequiredWhere
samplestops by default (end of turn, end of text).queue_messagestringrequiredWhile queued: why it waits (GPU capacity, the workspace's limit).
from_artifactstringrequiredfrom_checkpointstringrequiredlast_checkpointstringrequiredThe latest saved state (a save_state, an autosave, a park or the close): what
from_checkpointresumes after a failure.errorstringrequiredcreated_atstring (date-time)requiredclosed_atstring (date-time)requiredlogged_metricsarray of TrainerMetricPointRecent client-logged scalar metrics series, ordered oldest to newest (included on GET /v1/trainers/{id}).
3 child fields
stepintegerrequiredmetricsmap of numberrequiredtimestampstring (date-time)required
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
trainer = client.trainers.create(
model="qwen/qwen3-8b",
max_cost_usd=20,
name="support-loop",
)
print(trainer.id, trainer.status){
"id": "trn_1672e418bf19834898de1278",
"name": "support-loop",
"model": "qwen/qwen3-8b",
"modalities": [
"text"
],
"mode": "train",
"adapter": {
"kind": "lora",
"rank": 32,
"alpha": 32
},
"status": "queued",
"step": 0,
"total_steps": null,
"next_seq": 1,
"pending_ops": 0,
"closing": false,
"max_snapshots": 4,
"snapshot_ttl_s": 600,
"checkpoint_ttl_s": null,
"sample_queue": {
"queued": 0,
"running": 0
},
"utilization": {
"train_s": 0,
"sample_s": 0,
"ready_s": 0
},
"usage": {
"tokens": 0,
"cost_usd": 0
},
"max_cost_usd": 20,
"reserved_cost_usd": 0,
"price_per_million_tokens": 0.4,
"calibrated_lrs": {
"sft": 0.0005,
"rl": 0.000025,
"grpo": 0.000025,
"dpo": 0.00002,
"router": 0.0003,
"cartridge": 0.01,
"distill": 0.0002,
"reward": 0.0001
},
"idle_timeout_s": 300,
"max_seq_len": 32768,
"tokenizer": null,
"template_revision": "qwen3@3",
"stop_token_ids": null,
"queue_message": "Waiting for a GPU worker",
"from_artifact": null,
"from_checkpoint": null,
"last_checkpoint": null,
"error": null,
"created_at": "2026-12-02T15:49:00.029Z",
"closed_at": null
}List trainers#
GET/v1/trainers
Newest first.
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstringqstringOnly items whose name contains this text (any case), or whose id is exactly this.
Returns
200 object Trainers.
2 fields
dataarray of Trainerrequired36 child fields
idstringrequiredtrn_and 24 hex.namestringrequiredmodelstringrequiredThe base model.
modalitiesarray of ModalityrequiredInput modalities accepted by this trainer's base model (
text,image,audio).modeTrainerModerequiredtrain(default): full LoRA training and sampling;sample: inference-only sampling session (no optimizer/gradients, higher vLLM KV-cache headroom, allows sampling any catalog LLM)."train""sample"adapterobjectrequired4 child fields
kind"lora"required"lora"rankintegerrequiredalphaintegerrequiredtrain_multimodal_projectorboolean
statusTrainerStatusrequiredqueued (waiting for a GPU), loading (a worker is loading the base and adapter), ready (running ops), parked (idle: its state is saved and no GPU is held; the next op resumes it), closed, failed (see
error)."queued""loading""ready""parked""closed""failed"stepintegerrequiredOptimizer steps taken.
total_stepsintegerOptional target optimizer step count configured at creation (null if unset).
next_seqintegerrequiredThe
seqthe next op must carry.pending_opsintegerrequiredTrain-lane ops (the seq-ordered ones) submitted and not finished yet.
closingbooleanrequiredclosewas called: the ops already submitted run (with abort, the ones the worker has not taken fail), then it closes. It takes no new op.max_snapshotsintegerrequiredsnapshot_ttl_sintegerrequiredcheckpoint_ttl_sintegerConfigured TTL in seconds for automatic
autosave/parkcheckpoints (null: server default retention).sample_queueobjectrequiredSample-lane ops (snapshot samples) waiting and running. At most 1024 together (
429 sample_queue_full).2 child fields
queuedintegerrequiredrunningintegerrequired
utilizationobjectrequiredCumulative worker compute time per lane (
train_s: train-lane ops,sample_s: sample-lane batches) and wall time spent loaded (ready_s). The GPU's busy fraction over an interval is the change intrain_s + sample_sover the change inready_s.3 child fields
train_snumberrequiredsample_snumberrequiredready_snumberrequired
usageTrainerUsagerequired4 child fields
tokensintegerrequiredcost_usdnumberrequiredprompt_tokensintegersampled_tokensinteger
max_cost_usdnumberrequiredreserved_cost_usdnumberrequiredThe worst-case cost of the pending ops. An op is refused (
budget_exceeded) when spent + reserved + its worst case would passmax_cost_usd.price_per_million_tokensnumberrequiredcalibrated_lrsmap of numberrequiredCalibrated learning rates for this trainer's base model by objective (
sft,rl,dpo, ...); empty when uncalibrated.idle_timeout_sintegerrequiredmax_seq_lenintegerrequiredThe longest datum (and sample prompt + max_tokens) it takes.
tokenizerobjectrequiredThe base's tokenizer (Hugging Face repo and revision) for raw-token clients; null until a worker has loaded the trainer once.
template_revisionstringrequiredstop_token_idsarray of integerrequiredWhere
samplestops by default (end of turn, end of text).queue_messagestringrequiredWhile queued: why it waits (GPU capacity, the workspace's limit).
from_artifactstringrequiredfrom_checkpointstringrequiredlast_checkpointstringrequiredThe latest saved state (a save_state, an autosave, a park or the close): what
from_checkpointresumes after a failure.errorstringrequiredcreated_atstring (date-time)requiredclosed_atstring (date-time)requiredlogged_metricsarray of TrainerMetricPointRecent client-logged scalar metrics series, ordered oldest to newest (included on GET /v1/trainers/{id}).
3 child fields
stepintegerrequiredmetricsmap of numberrequiredtimestampstring (date-time)required
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
for trainer in client.trainers.list(search="support"):
print(trainer.id, trainer.status, trainer.step){
"data": [
{
"id": "trn_3f9c0a1b2c3d4e5f60718293",
"name": "support-prod",
"model": "qwen/qwen3-8b",
"modalities": [
"text"
],
"mode": "train",
"adapter": {
"kind": "lora",
"rank": 1,
"alpha": 1,
"train_multimodal_projector": false
},
"status": "queued",
"step": 0,
"total_steps": 1,
"next_seq": 1,
"pending_ops": 0,
"closing": false,
"max_snapshots": 1,
"snapshot_ttl_s": 1,
"checkpoint_ttl_s": 300,
"sample_queue": {
"queued": 0,
"running": 0
},
"utilization": {
"train_s": 0,
"sample_s": 0,
"ready_s": 0
},
"usage": {
"tokens": 0,
"cost_usd": 0,
"prompt_tokens": 0,
"sampled_tokens": 0
},
"max_cost_usd": 1,
"reserved_cost_usd": 0,
"price_per_million_tokens": 0,
"calibrated_lrs": {},
"idle_timeout_s": 1,
"max_seq_len": 1,
"tokenizer": {
"repo": "string",
"revision": "string"
},
"template_revision": "string",
"stop_token_ids": [
0
],
"queue_message": "string",
"from_artifact": "string",
"from_checkpoint": "string",
"last_checkpoint": "string",
"error": "…",
"created_at": "2026-11-28T09:30:00.000Z",
"closed_at": "2026-11-28T09:30:00.000Z",
"logged_metrics": [
{
"step": 0,
"metrics": {},
"timestamp": "2026-11-28T09:30:00.000Z"
}
],
"console_url": "string"
}
],
"next_cursor": "string"
}Get a trainer#
GET/v1/trainers/{id}
Path parameters
idstringrequired
Returns
200 Trainer The trainer.
36 fields
idstringrequiredtrn_and 24 hex.namestringrequiredmodelstringrequiredThe base model.
modalitiesarray of ModalityrequiredInput modalities accepted by this trainer's base model (
text,image,audio).modeTrainerModerequiredtrain(default): full LoRA training and sampling;sample: inference-only sampling session (no optimizer/gradients, higher vLLM KV-cache headroom, allows sampling any catalog LLM)."train""sample"adapterobjectrequired4 child fields
kind"lora"required"lora"rankintegerrequiredalphaintegerrequiredtrain_multimodal_projectorboolean
statusTrainerStatusrequiredqueued (waiting for a GPU), loading (a worker is loading the base and adapter), ready (running ops), parked (idle: its state is saved and no GPU is held; the next op resumes it), closed, failed (see
error)."queued""loading""ready""parked""closed""failed"stepintegerrequiredOptimizer steps taken.
total_stepsintegerOptional target optimizer step count configured at creation (null if unset).
next_seqintegerrequiredThe
seqthe next op must carry.pending_opsintegerrequiredTrain-lane ops (the seq-ordered ones) submitted and not finished yet.
closingbooleanrequiredclosewas called: the ops already submitted run (with abort, the ones the worker has not taken fail), then it closes. It takes no new op.max_snapshotsintegerrequiredsnapshot_ttl_sintegerrequiredcheckpoint_ttl_sintegerConfigured TTL in seconds for automatic
autosave/parkcheckpoints (null: server default retention).sample_queueobjectrequiredSample-lane ops (snapshot samples) waiting and running. At most 1024 together (
429 sample_queue_full).2 child fields
queuedintegerrequiredrunningintegerrequired
utilizationobjectrequiredCumulative worker compute time per lane (
train_s: train-lane ops,sample_s: sample-lane batches) and wall time spent loaded (ready_s). The GPU's busy fraction over an interval is the change intrain_s + sample_sover the change inready_s.3 child fields
train_snumberrequiredsample_snumberrequiredready_snumberrequired
usageTrainerUsagerequired4 child fields
tokensintegerrequiredcost_usdnumberrequiredprompt_tokensintegersampled_tokensinteger
max_cost_usdnumberrequiredreserved_cost_usdnumberrequiredThe worst-case cost of the pending ops. An op is refused (
budget_exceeded) when spent + reserved + its worst case would passmax_cost_usd.price_per_million_tokensnumberrequiredcalibrated_lrsmap of numberrequiredCalibrated learning rates for this trainer's base model by objective (
sft,rl,dpo, ...); empty when uncalibrated.idle_timeout_sintegerrequiredmax_seq_lenintegerrequiredThe longest datum (and sample prompt + max_tokens) it takes.
tokenizerobjectrequiredThe base's tokenizer (Hugging Face repo and revision) for raw-token clients; null until a worker has loaded the trainer once.
template_revisionstringrequiredstop_token_idsarray of integerrequiredWhere
samplestops by default (end of turn, end of text).queue_messagestringrequiredWhile queued: why it waits (GPU capacity, the workspace's limit).
from_artifactstringrequiredfrom_checkpointstringrequiredlast_checkpointstringrequiredThe latest saved state (a save_state, an autosave, a park or the close): what
from_checkpointresumes after a failure.errorstringrequiredcreated_atstring (date-time)requiredclosed_atstring (date-time)requiredlogged_metricsarray of TrainerMetricPointRecent client-logged scalar metrics series, ordered oldest to newest (included on GET /v1/trainers/{id}).
3 child fields
stepintegerrequiredmetricsmap of numberrequiredtimestampstring (date-time)required
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
print(trainer.status, trainer.step, trainer.usage().cost_usd){
"id": "trn_3f9c0a1b2c3d4e5f60718293",
"name": "support-prod",
"model": "qwen/qwen3-8b",
"modalities": [
"text"
],
"mode": "train",
"adapter": {
"kind": "lora",
"rank": 1,
"alpha": 1,
"train_multimodal_projector": false
},
"status": "queued",
"step": 0,
"total_steps": 1,
"next_seq": 1,
"pending_ops": 0,
"closing": false,
"max_snapshots": 1,
"snapshot_ttl_s": 1,
"checkpoint_ttl_s": 300,
"sample_queue": {
"queued": 0,
"running": 0
},
"utilization": {
"train_s": 0,
"sample_s": 0,
"ready_s": 0
},
"usage": {
"tokens": 0,
"cost_usd": 0,
"prompt_tokens": 0,
"sampled_tokens": 0
},
"max_cost_usd": 1,
"reserved_cost_usd": 0,
"price_per_million_tokens": 0,
"calibrated_lrs": {},
"idle_timeout_s": 1,
"max_seq_len": 1,
"tokenizer": {
"repo": "string",
"revision": "string"
},
"template_revision": "string",
"stop_token_ids": [
0
],
"queue_message": "string",
"from_artifact": "string",
"from_checkpoint": "string",
"last_checkpoint": "string",
"error": "…",
"created_at": "2026-11-28T09:30:00.000Z",
"closed_at": "2026-11-28T09:30:00.000Z",
"logged_metrics": [
{
"step": 0,
"metrics": {},
"timestamp": "2026-11-28T09:30:00.000Z"
}
],
"console_url": "string"
}Log client-side scalar metrics (e.g. mean_reward, mean_turns) for a trainer step#
POST/v1/trainers/{id}/metrics
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body LogTrainerMetricsRequest
stepintegerrequiredmetricsmap of numberrequiredtimestampstring (date-time)
Returns
201 TrainerMetricPoint Logged metrics point.
3 fields
stepintegerrequiredmetricsmap of numberrequiredtimestampstring (date-time)required
from grad import Grad
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
point = trainer.log_metrics(10, {"mean_reward": 0.75})
print(point.step, point.metrics){
"step": 0,
"metrics": {},
"timestamp": "2026-11-28T09:30:00.000Z"
}Close a trainer: run the ops already submitted (or fail them with abort), save the final state, release the GPU#
POST/v1/trainers/{id}/close
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body CloseTrainerRequest
abortbooleanFail the ops the worker has not taken yet (
trainer_closed) instead of running them; the ones it took (the one running, and the next it prefetched) finish.
Returns
200 Trainer The trainer (closing or closed).
36 fields
idstringrequiredtrn_and 24 hex.namestringrequiredmodelstringrequiredThe base model.
modalitiesarray of ModalityrequiredInput modalities accepted by this trainer's base model (
text,image,audio).modeTrainerModerequiredtrain(default): full LoRA training and sampling;sample: inference-only sampling session (no optimizer/gradients, higher vLLM KV-cache headroom, allows sampling any catalog LLM)."train""sample"adapterobjectrequired4 child fields
kind"lora"required"lora"rankintegerrequiredalphaintegerrequiredtrain_multimodal_projectorboolean
statusTrainerStatusrequiredqueued (waiting for a GPU), loading (a worker is loading the base and adapter), ready (running ops), parked (idle: its state is saved and no GPU is held; the next op resumes it), closed, failed (see
error)."queued""loading""ready""parked""closed""failed"stepintegerrequiredOptimizer steps taken.
total_stepsintegerOptional target optimizer step count configured at creation (null if unset).
next_seqintegerrequiredThe
seqthe next op must carry.pending_opsintegerrequiredTrain-lane ops (the seq-ordered ones) submitted and not finished yet.
closingbooleanrequiredclosewas called: the ops already submitted run (with abort, the ones the worker has not taken fail), then it closes. It takes no new op.max_snapshotsintegerrequiredsnapshot_ttl_sintegerrequiredcheckpoint_ttl_sintegerConfigured TTL in seconds for automatic
autosave/parkcheckpoints (null: server default retention).sample_queueobjectrequiredSample-lane ops (snapshot samples) waiting and running. At most 1024 together (
429 sample_queue_full).2 child fields
queuedintegerrequiredrunningintegerrequired
utilizationobjectrequiredCumulative worker compute time per lane (
train_s: train-lane ops,sample_s: sample-lane batches) and wall time spent loaded (ready_s). The GPU's busy fraction over an interval is the change intrain_s + sample_sover the change inready_s.3 child fields
train_snumberrequiredsample_snumberrequiredready_snumberrequired
usageTrainerUsagerequired4 child fields
tokensintegerrequiredcost_usdnumberrequiredprompt_tokensintegersampled_tokensinteger
max_cost_usdnumberrequiredreserved_cost_usdnumberrequiredThe worst-case cost of the pending ops. An op is refused (
budget_exceeded) when spent + reserved + its worst case would passmax_cost_usd.price_per_million_tokensnumberrequiredcalibrated_lrsmap of numberrequiredCalibrated learning rates for this trainer's base model by objective (
sft,rl,dpo, ...); empty when uncalibrated.idle_timeout_sintegerrequiredmax_seq_lenintegerrequiredThe longest datum (and sample prompt + max_tokens) it takes.
tokenizerobjectrequiredThe base's tokenizer (Hugging Face repo and revision) for raw-token clients; null until a worker has loaded the trainer once.
template_revisionstringrequiredstop_token_idsarray of integerrequiredWhere
samplestops by default (end of turn, end of text).queue_messagestringrequiredWhile queued: why it waits (GPU capacity, the workspace's limit).
from_artifactstringrequiredfrom_checkpointstringrequiredlast_checkpointstringrequiredThe latest saved state (a save_state, an autosave, a park or the close): what
from_checkpointresumes after a failure.errorstringrequiredcreated_atstring (date-time)requiredclosed_atstring (date-time)requiredlogged_metricsarray of TrainerMetricPointRecent client-logged scalar metrics series, ordered oldest to newest (included on GET /v1/trainers/{id}).
3 child fields
stepintegerrequiredmetricsmap of numberrequiredtimestampstring (date-time)required
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
trainer.close(abort=False){
"id": "trn_3f9c0a1b2c3d4e5f60718293",
"name": "support-prod",
"model": "qwen/qwen3-8b",
"modalities": [
"text"
],
"mode": "train",
"adapter": {
"kind": "lora",
"rank": 1,
"alpha": 1,
"train_multimodal_projector": false
},
"status": "queued",
"step": 0,
"total_steps": 1,
"next_seq": 1,
"pending_ops": 0,
"closing": false,
"max_snapshots": 1,
"snapshot_ttl_s": 1,
"checkpoint_ttl_s": 300,
"sample_queue": {
"queued": 0,
"running": 0
},
"utilization": {
"train_s": 0,
"sample_s": 0,
"ready_s": 0
},
"usage": {
"tokens": 0,
"cost_usd": 0,
"prompt_tokens": 0,
"sampled_tokens": 0
},
"max_cost_usd": 1,
"reserved_cost_usd": 0,
"price_per_million_tokens": 0,
"calibrated_lrs": {},
"idle_timeout_s": 1,
"max_seq_len": 1,
"tokenizer": {
"repo": "string",
"revision": "string"
},
"template_revision": "string",
"stop_token_ids": [
0
],
"queue_message": "string",
"from_artifact": "string",
"from_checkpoint": "string",
"last_checkpoint": "string",
"error": "…",
"created_at": "2026-11-28T09:30:00.000Z",
"closed_at": "2026-11-28T09:30:00.000Z",
"logged_metrics": [
{
"step": 0,
"metrics": {},
"timestamp": "2026-11-28T09:30:00.000Z"
}
],
"console_url": "string"
}Add the gradient of a loss over a batch#
POST/v1/trainers/{id}/forward_backward
Gradients accumulate until optim_step.
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body ForwardBackwardRequest
seqintegerrequiredThis op's place in the trainer's order: the trainer's
next_seq, then one more per op. A resend of the same seq and body returns the op it created; any other seq is 409seq_conflict.dataarray of DatumrequiredlossTrainerLossrequiredA weighted sum over tokens, additive over datums:
scale * sum(w * term).One of 12 shapes
- CrossEntropyLoss
type"cross_entropy"required"cross_entropy"scalenumberMultiplies
sum(weights * -logprobs). Default1 / sum(weights)of this call (the mean over trained tokens, SFTRecipe's per_token). Splitting one batch across calls: pass1 / sum(weights)of the whole batch.
- LinearLoss
type"linear"required"linear"scalenumberMultiplies
sum(coefficients * logprobs)(default 1).
- ImportanceSamplingLoss
type"importance_sampling"required"importance_sampling"scalenumberDefault
1 / sum(weights)of this call.
- PpoLoss
type"ppo"required"ppo"scalenumberDefault
1 / sum(weights)of this call.clip_lownumberclip_highnumber
- CispoLoss
type"cispo"required"cispo"scalenumberDefault
1 / sum(weights)of this call.clip_lownumberclip_highnumber
- DroLoss
type"dro"required"dro"scalenumberDefault
1 / sum(weights)of this call.betanumber
- StableReinforceLoss
type"stable_reinforce"required"stable_reinforce"scalenumberDefault
1 / sum(weights)of this call.clip_lownumberclip_highnumberkl_coefnumber
- SimpoLoss
type"simpo"required"simpo"scalenumberDefault
1 / num_pairsof this call.betanumbergammanumber
- OrpoLoss
type"orpo"required"orpo"scalenumberDefault
1 / num_pairsof this call.betanumber
- KtoLoss
type"kto"required"kto"scalenumberDefault
1 / num_active_datumsof this call.betanumberdesirable_weightnumberundesirable_weightnumber
- NpoLoss
type"npo"required"npo"scalenumberDefault
1 / num_active_datumsof this call.betanumber
- KlAnchorLoss
type"kl_anchor"required"kl_anchor"scalenumberDefault
1 / sum(weights)of this call.betanumbermodeenum"k3""mse"
- CrossEntropyLoss
temperaturenumberDivides the (soft-capped) logits before the log-softmax: the log-probs are those of the distribution sampled at this temperature. The RL losses need the sampling temperature here.
Returns
200 TrainerOp A resend: the op this seq created.
202 TrainerOp Queued: the op (its future).
16 fields
idstringrequiredop_and 24 hex.trainer_idstringrequiredseqintegerrequiredIts place in the train lane; null on the sample lane.
laneTrainerOpLanerequiredtrain: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.
"train""sample"snapshot_seqintegerrequiredA snapshot sample: the snapshot it samples from.
request_keystringrequiredA snapshot sample's idempotency key.
typeTrainerOpTyperequired"forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"statusTrainerOpStatusrequired"queued""running""done""failed"resultTrainerOpResultAn op's result once it is done (by
type); absent while it is pending, and when it is large (thenresult_url).One of 8 shapes
- ForwardBackwardResult
type"forward_backward"required"forward_backward"lossnumberrequiredscale * loss_sum.loss_sumnumberrequiredsum(w * term)before scale.weight_sumnumberrequiredsum(w): the weights (or coefficients) the loss read.metricsTrainerLossMetricsrequiredOver the tokens or datums the loss reads. The RL fields come with
importance_sampling,ppo,cispo,droandstable_reinforce; preference and reference diagnostics come withsimpo,orpo,kto,npoandkl_anchor.19 child fields
tokensintegerrequiredtrained_tokensintegerrequiredTokens the loss reads (nonzero weight or coefficient).
token_accuracynumberrequiredtruncatedintegerkl_sample_trainnumberRL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).
kl_sample_train_v2numberRL losses: 0.5 * mean((sampling_logprob - logprob)^2).
sample_train_max_diffnumberRL losses: max |sampling_logprob - logprob|.
entropynumberRL losses: mean token-level Shannon entropy (
-sum(p * log p)) of the current policy over the trained tokens.ratio_meannumberratio_maxnumberclip_fractionnumberppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.
preference_accuracynumbersimpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.
margin_meannumbersimpo and orpo: mean reward margin (
beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).chosen_reward_meannumbersimpo and kto: mean implicit reward on chosen / desirable sequences.
rejected_reward_meannumbersimpo and kto: mean implicit reward on rejected / undesirable sequences.
sft_loss_meannumberorpo and kl_anchor: mean SFT negative log-likelihood component.
or_loss_meannumberorpo: mean odds-ratio preference loss component.
kl_refnumberkto, npo and kl_anchor: reference divergence diagnostic (batch
z_reffor kto, mean log-ratio for npo, mean KL penalty for kl_anchor).ref_diff_maxnumberkto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.
- ForwardResult
type"forward"required"forward"logprobsarray of Tensorrequired2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
lossnumberrequiredloss_sumnumberrequiredweight_sumnumberrequiredmetricsTrainerLossMetricsrequired
- OptimStepResult
type"optim_step"required"optim_step"stepintegerrequiredgrad_normnumberrequiredskippedbooleanrequiredNo gradients were pending: nothing changed.
lrnumberThe numeric learning rate applied (resolved when
lr: "auto"was requested).
- SampleResult
type"sample"required"sample"resultsarray of objectrequired4 child fields
prompt_tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
prompt_logprobsTensorA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
resetbooleanrequiredA
continuewhose template rewrote history:prompt_tokensare a fresh render, nottokensplus a delta (the trajectory starts a new segment). False for other prompts.samplesarray of TrainerSamplerequired7 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
logprobsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
top_logprobsarray of array of TopLogprobPresent when
top_logprobs > 0: for each sampled token, up to K(token_id, logprob)pairs ordered highest logprob first.textstringrequiredfinish_reasonenumrequiredstop: a stop token or string; length:
max_tokens(or, on acontinue, the room left inmax_seq_len); context_full: acontinuewith no room left, no tokens."stop""length""context_full"messageSampledAssistantMessagerequiredThe sample parsed with the base's template (reasoning and OpenAI-style tool calls,
argumentsa JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays incontentandparsedis false.4 child fields
role"assistant"required"assistant"contentstringrequiredreasoning_contentstringtool_callsarray of object3 child fields
idstringrequiredtype"function"required"function"functionobjectrequired
parsedbooleanrequiredThe reply parsed cleanly (no malformed tool call). False:
message.contentholds the raw text, which an environment gets as text.
- SaveStateResult
type"save_state"required"save_state"checkpointobjectrequired5 child fields
idstringrequiredstepintegerrequirednamestringexpires_atstring (date-time)metadatamap of any
- ExportResult
type"export"required"export"artifactArtifactrequired16 child fields
idstringrequiredArtifact id:
name@version.workspace_idstringrequirednamestringrequiredArtifact name, usually the run name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredVersion,
YYYY-MM-DD-N: the release date and its sequence that day.run_idstringrequiredThe run that trained it; null for uploads and imports.
checkpoint_idstringrequiredThe checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.
base_modelstringrequiredThe base model the weights apply to.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"formatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sha256stringrequiredSHA-256 of the bundle; downloads verify it.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
manifestmap of anyrequiredThe bundle's manifest.json: format, base model, adapter and training settings.
provenanceArtifactProvenancerequired5 child fields
sourceenumrequiredrun: trained by a grad run; trainer: exported by a trainer (
trainer.export); upload: files uploaded withgrad artifacts upload; import: pulled from the Hugging Face Hub withgrad artifacts import."run""trainer""upload""import"run_idstringrequiredsource=run: the run that trained it.
trainer_idstringrequiredsource=trainer: the trainer that exported it.
uploaderstringrequiredsource=upload: the API key (principal) that uploaded it.
uristringrequiredsource=import:
hf://owner/name@<40-hex commit>, the pinned revision it was imported from.
eval_reportEvalReportrequiredcreated_atstring (date-time)requiredWhen it was released.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
- RenderResult
type"render"required"render"dataarray of RenderedDatumrequired4 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
weightsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
truncatedbooleanrequiredmediaarray of MediaItem4 child fields
kindenumrequired"image""audio"mimeenumrequired"image/png""image/jpeg""image/webp""audio/wav"datastringMatches
^[A-Za-z0-9+/]+={0,2}$media_idstringContent-addressed media upload id (
med_...fromPOST /v1/media); mutually exclusive withdata.Matches
^med_[0-9a-f]{24}$
- SnapshotResult
type"snapshot"required"snapshot"snapshotobjectrequired2 child fields
seqintegerrequiredstepintegerrequired
- ForwardBackwardResult
result_urlstringrequiredA result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.
errorTrainerOpErrorrequiredWhy it failed:
invalid_datum,invalid_continuation,trainer_lost(the worker died; ops after its last saved state are gone),trainer_closed,op_failed,result_expired,snapshot_released,deadline_exceeded,result_too_large.usageTrainerUsagerequired4 child fields
tokensintegerrequiredcost_usdnumberrequiredprompt_tokensintegersampled_tokensinteger
compute_msintegerrequiredWorker compute time (a sample-lane op: its batch's, shared by the ops batched together).
started_atis when the worker took the op, which may be before it ran (prefetch).created_atstring (date-time)requiredstarted_atstring (date-time)requiredfinished_atstring (date-time)required
from grad import Grad, Record, losses
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
out = trainer.forward_backward(
[
Record(messages=[
{"role": "user", "content": "Translate 'good morning' to French."},
{"role": "assistant", "content": "Bonjour."},
])
],
loss=losses.CrossEntropy(),
).result()
print(out.loss){
"id": "op_3f9c0a1b2c3d4e5f60718293",
"trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
"seq": 1,
"lane": "train",
"snapshot_seq": 1,
"request_key": "string",
"type": "forward_backward",
"status": "queued",
"result": {
"type": "forward_backward",
"loss": 0,
"loss_sum": 0,
"weight_sum": 0,
"metrics": {
"tokens": 0,
"trained_tokens": 0,
"token_accuracy": 0,
"truncated": 0,
"kl_sample_train": 0,
"kl_sample_train_v2": 0,
"sample_train_max_diff": 0,
"entropy": 0,
"ratio_mean": 0,
"ratio_max": 0,
"clip_fraction": 0,
"preference_accuracy": 0,
"margin_mean": 0,
"chosen_reward_mean": 0,
"rejected_reward_mean": 0,
"sft_loss_mean": 0,
"or_loss_mean": 0,
"kl_ref": 0,
"ref_diff_max": 0
}
},
"result_url": "string",
"error": {
"code": "string",
"message": "…"
},
"usage": {
"tokens": 0,
"cost_usd": 0,
"prompt_tokens": 0,
"sampled_tokens": 0
},
"compute_ms": 0,
"created_at": "2026-11-28T09:30:00.000Z",
"started_at": "2026-11-28T09:30:00.000Z",
"finished_at": "2026-11-28T09:30:00.000Z"
}Per-token log-probs of a batch (current, base or initial weights); no gradient#
POST/v1/trainers/{id}/forward
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body ForwardRequest
seqintegerrequiredThis op's place in the trainer's order: the trainer's
next_seq, then one more per op. A resend of the same seq and body returns the op it created; any other seq is 409seq_conflict.dataarray of Datumrequiredweightsstringcurrent: the trained adapter; base: the base model (the LoRA disabled in place); initial: the adapter the trainer started from (a from_artifact's; a fresh LoRA's is the base);
snapshot:<seq>: a live snapshot's frozen weights (exact PPO ratios against the weights that sampled). Reference log-probs without a second model.Matches
^(current|base|initial|snapshot:[1-9][0-9]{0,9})$temperaturenumberDivides the (soft-capped) logits before the log-softmax: the log-probs are those of the distribution sampled at this temperature. The RL losses need the sampling temperature here.
Returns
200 TrainerOp A resend: the op this seq created.
202 TrainerOp Queued: the op (its future).
16 fields
idstringrequiredop_and 24 hex.trainer_idstringrequiredseqintegerrequiredIts place in the train lane; null on the sample lane.
laneTrainerOpLanerequiredtrain: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.
"train""sample"snapshot_seqintegerrequiredA snapshot sample: the snapshot it samples from.
request_keystringrequiredA snapshot sample's idempotency key.
typeTrainerOpTyperequired"forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"statusTrainerOpStatusrequired"queued""running""done""failed"resultTrainerOpResultAn op's result once it is done (by
type); absent while it is pending, and when it is large (thenresult_url).One of 8 shapes
- ForwardBackwardResult
type"forward_backward"required"forward_backward"lossnumberrequiredscale * loss_sum.loss_sumnumberrequiredsum(w * term)before scale.weight_sumnumberrequiredsum(w): the weights (or coefficients) the loss read.metricsTrainerLossMetricsrequiredOver the tokens or datums the loss reads. The RL fields come with
importance_sampling,ppo,cispo,droandstable_reinforce; preference and reference diagnostics come withsimpo,orpo,kto,npoandkl_anchor.19 child fields
tokensintegerrequiredtrained_tokensintegerrequiredTokens the loss reads (nonzero weight or coefficient).
token_accuracynumberrequiredtruncatedintegerkl_sample_trainnumberRL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).
kl_sample_train_v2numberRL losses: 0.5 * mean((sampling_logprob - logprob)^2).
sample_train_max_diffnumberRL losses: max |sampling_logprob - logprob|.
entropynumberRL losses: mean token-level Shannon entropy (
-sum(p * log p)) of the current policy over the trained tokens.ratio_meannumberratio_maxnumberclip_fractionnumberppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.
preference_accuracynumbersimpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.
margin_meannumbersimpo and orpo: mean reward margin (
beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).chosen_reward_meannumbersimpo and kto: mean implicit reward on chosen / desirable sequences.
rejected_reward_meannumbersimpo and kto: mean implicit reward on rejected / undesirable sequences.
sft_loss_meannumberorpo and kl_anchor: mean SFT negative log-likelihood component.
or_loss_meannumberorpo: mean odds-ratio preference loss component.
kl_refnumberkto, npo and kl_anchor: reference divergence diagnostic (batch
z_reffor kto, mean log-ratio for npo, mean KL penalty for kl_anchor).ref_diff_maxnumberkto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.
- ForwardResult
type"forward"required"forward"logprobsarray of Tensorrequired2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
lossnumberrequiredloss_sumnumberrequiredweight_sumnumberrequiredmetricsTrainerLossMetricsrequired
- OptimStepResult
type"optim_step"required"optim_step"stepintegerrequiredgrad_normnumberrequiredskippedbooleanrequiredNo gradients were pending: nothing changed.
lrnumberThe numeric learning rate applied (resolved when
lr: "auto"was requested).
- SampleResult
type"sample"required"sample"resultsarray of objectrequired4 child fields
prompt_tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
prompt_logprobsTensorA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
resetbooleanrequiredA
continuewhose template rewrote history:prompt_tokensare a fresh render, nottokensplus a delta (the trajectory starts a new segment). False for other prompts.samplesarray of TrainerSamplerequired7 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
logprobsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
top_logprobsarray of array of TopLogprobPresent when
top_logprobs > 0: for each sampled token, up to K(token_id, logprob)pairs ordered highest logprob first.textstringrequiredfinish_reasonenumrequiredstop: a stop token or string; length:
max_tokens(or, on acontinue, the room left inmax_seq_len); context_full: acontinuewith no room left, no tokens."stop""length""context_full"messageSampledAssistantMessagerequiredThe sample parsed with the base's template (reasoning and OpenAI-style tool calls,
argumentsa JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays incontentandparsedis false.4 child fields
role"assistant"required"assistant"contentstringrequiredreasoning_contentstringtool_callsarray of object3 child fields
idstringrequiredtype"function"required"function"functionobjectrequired
parsedbooleanrequiredThe reply parsed cleanly (no malformed tool call). False:
message.contentholds the raw text, which an environment gets as text.
- SaveStateResult
type"save_state"required"save_state"checkpointobjectrequired5 child fields
idstringrequiredstepintegerrequirednamestringexpires_atstring (date-time)metadatamap of any
- ExportResult
type"export"required"export"artifactArtifactrequired16 child fields
idstringrequiredArtifact id:
name@version.workspace_idstringrequirednamestringrequiredArtifact name, usually the run name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredVersion,
YYYY-MM-DD-N: the release date and its sequence that day.run_idstringrequiredThe run that trained it; null for uploads and imports.
checkpoint_idstringrequiredThe checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.
base_modelstringrequiredThe base model the weights apply to.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"formatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sha256stringrequiredSHA-256 of the bundle; downloads verify it.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
manifestmap of anyrequiredThe bundle's manifest.json: format, base model, adapter and training settings.
provenanceArtifactProvenancerequired5 child fields
sourceenumrequiredrun: trained by a grad run; trainer: exported by a trainer (
trainer.export); upload: files uploaded withgrad artifacts upload; import: pulled from the Hugging Face Hub withgrad artifacts import."run""trainer""upload""import"run_idstringrequiredsource=run: the run that trained it.
trainer_idstringrequiredsource=trainer: the trainer that exported it.
uploaderstringrequiredsource=upload: the API key (principal) that uploaded it.
uristringrequiredsource=import:
hf://owner/name@<40-hex commit>, the pinned revision it was imported from.
eval_reportEvalReportrequiredcreated_atstring (date-time)requiredWhen it was released.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
- RenderResult
type"render"required"render"dataarray of RenderedDatumrequired4 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
weightsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
truncatedbooleanrequiredmediaarray of MediaItem4 child fields
kindenumrequired"image""audio"mimeenumrequired"image/png""image/jpeg""image/webp""audio/wav"datastringMatches
^[A-Za-z0-9+/]+={0,2}$media_idstringContent-addressed media upload id (
med_...fromPOST /v1/media); mutually exclusive withdata.Matches
^med_[0-9a-f]{24}$
- SnapshotResult
type"snapshot"required"snapshot"snapshotobjectrequired2 child fields
seqintegerrequiredstepintegerrequired
- ForwardBackwardResult
result_urlstringrequiredA result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.
errorTrainerOpErrorrequiredWhy it failed:
invalid_datum,invalid_continuation,trainer_lost(the worker died; ops after its last saved state are gone),trainer_closed,op_failed,result_expired,snapshot_released,deadline_exceeded,result_too_large.usageTrainerUsagerequired4 child fields
tokensintegerrequiredcost_usdnumberrequiredprompt_tokensintegersampled_tokensinteger
compute_msintegerrequiredWorker compute time (a sample-lane op: its batch's, shared by the ops batched together).
started_atis when the worker took the op, which may be before it ran (prefetch).created_atstring (date-time)requiredstarted_atstring (date-time)requiredfinished_atstring (date-time)required
from grad import Grad, Record
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
out = trainer.forward(
[
Record(messages=[
{"role": "user", "content": "Translate 'good morning' to French."},
{"role": "assistant", "content": "Bonjour."},
])
],
weights="current",
).result()
print(out.loss){
"id": "op_3f9c0a1b2c3d4e5f60718293",
"trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
"seq": 1,
"lane": "train",
"snapshot_seq": 1,
"request_key": "string",
"type": "forward_backward",
"status": "queued",
"result": {
"type": "forward_backward",
"loss": 0,
"loss_sum": 0,
"weight_sum": 0,
"metrics": {
"tokens": 0,
"trained_tokens": 0,
"token_accuracy": 0,
"truncated": 0,
"kl_sample_train": 0,
"kl_sample_train_v2": 0,
"sample_train_max_diff": 0,
"entropy": 0,
"ratio_mean": 0,
"ratio_max": 0,
"clip_fraction": 0,
"preference_accuracy": 0,
"margin_mean": 0,
"chosen_reward_mean": 0,
"rejected_reward_mean": 0,
"sft_loss_mean": 0,
"or_loss_mean": 0,
"kl_ref": 0,
"ref_diff_max": 0
}
},
"result_url": "string",
"error": {
"code": "string",
"message": "…"
},
"usage": {
"tokens": 0,
"cost_usd": 0,
"prompt_tokens": 0,
"sampled_tokens": 0
},
"compute_ms": 0,
"created_at": "2026-11-28T09:30:00.000Z",
"started_at": "2026-11-28T09:30:00.000Z",
"finished_at": "2026-11-28T09:30:00.000Z"
}One AdamW step from the accumulated gradients#
POST/v1/trainers/{id}/optim_step
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body OptimStepRequest
seqintegerrequiredThis op's place in the trainer's order: the trainer's
next_seq, then one more per op. A resend of the same seq and body returns the op it created; any other seq is 409seq_conflict.lrnumber or "auto"requiredPositive learning rate (<= 1), or
"auto"to resolve from the base model's calibrated learning rate forobjective(refused with422 uncalibrated_modelwhen uncalibrated).One of 2 shapes
- number
- "auto"
objectiveOptimStepObjectiveTraining objective used to resolve
lr: "auto"(sft,rl,dpo; defaults tosft)."sft""rl""dpo"beta1numberbeta2numberepsnumberweight_decaynumbergrad_clip_normnumberClip the gradient's global norm to this (0: no clipping).
Returns
200 TrainerOp A resend: the op this seq created.
202 TrainerOp Queued: the op (its future).
16 fields
idstringrequiredop_and 24 hex.trainer_idstringrequiredseqintegerrequiredIts place in the train lane; null on the sample lane.
laneTrainerOpLanerequiredtrain: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.
"train""sample"snapshot_seqintegerrequiredA snapshot sample: the snapshot it samples from.
request_keystringrequiredA snapshot sample's idempotency key.
typeTrainerOpTyperequired"forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"statusTrainerOpStatusrequired"queued""running""done""failed"resultTrainerOpResultAn op's result once it is done (by
type); absent while it is pending, and when it is large (thenresult_url).One of 8 shapes
- ForwardBackwardResult
type"forward_backward"required"forward_backward"lossnumberrequiredscale * loss_sum.loss_sumnumberrequiredsum(w * term)before scale.weight_sumnumberrequiredsum(w): the weights (or coefficients) the loss read.metricsTrainerLossMetricsrequiredOver the tokens or datums the loss reads. The RL fields come with
importance_sampling,ppo,cispo,droandstable_reinforce; preference and reference diagnostics come withsimpo,orpo,kto,npoandkl_anchor.19 child fields
tokensintegerrequiredtrained_tokensintegerrequiredTokens the loss reads (nonzero weight or coefficient).
token_accuracynumberrequiredtruncatedintegerkl_sample_trainnumberRL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).
kl_sample_train_v2numberRL losses: 0.5 * mean((sampling_logprob - logprob)^2).
sample_train_max_diffnumberRL losses: max |sampling_logprob - logprob|.
entropynumberRL losses: mean token-level Shannon entropy (
-sum(p * log p)) of the current policy over the trained tokens.ratio_meannumberratio_maxnumberclip_fractionnumberppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.
preference_accuracynumbersimpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.
margin_meannumbersimpo and orpo: mean reward margin (
beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).chosen_reward_meannumbersimpo and kto: mean implicit reward on chosen / desirable sequences.
rejected_reward_meannumbersimpo and kto: mean implicit reward on rejected / undesirable sequences.
sft_loss_meannumberorpo and kl_anchor: mean SFT negative log-likelihood component.
or_loss_meannumberorpo: mean odds-ratio preference loss component.
kl_refnumberkto, npo and kl_anchor: reference divergence diagnostic (batch
z_reffor kto, mean log-ratio for npo, mean KL penalty for kl_anchor).ref_diff_maxnumberkto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.
- ForwardResult
type"forward"required"forward"logprobsarray of Tensorrequired2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
lossnumberrequiredloss_sumnumberrequiredweight_sumnumberrequiredmetricsTrainerLossMetricsrequired
- OptimStepResult
type"optim_step"required"optim_step"stepintegerrequiredgrad_normnumberrequiredskippedbooleanrequiredNo gradients were pending: nothing changed.
lrnumberThe numeric learning rate applied (resolved when
lr: "auto"was requested).
- SampleResult
type"sample"required"sample"resultsarray of objectrequired4 child fields
prompt_tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
prompt_logprobsTensorA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
resetbooleanrequiredA
continuewhose template rewrote history:prompt_tokensare a fresh render, nottokensplus a delta (the trajectory starts a new segment). False for other prompts.samplesarray of TrainerSamplerequired7 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
logprobsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
top_logprobsarray of array of TopLogprobPresent when
top_logprobs > 0: for each sampled token, up to K(token_id, logprob)pairs ordered highest logprob first.textstringrequiredfinish_reasonenumrequiredstop: a stop token or string; length:
max_tokens(or, on acontinue, the room left inmax_seq_len); context_full: acontinuewith no room left, no tokens."stop""length""context_full"messageSampledAssistantMessagerequiredThe sample parsed with the base's template (reasoning and OpenAI-style tool calls,
argumentsa JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays incontentandparsedis false.4 child fields
role"assistant"required"assistant"contentstringrequiredreasoning_contentstringtool_callsarray of object3 child fields
idstringrequiredtype"function"required"function"functionobjectrequired
parsedbooleanrequiredThe reply parsed cleanly (no malformed tool call). False:
message.contentholds the raw text, which an environment gets as text.
- SaveStateResult
type"save_state"required"save_state"checkpointobjectrequired5 child fields
idstringrequiredstepintegerrequirednamestringexpires_atstring (date-time)metadatamap of any
- ExportResult
type"export"required"export"artifactArtifactrequired16 child fields
idstringrequiredArtifact id:
name@version.workspace_idstringrequirednamestringrequiredArtifact name, usually the run name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredVersion,
YYYY-MM-DD-N: the release date and its sequence that day.run_idstringrequiredThe run that trained it; null for uploads and imports.
checkpoint_idstringrequiredThe checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.
base_modelstringrequiredThe base model the weights apply to.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"formatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sha256stringrequiredSHA-256 of the bundle; downloads verify it.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
manifestmap of anyrequiredThe bundle's manifest.json: format, base model, adapter and training settings.
provenanceArtifactProvenancerequired5 child fields
sourceenumrequiredrun: trained by a grad run; trainer: exported by a trainer (
trainer.export); upload: files uploaded withgrad artifacts upload; import: pulled from the Hugging Face Hub withgrad artifacts import."run""trainer""upload""import"run_idstringrequiredsource=run: the run that trained it.
trainer_idstringrequiredsource=trainer: the trainer that exported it.
uploaderstringrequiredsource=upload: the API key (principal) that uploaded it.
uristringrequiredsource=import:
hf://owner/name@<40-hex commit>, the pinned revision it was imported from.
eval_reportEvalReportrequiredcreated_atstring (date-time)requiredWhen it was released.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
- RenderResult
type"render"required"render"dataarray of RenderedDatumrequired4 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
weightsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
truncatedbooleanrequiredmediaarray of MediaItem4 child fields
kindenumrequired"image""audio"mimeenumrequired"image/png""image/jpeg""image/webp""audio/wav"datastringMatches
^[A-Za-z0-9+/]+={0,2}$media_idstringContent-addressed media upload id (
med_...fromPOST /v1/media); mutually exclusive withdata.Matches
^med_[0-9a-f]{24}$
- SnapshotResult
type"snapshot"required"snapshot"snapshotobjectrequired2 child fields
seqintegerrequiredstepintegerrequired
- ForwardBackwardResult
result_urlstringrequiredA result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.
errorTrainerOpErrorrequiredWhy it failed:
invalid_datum,invalid_continuation,trainer_lost(the worker died; ops after its last saved state are gone),trainer_closed,op_failed,result_expired,snapshot_released,deadline_exceeded,result_too_large.usageTrainerUsagerequired4 child fields
tokensintegerrequiredcost_usdnumberrequiredprompt_tokensintegersampled_tokensinteger
compute_msintegerrequiredWorker compute time (a sample-lane op: its batch's, shared by the ops batched together).
started_atis when the worker took the op, which may be before it ran (prefetch).created_atstring (date-time)requiredstarted_atstring (date-time)requiredfinished_atstring (date-time)required
from grad import Grad, optim
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
step = trainer.optim_step(optim.AdamW(lr="auto", objective="sft")).result()
print(step.step, step.lr, step.grad_norm){
"id": "op_3f9c0a1b2c3d4e5f60718293",
"trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
"seq": 1,
"lane": "train",
"snapshot_seq": 1,
"request_key": "string",
"type": "forward_backward",
"status": "queued",
"result": {
"type": "forward_backward",
"loss": 0,
"loss_sum": 0,
"weight_sum": 0,
"metrics": {
"tokens": 0,
"trained_tokens": 0,
"token_accuracy": 0,
"truncated": 0,
"kl_sample_train": 0,
"kl_sample_train_v2": 0,
"sample_train_max_diff": 0,
"entropy": 0,
"ratio_mean": 0,
"ratio_max": 0,
"clip_fraction": 0,
"preference_accuracy": 0,
"margin_mean": 0,
"chosen_reward_mean": 0,
"rejected_reward_mean": 0,
"sft_loss_mean": 0,
"or_loss_mean": 0,
"kl_ref": 0,
"ref_diff_max": 0
}
},
"result_url": "string",
"error": {
"code": "string",
"message": "…"
},
"usage": {
"tokens": 0,
"cost_usd": 0,
"prompt_tokens": 0,
"sampled_tokens": 0
},
"compute_ms": 0,
"created_at": "2026-11-28T09:30:00.000Z",
"started_at": "2026-11-28T09:30:00.000Z",
"finished_at": "2026-11-28T09:30:00.000Z"
}Sample from the current weights, in op order#
POST/v1/trainers/{id}/sample
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body SampleRequest
seqintegerrequiredThis op's place in the trainer's order: the trainer's
next_seq, then one more per op. A resend of the same seq and body returns the op it created; any other seq is 409seq_conflict.promptsarray of SamplePromptrequirednum_samplesintegermax_tokensintegerrequiredtemperaturenumbertop_pnumbertop_kintegerKeep only the top K tokens before sampling (omitted or null: disabled).
top_logprobsintegerNumber of highest-probability
(token_id, logprob)pairs to return per generated token from the processed distribution (default 0: omitted).prompt_logprobsbooleanReturn per-prompt-token logprobs under the active weights (
float32lengthlen(prompt_tokens), index 0 is0.0; default false).stoparray of string or integerStop strings and token ids; they replace the base's stop tokens (the trainer's
stop_token_ids).[]: run tomax_tokens. A stop token is kept intokens.seedintegerReproducible sampling for the same request. On a snapshot, a seeded op runs alone (not batched with others).
streambooleanEmit incremental token deltas to
GET /v1/trainers/{id}/ops/{op_id}/stream(SSE) while generating. Streaming snapshot samples run alone (never coalesced) for minimal time-to-first-token.weightsstringWeights to sample with (default
"current")."base"disables the LoRA;"initial"uses the starting adapter;"checkpoint:<id>"or"artifact:<id>"hot-swaps a compatible PEFT LoRA adapter on amode: "sample"session.Matches
^(current|base|initial|(?:checkpoint|artifact):[A-Za-z0-9._@:-]{1,200})$
Returns
200 TrainerOp A resend: the op this seq created.
202 TrainerOp Queued: the op (its future).
16 fields
idstringrequiredop_and 24 hex.trainer_idstringrequiredseqintegerrequiredIts place in the train lane; null on the sample lane.
laneTrainerOpLanerequiredtrain: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.
"train""sample"snapshot_seqintegerrequiredA snapshot sample: the snapshot it samples from.
request_keystringrequiredA snapshot sample's idempotency key.
typeTrainerOpTyperequired"forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"statusTrainerOpStatusrequired"queued""running""done""failed"resultTrainerOpResultAn op's result once it is done (by
type); absent while it is pending, and when it is large (thenresult_url).One of 8 shapes
- ForwardBackwardResult
type"forward_backward"required"forward_backward"lossnumberrequiredscale * loss_sum.loss_sumnumberrequiredsum(w * term)before scale.weight_sumnumberrequiredsum(w): the weights (or coefficients) the loss read.metricsTrainerLossMetricsrequiredOver the tokens or datums the loss reads. The RL fields come with
importance_sampling,ppo,cispo,droandstable_reinforce; preference and reference diagnostics come withsimpo,orpo,kto,npoandkl_anchor.19 child fields
tokensintegerrequiredtrained_tokensintegerrequiredTokens the loss reads (nonzero weight or coefficient).
token_accuracynumberrequiredtruncatedintegerkl_sample_trainnumberRL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).
kl_sample_train_v2numberRL losses: 0.5 * mean((sampling_logprob - logprob)^2).
sample_train_max_diffnumberRL losses: max |sampling_logprob - logprob|.
entropynumberRL losses: mean token-level Shannon entropy (
-sum(p * log p)) of the current policy over the trained tokens.ratio_meannumberratio_maxnumberclip_fractionnumberppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.
preference_accuracynumbersimpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.
margin_meannumbersimpo and orpo: mean reward margin (
beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).chosen_reward_meannumbersimpo and kto: mean implicit reward on chosen / desirable sequences.
rejected_reward_meannumbersimpo and kto: mean implicit reward on rejected / undesirable sequences.
sft_loss_meannumberorpo and kl_anchor: mean SFT negative log-likelihood component.
or_loss_meannumberorpo: mean odds-ratio preference loss component.
kl_refnumberkto, npo and kl_anchor: reference divergence diagnostic (batch
z_reffor kto, mean log-ratio for npo, mean KL penalty for kl_anchor).ref_diff_maxnumberkto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.
- ForwardResult
type"forward"required"forward"logprobsarray of Tensorrequired2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
lossnumberrequiredloss_sumnumberrequiredweight_sumnumberrequiredmetricsTrainerLossMetricsrequired
- OptimStepResult
type"optim_step"required"optim_step"stepintegerrequiredgrad_normnumberrequiredskippedbooleanrequiredNo gradients were pending: nothing changed.
lrnumberThe numeric learning rate applied (resolved when
lr: "auto"was requested).
- SampleResult
type"sample"required"sample"resultsarray of objectrequired4 child fields
prompt_tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
prompt_logprobsTensorA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
resetbooleanrequiredA
continuewhose template rewrote history:prompt_tokensare a fresh render, nottokensplus a delta (the trajectory starts a new segment). False for other prompts.samplesarray of TrainerSamplerequired7 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
logprobsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
top_logprobsarray of array of TopLogprobPresent when
top_logprobs > 0: for each sampled token, up to K(token_id, logprob)pairs ordered highest logprob first.textstringrequiredfinish_reasonenumrequiredstop: a stop token or string; length:
max_tokens(or, on acontinue, the room left inmax_seq_len); context_full: acontinuewith no room left, no tokens."stop""length""context_full"messageSampledAssistantMessagerequiredThe sample parsed with the base's template (reasoning and OpenAI-style tool calls,
argumentsa JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays incontentandparsedis false.4 child fields
role"assistant"required"assistant"contentstringrequiredreasoning_contentstringtool_callsarray of object3 child fields
idstringrequiredtype"function"required"function"functionobjectrequired
parsedbooleanrequiredThe reply parsed cleanly (no malformed tool call). False:
message.contentholds the raw text, which an environment gets as text.
- SaveStateResult
type"save_state"required"save_state"checkpointobjectrequired5 child fields
idstringrequiredstepintegerrequirednamestringexpires_atstring (date-time)metadatamap of any
- ExportResult
type"export"required"export"artifactArtifactrequired16 child fields
idstringrequiredArtifact id:
name@version.workspace_idstringrequirednamestringrequiredArtifact name, usually the run name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredVersion,
YYYY-MM-DD-N: the release date and its sequence that day.run_idstringrequiredThe run that trained it; null for uploads and imports.
checkpoint_idstringrequiredThe checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.
base_modelstringrequiredThe base model the weights apply to.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"formatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sha256stringrequiredSHA-256 of the bundle; downloads verify it.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
manifestmap of anyrequiredThe bundle's manifest.json: format, base model, adapter and training settings.
provenanceArtifactProvenancerequired5 child fields
sourceenumrequiredrun: trained by a grad run; trainer: exported by a trainer (
trainer.export); upload: files uploaded withgrad artifacts upload; import: pulled from the Hugging Face Hub withgrad artifacts import."run""trainer""upload""import"run_idstringrequiredsource=run: the run that trained it.
trainer_idstringrequiredsource=trainer: the trainer that exported it.
uploaderstringrequiredsource=upload: the API key (principal) that uploaded it.
uristringrequiredsource=import:
hf://owner/name@<40-hex commit>, the pinned revision it was imported from.
eval_reportEvalReportrequiredcreated_atstring (date-time)requiredWhen it was released.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
- RenderResult
type"render"required"render"dataarray of RenderedDatumrequired4 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
weightsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
truncatedbooleanrequiredmediaarray of MediaItem4 child fields
kindenumrequired"image""audio"mimeenumrequired"image/png""image/jpeg""image/webp""audio/wav"datastringMatches
^[A-Za-z0-9+/]+={0,2}$media_idstringContent-addressed media upload id (
med_...fromPOST /v1/media); mutually exclusive withdata.Matches
^med_[0-9a-f]{24}$
- SnapshotResult
type"snapshot"required"snapshot"snapshotobjectrequired2 child fields
seqintegerrequiredstepintegerrequired
- ForwardBackwardResult
result_urlstringrequiredA result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.
errorTrainerOpErrorrequiredWhy it failed:
invalid_datum,invalid_continuation,trainer_lost(the worker died; ops after its last saved state are gone),trainer_closed,op_failed,result_expired,snapshot_released,deadline_exceeded,result_too_large.usageTrainerUsagerequired4 child fields
tokensintegerrequiredcost_usdnumberrequiredprompt_tokensintegersampled_tokensinteger
compute_msintegerrequiredWorker compute time (a sample-lane op: its batch's, shared by the ops batched together).
started_atis when the worker took the op, which may be before it ran (prefetch).created_atstring (date-time)requiredstarted_atstring (date-time)requiredfinished_atstring (date-time)required
from grad import Grad
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
out = trainer.sample(
[{"messages": [{"role": "user", "content": "What is 12 * 7?"}]}],
max_tokens=128,
).result()
print(out.results[0].samples[0].text){
"id": "op_3f9c0a1b2c3d4e5f60718293",
"trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
"seq": 1,
"lane": "train",
"snapshot_seq": 1,
"request_key": "string",
"type": "forward_backward",
"status": "queued",
"result": {
"type": "forward_backward",
"loss": 0,
"loss_sum": 0,
"weight_sum": 0,
"metrics": {
"tokens": 0,
"trained_tokens": 0,
"token_accuracy": 0,
"truncated": 0,
"kl_sample_train": 0,
"kl_sample_train_v2": 0,
"sample_train_max_diff": 0,
"entropy": 0,
"ratio_mean": 0,
"ratio_max": 0,
"clip_fraction": 0,
"preference_accuracy": 0,
"margin_mean": 0,
"chosen_reward_mean": 0,
"rejected_reward_mean": 0,
"sft_loss_mean": 0,
"or_loss_mean": 0,
"kl_ref": 0,
"ref_diff_max": 0
}
},
"result_url": "string",
"error": {
"code": "string",
"message": "…"
},
"usage": {
"tokens": 0,
"cost_usd": 0,
"prompt_tokens": 0,
"sampled_tokens": 0
},
"compute_ms": 0,
"created_at": "2026-11-28T09:30:00.000Z",
"started_at": "2026-11-28T09:30:00.000Z",
"finished_at": "2026-11-28T09:30:00.000Z"
}Save the weights, optimizer, pending gradients and step as a checkpoint#
POST/v1/trainers/{id}/save_state
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body SaveStateRequest
seqintegerrequiredThis op's place in the trainer's order: the trainer's
next_seq, then one more per op. A resend of the same seq and body returns the op it created; any other seq is 409seq_conflict.namestringttl_sintegerOptional TTL in seconds (300 to 7776000). Omitted or null keeps this checkpoint permanent.
metadatamap of anyOptional user metadata JSON object (at most 16 KiB serialized UTF-8) stored on the checkpoint.
Returns
200 TrainerOp A resend: the op this seq created.
202 TrainerOp Queued: the op (its future).
16 fields
idstringrequiredop_and 24 hex.trainer_idstringrequiredseqintegerrequiredIts place in the train lane; null on the sample lane.
laneTrainerOpLanerequiredtrain: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.
"train""sample"snapshot_seqintegerrequiredA snapshot sample: the snapshot it samples from.
request_keystringrequiredA snapshot sample's idempotency key.
typeTrainerOpTyperequired"forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"statusTrainerOpStatusrequired"queued""running""done""failed"resultTrainerOpResultAn op's result once it is done (by
type); absent while it is pending, and when it is large (thenresult_url).One of 8 shapes
- ForwardBackwardResult
type"forward_backward"required"forward_backward"lossnumberrequiredscale * loss_sum.loss_sumnumberrequiredsum(w * term)before scale.weight_sumnumberrequiredsum(w): the weights (or coefficients) the loss read.metricsTrainerLossMetricsrequiredOver the tokens or datums the loss reads. The RL fields come with
importance_sampling,ppo,cispo,droandstable_reinforce; preference and reference diagnostics come withsimpo,orpo,kto,npoandkl_anchor.19 child fields
tokensintegerrequiredtrained_tokensintegerrequiredTokens the loss reads (nonzero weight or coefficient).
token_accuracynumberrequiredtruncatedintegerkl_sample_trainnumberRL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).
kl_sample_train_v2numberRL losses: 0.5 * mean((sampling_logprob - logprob)^2).
sample_train_max_diffnumberRL losses: max |sampling_logprob - logprob|.
entropynumberRL losses: mean token-level Shannon entropy (
-sum(p * log p)) of the current policy over the trained tokens.ratio_meannumberratio_maxnumberclip_fractionnumberppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.
preference_accuracynumbersimpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.
margin_meannumbersimpo and orpo: mean reward margin (
beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).chosen_reward_meannumbersimpo and kto: mean implicit reward on chosen / desirable sequences.
rejected_reward_meannumbersimpo and kto: mean implicit reward on rejected / undesirable sequences.
sft_loss_meannumberorpo and kl_anchor: mean SFT negative log-likelihood component.
or_loss_meannumberorpo: mean odds-ratio preference loss component.
kl_refnumberkto, npo and kl_anchor: reference divergence diagnostic (batch
z_reffor kto, mean log-ratio for npo, mean KL penalty for kl_anchor).ref_diff_maxnumberkto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.
- ForwardResult
type"forward"required"forward"logprobsarray of Tensorrequired2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
lossnumberrequiredloss_sumnumberrequiredweight_sumnumberrequiredmetricsTrainerLossMetricsrequired
- OptimStepResult
type"optim_step"required"optim_step"stepintegerrequiredgrad_normnumberrequiredskippedbooleanrequiredNo gradients were pending: nothing changed.
lrnumberThe numeric learning rate applied (resolved when
lr: "auto"was requested).
- SampleResult
type"sample"required"sample"resultsarray of objectrequired4 child fields
prompt_tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
prompt_logprobsTensorA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
resetbooleanrequiredA
continuewhose template rewrote history:prompt_tokensare a fresh render, nottokensplus a delta (the trajectory starts a new segment). False for other prompts.samplesarray of TrainerSamplerequired7 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
logprobsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
top_logprobsarray of array of TopLogprobPresent when
top_logprobs > 0: for each sampled token, up to K(token_id, logprob)pairs ordered highest logprob first.textstringrequiredfinish_reasonenumrequiredstop: a stop token or string; length:
max_tokens(or, on acontinue, the room left inmax_seq_len); context_full: acontinuewith no room left, no tokens."stop""length""context_full"messageSampledAssistantMessagerequiredThe sample parsed with the base's template (reasoning and OpenAI-style tool calls,
argumentsa JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays incontentandparsedis false.4 child fields
role"assistant"required"assistant"contentstringrequiredreasoning_contentstringtool_callsarray of object3 child fields
idstringrequiredtype"function"required"function"functionobjectrequired
parsedbooleanrequiredThe reply parsed cleanly (no malformed tool call). False:
message.contentholds the raw text, which an environment gets as text.
- SaveStateResult
type"save_state"required"save_state"checkpointobjectrequired5 child fields
idstringrequiredstepintegerrequirednamestringexpires_atstring (date-time)metadatamap of any
- ExportResult
type"export"required"export"artifactArtifactrequired16 child fields
idstringrequiredArtifact id:
name@version.workspace_idstringrequirednamestringrequiredArtifact name, usually the run name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredVersion,
YYYY-MM-DD-N: the release date and its sequence that day.run_idstringrequiredThe run that trained it; null for uploads and imports.
checkpoint_idstringrequiredThe checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.
base_modelstringrequiredThe base model the weights apply to.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"formatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sha256stringrequiredSHA-256 of the bundle; downloads verify it.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
manifestmap of anyrequiredThe bundle's manifest.json: format, base model, adapter and training settings.
provenanceArtifactProvenancerequired5 child fields
sourceenumrequiredrun: trained by a grad run; trainer: exported by a trainer (
trainer.export); upload: files uploaded withgrad artifacts upload; import: pulled from the Hugging Face Hub withgrad artifacts import."run""trainer""upload""import"run_idstringrequiredsource=run: the run that trained it.
trainer_idstringrequiredsource=trainer: the trainer that exported it.
uploaderstringrequiredsource=upload: the API key (principal) that uploaded it.
uristringrequiredsource=import:
hf://owner/name@<40-hex commit>, the pinned revision it was imported from.
eval_reportEvalReportrequiredcreated_atstring (date-time)requiredWhen it was released.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
- RenderResult
type"render"required"render"dataarray of RenderedDatumrequired4 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
weightsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
truncatedbooleanrequiredmediaarray of MediaItem4 child fields
kindenumrequired"image""audio"mimeenumrequired"image/png""image/jpeg""image/webp""audio/wav"datastringMatches
^[A-Za-z0-9+/]+={0,2}$media_idstringContent-addressed media upload id (
med_...fromPOST /v1/media); mutually exclusive withdata.Matches
^med_[0-9a-f]{24}$
- SnapshotResult
type"snapshot"required"snapshot"snapshotobjectrequired2 child fields
seqintegerrequiredstepintegerrequired
- ForwardBackwardResult
result_urlstringrequiredA result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.
errorTrainerOpErrorrequiredWhy it failed:
invalid_datum,invalid_continuation,trainer_lost(the worker died; ops after its last saved state are gone),trainer_closed,op_failed,result_expired,snapshot_released,deadline_exceeded,result_too_large.usageTrainerUsagerequired4 child fields
tokensintegerrequiredcost_usdnumberrequiredprompt_tokensintegersampled_tokensinteger
compute_msintegerrequiredWorker compute time (a sample-lane op: its batch's, shared by the ops batched together).
started_atis when the worker took the op, which may be before it ran (prefetch).created_atstring (date-time)requiredstarted_atstring (date-time)requiredfinished_atstring (date-time)required
from grad import Grad
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
saved = trainer.save_state(name="step-1", ttl_s=86400).result()
print(saved.checkpoint.id, saved.checkpoint.expires_at){
"id": "op_3f9c0a1b2c3d4e5f60718293",
"trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
"seq": 1,
"lane": "train",
"snapshot_seq": 1,
"request_key": "string",
"type": "forward_backward",
"status": "queued",
"result": {
"type": "forward_backward",
"loss": 0,
"loss_sum": 0,
"weight_sum": 0,
"metrics": {
"tokens": 0,
"trained_tokens": 0,
"token_accuracy": 0,
"truncated": 0,
"kl_sample_train": 0,
"kl_sample_train_v2": 0,
"sample_train_max_diff": 0,
"entropy": 0,
"ratio_mean": 0,
"ratio_max": 0,
"clip_fraction": 0,
"preference_accuracy": 0,
"margin_mean": 0,
"chosen_reward_mean": 0,
"rejected_reward_mean": 0,
"sft_loss_mean": 0,
"or_loss_mean": 0,
"kl_ref": 0,
"ref_diff_max": 0
}
},
"result_url": "string",
"error": {
"code": "string",
"message": "…"
},
"usage": {
"tokens": 0,
"cost_usd": 0,
"prompt_tokens": 0,
"sampled_tokens": 0
},
"compute_ms": 0,
"created_at": "2026-11-28T09:30:00.000Z",
"started_at": "2026-11-28T09:30:00.000Z",
"finished_at": "2026-11-28T09:30:00.000Z"
}Release the current adapter as a peft_lora artifact#
POST/v1/trainers/{id}/export
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body TrainerExportRequest
seqintegerrequiredThis op's place in the trainer's order: the trainer's
next_seq, then one more per op. A resend of the same seq and body returns the op it created; any other seq is 409seq_conflict.namestringThe artifact's name (default: the trainer's).
Returns
200 TrainerOp A resend: the op this seq created.
202 TrainerOp Queued: the op (its future).
16 fields
idstringrequiredop_and 24 hex.trainer_idstringrequiredseqintegerrequiredIts place in the train lane; null on the sample lane.
laneTrainerOpLanerequiredtrain: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.
"train""sample"snapshot_seqintegerrequiredA snapshot sample: the snapshot it samples from.
request_keystringrequiredA snapshot sample's idempotency key.
typeTrainerOpTyperequired"forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"statusTrainerOpStatusrequired"queued""running""done""failed"resultTrainerOpResultAn op's result once it is done (by
type); absent while it is pending, and when it is large (thenresult_url).One of 8 shapes
- ForwardBackwardResult
type"forward_backward"required"forward_backward"lossnumberrequiredscale * loss_sum.loss_sumnumberrequiredsum(w * term)before scale.weight_sumnumberrequiredsum(w): the weights (or coefficients) the loss read.metricsTrainerLossMetricsrequiredOver the tokens or datums the loss reads. The RL fields come with
importance_sampling,ppo,cispo,droandstable_reinforce; preference and reference diagnostics come withsimpo,orpo,kto,npoandkl_anchor.19 child fields
tokensintegerrequiredtrained_tokensintegerrequiredTokens the loss reads (nonzero weight or coefficient).
token_accuracynumberrequiredtruncatedintegerkl_sample_trainnumberRL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).
kl_sample_train_v2numberRL losses: 0.5 * mean((sampling_logprob - logprob)^2).
sample_train_max_diffnumberRL losses: max |sampling_logprob - logprob|.
entropynumberRL losses: mean token-level Shannon entropy (
-sum(p * log p)) of the current policy over the trained tokens.ratio_meannumberratio_maxnumberclip_fractionnumberppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.
preference_accuracynumbersimpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.
margin_meannumbersimpo and orpo: mean reward margin (
beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).chosen_reward_meannumbersimpo and kto: mean implicit reward on chosen / desirable sequences.
rejected_reward_meannumbersimpo and kto: mean implicit reward on rejected / undesirable sequences.
sft_loss_meannumberorpo and kl_anchor: mean SFT negative log-likelihood component.
or_loss_meannumberorpo: mean odds-ratio preference loss component.
kl_refnumberkto, npo and kl_anchor: reference divergence diagnostic (batch
z_reffor kto, mean log-ratio for npo, mean KL penalty for kl_anchor).ref_diff_maxnumberkto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.
- ForwardResult
type"forward"required"forward"logprobsarray of Tensorrequired2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
lossnumberrequiredloss_sumnumberrequiredweight_sumnumberrequiredmetricsTrainerLossMetricsrequired
- OptimStepResult
type"optim_step"required"optim_step"stepintegerrequiredgrad_normnumberrequiredskippedbooleanrequiredNo gradients were pending: nothing changed.
lrnumberThe numeric learning rate applied (resolved when
lr: "auto"was requested).
- SampleResult
type"sample"required"sample"resultsarray of objectrequired4 child fields
prompt_tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
prompt_logprobsTensorA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
resetbooleanrequiredA
continuewhose template rewrote history:prompt_tokensare a fresh render, nottokensplus a delta (the trajectory starts a new segment). False for other prompts.samplesarray of TrainerSamplerequired7 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
logprobsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
top_logprobsarray of array of TopLogprobPresent when
top_logprobs > 0: for each sampled token, up to K(token_id, logprob)pairs ordered highest logprob first.textstringrequiredfinish_reasonenumrequiredstop: a stop token or string; length:
max_tokens(or, on acontinue, the room left inmax_seq_len); context_full: acontinuewith no room left, no tokens."stop""length""context_full"messageSampledAssistantMessagerequiredThe sample parsed with the base's template (reasoning and OpenAI-style tool calls,
argumentsa JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays incontentandparsedis false.4 child fields
role"assistant"required"assistant"contentstringrequiredreasoning_contentstringtool_callsarray of object3 child fields
idstringrequiredtype"function"required"function"functionobjectrequired
parsedbooleanrequiredThe reply parsed cleanly (no malformed tool call). False:
message.contentholds the raw text, which an environment gets as text.
- SaveStateResult
type"save_state"required"save_state"checkpointobjectrequired5 child fields
idstringrequiredstepintegerrequirednamestringexpires_atstring (date-time)metadatamap of any
- ExportResult
type"export"required"export"artifactArtifactrequired16 child fields
idstringrequiredArtifact id:
name@version.workspace_idstringrequirednamestringrequiredArtifact name, usually the run name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredVersion,
YYYY-MM-DD-N: the release date and its sequence that day.run_idstringrequiredThe run that trained it; null for uploads and imports.
checkpoint_idstringrequiredThe checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.
base_modelstringrequiredThe base model the weights apply to.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"formatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sha256stringrequiredSHA-256 of the bundle; downloads verify it.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
manifestmap of anyrequiredThe bundle's manifest.json: format, base model, adapter and training settings.
provenanceArtifactProvenancerequired5 child fields
sourceenumrequiredrun: trained by a grad run; trainer: exported by a trainer (
trainer.export); upload: files uploaded withgrad artifacts upload; import: pulled from the Hugging Face Hub withgrad artifacts import."run""trainer""upload""import"run_idstringrequiredsource=run: the run that trained it.
trainer_idstringrequiredsource=trainer: the trainer that exported it.
uploaderstringrequiredsource=upload: the API key (principal) that uploaded it.
uristringrequiredsource=import:
hf://owner/name@<40-hex commit>, the pinned revision it was imported from.
eval_reportEvalReportrequiredcreated_atstring (date-time)requiredWhen it was released.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
- RenderResult
type"render"required"render"dataarray of RenderedDatumrequired4 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
weightsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
truncatedbooleanrequiredmediaarray of MediaItem4 child fields
kindenumrequired"image""audio"mimeenumrequired"image/png""image/jpeg""image/webp""audio/wav"datastringMatches
^[A-Za-z0-9+/]+={0,2}$media_idstringContent-addressed media upload id (
med_...fromPOST /v1/media); mutually exclusive withdata.Matches
^med_[0-9a-f]{24}$
- SnapshotResult
type"snapshot"required"snapshot"snapshotobjectrequired2 child fields
seqintegerrequiredstepintegerrequired
- ForwardBackwardResult
result_urlstringrequiredA result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.
errorTrainerOpErrorrequiredWhy it failed:
invalid_datum,invalid_continuation,trainer_lost(the worker died; ops after its last saved state are gone),trainer_closed,op_failed,result_expired,snapshot_released,deadline_exceeded,result_too_large.usageTrainerUsagerequired4 child fields
tokensintegerrequiredcost_usdnumberrequiredprompt_tokensintegersampled_tokensinteger
compute_msintegerrequiredWorker compute time (a sample-lane op: its batch's, shared by the ops batched together).
started_atis when the worker took the op, which may be before it ran (prefetch).created_atstring (date-time)requiredstarted_atstring (date-time)requiredfinished_atstring (date-time)required
from grad import Grad
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
exported = trainer.export(name="support-loop-lora").result()
assert exported.artifact is not None
print(exported.artifact.id){
"id": "op_3f9c0a1b2c3d4e5f60718293",
"trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
"seq": 1,
"lane": "train",
"snapshot_seq": 1,
"request_key": "string",
"type": "forward_backward",
"status": "queued",
"result": {
"type": "forward_backward",
"loss": 0,
"loss_sum": 0,
"weight_sum": 0,
"metrics": {
"tokens": 0,
"trained_tokens": 0,
"token_accuracy": 0,
"truncated": 0,
"kl_sample_train": 0,
"kl_sample_train_v2": 0,
"sample_train_max_diff": 0,
"entropy": 0,
"ratio_mean": 0,
"ratio_max": 0,
"clip_fraction": 0,
"preference_accuracy": 0,
"margin_mean": 0,
"chosen_reward_mean": 0,
"rejected_reward_mean": 0,
"sft_loss_mean": 0,
"or_loss_mean": 0,
"kl_ref": 0,
"ref_diff_max": 0
}
},
"result_url": "string",
"error": {
"code": "string",
"message": "…"
},
"usage": {
"tokens": 0,
"cost_usd": 0,
"prompt_tokens": 0,
"sampled_tokens": 0
},
"compute_ms": 0,
"created_at": "2026-11-28T09:30:00.000Z",
"started_at": "2026-11-28T09:30:00.000Z",
"finished_at": "2026-11-28T09:30:00.000Z"
}Render chats with the base's chat template: the exact tokens and weights a messages datum trains#
POST/v1/trainers/{id}/render
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body TrainerRenderRequest
seqintegerrequiredThis op's place in the trainer's order: the trainer's
next_seq, then one more per op. A resend of the same seq and body returns the op it created; any other seq is 409seq_conflict.dataarray of objectrequired4 child fields
messagesarray of ChatMessagerequired7 child fields
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
toolsarray of map of anytrain_onenumWhich assistant turns get weight 1 (the rest of the chat is context), as in recipes.
"last""all_assistant"thinkingenum"auto""on""off"
Returns
200 TrainerOp A resend: the op this seq created.
202 TrainerOp Queued: the op (its future).
16 fields
idstringrequiredop_and 24 hex.trainer_idstringrequiredseqintegerrequiredIts place in the train lane; null on the sample lane.
laneTrainerOpLanerequiredtrain: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.
"train""sample"snapshot_seqintegerrequiredA snapshot sample: the snapshot it samples from.
request_keystringrequiredA snapshot sample's idempotency key.
typeTrainerOpTyperequired"forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"statusTrainerOpStatusrequired"queued""running""done""failed"resultTrainerOpResultAn op's result once it is done (by
type); absent while it is pending, and when it is large (thenresult_url).One of 8 shapes
- ForwardBackwardResult
type"forward_backward"required"forward_backward"lossnumberrequiredscale * loss_sum.loss_sumnumberrequiredsum(w * term)before scale.weight_sumnumberrequiredsum(w): the weights (or coefficients) the loss read.metricsTrainerLossMetricsrequiredOver the tokens or datums the loss reads. The RL fields come with
importance_sampling,ppo,cispo,droandstable_reinforce; preference and reference diagnostics come withsimpo,orpo,kto,npoandkl_anchor.19 child fields
tokensintegerrequiredtrained_tokensintegerrequiredTokens the loss reads (nonzero weight or coefficient).
token_accuracynumberrequiredtruncatedintegerkl_sample_trainnumberRL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).
kl_sample_train_v2numberRL losses: 0.5 * mean((sampling_logprob - logprob)^2).
sample_train_max_diffnumberRL losses: max |sampling_logprob - logprob|.
entropynumberRL losses: mean token-level Shannon entropy (
-sum(p * log p)) of the current policy over the trained tokens.ratio_meannumberratio_maxnumberclip_fractionnumberppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.
preference_accuracynumbersimpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.
margin_meannumbersimpo and orpo: mean reward margin (
beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).chosen_reward_meannumbersimpo and kto: mean implicit reward on chosen / desirable sequences.
rejected_reward_meannumbersimpo and kto: mean implicit reward on rejected / undesirable sequences.
sft_loss_meannumberorpo and kl_anchor: mean SFT negative log-likelihood component.
or_loss_meannumberorpo: mean odds-ratio preference loss component.
kl_refnumberkto, npo and kl_anchor: reference divergence diagnostic (batch
z_reffor kto, mean log-ratio for npo, mean KL penalty for kl_anchor).ref_diff_maxnumberkto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.
- ForwardResult
type"forward"required"forward"logprobsarray of Tensorrequired2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
lossnumberrequiredloss_sumnumberrequiredweight_sumnumberrequiredmetricsTrainerLossMetricsrequired
- OptimStepResult
type"optim_step"required"optim_step"stepintegerrequiredgrad_normnumberrequiredskippedbooleanrequiredNo gradients were pending: nothing changed.
lrnumberThe numeric learning rate applied (resolved when
lr: "auto"was requested).
- SampleResult
type"sample"required"sample"resultsarray of objectrequired4 child fields
prompt_tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
prompt_logprobsTensorA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
resetbooleanrequiredA
continuewhose template rewrote history:prompt_tokensare a fresh render, nottokensplus a delta (the trajectory starts a new segment). False for other prompts.samplesarray of TrainerSamplerequired7 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
logprobsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
top_logprobsarray of array of TopLogprobPresent when
top_logprobs > 0: for each sampled token, up to K(token_id, logprob)pairs ordered highest logprob first.textstringrequiredfinish_reasonenumrequiredstop: a stop token or string; length:
max_tokens(or, on acontinue, the room left inmax_seq_len); context_full: acontinuewith no room left, no tokens."stop""length""context_full"messageSampledAssistantMessagerequiredThe sample parsed with the base's template (reasoning and OpenAI-style tool calls,
argumentsa JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays incontentandparsedis false.4 child fields
role"assistant"required"assistant"contentstringrequiredreasoning_contentstringtool_callsarray of object3 child fields
idstringrequiredtype"function"required"function"functionobjectrequired
parsedbooleanrequiredThe reply parsed cleanly (no malformed tool call). False:
message.contentholds the raw text, which an environment gets as text.
- SaveStateResult
type"save_state"required"save_state"checkpointobjectrequired5 child fields
idstringrequiredstepintegerrequirednamestringexpires_atstring (date-time)metadatamap of any
- ExportResult
type"export"required"export"artifactArtifactrequired16 child fields
idstringrequiredArtifact id:
name@version.workspace_idstringrequirednamestringrequiredArtifact name, usually the run name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredVersion,
YYYY-MM-DD-N: the release date and its sequence that day.run_idstringrequiredThe run that trained it; null for uploads and imports.
checkpoint_idstringrequiredThe checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.
base_modelstringrequiredThe base model the weights apply to.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"formatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sha256stringrequiredSHA-256 of the bundle; downloads verify it.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
manifestmap of anyrequiredThe bundle's manifest.json: format, base model, adapter and training settings.
provenanceArtifactProvenancerequired5 child fields
sourceenumrequiredrun: trained by a grad run; trainer: exported by a trainer (
trainer.export); upload: files uploaded withgrad artifacts upload; import: pulled from the Hugging Face Hub withgrad artifacts import."run""trainer""upload""import"run_idstringrequiredsource=run: the run that trained it.
trainer_idstringrequiredsource=trainer: the trainer that exported it.
uploaderstringrequiredsource=upload: the API key (principal) that uploaded it.
uristringrequiredsource=import:
hf://owner/name@<40-hex commit>, the pinned revision it was imported from.
eval_reportEvalReportrequiredcreated_atstring (date-time)requiredWhen it was released.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
- RenderResult
type"render"required"render"dataarray of RenderedDatumrequired4 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
weightsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
truncatedbooleanrequiredmediaarray of MediaItem4 child fields
kindenumrequired"image""audio"mimeenumrequired"image/png""image/jpeg""image/webp""audio/wav"datastringMatches
^[A-Za-z0-9+/]+={0,2}$media_idstringContent-addressed media upload id (
med_...fromPOST /v1/media); mutually exclusive withdata.Matches
^med_[0-9a-f]{24}$
- SnapshotResult
type"snapshot"required"snapshot"snapshotobjectrequired2 child fields
seqintegerrequiredstepintegerrequired
- ForwardBackwardResult
result_urlstringrequiredA result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.
errorTrainerOpErrorrequiredWhy it failed:
invalid_datum,invalid_continuation,trainer_lost(the worker died; ops after its last saved state are gone),trainer_closed,op_failed,result_expired,snapshot_released,deadline_exceeded,result_too_large.usageTrainerUsagerequired4 child fields
tokensintegerrequiredcost_usdnumberrequiredprompt_tokensintegersampled_tokensinteger
compute_msintegerrequiredWorker compute time (a sample-lane op: its batch's, shared by the ops batched together).
started_atis when the worker took the op, which may be before it ran (prefetch).created_atstring (date-time)requiredstarted_atstring (date-time)requiredfinished_atstring (date-time)required
from grad import Grad, Record
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
rendered = trainer.render([
Record(messages=[
{"role": "user", "content": "Translate 'good morning' to French."},
{"role": "assistant", "content": "Bonjour."},
])
]).result()
print(len(rendered.data[0].tokens)){
"id": "op_3f9c0a1b2c3d4e5f60718293",
"trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
"seq": 1,
"lane": "train",
"snapshot_seq": 1,
"request_key": "string",
"type": "forward_backward",
"status": "queued",
"result": {
"type": "forward_backward",
"loss": 0,
"loss_sum": 0,
"weight_sum": 0,
"metrics": {
"tokens": 0,
"trained_tokens": 0,
"token_accuracy": 0,
"truncated": 0,
"kl_sample_train": 0,
"kl_sample_train_v2": 0,
"sample_train_max_diff": 0,
"entropy": 0,
"ratio_mean": 0,
"ratio_max": 0,
"clip_fraction": 0,
"preference_accuracy": 0,
"margin_mean": 0,
"chosen_reward_mean": 0,
"rejected_reward_mean": 0,
"sft_loss_mean": 0,
"or_loss_mean": 0,
"kl_ref": 0,
"ref_diff_max": 0
}
},
"result_url": "string",
"error": {
"code": "string",
"message": "…"
},
"usage": {
"tokens": 0,
"cost_usd": 0,
"prompt_tokens": 0,
"sampled_tokens": 0
},
"compute_ms": 0,
"created_at": "2026-11-28T09:30:00.000Z",
"started_at": "2026-11-28T09:30:00.000Z",
"finished_at": "2026-11-28T09:30:00.000Z"
}Freeze the adapter as a snapshot to sample from while training goes on#
POST/v1/trainers/{id}/snapshot
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body SnapshotRequest
seqintegerrequiredThis op's place in the trainer's order: the trainer's
next_seq, then one more per op. A resend of the same seq and body returns the op it created; any other seq is 409seq_conflict.
Returns
200 TrainerOp A resend: the op this seq created.
202 TrainerOp Queued: the op (its future).
16 fields
idstringrequiredop_and 24 hex.trainer_idstringrequiredseqintegerrequiredIts place in the train lane; null on the sample lane.
laneTrainerOpLanerequiredtrain: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.
"train""sample"snapshot_seqintegerrequiredA snapshot sample: the snapshot it samples from.
request_keystringrequiredA snapshot sample's idempotency key.
typeTrainerOpTyperequired"forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"statusTrainerOpStatusrequired"queued""running""done""failed"resultTrainerOpResultAn op's result once it is done (by
type); absent while it is pending, and when it is large (thenresult_url).One of 8 shapes
- ForwardBackwardResult
type"forward_backward"required"forward_backward"lossnumberrequiredscale * loss_sum.loss_sumnumberrequiredsum(w * term)before scale.weight_sumnumberrequiredsum(w): the weights (or coefficients) the loss read.metricsTrainerLossMetricsrequiredOver the tokens or datums the loss reads. The RL fields come with
importance_sampling,ppo,cispo,droandstable_reinforce; preference and reference diagnostics come withsimpo,orpo,kto,npoandkl_anchor.19 child fields
tokensintegerrequiredtrained_tokensintegerrequiredTokens the loss reads (nonzero weight or coefficient).
token_accuracynumberrequiredtruncatedintegerkl_sample_trainnumberRL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).
kl_sample_train_v2numberRL losses: 0.5 * mean((sampling_logprob - logprob)^2).
sample_train_max_diffnumberRL losses: max |sampling_logprob - logprob|.
entropynumberRL losses: mean token-level Shannon entropy (
-sum(p * log p)) of the current policy over the trained tokens.ratio_meannumberratio_maxnumberclip_fractionnumberppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.
preference_accuracynumbersimpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.
margin_meannumbersimpo and orpo: mean reward margin (
beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).chosen_reward_meannumbersimpo and kto: mean implicit reward on chosen / desirable sequences.
rejected_reward_meannumbersimpo and kto: mean implicit reward on rejected / undesirable sequences.
sft_loss_meannumberorpo and kl_anchor: mean SFT negative log-likelihood component.
or_loss_meannumberorpo: mean odds-ratio preference loss component.
kl_refnumberkto, npo and kl_anchor: reference divergence diagnostic (batch
z_reffor kto, mean log-ratio for npo, mean KL penalty for kl_anchor).ref_diff_maxnumberkto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.
- ForwardResult
type"forward"required"forward"logprobsarray of Tensorrequired2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
lossnumberrequiredloss_sumnumberrequiredweight_sumnumberrequiredmetricsTrainerLossMetricsrequired
- OptimStepResult
type"optim_step"required"optim_step"stepintegerrequiredgrad_normnumberrequiredskippedbooleanrequiredNo gradients were pending: nothing changed.
lrnumberThe numeric learning rate applied (resolved when
lr: "auto"was requested).
- SampleResult
type"sample"required"sample"resultsarray of objectrequired4 child fields
prompt_tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
prompt_logprobsTensorA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
resetbooleanrequiredA
continuewhose template rewrote history:prompt_tokensare a fresh render, nottokensplus a delta (the trajectory starts a new segment). False for other prompts.samplesarray of TrainerSamplerequired7 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
logprobsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
top_logprobsarray of array of TopLogprobPresent when
top_logprobs > 0: for each sampled token, up to K(token_id, logprob)pairs ordered highest logprob first.textstringrequiredfinish_reasonenumrequiredstop: a stop token or string; length:
max_tokens(or, on acontinue, the room left inmax_seq_len); context_full: acontinuewith no room left, no tokens."stop""length""context_full"messageSampledAssistantMessagerequiredThe sample parsed with the base's template (reasoning and OpenAI-style tool calls,
argumentsa JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays incontentandparsedis false.4 child fields
role"assistant"required"assistant"contentstringrequiredreasoning_contentstringtool_callsarray of object3 child fields
idstringrequiredtype"function"required"function"functionobjectrequired
parsedbooleanrequiredThe reply parsed cleanly (no malformed tool call). False:
message.contentholds the raw text, which an environment gets as text.
- SaveStateResult
type"save_state"required"save_state"checkpointobjectrequired5 child fields
idstringrequiredstepintegerrequirednamestringexpires_atstring (date-time)metadatamap of any
- ExportResult
type"export"required"export"artifactArtifactrequired16 child fields
idstringrequiredArtifact id:
name@version.workspace_idstringrequirednamestringrequiredArtifact name, usually the run name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredVersion,
YYYY-MM-DD-N: the release date and its sequence that day.run_idstringrequiredThe run that trained it; null for uploads and imports.
checkpoint_idstringrequiredThe checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.
base_modelstringrequiredThe base model the weights apply to.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"formatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sha256stringrequiredSHA-256 of the bundle; downloads verify it.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
manifestmap of anyrequiredThe bundle's manifest.json: format, base model, adapter and training settings.
provenanceArtifactProvenancerequired5 child fields
sourceenumrequiredrun: trained by a grad run; trainer: exported by a trainer (
trainer.export); upload: files uploaded withgrad artifacts upload; import: pulled from the Hugging Face Hub withgrad artifacts import."run""trainer""upload""import"run_idstringrequiredsource=run: the run that trained it.
trainer_idstringrequiredsource=trainer: the trainer that exported it.
uploaderstringrequiredsource=upload: the API key (principal) that uploaded it.
uristringrequiredsource=import:
hf://owner/name@<40-hex commit>, the pinned revision it was imported from.
eval_reportEvalReportrequiredcreated_atstring (date-time)requiredWhen it was released.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
- RenderResult
type"render"required"render"dataarray of RenderedDatumrequired4 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
weightsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
truncatedbooleanrequiredmediaarray of MediaItem4 child fields
kindenumrequired"image""audio"mimeenumrequired"image/png""image/jpeg""image/webp""audio/wav"datastringMatches
^[A-Za-z0-9+/]+={0,2}$media_idstringContent-addressed media upload id (
med_...fromPOST /v1/media); mutually exclusive withdata.Matches
^med_[0-9a-f]{24}$
- SnapshotResult
type"snapshot"required"snapshot"snapshotobjectrequired2 child fields
seqintegerrequiredstepintegerrequired
- ForwardBackwardResult
result_urlstringrequiredA result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.
errorTrainerOpErrorrequiredWhy it failed:
invalid_datum,invalid_continuation,trainer_lost(the worker died; ops after its last saved state are gone),trainer_closed,op_failed,result_expired,snapshot_released,deadline_exceeded,result_too_large.usageTrainerUsagerequired4 child fields
tokensintegerrequiredcost_usdnumberrequiredprompt_tokensintegersampled_tokensinteger
compute_msintegerrequiredWorker compute time (a sample-lane op: its batch's, shared by the ops batched together).
started_atis when the worker took the op, which may be before it ran (prefetch).created_atstring (date-time)requiredstarted_atstring (date-time)requiredfinished_atstring (date-time)required
from grad import Grad
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
with trainer.snapshot() as snap:
print(snap.seq){
"id": "op_3f9c0a1b2c3d4e5f60718293",
"trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
"seq": 1,
"lane": "train",
"snapshot_seq": 1,
"request_key": "string",
"type": "forward_backward",
"status": "queued",
"result": {
"type": "forward_backward",
"loss": 0,
"loss_sum": 0,
"weight_sum": 0,
"metrics": {
"tokens": 0,
"trained_tokens": 0,
"token_accuracy": 0,
"truncated": 0,
"kl_sample_train": 0,
"kl_sample_train_v2": 0,
"sample_train_max_diff": 0,
"entropy": 0,
"ratio_mean": 0,
"ratio_max": 0,
"clip_fraction": 0,
"preference_accuracy": 0,
"margin_mean": 0,
"chosen_reward_mean": 0,
"rejected_reward_mean": 0,
"sft_loss_mean": 0,
"or_loss_mean": 0,
"kl_ref": 0,
"ref_diff_max": 0
}
},
"result_url": "string",
"error": {
"code": "string",
"message": "…"
},
"usage": {
"tokens": 0,
"cost_usd": 0,
"prompt_tokens": 0,
"sampled_tokens": 0
},
"compute_ms": 0,
"created_at": "2026-11-28T09:30:00.000Z",
"started_at": "2026-11-28T09:30:00.000Z",
"finished_at": "2026-11-28T09:30:00.000Z"
}List a trainer's ops (newest first), or with after_seq the finished ones after it, in order, waiting for the first#
GET/v1/trainers/{id}/ops
Path parameters
idstringrequired
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstringafter_seqintegerOnly finished ops after this seq, ascending; with
wait, answers once the first is done (one long-poll resolves every future).waitnumberSeconds to wait for the op to finish (long-poll, at most 30); it answers as soon as it is done or failed.
Returns
200 object Ops.
2 fields
dataarray of TrainerOprequired16 child fields
idstringrequiredop_and 24 hex.trainer_idstringrequiredseqintegerrequiredIts place in the train lane; null on the sample lane.
laneTrainerOpLanerequiredtrain: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.
"train""sample"snapshot_seqintegerrequiredA snapshot sample: the snapshot it samples from.
request_keystringrequiredA snapshot sample's idempotency key.
typeTrainerOpTyperequired"forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"statusTrainerOpStatusrequired"queued""running""done""failed"resultTrainerOpResultAn op's result once it is done (by
type); absent while it is pending, and when it is large (thenresult_url).One of 8 shapes
- ForwardBackwardResult
type"forward_backward"required"forward_backward"lossnumberrequiredscale * loss_sum.loss_sumnumberrequiredsum(w * term)before scale.weight_sumnumberrequiredsum(w): the weights (or coefficients) the loss read.metricsTrainerLossMetricsrequiredOver the tokens or datums the loss reads. The RL fields come with
importance_sampling,ppo,cispo,droandstable_reinforce; preference and reference diagnostics come withsimpo,orpo,kto,npoandkl_anchor.19 child fields
tokensintegerrequiredtrained_tokensintegerrequiredTokens the loss reads (nonzero weight or coefficient).
token_accuracynumberrequiredtruncatedintegerkl_sample_trainnumberRL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).
kl_sample_train_v2numberRL losses: 0.5 * mean((sampling_logprob - logprob)^2).
sample_train_max_diffnumberRL losses: max |sampling_logprob - logprob|.
entropynumberRL losses: mean token-level Shannon entropy (
-sum(p * log p)) of the current policy over the trained tokens.ratio_meannumberratio_maxnumberclip_fractionnumberppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.
preference_accuracynumbersimpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.
margin_meannumbersimpo and orpo: mean reward margin (
beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).chosen_reward_meannumbersimpo and kto: mean implicit reward on chosen / desirable sequences.
rejected_reward_meannumbersimpo and kto: mean implicit reward on rejected / undesirable sequences.
sft_loss_meannumberorpo and kl_anchor: mean SFT negative log-likelihood component.
or_loss_meannumberorpo: mean odds-ratio preference loss component.
kl_refnumberkto, npo and kl_anchor: reference divergence diagnostic (batch
z_reffor kto, mean log-ratio for npo, mean KL penalty for kl_anchor).ref_diff_maxnumberkto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.
- ForwardResult
type"forward"required"forward"logprobsarray of Tensorrequired2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
lossnumberrequiredloss_sumnumberrequiredweight_sumnumberrequiredmetricsTrainerLossMetricsrequired
- OptimStepResult
type"optim_step"required"optim_step"stepintegerrequiredgrad_normnumberrequiredskippedbooleanrequiredNo gradients were pending: nothing changed.
lrnumberThe numeric learning rate applied (resolved when
lr: "auto"was requested).
- SampleResult
type"sample"required"sample"resultsarray of objectrequired4 child fields
prompt_tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
prompt_logprobsTensorA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
resetbooleanrequiredA
continuewhose template rewrote history:prompt_tokensare a fresh render, nottokensplus a delta (the trajectory starts a new segment). False for other prompts.samplesarray of TrainerSamplerequired7 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
logprobsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
top_logprobsarray of array of TopLogprobPresent when
top_logprobs > 0: for each sampled token, up to K(token_id, logprob)pairs ordered highest logprob first.textstringrequiredfinish_reasonenumrequiredstop: a stop token or string; length:
max_tokens(or, on acontinue, the room left inmax_seq_len); context_full: acontinuewith no room left, no tokens."stop""length""context_full"messageSampledAssistantMessagerequiredThe sample parsed with the base's template (reasoning and OpenAI-style tool calls,
argumentsa JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays incontentandparsedis false.4 child fields
role"assistant"required"assistant"contentstringrequiredreasoning_contentstringtool_callsarray of object
parsedbooleanrequiredThe reply parsed cleanly (no malformed tool call). False:
message.contentholds the raw text, which an environment gets as text.
- SaveStateResult
type"save_state"required"save_state"checkpointobjectrequired5 child fields
idstringrequiredstepintegerrequirednamestringexpires_atstring (date-time)metadatamap of any
- ExportResult
type"export"required"export"artifactArtifactrequired16 child fields
idstringrequiredArtifact id:
name@version.workspace_idstringrequirednamestringrequiredArtifact name, usually the run name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredVersion,
YYYY-MM-DD-N: the release date and its sequence that day.run_idstringrequiredThe run that trained it; null for uploads and imports.
checkpoint_idstringrequiredThe checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.
base_modelstringrequiredThe base model the weights apply to.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"formatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sha256stringrequiredSHA-256 of the bundle; downloads verify it.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
manifestmap of anyrequiredThe bundle's manifest.json: format, base model, adapter and training settings.
provenanceArtifactProvenancerequired5 child fields
sourceenumrequiredrun: trained by a grad run; trainer: exported by a trainer (
trainer.export); upload: files uploaded withgrad artifacts upload; import: pulled from the Hugging Face Hub withgrad artifacts import."run""trainer""upload""import"run_idstringrequiredsource=run: the run that trained it.
trainer_idstringrequiredsource=trainer: the trainer that exported it.
uploaderstringrequiredsource=upload: the API key (principal) that uploaded it.
uristringrequiredsource=import:
hf://owner/name@<40-hex commit>, the pinned revision it was imported from.
eval_reportEvalReportrequiredcreated_atstring (date-time)requiredWhen it was released.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
- RenderResult
type"render"required"render"dataarray of RenderedDatumrequired4 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
weightsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
truncatedbooleanrequiredmediaarray of MediaItem4 child fields
kindenumrequired"image""audio"mimeenumrequired"image/png""image/jpeg""image/webp""audio/wav"datastringMatches
^[A-Za-z0-9+/]+={0,2}$media_idstringContent-addressed media upload id (
med_...fromPOST /v1/media); mutually exclusive withdata.Matches
^med_[0-9a-f]{24}$
- SnapshotResult
type"snapshot"required"snapshot"snapshotobjectrequired2 child fields
seqintegerrequiredstepintegerrequired
- ForwardBackwardResult
result_urlstringrequiredA result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.
errorTrainerOpErrorrequiredWhy it failed:
invalid_datum,invalid_continuation,trainer_lost(the worker died; ops after its last saved state are gone),trainer_closed,op_failed,result_expired,snapshot_released,deadline_exceeded,result_too_large.usageTrainerUsagerequired4 child fields
tokensintegerrequiredcost_usdnumberrequiredprompt_tokensintegersampled_tokensinteger
compute_msintegerrequiredWorker compute time (a sample-lane op: its batch's, shared by the ops batched together).
started_atis when the worker took the op, which may be before it ran (prefetch).created_atstring (date-time)requiredstarted_atstring (date-time)requiredfinished_atstring (date-time)required
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
curl "$GRADIATED_BASE_URL/v1/trainers/trn_3f9c0a1b2c3d4e5f60718293/ops" \
-H "Authorization: Bearer $GRADIATED_API_KEY"{
"data": [
{
"id": "op_3f9c0a1b2c3d4e5f60718293",
"trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
"seq": 1,
"lane": "train",
"snapshot_seq": 1,
"request_key": "string",
"type": "forward_backward",
"status": "queued",
"result": {
"type": "forward_backward",
"loss": 0,
"loss_sum": 0,
"weight_sum": 0,
"metrics": {
"tokens": 0,
"trained_tokens": 0,
"token_accuracy": 0,
"truncated": 0,
"kl_sample_train": 0,
"kl_sample_train_v2": 0,
"sample_train_max_diff": 0,
"entropy": 0,
"ratio_mean": 0,
"ratio_max": 0,
"clip_fraction": 0,
"preference_accuracy": 0,
"margin_mean": 0,
"chosen_reward_mean": 0,
"rejected_reward_mean": 0,
"sft_loss_mean": 0,
"or_loss_mean": 0,
"kl_ref": 0,
"ref_diff_max": 0
}
},
"result_url": "string",
"error": {
"code": "string",
"message": "…"
},
"usage": {
"tokens": 0,
"cost_usd": 0,
"prompt_tokens": 0,
"sampled_tokens": 0
},
"compute_ms": 0,
"created_at": "2026-11-28T09:30:00.000Z",
"started_at": "2026-11-28T09:30:00.000Z",
"finished_at": "2026-11-28T09:30:00.000Z"
}
],
"next_cursor": "string"
}Get an op; with wait, long-poll until it finishes#
GET/v1/trainers/{id}/ops/{op_id}
Path parameters
idstringrequiredop_idstringrequired
Query parameters
waitnumberSeconds to wait for the op to finish (long-poll, at most 30); it answers as soon as it is done or failed.
Returns
200 TrainerOp The op.
16 fields
idstringrequiredop_and 24 hex.trainer_idstringrequiredseqintegerrequiredIts place in the train lane; null on the sample lane.
laneTrainerOpLanerequiredtrain: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.
"train""sample"snapshot_seqintegerrequiredA snapshot sample: the snapshot it samples from.
request_keystringrequiredA snapshot sample's idempotency key.
typeTrainerOpTyperequired"forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"statusTrainerOpStatusrequired"queued""running""done""failed"resultTrainerOpResultAn op's result once it is done (by
type); absent while it is pending, and when it is large (thenresult_url).One of 8 shapes
- ForwardBackwardResult
type"forward_backward"required"forward_backward"lossnumberrequiredscale * loss_sum.loss_sumnumberrequiredsum(w * term)before scale.weight_sumnumberrequiredsum(w): the weights (or coefficients) the loss read.metricsTrainerLossMetricsrequiredOver the tokens or datums the loss reads. The RL fields come with
importance_sampling,ppo,cispo,droandstable_reinforce; preference and reference diagnostics come withsimpo,orpo,kto,npoandkl_anchor.19 child fields
tokensintegerrequiredtrained_tokensintegerrequiredTokens the loss reads (nonzero weight or coefficient).
token_accuracynumberrequiredtruncatedintegerkl_sample_trainnumberRL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).
kl_sample_train_v2numberRL losses: 0.5 * mean((sampling_logprob - logprob)^2).
sample_train_max_diffnumberRL losses: max |sampling_logprob - logprob|.
entropynumberRL losses: mean token-level Shannon entropy (
-sum(p * log p)) of the current policy over the trained tokens.ratio_meannumberratio_maxnumberclip_fractionnumberppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.
preference_accuracynumbersimpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.
margin_meannumbersimpo and orpo: mean reward margin (
beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).chosen_reward_meannumbersimpo and kto: mean implicit reward on chosen / desirable sequences.
rejected_reward_meannumbersimpo and kto: mean implicit reward on rejected / undesirable sequences.
sft_loss_meannumberorpo and kl_anchor: mean SFT negative log-likelihood component.
or_loss_meannumberorpo: mean odds-ratio preference loss component.
kl_refnumberkto, npo and kl_anchor: reference divergence diagnostic (batch
z_reffor kto, mean log-ratio for npo, mean KL penalty for kl_anchor).ref_diff_maxnumberkto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.
- ForwardResult
type"forward"required"forward"logprobsarray of Tensorrequired2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
lossnumberrequiredloss_sumnumberrequiredweight_sumnumberrequiredmetricsTrainerLossMetricsrequired
- OptimStepResult
type"optim_step"required"optim_step"stepintegerrequiredgrad_normnumberrequiredskippedbooleanrequiredNo gradients were pending: nothing changed.
lrnumberThe numeric learning rate applied (resolved when
lr: "auto"was requested).
- SampleResult
type"sample"required"sample"resultsarray of objectrequired4 child fields
prompt_tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
prompt_logprobsTensorA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
resetbooleanrequiredA
continuewhose template rewrote history:prompt_tokensare a fresh render, nottokensplus a delta (the trajectory starts a new segment). False for other prompts.samplesarray of TrainerSamplerequired7 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
logprobsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
top_logprobsarray of array of TopLogprobPresent when
top_logprobs > 0: for each sampled token, up to K(token_id, logprob)pairs ordered highest logprob first.textstringrequiredfinish_reasonenumrequiredstop: a stop token or string; length:
max_tokens(or, on acontinue, the room left inmax_seq_len); context_full: acontinuewith no room left, no tokens."stop""length""context_full"messageSampledAssistantMessagerequiredThe sample parsed with the base's template (reasoning and OpenAI-style tool calls,
argumentsa JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays incontentandparsedis false.4 child fields
role"assistant"required"assistant"contentstringrequiredreasoning_contentstringtool_callsarray of object3 child fields
idstringrequiredtype"function"required"function"functionobjectrequired
parsedbooleanrequiredThe reply parsed cleanly (no malformed tool call). False:
message.contentholds the raw text, which an environment gets as text.
- SaveStateResult
type"save_state"required"save_state"checkpointobjectrequired5 child fields
idstringrequiredstepintegerrequirednamestringexpires_atstring (date-time)metadatamap of any
- ExportResult
type"export"required"export"artifactArtifactrequired16 child fields
idstringrequiredArtifact id:
name@version.workspace_idstringrequirednamestringrequiredArtifact name, usually the run name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredVersion,
YYYY-MM-DD-N: the release date and its sequence that day.run_idstringrequiredThe run that trained it; null for uploads and imports.
checkpoint_idstringrequiredThe checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.
base_modelstringrequiredThe base model the weights apply to.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"formatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sha256stringrequiredSHA-256 of the bundle; downloads verify it.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
manifestmap of anyrequiredThe bundle's manifest.json: format, base model, adapter and training settings.
provenanceArtifactProvenancerequired5 child fields
sourceenumrequiredrun: trained by a grad run; trainer: exported by a trainer (
trainer.export); upload: files uploaded withgrad artifacts upload; import: pulled from the Hugging Face Hub withgrad artifacts import."run""trainer""upload""import"run_idstringrequiredsource=run: the run that trained it.
trainer_idstringrequiredsource=trainer: the trainer that exported it.
uploaderstringrequiredsource=upload: the API key (principal) that uploaded it.
uristringrequiredsource=import:
hf://owner/name@<40-hex commit>, the pinned revision it was imported from.
eval_reportEvalReportrequiredcreated_atstring (date-time)requiredWhen it was released.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
- RenderResult
type"render"required"render"dataarray of RenderedDatumrequired4 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
weightsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
truncatedbooleanrequiredmediaarray of MediaItem4 child fields
kindenumrequired"image""audio"mimeenumrequired"image/png""image/jpeg""image/webp""audio/wav"datastringMatches
^[A-Za-z0-9+/]+={0,2}$media_idstringContent-addressed media upload id (
med_...fromPOST /v1/media); mutually exclusive withdata.Matches
^med_[0-9a-f]{24}$
- SnapshotResult
type"snapshot"required"snapshot"snapshotobjectrequired2 child fields
seqintegerrequiredstepintegerrequired
- ForwardBackwardResult
result_urlstringrequiredA result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.
errorTrainerOpErrorrequiredWhy it failed:
invalid_datum,invalid_continuation,trainer_lost(the worker died; ops after its last saved state are gone),trainer_closed,op_failed,result_expired,snapshot_released,deadline_exceeded,result_too_large.usageTrainerUsagerequired4 child fields
tokensintegerrequiredcost_usdnumberrequiredprompt_tokensintegersampled_tokensinteger
compute_msintegerrequiredWorker compute time (a sample-lane op: its batch's, shared by the ops batched together).
started_atis when the worker took the op, which may be before it ran (prefetch).created_atstring (date-time)requiredstarted_atstring (date-time)requiredfinished_atstring (date-time)required
curl "$GRADIATED_BASE_URL/v1/trainers/trn_3f9c0a1b2c3d4e5f60718293/ops/op_3f9c0a1b2c3d4e5f60718293" \
-H "Authorization: Bearer $GRADIATED_API_KEY"{
"id": "op_3f9c0a1b2c3d4e5f60718293",
"trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
"seq": 1,
"lane": "train",
"snapshot_seq": 1,
"request_key": "string",
"type": "forward_backward",
"status": "queued",
"result": {
"type": "forward_backward",
"loss": 0,
"loss_sum": 0,
"weight_sum": 0,
"metrics": {
"tokens": 0,
"trained_tokens": 0,
"token_accuracy": 0,
"truncated": 0,
"kl_sample_train": 0,
"kl_sample_train_v2": 0,
"sample_train_max_diff": 0,
"entropy": 0,
"ratio_mean": 0,
"ratio_max": 0,
"clip_fraction": 0,
"preference_accuracy": 0,
"margin_mean": 0,
"chosen_reward_mean": 0,
"rejected_reward_mean": 0,
"sft_loss_mean": 0,
"or_loss_mean": 0,
"kl_ref": 0,
"ref_diff_max": 0
}
},
"result_url": "string",
"error": {
"code": "string",
"message": "…"
},
"usage": {
"tokens": 0,
"cost_usd": 0,
"prompt_tokens": 0,
"sampled_tokens": 0
},
"compute_ms": 0,
"created_at": "2026-11-28T09:30:00.000Z",
"started_at": "2026-11-28T09:30:00.000Z",
"finished_at": "2026-11-28T09:30:00.000Z"
}Stream incremental token deltas of a sample op as Server-Sent Events#
GET/v1/trainers/{id}/ops/{op_id}/stream
Emits event: delta JSON frames in seq order (id = chunk seq; pass Last-Event-ID to resume) and terminates with event: done carrying the final TrainerOp, or event: error on failure.
Path parameters
idstringrequiredop_idstringrequired
Returns
200 string SSE stream of sample deltas and terminal op event.
from grad import Grad
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
stream = trainer.sample_stream(
[{"messages": [{"role": "user", "content": "What is 12 * 7?"}]}],
max_tokens=128,
)
for delta in stream:
print(delta.text, end="", flush=True)text/event-stream: SSE stream of sample deltas and terminal op event.
Long-poll many ops (either lane): the finished ones among ids, as soon as there is one#
POST/v1/trainers/{id}/ops/wait
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body WaitTrainerOpsRequest
idsarray of stringrequiredwait_snumber
Returns
200 object The finished ops among ids (none after wait_s).
1 fields
dataarray of TrainerOprequired16 child fields
idstringrequiredop_and 24 hex.trainer_idstringrequiredseqintegerrequiredIts place in the train lane; null on the sample lane.
laneTrainerOpLanerequiredtrain: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.
"train""sample"snapshot_seqintegerrequiredA snapshot sample: the snapshot it samples from.
request_keystringrequiredA snapshot sample's idempotency key.
typeTrainerOpTyperequired"forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"statusTrainerOpStatusrequired"queued""running""done""failed"resultTrainerOpResultAn op's result once it is done (by
type); absent while it is pending, and when it is large (thenresult_url).One of 8 shapes
- ForwardBackwardResult
type"forward_backward"required"forward_backward"lossnumberrequiredscale * loss_sum.loss_sumnumberrequiredsum(w * term)before scale.weight_sumnumberrequiredsum(w): the weights (or coefficients) the loss read.metricsTrainerLossMetricsrequiredOver the tokens or datums the loss reads. The RL fields come with
importance_sampling,ppo,cispo,droandstable_reinforce; preference and reference diagnostics come withsimpo,orpo,kto,npoandkl_anchor.19 child fields
tokensintegerrequiredtrained_tokensintegerrequiredTokens the loss reads (nonzero weight or coefficient).
token_accuracynumberrequiredtruncatedintegerkl_sample_trainnumberRL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).
kl_sample_train_v2numberRL losses: 0.5 * mean((sampling_logprob - logprob)^2).
sample_train_max_diffnumberRL losses: max |sampling_logprob - logprob|.
entropynumberRL losses: mean token-level Shannon entropy (
-sum(p * log p)) of the current policy over the trained tokens.ratio_meannumberratio_maxnumberclip_fractionnumberppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.
preference_accuracynumbersimpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.
margin_meannumbersimpo and orpo: mean reward margin (
beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).chosen_reward_meannumbersimpo and kto: mean implicit reward on chosen / desirable sequences.
rejected_reward_meannumbersimpo and kto: mean implicit reward on rejected / undesirable sequences.
sft_loss_meannumberorpo and kl_anchor: mean SFT negative log-likelihood component.
or_loss_meannumberorpo: mean odds-ratio preference loss component.
kl_refnumberkto, npo and kl_anchor: reference divergence diagnostic (batch
z_reffor kto, mean log-ratio for npo, mean KL penalty for kl_anchor).ref_diff_maxnumberkto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.
- ForwardResult
type"forward"required"forward"logprobsarray of Tensorrequired2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
lossnumberrequiredloss_sumnumberrequiredweight_sumnumberrequiredmetricsTrainerLossMetricsrequired
- OptimStepResult
type"optim_step"required"optim_step"stepintegerrequiredgrad_normnumberrequiredskippedbooleanrequiredNo gradients were pending: nothing changed.
lrnumberThe numeric learning rate applied (resolved when
lr: "auto"was requested).
- SampleResult
type"sample"required"sample"resultsarray of objectrequired4 child fields
prompt_tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
prompt_logprobsTensorA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
resetbooleanrequiredA
continuewhose template rewrote history:prompt_tokensare a fresh render, nottokensplus a delta (the trajectory starts a new segment). False for other prompts.samplesarray of TrainerSamplerequired7 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
logprobsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
top_logprobsarray of array of TopLogprobPresent when
top_logprobs > 0: for each sampled token, up to K(token_id, logprob)pairs ordered highest logprob first.textstringrequiredfinish_reasonenumrequiredstop: a stop token or string; length:
max_tokens(or, on acontinue, the room left inmax_seq_len); context_full: acontinuewith no room left, no tokens."stop""length""context_full"messageSampledAssistantMessagerequiredThe sample parsed with the base's template (reasoning and OpenAI-style tool calls,
argumentsa JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays incontentandparsedis false.4 child fields
role"assistant"required"assistant"contentstringrequiredreasoning_contentstringtool_callsarray of object
parsedbooleanrequiredThe reply parsed cleanly (no malformed tool call). False:
message.contentholds the raw text, which an environment gets as text.
- SaveStateResult
type"save_state"required"save_state"checkpointobjectrequired5 child fields
idstringrequiredstepintegerrequirednamestringexpires_atstring (date-time)metadatamap of any
- ExportResult
type"export"required"export"artifactArtifactrequired16 child fields
idstringrequiredArtifact id:
name@version.workspace_idstringrequirednamestringrequiredArtifact name, usually the run name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredVersion,
YYYY-MM-DD-N: the release date and its sequence that day.run_idstringrequiredThe run that trained it; null for uploads and imports.
checkpoint_idstringrequiredThe checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.
base_modelstringrequiredThe base model the weights apply to.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"formatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sha256stringrequiredSHA-256 of the bundle; downloads verify it.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
manifestmap of anyrequiredThe bundle's manifest.json: format, base model, adapter and training settings.
provenanceArtifactProvenancerequired5 child fields
sourceenumrequiredrun: trained by a grad run; trainer: exported by a trainer (
trainer.export); upload: files uploaded withgrad artifacts upload; import: pulled from the Hugging Face Hub withgrad artifacts import."run""trainer""upload""import"run_idstringrequiredsource=run: the run that trained it.
trainer_idstringrequiredsource=trainer: the trainer that exported it.
uploaderstringrequiredsource=upload: the API key (principal) that uploaded it.
uristringrequiredsource=import:
hf://owner/name@<40-hex commit>, the pinned revision it was imported from.
eval_reportEvalReportrequiredcreated_atstring (date-time)requiredWhen it was released.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
- RenderResult
type"render"required"render"dataarray of RenderedDatumrequired4 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
weightsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
truncatedbooleanrequiredmediaarray of MediaItem4 child fields
kindenumrequired"image""audio"mimeenumrequired"image/png""image/jpeg""image/webp""audio/wav"datastringMatches
^[A-Za-z0-9+/]+={0,2}$media_idstringContent-addressed media upload id (
med_...fromPOST /v1/media); mutually exclusive withdata.Matches
^med_[0-9a-f]{24}$
- SnapshotResult
type"snapshot"required"snapshot"snapshotobjectrequired2 child fields
seqintegerrequiredstepintegerrequired
- ForwardBackwardResult
result_urlstringrequiredA result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.
errorTrainerOpErrorrequiredWhy it failed:
invalid_datum,invalid_continuation,trainer_lost(the worker died; ops after its last saved state are gone),trainer_closed,op_failed,result_expired,snapshot_released,deadline_exceeded,result_too_large.usageTrainerUsagerequired4 child fields
tokensintegerrequiredcost_usdnumberrequiredprompt_tokensintegersampled_tokensinteger
compute_msintegerrequiredWorker compute time (a sample-lane op: its batch's, shared by the ops batched together).
started_atis when the worker took the op, which may be before it ran (prefetch).created_atstring (date-time)requiredstarted_atstring (date-time)requiredfinished_atstring (date-time)required
curl -X POST "$GRADIATED_BASE_URL/v1/trainers/trn_3f9c0a1b2c3d4e5f60718293/ops/wait" \
-H "Authorization: Bearer $GRADIATED_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"ids": [
"op_3f9c0a1b2c3d4e5f60718293"
],
"wait_s": 30
}'{
"data": [
{
"id": "op_3f9c0a1b2c3d4e5f60718293",
"trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
"seq": 1,
"lane": "train",
"snapshot_seq": 1,
"request_key": "string",
"type": "forward_backward",
"status": "queued",
"result": {
"type": "forward_backward",
"loss": 0,
"loss_sum": 0,
"weight_sum": 0,
"metrics": {
"tokens": 0,
"trained_tokens": 0,
"token_accuracy": 0,
"truncated": 0,
"kl_sample_train": 0,
"kl_sample_train_v2": 0,
"sample_train_max_diff": 0,
"entropy": 0,
"ratio_mean": 0,
"ratio_max": 0,
"clip_fraction": 0,
"preference_accuracy": 0,
"margin_mean": 0,
"chosen_reward_mean": 0,
"rejected_reward_mean": 0,
"sft_loss_mean": 0,
"or_loss_mean": 0,
"kl_ref": 0,
"ref_diff_max": 0
}
},
"result_url": "string",
"error": {
"code": "string",
"message": "…"
},
"usage": {
"tokens": 0,
"cost_usd": 0,
"prompt_tokens": 0,
"sampled_tokens": 0
},
"compute_ms": 0,
"created_at": "2026-11-28T09:30:00.000Z",
"started_at": "2026-11-28T09:30:00.000Z",
"finished_at": "2026-11-28T09:30:00.000Z"
}
]
}List a trainer's pending and live snapshots#
GET/v1/trainers/{id}/snapshots
Path parameters
idstringrequired
Returns
200 object Snapshots, oldest first.
1 fields
dataarray of Snapshotrequired7 child fields
trainer_idstringrequiredseqintegerrequiredThe snapshot op's seq: its id within the trainer.
stepintegerrequiredThe optimizer step it froze (null while pending).
statusSnapshotStatusrequiredpending: its op has not run yet (samples queue and run once it has); live: frozen weights on the worker; released: gone (its queued samples failed
snapshot_released)."pending""live""released"created_atstring (date-time)requiredlast_sample_atstring (date-time)requiredreleased_atstring (date-time)required
from grad import Grad
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
for snap in trainer.snapshots():
print(snap.seq, snap.status, snap.step){
"data": [
{
"trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
"seq": 1,
"step": 0,
"status": "pending",
"created_at": "2026-11-28T09:30:00.000Z",
"last_sample_at": "2026-11-28T09:30:00.000Z",
"released_at": "2026-11-28T09:30:00.000Z"
}
]
}Release a snapshot (idempotent): its queued samples fail snapshot_released#
DELETE/v1/trainers/{id}/snapshots/{seq}
Path parameters
idstringrequiredseqintegerrequired
Returns
200 Snapshot The snapshot, released.
7 fields
trainer_idstringrequiredseqintegerrequiredThe snapshot op's seq: its id within the trainer.
stepintegerrequiredThe optimizer step it froze (null while pending).
statusSnapshotStatusrequiredpending: its op has not run yet (samples queue and run once it has); live: frozen weights on the worker; released: gone (its queued samples failed
snapshot_released)."pending""live""released"created_atstring (date-time)requiredlast_sample_atstring (date-time)requiredreleased_atstring (date-time)required
from grad import Grad
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
snap = trainer.snapshot()
snap.release(){
"trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
"seq": 1,
"step": 0,
"status": "pending",
"created_at": "2026-11-28T09:30:00.000Z",
"last_sample_at": "2026-11-28T09:30:00.000Z",
"released_at": "2026-11-28T09:30:00.000Z"
}Sample from a snapshot on the sample lane#
POST/v1/trainers/{id}/snapshots/{seq}/sample
No seq; runs between train ops.
Path parameters
idstringrequiredseqintegerrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body SnapshotSampleRequest
promptsarray of SamplePromptrequirednum_samplesintegermax_tokensintegerrequiredtemperaturenumbertop_pnumbertop_kintegerKeep only the top K tokens before sampling (omitted or null: disabled).
top_logprobsintegerNumber of highest-probability
(token_id, logprob)pairs to return per generated token from the processed distribution (default 0: omitted).prompt_logprobsbooleanReturn per-prompt-token logprobs under the active weights (
float32lengthlen(prompt_tokens), index 0 is0.0; default false).stoparray of string or integerStop strings and token ids; they replace the base's stop tokens (the trainer's
stop_token_ids).[]: run tomax_tokens. A stop token is kept intokens.seedintegerReproducible sampling for the same request. On a snapshot, a seeded op runs alone (not batched with others).
streambooleanEmit incremental token deltas to
GET /v1/trainers/{id}/ops/{op_id}/stream(SSE) while generating. Streaming snapshot samples run alone (never coalesced) for minimal time-to-first-token.request_keystringrequiredMakes the POST idempotent: a resend with the same key and body returns the op it created (200); the same key with another body is
409 request_key_conflict.deadline_sintegerA sample still queued this long after its POST fails
deadline_exceeded, unrun and unbilled (a crashed client's turns don't run).
Returns
200 TrainerOp A resend: the op this request_key created.
202 TrainerOp Queued: the op (its future).
16 fields
idstringrequiredop_and 24 hex.trainer_idstringrequiredseqintegerrequiredIts place in the train lane; null on the sample lane.
laneTrainerOpLanerequiredtrain: the seq-ordered ops; sample: samples from a snapshot, which take no seq and run between train ops.
"train""sample"snapshot_seqintegerrequiredA snapshot sample: the snapshot it samples from.
request_keystringrequiredA snapshot sample's idempotency key.
typeTrainerOpTyperequired"forward_backward""forward""optim_step""sample""save_state""export""render""snapshot"statusTrainerOpStatusrequired"queued""running""done""failed"resultTrainerOpResultAn op's result once it is done (by
type); absent while it is pending, and when it is large (thenresult_url).One of 8 shapes
- ForwardBackwardResult
type"forward_backward"required"forward_backward"lossnumberrequiredscale * loss_sum.loss_sumnumberrequiredsum(w * term)before scale.weight_sumnumberrequiredsum(w): the weights (or coefficients) the loss read.metricsTrainerLossMetricsrequiredOver the tokens or datums the loss reads. The RL fields come with
importance_sampling,ppo,cispo,droandstable_reinforce; preference and reference diagnostics come withsimpo,orpo,kto,npoandkl_anchor.19 child fields
tokensintegerrequiredtrained_tokensintegerrequiredTokens the loss reads (nonzero weight or coefficient).
token_accuracynumberrequiredtruncatedintegerkl_sample_trainnumberRL losses: mean(sampling_logprob - logprob) over the trained tokens (k1; it can cancel to about 0).
kl_sample_train_v2numberRL losses: 0.5 * mean((sampling_logprob - logprob)^2).
sample_train_max_diffnumberRL losses: max |sampling_logprob - logprob|.
entropynumberRL losses: mean token-level Shannon entropy (
-sum(p * log p)) of the current policy over the trained tokens.ratio_meannumberratio_maxnumberclip_fractionnumberppo, cispo, and stable_reinforce: the share of trained tokens whose ratio was clipped.
preference_accuracynumbersimpo and orpo: fraction of preference pairs where chosen has higher length-normalized log-prob than rejected.
margin_meannumbersimpo and orpo: mean reward margin (
beta * (avg_lp_chosen - avg_lp_rejected)) or log-odds ratio (log_odds_chosen - log_odds_rejected).chosen_reward_meannumbersimpo and kto: mean implicit reward on chosen / desirable sequences.
rejected_reward_meannumbersimpo and kto: mean implicit reward on rejected / undesirable sequences.
sft_loss_meannumberorpo and kl_anchor: mean SFT negative log-likelihood component.
or_loss_meannumberorpo: mean odds-ratio preference loss component.
kl_refnumberkto, npo and kl_anchor: reference divergence diagnostic (batch
z_reffor kto, mean log-ratio for npo, mean KL penalty for kl_anchor).ref_diff_maxnumberkto, npo and kl_anchor: max |logprob - ref_logprob| over trained tokens.
- ForwardResult
type"forward"required"forward"logprobsarray of Tensorrequired2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
lossnumberrequiredloss_sumnumberrequiredweight_sumnumberrequiredmetricsTrainerLossMetricsrequired
- OptimStepResult
type"optim_step"required"optim_step"stepintegerrequiredgrad_normnumberrequiredskippedbooleanrequiredNo gradients were pending: nothing changed.
lrnumberThe numeric learning rate applied (resolved when
lr: "auto"was requested).
- SampleResult
type"sample"required"sample"resultsarray of objectrequired4 child fields
prompt_tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
prompt_logprobsTensorA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
resetbooleanrequiredA
continuewhose template rewrote history:prompt_tokensare a fresh render, nottokensplus a delta (the trajectory starts a new segment). False for other prompts.samplesarray of TrainerSamplerequired7 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
logprobsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
top_logprobsarray of array of TopLogprobPresent when
top_logprobs > 0: for each sampled token, up to K(token_id, logprob)pairs ordered highest logprob first.textstringrequiredfinish_reasonenumrequiredstop: a stop token or string; length:
max_tokens(or, on acontinue, the room left inmax_seq_len); context_full: acontinuewith no room left, no tokens."stop""length""context_full"messageSampledAssistantMessagerequiredThe sample parsed with the base's template (reasoning and OpenAI-style tool calls,
argumentsa JSON string), from its tokens decoded with special tokens kept. Unparseable markup stays incontentandparsedis false.4 child fields
role"assistant"required"assistant"contentstringrequiredreasoning_contentstringtool_callsarray of object3 child fields
idstringrequiredtype"function"required"function"functionobjectrequired
parsedbooleanrequiredThe reply parsed cleanly (no malformed tool call). False:
message.contentholds the raw text, which an environment gets as text.
- SaveStateResult
type"save_state"required"save_state"checkpointobjectrequired5 child fields
idstringrequiredstepintegerrequirednamestringexpires_atstring (date-time)metadatamap of any
- ExportResult
type"export"required"export"artifactArtifactrequired16 child fields
idstringrequiredArtifact id:
name@version.workspace_idstringrequirednamestringrequiredArtifact name, usually the run name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredVersion,
YYYY-MM-DD-N: the release date and its sequence that day.run_idstringrequiredThe run that trained it; null for uploads and imports.
checkpoint_idstringrequiredThe checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.
base_modelstringrequiredThe base model the weights apply to.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"formatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sha256stringrequiredSHA-256 of the bundle; downloads verify it.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
manifestmap of anyrequiredThe bundle's manifest.json: format, base model, adapter and training settings.
provenanceArtifactProvenancerequired5 child fields
sourceenumrequiredrun: trained by a grad run; trainer: exported by a trainer (
trainer.export); upload: files uploaded withgrad artifacts upload; import: pulled from the Hugging Face Hub withgrad artifacts import."run""trainer""upload""import"run_idstringrequiredsource=run: the run that trained it.
trainer_idstringrequiredsource=trainer: the trainer that exported it.
uploaderstringrequiredsource=upload: the API key (principal) that uploaded it.
uristringrequiredsource=import:
hf://owner/name@<40-hex commit>, the pinned revision it was imported from.
eval_reportEvalReportrequiredcreated_atstring (date-time)requiredWhen it was released.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
- RenderResult
type"render"required"render"dataarray of RenderedDatumrequired4 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
weightsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
truncatedbooleanrequiredmediaarray of MediaItem4 child fields
kindenumrequired"image""audio"mimeenumrequired"image/png""image/jpeg""image/webp""audio/wav"datastringMatches
^[A-Za-z0-9+/]+={0,2}$media_idstringContent-addressed media upload id (
med_...fromPOST /v1/media); mutually exclusive withdata.Matches
^med_[0-9a-f]{24}$
- SnapshotResult
type"snapshot"required"snapshot"snapshotobjectrequired2 child fields
seqintegerrequiredstepintegerrequired
- ForwardBackwardResult
result_urlstringrequiredA result over 256 KiB (forward log-probs, samples): a presigned GET of its JSON, valid 15 minutes. Results are kept 24 hours.
errorTrainerOpErrorrequiredWhy it failed:
invalid_datum,invalid_continuation,trainer_lost(the worker died; ops after its last saved state are gone),trainer_closed,op_failed,result_expired,snapshot_released,deadline_exceeded,result_too_large.usageTrainerUsagerequired4 child fields
tokensintegerrequiredcost_usdnumberrequiredprompt_tokensintegersampled_tokensinteger
compute_msintegerrequiredWorker compute time (a sample-lane op: its batch's, shared by the ops batched together).
started_atis when the worker took the op, which may be before it ran (prefetch).created_atstring (date-time)requiredstarted_atstring (date-time)requiredfinished_atstring (date-time)required
from grad import Grad
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
with trainer.snapshot() as snap:
out = snap.sample(
[{"messages": [{"role": "user", "content": "What is 12 * 7?"}]}],
max_tokens=128,
request_key="ep-1-turn-0",
).result()
print(out.results[0].samples[0].text){
"id": "op_3f9c0a1b2c3d4e5f60718293",
"trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
"seq": 1,
"lane": "train",
"snapshot_seq": 1,
"request_key": "string",
"type": "forward_backward",
"status": "queued",
"result": {
"type": "forward_backward",
"loss": 0,
"loss_sum": 0,
"weight_sum": 0,
"metrics": {
"tokens": 0,
"trained_tokens": 0,
"token_accuracy": 0,
"truncated": 0,
"kl_sample_train": 0,
"kl_sample_train_v2": 0,
"sample_train_max_diff": 0,
"entropy": 0,
"ratio_mean": 0,
"ratio_max": 0,
"clip_fraction": 0,
"preference_accuracy": 0,
"margin_mean": 0,
"chosen_reward_mean": 0,
"rejected_reward_mean": 0,
"sft_loss_mean": 0,
"or_loss_mean": 0,
"kl_ref": 0,
"ref_diff_max": 0
}
},
"result_url": "string",
"error": {
"code": "string",
"message": "…"
},
"usage": {
"tokens": 0,
"cost_usd": 0,
"prompt_tokens": 0,
"sampled_tokens": 0
},
"compute_ms": 0,
"created_at": "2026-11-28T09:30:00.000Z",
"started_at": "2026-11-28T09:30:00.000Z",
"finished_at": "2026-11-28T09:30:00.000Z"
}Mint a short-lived token scoped strictly to OpenAI/Anthropic sampling on this trainer#
POST/v1/trainers/{id}/endpoint-tokens
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body CreateTrainerEndpointTokenRequest
snapshot_seqintegerOptional snapshot seq to bind this token to. When set, the token can only sample from that snapshot.
ttl_sintegerToken lifetime in seconds (60..86400, default 3600). Automatically invalid once the trainer closes.
thinkingenumDefault thinking mode applied to OpenAI/Anthropic requests authenticated with this token.
"auto""on""off"preserve_thinkingbooleanDefault preserve_thinking flag applied to multi-turn continuations authenticated with this token.
Returns
201 TrainerEndpointTokenResponse Scoped endpoint token and OpenAI/Anthropic base URLs.
6 fields
tokenstringrequiredShort-lived bearer / x-api-key token scoped strictly to OpenAI/Anthropic sampling on this trainer (and optional snapshot).
expires_atstring (date-time)requiredtrainer_idstringrequiredsnapshot_seqintegerrequiredopenai_base_urlstringrequiredOpenAI-compatible base URL (pass as OPENAI_BASE_URL; SDK appends /chat/completions).
anthropic_base_urlstringrequiredAnthropic-compatible base URL (pass as ANTHROPIC_BASE_URL; SDK appends /v1/messages).
from grad import Grad
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
ep = trainer.endpoint(ttl_s=3600, thinking="auto")
print(ep.openai_base_url, ep.anthropic_base_url, ep.expires_at){
"token": "string",
"expires_at": "2026-11-28T09:30:00.000Z",
"trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
"snapshot_seq": 1,
"openai_base_url": "string",
"anthropic_base_url": "string"
}List recorded token-aligned trajectories from this trainer's OpenAI/Anthropic endpoint#
GET/v1/trainers/{id}/sessions
Path parameters
idstringrequired
Query parameters
sessionstring
Returns
200 TrainerSessionsResponse Recorded session trajectories.
1 fields
dataarray of TrainerSessionTrajectoryrequired11 child fields
rollout_idstringrequiredsession_idstringrequiredmessagesarray of map of anyrequiredtoolsarray of map of anysegmentsarray of TrainerSessionSegmentrequired5 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
weightsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
sampling_logprobsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
turn_idsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
mediaarray of MediaItem4 child fields
kindenumrequired"image""audio"mimeenumrequired"image/png""image/jpeg""image/webp""audio/wav"datastringMatches
^[A-Za-z0-9+/]+={0,2}$media_idstringContent-addressed media upload id (
med_...fromPOST /v1/media); mutually exclusive withdata.Matches
^med_[0-9a-f]{24}$
turnsintegerrequiredfinish_reasonstringrequiredpolicymap of anyrequiredsamplingmap of anyrequiredusageobjectrequired3 child fields
prompt_tokensintegerrequiredcompletion_tokensintegerrequiredcost_usdnumberrequired
metricsmap of numberrequired
from grad import Grad
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
trajs = trainer.trajectories()
print(len(trajs)){
"data": [
{
"rollout_id": "obj_3f9c0a1b2c3d4e5f60718293",
"session_id": "obj_3f9c0a1b2c3d4e5f60718293",
"messages": [
{}
],
"tools": [
{}
],
"segments": [
{
"tokens": {},
"weights": {},
"sampling_logprobs": {},
"turn_ids": {},
"media": []
}
],
"turns": 0,
"finish_reason": "string",
"policy": {},
"sampling": {},
"usage": {
"prompt_tokens": 0,
"completion_tokens": 0,
"cost_usd": 0
},
"metrics": {}
}
]
}Clear recorded trajectories for all sessions (or one ?session=...) on a trainer#
DELETE/v1/trainers/{id}/sessions
Path parameters
idstringrequired
Query parameters
sessionstring
Returns
200 ClearTrainerSessionsResponse Cleared session count.
1 fields
clearedintegerrequired
from grad import Grad
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
cleared = trainer.clear_sessions()
print(cleared){
"cleared": 0
}Get recorded token-aligned trajectories for one trainer session#
GET/v1/trainers/{id}/sessions/{session_id}/trajectories
Path parameters
idstringrequiredsession_idstringrequired
Returns
200 TrainerSessionsResponse Trajectories recorded for this session.
1 fields
dataarray of TrainerSessionTrajectoryrequired11 child fields
rollout_idstringrequiredsession_idstringrequiredmessagesarray of map of anyrequiredtoolsarray of map of anysegmentsarray of TrainerSessionSegmentrequired5 child fields
tokensTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
weightsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
sampling_logprobsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
turn_idsTensorrequiredA 1-D array:
dtype(int32 or float32, little-endian) and its bytes in standard base64. The SDKs take and return numpy/torch arrays (Python) or typed arrays.2 child fields
dtypeenumrequired"int32""float32"b64stringrequiredMatches
^[A-Za-z0-9+/]*={0,2}$
mediaarray of MediaItem4 child fields
kindenumrequired"image""audio"mimeenumrequired"image/png""image/jpeg""image/webp""audio/wav"datastringMatches
^[A-Za-z0-9+/]+={0,2}$media_idstringContent-addressed media upload id (
med_...fromPOST /v1/media); mutually exclusive withdata.Matches
^med_[0-9a-f]{24}$
turnsintegerrequiredfinish_reasonstringrequiredpolicymap of anyrequiredsamplingmap of anyrequiredusageobjectrequired3 child fields
prompt_tokensintegerrequiredcompletion_tokensintegerrequiredcost_usdnumberrequired
metricsmap of numberrequired
from grad import Grad
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
trajs = trainer.trajectories("ep-1")
print(len(trajs)){
"data": [
{
"rollout_id": "obj_3f9c0a1b2c3d4e5f60718293",
"session_id": "obj_3f9c0a1b2c3d4e5f60718293",
"messages": [
{}
],
"tools": [
{}
],
"segments": [
{
"tokens": {},
"weights": {},
"sampling_logprobs": {},
"turn_ids": {},
"media": []
}
],
"turns": 0,
"finish_reason": "string",
"policy": {},
"sampling": {},
"usage": {
"prompt_tokens": 0,
"completion_tokens": 0,
"cost_usd": 0
},
"metrics": {}
}
]
}Clear recorded trajectories for one trainer session#
DELETE/v1/trainers/{id}/sessions/{session_id}
Path parameters
idstringrequiredsession_idstringrequired
Returns
200 ClearTrainerSessionsResponse Cleared session count.
1 fields
clearedintegerrequired
from grad import Grad
client = Grad()
trainer = client.trainers.get("trn_3f9c0a1b2c3d4e5f60718293")
cleared = trainer.clear_sessions("ep-1")
print(cleared){
"cleared": 0
}Environments#
Register a versioned Harbor or sandbox environment bundle#
POST/v1/environments
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body CreateEnvironmentRequest
namestringrequiredEnvironment name slug (unique per workspace with version).
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringOptional version tag; auto-increments
v1,v2, ... when omitted.Matches
^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$formatEnvironmentFormatEnvironment bundle format:
harbor(Harbor task or benchmark suite) orsandbox(Dockerfile/Compose workspace)."harbor""sandbox"upload_idstringStaged
.tar.gzbundle uploaded viaPOST /v1/uploads(purpose: "environment_bundle", max 64 MiB). Mutually exclusive withbundle_tar_gz_b64.Matches
^[0-9a-f]{64}$bundle_tar_gz_b64stringBase64-encoded gzipped tar archive for small inline uploads (max 2 MiB decoded). Prefer
upload_idfor larger bundles; mutually exclusive withupload_id.default_specmap of anyOptional default sandbox spec overrides (cpus, memory_mb, network, env, workdir, etc.).
Returns
201 Environment Created environment.
13 fields
idstringrequiredEnvironment id (
env_and 24 hex characters).workspace_idstringrequirednamestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredformatEnvironmentFormatrequiredEnvironment bundle format:
harbor(Harbor task or benchmark suite) orsandbox(Dockerfile/Compose workspace)."harbor""sandbox"bundle_sha256stringrequiredMatches
^[0-9a-f]{64}$bundle_bytesintegerrequiredtask_countintegerrequiredtasks_metaarray of EnvironmentTaskMetarequired6 child fields
namestringrequiredinstruction_summarystringrequiredtimeout_snumberrequiredcpusnumberrequiredmemory_mbintegerrequiredrequires_composebooleanrequired
default_specmap of anyrequiredrequires_composebooleanrequiredcreated_atstring (date-time)requiredbundle_urlstringShort-lived presigned bundle download URL (returned only when
include_bundle_url=true).
from grad import Grad
client = Grad()
env = client.environments.push("./fix-bug", name="fix-bug", version="v1", format="harbor")
print(env.id, env.ref){
"id": "env_3f9c0a1b2c3d4e5f60718293",
"workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
"name": "support-prod",
"version": "string",
"format": "harbor",
"bundle_sha256": "string",
"bundle_bytes": 0,
"task_count": 0,
"tasks_meta": [
{
"name": "support-prod",
"instruction_summary": "string",
"timeout_s": 1,
"cpus": 1,
"memory_mb": 1,
"requires_compose": false
}
],
"default_spec": {},
"requires_compose": false,
"created_at": "2026-11-28T09:30:00.000Z",
"bundle_url": "string"
}List registered environments#
GET/v1/environments
Newest first.
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstringnamestringMatches
^[a-z0-9][a-z0-9._-]{0,63}$qstringOnly items whose name contains this text (any case), or whose id is exactly this.
Returns
200 object Environments.
2 fields
dataarray of Environmentrequired13 child fields
idstringrequiredEnvironment id (
env_and 24 hex characters).workspace_idstringrequirednamestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredformatEnvironmentFormatrequiredEnvironment bundle format:
harbor(Harbor task or benchmark suite) orsandbox(Dockerfile/Compose workspace)."harbor""sandbox"bundle_sha256stringrequiredMatches
^[0-9a-f]{64}$bundle_bytesintegerrequiredtask_countintegerrequiredtasks_metaarray of EnvironmentTaskMetarequired6 child fields
namestringrequiredinstruction_summarystringrequiredtimeout_snumberrequiredcpusnumberrequiredmemory_mbintegerrequiredrequires_composebooleanrequired
default_specmap of anyrequiredrequires_composebooleanrequiredcreated_atstring (date-time)requiredbundle_urlstringShort-lived presigned bundle download URL (returned only when
include_bundle_url=true).
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
for env in client.environments.list():
print(env.id, env.ref, env.task_count){
"data": [],
"next_cursor": null
}Get an environment by id (`env_...`) or `name@version` / `name@latest`#
GET/v1/environments/{id}
Path parameters
idstringrequired
Query parameters
include_bundle_urlbooleanWhen true, include a short-lived presigned S3 download URL (
bundle_url) for the.tar.gzbundle.
Returns
200 Environment Environment metadata.
13 fields
idstringrequiredEnvironment id (
env_and 24 hex characters).workspace_idstringrequirednamestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredformatEnvironmentFormatrequiredEnvironment bundle format:
harbor(Harbor task or benchmark suite) orsandbox(Dockerfile/Compose workspace)."harbor""sandbox"bundle_sha256stringrequiredMatches
^[0-9a-f]{64}$bundle_bytesintegerrequiredtask_countintegerrequiredtasks_metaarray of EnvironmentTaskMetarequired6 child fields
namestringrequiredinstruction_summarystringrequiredtimeout_snumberrequiredcpusnumberrequiredmemory_mbintegerrequiredrequires_composebooleanrequired
default_specmap of anyrequiredrequires_composebooleanrequiredcreated_atstring (date-time)requiredbundle_urlstringShort-lived presigned bundle download URL (returned only when
include_bundle_url=true).
from grad import Grad
client = Grad()
env = client.environments.get("env_3f9c0a1b2c3d4e5f60718293")
print(env.ref, env.format, env.task_count){
"id": "env_3f9c0a1b2c3d4e5f60718293",
"workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
"name": "support-prod",
"version": "string",
"format": "harbor",
"bundle_sha256": "string",
"bundle_bytes": 0,
"task_count": 0,
"tasks_meta": [
{
"name": "support-prod",
"instruction_summary": "string",
"timeout_s": 1,
"cpus": 1,
"memory_mb": 1,
"requires_compose": false
}
],
"default_spec": {},
"requires_compose": false,
"created_at": "2026-11-28T09:30:00.000Z",
"bundle_url": "string"
}Soft-delete a registered environment#
DELETE/v1/environments/{id}
Path parameters
idstringrequired
Returns
200 DeleteEnvironmentResponse Deleted environment.
2 fields
idstringrequireddeletedbooleanrequired
from grad import Grad
client = Grad()
client.environments.delete("env_3f9c0a1b2c3d4e5f60718293"){
"id": "obj_3f9c0a1b2c3d4e5f60718293",
"deleted": false
}Media#
Upload a content-addressed image or WAV audio blob for multimodal trainer ops#
POST/v1/media
Idempotent per workspace by SHA-256. Accepts JSON ({ kind, mime, data }) or raw binary bytes with Content-Type: image/png, image/jpeg, image/webp, or audio/wav. Reference the returned id as grad://media/<id> in image_url.url or media_id in input_audio / MediaItem.
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body UploadMediaRequest
kindMediaKindrequired"image""audio"mimeMediaMimerequired"image/png""image/jpeg""image/webp""audio/wav"datastringrequiredMatches
^[A-Za-z0-9+/]+={0,2}$
Returns
201 MediaObject Uploaded (or existing) media.
6 fields
idstringrequiredmed_and 24 hex.Matches
^med_[0-9a-f]{24}$kindMediaKindrequired"image""audio"mimeMediaMimerequired"image/png""image/jpeg""image/webp""audio/wav"size_bytesintegerrequiredsha256stringrequiredMatches
^[0-9a-f]{64}$created_atstring (date-time)required
import base64
from grad import Grad
client = Grad()
raw = base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
)
media = client.media.upload(raw, mime="image/png")
print(media.id){
"id": "med_586752718400c4c6dccc2db3",
"kind": "image",
"mime": "image/png",
"size_bytes": 68,
"sha256": "431ced6916a2a21a156e38701afe55bbd7f88969fbbfc56d7fe099d47f265460",
"created_at": "2026-12-02T15:49:00.022Z"
}Get metadata for an uploaded media blob#
GET/v1/media/{id}
Path parameters
idstringrequired
Returns
200 MediaObject Media metadata.
6 fields
idstringrequiredmed_and 24 hex.Matches
^med_[0-9a-f]{24}$kindMediaKindrequired"image""audio"mimeMediaMimerequired"image/png""image/jpeg""image/webp""audio/wav"size_bytesintegerrequiredsha256stringrequiredMatches
^[0-9a-f]{64}$created_atstring (date-time)required
from grad import Grad
client = Grad()
media = client.media.get("med_3f9c0a1b2c3d4e5f60718293")
print(media.mime, media.size_bytes){
"id": "med_3f9c0a1b2c3d4e5f60718293",
"kind": "image",
"mime": "image/png",
"size_bytes": 1,
"sha256": "9f2c4e1ab0d3c5e7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c9d1e3f5a7b9c1d3e5",
"created_at": "2026-11-28T09:30:00.000Z"
}Checkpoints#
List unexpired checkpoints of a run#
GET/v1/runs/{id}/checkpoints
Best and final never expire.
Path parameters
idstringrequired
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstring
Returns
200 object Checkpoints by step.
2 fields
dataarray of Checkpointrequired17 child fields
idstringrequiredCheckpoint id (
ckpt_and 24 hex characters).workspace_idstringrequiredrun_idstringrequiredThe run that saved it (null for a trainer's).
trainer_idstringrequiredThe trainer that saved it (a save_state, autosave, park or close); null for a run's.
namestringOptional human-readable label passed to
trainer.save_state(name=...).attemptintegerrequiredThe attempt that saved it.
stepintegerrequiredOptimizer step it was saved at.
eval_scorenumberrequiredHeld-out score at this step; null when it wasn't evaluated.
formatCheckpointFormatrequiredArtifact format when this checkpoint is exportable (promotable);
trainer_statefor an interactive trainer's optimizer-bearing saved state (export weights viatrainer.export()), or null for training state only.sha256stringrequiredSHA-256 of the checkpoint bundle.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
metadatamap of anyrequiredbestbooleanrequiredTrue for the checkpoint
select="best"picks; it never expires.finalbooleanrequiredTrue for the run's last checkpoint; it never expires.
expires_atstring (date-time)requiredWhen it expires (after
checkpoint_ttl_days, 30 by default); null for checkpoints that never expire, such as the best and final.created_atstring (date-time)requiredconsole_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
for checkpoint in client.runs.checkpoints("run_3f9c0a1b2c3d4e5f60718293"):
print(checkpoint.id, checkpoint.step, checkpoint.eval_score){
"data": [
{
"id": "ckpt_066d90a41b4c935f305b88d3",
"workspace_id": "ws_e2e",
"run_id": "run_ed1c235f0c631d8f209e22a5",
"trainer_id": null,
"name": null,
"attempt": 1,
"step": 1,
"eval_score": null,
"format": "reference",
"base_model": "qwen/qwen3-8b",
"sha256": "a53f5b288340a261253b968d4a0252a8200e51ee95a5087124af049cd1f2b480",
"size_bytes": 10263,
"metadata": {
"lr": 0.000125,
"seed": 42,
"step": 1,
"select": "best",
"backend": "reference",
"manifest": {
"lr": 0.000125,
"seed": 42,
"format": "reference",
"select": "best",
"backend": "reference",
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"base_model": "qwen/qwen3-8b",
"deployable": false,
"recipe_kind": "sft",
"rule_version": "auto@2",
"base_artifact": null,
"base_model_repo": null,
"checkpoint_step": 1,
"base_model_revision": null
},
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"base_model": "qwen/qwen3-8b",
"deployable": false,
"metric_mode": "min",
"metric_name": "eval_loss",
"recipe_kind": "sft",
"eval_metrics": null,
"rule_version": "auto@2",
"tokens_total": 21,
"base_artifact": null,
"upload_seconds": 0.01,
"base_model_repo": null,
"base_model_revision": null
},
"best": false,
"final": true,
"expires_at": null,
"created_at": "2026-12-02T15:49:00.146Z"
}
],
"next_cursor": null
}Get an active checkpoint by id#
GET/v1/checkpoints/{id}
Path parameters
idstringrequired
Returns
200 Checkpoint Checkpoint.
17 fields
idstringrequiredCheckpoint id (
ckpt_and 24 hex characters).workspace_idstringrequiredrun_idstringrequiredThe run that saved it (null for a trainer's).
trainer_idstringrequiredThe trainer that saved it (a save_state, autosave, park or close); null for a run's.
namestringOptional human-readable label passed to
trainer.save_state(name=...).attemptintegerrequiredThe attempt that saved it.
stepintegerrequiredOptimizer step it was saved at.
eval_scorenumberrequiredHeld-out score at this step; null when it wasn't evaluated.
formatCheckpointFormatrequiredArtifact format when this checkpoint is exportable (promotable);
trainer_statefor an interactive trainer's optimizer-bearing saved state (export weights viatrainer.export()), or null for training state only.sha256stringrequiredSHA-256 of the checkpoint bundle.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
metadatamap of anyrequiredbestbooleanrequiredTrue for the checkpoint
select="best"picks; it never expires.finalbooleanrequiredTrue for the run's last checkpoint; it never expires.
expires_atstring (date-time)requiredWhen it expires (after
checkpoint_ttl_days, 30 by default); null for checkpoints that never expire, such as the best and final.created_atstring (date-time)requiredconsole_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
checkpoint = client.checkpoints.get("ckpt_3f9c0a1b2c3d4e5f60718293")
print(checkpoint.id, checkpoint.step, checkpoint.eval_score){
"id": "ckpt_066d90a41b4c935f305b88d3",
"workspace_id": "ws_e2e",
"run_id": "run_ed1c235f0c631d8f209e22a5",
"trainer_id": null,
"name": null,
"attempt": 1,
"step": 1,
"eval_score": null,
"format": "reference",
"base_model": "qwen/qwen3-8b",
"sha256": "a53f5b288340a261253b968d4a0252a8200e51ee95a5087124af049cd1f2b480",
"size_bytes": 10263,
"metadata": {
"lr": 0.000125,
"seed": 42,
"step": 1,
"select": "best",
"backend": "reference",
"manifest": {
"lr": 0.000125,
"seed": 42,
"format": "reference",
"select": "best",
"backend": "reference",
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"base_model": "qwen/qwen3-8b",
"deployable": false,
"recipe_kind": "sft",
"rule_version": "auto@2",
"base_artifact": null,
"base_model_repo": null,
"checkpoint_step": 1,
"base_model_revision": null
},
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"base_model": "qwen/qwen3-8b",
"deployable": false,
"metric_mode": "min",
"metric_name": "eval_loss",
"recipe_kind": "sft",
"eval_metrics": null,
"rule_version": "auto@2",
"tokens_total": 21,
"base_artifact": null,
"upload_seconds": 0.01,
"base_model_repo": null,
"base_model_revision": null
},
"best": false,
"final": true,
"expires_at": null,
"created_at": "2026-12-02T15:49:00.146Z"
}Update an active checkpoint's TTL and/or user metadata#
PATCH/v1/checkpoints/{id}
Path parameters
idstringrequired
Body UpdateCheckpointRequest
ttl_sintegerNew TTL in seconds (300 to 7776000) from now, or null to make the checkpoint permanent (never expires).
metadatamap of anyReplacement user metadata JSON object (at most 16 KiB serialized UTF-8).
Returns
200 Checkpoint Updated checkpoint.
17 fields
idstringrequiredCheckpoint id (
ckpt_and 24 hex characters).workspace_idstringrequiredrun_idstringrequiredThe run that saved it (null for a trainer's).
trainer_idstringrequiredThe trainer that saved it (a save_state, autosave, park or close); null for a run's.
namestringOptional human-readable label passed to
trainer.save_state(name=...).attemptintegerrequiredThe attempt that saved it.
stepintegerrequiredOptimizer step it was saved at.
eval_scorenumberrequiredHeld-out score at this step; null when it wasn't evaluated.
formatCheckpointFormatrequiredArtifact format when this checkpoint is exportable (promotable);
trainer_statefor an interactive trainer's optimizer-bearing saved state (export weights viatrainer.export()), or null for training state only.sha256stringrequiredSHA-256 of the checkpoint bundle.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
metadatamap of anyrequiredbestbooleanrequiredTrue for the checkpoint
select="best"picks; it never expires.finalbooleanrequiredTrue for the run's last checkpoint; it never expires.
expires_atstring (date-time)requiredWhen it expires (after
checkpoint_ttl_days, 30 by default); null for checkpoints that never expire, such as the best and final.created_atstring (date-time)requiredconsole_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
checkpoint = client.checkpoints.update(
"ckpt_3f9c0a1b2c3d4e5f60718293",
ttl_s=86400,
metadata={"stage": "eval-pass"},
)
print(checkpoint.expires_at){
"id": "ckpt_3f9c0a1b2c3d4e5f60718293",
"workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
"run_id": "run_3f9c0a1b2c3d4e5f60718293",
"trainer_id": "trn_3f9c0a1b2c3d4e5f60718293",
"name": "support-prod",
"attempt": 1,
"step": 0,
"eval_score": 0,
"format": "peft_lora",
"sha256": "9f2c4e1ab0d3c5e7f9a1b3c5d7e9f1a3b5c7d9e1f3a5b7c9d1e3f5a7b9c1d3e5",
"size_bytes": 0,
"metadata": {},
"best": false,
"final": false,
"expires_at": "2026-11-28T09:30:00.000Z",
"created_at": "2026-11-28T09:30:00.000Z",
"console_url": "string"
}Release an exportable checkpoint as a named, versioned artifact#
POST/v1/checkpoints/{id}/promote
Promoting it again under the same name returns that release.
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body PromoteCheckpointRequest
namestringMatches
^[a-z0-9][a-z0-9._-]{0,63}$
Returns
201 Artifact Promoted artifact.
16 fields
idstringrequiredArtifact id:
name@version.workspace_idstringrequirednamestringrequiredArtifact name, usually the run name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredVersion,
YYYY-MM-DD-N: the release date and its sequence that day.run_idstringrequiredThe run that trained it; null for uploads and imports.
checkpoint_idstringrequiredThe checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.
base_modelstringrequiredThe base model the weights apply to.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"formatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sha256stringrequiredSHA-256 of the bundle; downloads verify it.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
manifestmap of anyrequiredThe bundle's manifest.json: format, base model, adapter and training settings.
provenanceArtifactProvenancerequired5 child fields
sourceenumrequiredrun: trained by a grad run; trainer: exported by a trainer (
trainer.export); upload: files uploaded withgrad artifacts upload; import: pulled from the Hugging Face Hub withgrad artifacts import."run""trainer""upload""import"run_idstringrequiredsource=run: the run that trained it.
trainer_idstringrequiredsource=trainer: the trainer that exported it.
uploaderstringrequiredsource=upload: the API key (principal) that uploaded it.
uristringrequiredsource=import:
hf://owner/name@<40-hex commit>, the pinned revision it was imported from.
eval_reportEvalReportrequiredcreated_atstring (date-time)requiredWhen it was released.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
artifact = client.checkpoints.promote("ckpt_3f9c0a1b2c3d4e5f60718293", name="support-sft-step-400")
print(artifact.id){
"id": "support-sft-step-400@2026-12-02-1",
"workspace_id": "ws_e2e",
"name": "support-sft-step-400",
"version": "2026-12-02-1",
"run_id": "run_ed1c235f0c631d8f209e22a5",
"checkpoint_id": "ckpt_066d90a41b4c935f305b88d3",
"base_model": "qwen/qwen3-8b",
"recipe_kind": "sft",
"format": "reference",
"sha256": "a53f5b288340a261253b968d4a0252a8200e51ee95a5087124af049cd1f2b480",
"size_bytes": 10263,
"manifest": {
"lr": 0.000125,
"seed": 42,
"step": 1,
"run_id": "run_ed1c235f0c631d8f209e22a5",
"schema": "grad.artifact/1",
"select": "best",
"attempt": 1,
"backend": "reference",
"manifest": {
"lr": 0.000125,
"seed": 42,
"format": "reference",
"select": "best",
"backend": "reference",
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"base_model": "qwen/qwen3-8b",
"deployable": false,
"recipe_kind": "sft",
"rule_version": "auto@2",
"base_artifact": null,
"base_model_repo": null,
"checkpoint_step": 1,
"base_model_revision": null
},
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"base_model": "qwen/qwen3-8b",
"deployable": false,
"provenance": {
"run_id": "run_ed1c235f0c631d8f209e22a5",
"source": "run"
},
"metric_mode": "min",
"metric_name": "eval_loss",
"recipe_kind": "sft",
"eval_metrics": null,
"rule_version": "auto@2",
"tokens_total": 21,
"base_artifact": null,
"upload_seconds": 0.01,
"base_model_repo": null,
"resolved_config": {
"lr": 0.000125,
"name": "support-sft",
"model": "qwen/qwen3-8b",
"split": {
"seed": 42,
"strategy": "by_session",
"eval_records": 0,
"eval_fraction": 0.1,
"train_records": 1
},
"epochs": 1,
"select": "best",
"warmup": 0.03,
"adapter": {
"kind": "lora",
"rank": 32,
"alpha": 32,
"merge_on_export": false,
"train_multimodal_projector": false
},
"dataset": "support-prod",
"schedule": "linear",
"thinking": "auto",
"train_on": "last",
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"optimizer": {
"kind": "adamw",
"betas": [
0.9,
0.95
],
"grad_clip": 1,
"weight_decay": 0
},
"reduction": "per_example",
"batch_size": 8,
"recipe_kind": "sft",
"rule_version": "auto@2",
"base_artifact": null,
"label_eval_id": null,
"recipe_params": {},
"dataset_version": 1,
"eval_every_steps": 1,
"preserve_thinking": false,
"template_revision": "qwen3@3",
"checkpoint_ttl_days": 30,
"checkpoint_every_steps": 1
},
"base_model_revision": null,
"promoted_from_checkpoint": "ckpt_066d90a41b4c935f305b88d3"
},
"provenance": {
"source": "run",
"run_id": "run_ed1c235f0c631d8f209e22a5",
"trainer_id": null,
"uploader": null,
"uri": null
},
"eval_report": null,
"created_at": "2026-12-02T15:49:01.130Z"
}Artifacts#
List immutable artifacts#
GET/v1/artifacts
Newest first.
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstringnamestringMatches
^[a-z0-9][a-z0-9._-]{0,63}$qstringOnly items whose name contains this text (any case), or whose id is exactly this.
Returns
200 object Artifacts.
2 fields
dataarray of Artifactrequired16 child fields
idstringrequiredArtifact id:
name@version.workspace_idstringrequirednamestringrequiredArtifact name, usually the run name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredVersion,
YYYY-MM-DD-N: the release date and its sequence that day.run_idstringrequiredThe run that trained it; null for uploads and imports.
checkpoint_idstringrequiredThe checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.
base_modelstringrequiredThe base model the weights apply to.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"formatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sha256stringrequiredSHA-256 of the bundle; downloads verify it.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
manifestmap of anyrequiredThe bundle's manifest.json: format, base model, adapter and training settings.
provenanceArtifactProvenancerequired5 child fields
sourceenumrequiredrun: trained by a grad run; trainer: exported by a trainer (
trainer.export); upload: files uploaded withgrad artifacts upload; import: pulled from the Hugging Face Hub withgrad artifacts import."run""trainer""upload""import"run_idstringrequiredsource=run: the run that trained it.
trainer_idstringrequiredsource=trainer: the trainer that exported it.
uploaderstringrequiredsource=upload: the API key (principal) that uploaded it.
uristringrequiredsource=import:
hf://owner/name@<40-hex commit>, the pinned revision it was imported from.
eval_reportEvalReportrequiredcreated_atstring (date-time)requiredWhen it was released.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
for artifact in client.artifacts.list(search="support"):
print(artifact.id, artifact.base_model){
"data": [
{
"id": "support-sft-step-400@2026-12-02-1",
"workspace_id": "ws_e2e",
"name": "support-sft-step-400",
"version": "2026-12-02-1",
"run_id": "run_ed1c235f0c631d8f209e22a5",
"checkpoint_id": "ckpt_066d90a41b4c935f305b88d3",
"base_model": "qwen/qwen3-8b",
"recipe_kind": "sft",
"format": "reference",
"sha256": "a53f5b288340a261253b968d4a0252a8200e51ee95a5087124af049cd1f2b480",
"size_bytes": 10263,
"manifest": {
"lr": 0.000125,
"seed": 42,
"step": 1,
"run_id": "run_ed1c235f0c631d8f209e22a5",
"schema": "grad.artifact/1",
"select": "best",
"attempt": 1,
"backend": "reference",
"manifest": {
"lr": 0.000125,
"seed": 42,
"format": "reference",
"select": "best",
"backend": "reference",
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"base_model": "qwen/qwen3-8b",
"deployable": false,
"recipe_kind": "sft",
"rule_version": "auto@2",
"base_artifact": null,
"base_model_repo": null,
"checkpoint_step": 1,
"base_model_revision": null
},
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"base_model": "qwen/qwen3-8b",
"deployable": false,
"provenance": {
"run_id": "run_ed1c235f0c631d8f209e22a5",
"source": "run"
},
"metric_mode": "min",
"metric_name": "eval_loss",
"recipe_kind": "sft",
"eval_metrics": null,
"rule_version": "auto@2",
"tokens_total": 21,
"base_artifact": null,
"upload_seconds": 0.01,
"base_model_repo": null,
"resolved_config": {
"lr": 0.000125,
"name": "support-sft",
"model": "qwen/qwen3-8b",
"split": {
"seed": 42,
"strategy": "by_session",
"eval_records": 0,
"eval_fraction": 0.1,
"train_records": 1
},
"epochs": 1,
"select": "best",
"warmup": 0.03,
"adapter": {
"kind": "lora",
"rank": 32,
"alpha": 32,
"merge_on_export": false,
"train_multimodal_projector": false
},
"dataset": "support-prod",
"schedule": "linear",
"thinking": "auto",
"train_on": "last",
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"optimizer": {
"kind": "adamw",
"betas": [
0.9,
0.95
],
"grad_clip": 1,
"weight_decay": 0
},
"reduction": "per_example",
"batch_size": 8,
"recipe_kind": "sft",
"rule_version": "auto@2",
"base_artifact": null,
"label_eval_id": null,
"recipe_params": {},
"dataset_version": 1,
"eval_every_steps": 1,
"preserve_thinking": false,
"template_revision": "qwen3@3",
"checkpoint_ttl_days": 30,
"checkpoint_every_steps": 1
},
"base_model_revision": null,
"promoted_from_checkpoint": "ckpt_066d90a41b4c935f305b88d3"
},
"provenance": {
"source": "run",
"run_id": "run_ed1c235f0c631d8f209e22a5",
"trainer_id": null,
"uploader": null,
"uri": null
},
"eval_report": null,
"created_at": "2026-12-02T15:49:01.130Z"
},
{
"id": "support-sft@2026-12-02-1",
"workspace_id": "ws_e2e",
"name": "support-sft",
"version": "2026-12-02-1",
"run_id": "run_ed1c235f0c631d8f209e22a5",
"checkpoint_id": null,
"base_model": "qwen/qwen3-8b",
"recipe_kind": "sft",
"format": "reference",
"sha256": "144d0e25503494bfce90a8919a295505ac2759b0ae331e45ea16fade495c137c",
"size_bytes": 10263,
"manifest": {
"lr": 0.000125,
"kind": "final",
"seed": 42,
"files": {
"reference_model.json": "59abd7749fec876cab4e168ea5a73ba432cbd5b568a7c8070258ec7f945b454b"
},
"format": "reference",
"run_id": "run_ed1c235f0c631d8f209e22a5",
"schema": "grad.artifact/1",
"select": "last",
"status": "completed",
"attempt": 1,
"backend": "reference",
"dataset": "support-prod",
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"base_model": "qwen/qwen3-8b",
"created_by": {
"name": "grad-trainer",
"version": "0.2.0-alpha.15"
},
"deployable": false,
"provenance": {
"run_id": "run_ed1c235f0c631d8f209e22a5",
"source": "run"
},
"recipe_kind": "sft",
"total_steps": 1,
"rule_version": "auto@2",
"tokens_total": 21,
"base_artifact": null,
"selected_step": 1,
"format_version": 2,
"base_model_repo": null,
"dataset_version": 1,
"resolved_config": {
"lr": 0.000125,
"name": "support-sft",
"model": "qwen/qwen3-8b",
"split": {
"seed": 42,
"strategy": "by_session",
"eval_records": 0,
"eval_fraction": 0.1,
"train_records": 1
},
"epochs": 1,
"select": "best",
"warmup": 0.03,
"adapter": {
"kind": "lora",
"rank": 32,
"alpha": 32,
"merge_on_export": false,
"train_multimodal_projector": false
},
"dataset": "support-prod",
"schedule": "linear",
"thinking": "auto",
"train_on": "last",
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"optimizer": {
"kind": "adamw",
"betas": [
0.9,
0.95
],
"grad_clip": 1,
"weight_decay": 0
},
"reduction": "per_example",
"batch_size": 8,
"recipe_kind": "sft",
"rule_version": "auto@2",
"base_artifact": null,
"label_eval_id": null,
"recipe_params": {},
"dataset_version": 1,
"eval_every_steps": 1,
"preserve_thinking": false,
"template_revision": "qwen3@3",
"checkpoint_ttl_days": 30,
"checkpoint_every_steps": 1
},
"steps_completed": 1,
"eval_report_sha256": "782d3768b9a29b35b624e5fb6e013ad89598c2cd770421c0a5b7db8be230d56c",
"base_model_revision": null
},
"provenance": {
"source": "run",
"run_id": "run_ed1c235f0c631d8f209e22a5",
"trainer_id": null,
"uploader": null,
"uri": null
},
"eval_report": {
"warnings": [
"Reference test backend: the base model was not trained; the artifact is not deployable.",
"No held-out examples: eval metrics are null and select='last' was used."
],
"best_step": null,
"eval_loss": null,
"final_step": 1,
"metric_mode": "min",
"metric_name": "eval_loss",
"eval_records": 0,
"eval_examples": 0,
"selected_step": 1,
"train_records": 1,
"train_examples": 1,
"reference_backend": true
},
"created_at": "2026-12-02T15:49:00.199Z"
}
],
"next_cursor": null
}Get an artifact by id or name@latest#
GET/v1/artifacts/{id}
Path parameters
idstringrequired
Returns
200 Artifact Artifact metadata.
16 fields
idstringrequiredArtifact id:
name@version.workspace_idstringrequirednamestringrequiredArtifact name, usually the run name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$versionstringrequiredVersion,
YYYY-MM-DD-N: the release date and its sequence that day.run_idstringrequiredThe run that trained it; null for uploads and imports.
checkpoint_idstringrequiredThe checkpoint it was promoted from; null when it is a run's final artifact or was uploaded or imported.
base_modelstringrequiredThe base model the weights apply to.
recipe_kindRecipeKindrequired"sft""dpo""router""decision""cartridge""embedding""distill""reward""grpo""rl""trainer"formatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sha256stringrequiredSHA-256 of the bundle; downloads verify it.
Matches
^[0-9a-f]{64}$size_bytesintegerrequiredBundle size in bytes.
manifestmap of anyrequiredThe bundle's manifest.json: format, base model, adapter and training settings.
provenanceArtifactProvenancerequired5 child fields
sourceenumrequiredrun: trained by a grad run; trainer: exported by a trainer (
trainer.export); upload: files uploaded withgrad artifacts upload; import: pulled from the Hugging Face Hub withgrad artifacts import."run""trainer""upload""import"run_idstringrequiredsource=run: the run that trained it.
trainer_idstringrequiredsource=trainer: the trainer that exported it.
uploaderstringrequiredsource=upload: the API key (principal) that uploaded it.
uristringrequiredsource=import:
hf://owner/name@<40-hex commit>, the pinned revision it was imported from.
eval_reportEvalReportrequiredcreated_atstring (date-time)requiredWhen it was released.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
artifact = client.artifacts.get("support-sft@2026-11-28-1")
print(artifact.base_model, artifact.size_bytes){
"id": "support-sft@2026-12-02-1",
"workspace_id": "ws_e2e",
"name": "support-sft",
"version": "2026-12-02-1",
"run_id": "run_ed1c235f0c631d8f209e22a5",
"checkpoint_id": null,
"base_model": "qwen/qwen3-8b",
"recipe_kind": "sft",
"format": "reference",
"sha256": "144d0e25503494bfce90a8919a295505ac2759b0ae331e45ea16fade495c137c",
"size_bytes": 10263,
"manifest": {
"lr": 0.000125,
"kind": "final",
"seed": 42,
"files": {
"reference_model.json": "59abd7749fec876cab4e168ea5a73ba432cbd5b568a7c8070258ec7f945b454b"
},
"format": "reference",
"run_id": "run_ed1c235f0c631d8f209e22a5",
"schema": "grad.artifact/1",
"select": "last",
"status": "completed",
"attempt": 1,
"backend": "reference",
"dataset": "support-prod",
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"base_model": "qwen/qwen3-8b",
"created_by": {
"name": "grad-trainer",
"version": "0.2.0-alpha.15"
},
"deployable": false,
"provenance": {
"run_id": "run_ed1c235f0c631d8f209e22a5",
"source": "run"
},
"recipe_kind": "sft",
"total_steps": 1,
"rule_version": "auto@2",
"tokens_total": 21,
"base_artifact": null,
"selected_step": 1,
"format_version": 2,
"base_model_repo": null,
"dataset_version": 1,
"resolved_config": {
"lr": 0.000125,
"name": "support-sft",
"model": "qwen/qwen3-8b",
"split": {
"seed": 42,
"strategy": "by_session",
"eval_records": 0,
"eval_fraction": 0.1,
"train_records": 1
},
"epochs": 1,
"select": "best",
"warmup": 0.03,
"adapter": {
"kind": "lora",
"rank": 32,
"alpha": 32,
"merge_on_export": false,
"train_multimodal_projector": false
},
"dataset": "support-prod",
"schedule": "linear",
"thinking": "auto",
"train_on": "last",
"lr_source": "auto@2: calibrated for qwen/qwen3-8b at batch 128, sqrt batch scaling",
"optimizer": {
"kind": "adamw",
"betas": [
0.9,
0.95
],
"grad_clip": 1,
"weight_decay": 0
},
"reduction": "per_example",
"batch_size": 8,
"recipe_kind": "sft",
"rule_version": "auto@2",
"base_artifact": null,
"label_eval_id": null,
"recipe_params": {},
"dataset_version": 1,
"eval_every_steps": 1,
"preserve_thinking": false,
"template_revision": "qwen3@3",
"checkpoint_ttl_days": 30,
"checkpoint_every_steps": 1
},
"steps_completed": 1,
"eval_report_sha256": "782d3768b9a29b35b624e5fb6e013ad89598c2cd770421c0a5b7db8be230d56c",
"base_model_revision": null
},
"provenance": {
"source": "run",
"run_id": "run_ed1c235f0c631d8f209e22a5",
"trainer_id": null,
"uploader": null,
"uri": null
},
"eval_report": {
"warnings": [
"Reference test backend: the base model was not trained; the artifact is not deployable.",
"No held-out examples: eval metrics are null and select='last' was used."
],
"best_step": null,
"eval_loss": null,
"final_step": 1,
"metric_mode": "min",
"metric_name": "eval_loss",
"eval_records": 0,
"eval_examples": 0,
"selected_step": 1,
"train_records": 1,
"train_examples": 1,
"reference_backend": true
},
"created_at": "2026-12-02T15:49:00.199Z"
}A short-lived presigned URL of an artifact bundle#
GET/v1/artifacts/{id}/download-url
Browsers download straight from storage.
Path parameters
idstringrequired
Returns
200 ArtifactDownloadUrl Presigned download.
5 fields
urlstring (uri)requiredA presigned GET of the bundle (.grad.tar.gz) straight from storage; no Authorization header. Verify its SHA-256.
expires_atstring (date-time)requiredsha256stringrequiredMatches
^[0-9a-f]{64}$size_bytesintegerrequiredfilenamestringrequired
from grad import Grad
client = Grad()
link = client.artifacts.download_url("support-sft@2026-11-28-1")
print(link["url"], link["expires_at"]){
"url": "https://storage.example.com/grad-test/artifacts/ws_e2e/144d0e25503494bfce90a8919a295505ac2759b0ae331e45ea16fade495c137c?X-Amz-Algorithm=…&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=…&X-Amz-Date=…&X-Amz-Expires=…&X-Amz-Signature=…&X-Amz-SignedHeaders=…&response-content-disposition=attachment%3B%20filename%3D%22support-sft-2026-12-02-1.grad.tar.gz%22%3B%20filename%2A%3DUTF-8%27%27support…",
"expires_at": "2026-12-02T16:04:01.192Z",
"sha256": "144d0e25503494bfce90a8919a295505ac2759b0ae331e45ea16fade495c137c",
"size_bytes": 10263,
"filename": "support-sft-2026-12-02-1.grad.tar.gz"
}Download an artifact bundle (.grad.tar.gz); verify X-Artifact-Sha256#
GET/v1/artifacts/{id}/download
Path parameters
idstringrequired
Returns
200 string (binary) Artifact bundle.
from grad import Grad
client = Grad()
path = client.artifacts.download("support-sft@2026-11-28-1", "./support-sft") # verified PEFT directoryapplication/octet-stream: Artifact bundle.
Register uploaded files or a Hugging Face repo as an artifact#
POST/v1/artifact-imports
Async import job.
An import worker validates the files against docs/ARTIFACT_FORMATS.md and the base model's config.json, bundles them as grad.artifact/1 and releases them as name@YYYY-MM-DD-n. A validation failure fails the import with error_code invalid_artifact and an error that names the file.
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body CreateArtifactImportRequest
sourceArtifactImportSourcerequiredOne of 2 shapes
- object
kind"upload"required"upload"upload_idstringrequiredA tar (optionally gzip) of the artifact's files, uploaded with POST /v1/uploads.
Matches
^[0-9a-f]{64}$
- object
kind"hf"required"hf"repostringrequiredMatches
^[A-Za-z0-9](?:[\w-]|\.(?!\.))*(\/[A-Za-z0-9](?:[\w-]|\.(?!\.))*)?$revisionstringBranch, tag or commit (default main). The import pins the commit it resolves.
Matches
^(?!.*\.\.)[A-Za-z0-9][A-Za-z0-9._/-]*$integrationstringA huggingface integration whose token reads gated or private repos. Default: the workspace's only huggingface integration; with none, public access.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$
- object
base_modelstringrequiredThe catalog base model (GET /v1/base-models) the files were trained on.
formatImportableArtifactFormat"peft_lora""merged_safetensors""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle"namestringThe artifact name (name@YYYY-MM-DD-n). Required for uploads; HF imports default to the repo's name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$
Returns
202 ArtifactImport Queued import.
13 fields
idstringrequiredworkspace_idstringrequiredstatusArtifactImportStatusrequired"queued""running""completed""failed"namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$base_modelstringrequiredformatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sourceobjectrequired5 child fields
kindenumrequired"upload""hf"upload_idstringrequiredrepostringrequiredrevisionstringrequiredHF imports: the requested revision, then the pinned commit once imported.
integrationstringrequiredHF imports: the huggingface integration used, if any.
artifact_idstringrequiredThe artifact (name@version) once the import completed.
errorstringrequiredWhy it failed. Validation failures name the file and the problem (
adapter_config.json: ...).error_codestringrequiredinvalid_artifact (the files don't match the format spec or the base model), source_unavailable, or null.
attemptintegerrequiredcreated_atstring (date-time)requiredupdated_atstring (date-time)required
from grad import Grad
client = Grad()
pending = client.artifacts.from_hf(
"hf://acme/support-lora", base="qwen/qwen3-8b", revision="main", name="support-lora"
)
artifact = pending.wait(){
"id": "imp_fbde7c15de104d8eb2e3abbf",
"workspace_id": "ws_e2e",
"status": "queued",
"name": "support-lora",
"base_model": "qwen/qwen3-8b",
"format": "peft_lora",
"source": {
"kind": "hf",
"upload_id": null,
"repo": "acme/support-lora",
"revision": "main",
"integration": null
},
"artifact_id": null,
"error": null,
"error_code": null,
"attempt": 0,
"created_at": "2026-12-02T15:48:59.921Z",
"updated_at": "2026-12-02T15:48:59.921Z"
}List artifact imports#
GET/v1/artifact-imports
Newest first.
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstringstatusstringOnly these statuses, comma-separated: queued, running, completed, failed.
Returns
200 object Artifact imports.
2 fields
dataarray of ArtifactImportrequired13 child fields
idstringrequiredworkspace_idstringrequiredstatusArtifactImportStatusrequired"queued""running""completed""failed"namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$base_modelstringrequiredformatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sourceobjectrequired5 child fields
kindenumrequired"upload""hf"upload_idstringrequiredrepostringrequiredrevisionstringrequiredHF imports: the requested revision, then the pinned commit once imported.
integrationstringrequiredHF imports: the huggingface integration used, if any.
artifact_idstringrequiredThe artifact (name@version) once the import completed.
errorstringrequiredWhy it failed. Validation failures name the file and the problem (
adapter_config.json: ...).error_codestringrequiredinvalid_artifact (the files don't match the format spec or the base model), source_unavailable, or null.
attemptintegerrequiredcreated_atstring (date-time)requiredupdated_atstring (date-time)required
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
for job in client.artifacts.list_imports():
print(job.id, job.status, job.artifact_id){
"data": [
{
"id": "imp_3f9c0a1b2c3d4e5f60718293",
"workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
"status": "queued",
"name": "support-prod",
"base_model": "qwen/qwen3-8b",
"format": "peft_lora",
"source": {
"kind": "upload",
"upload_id": "obj_3f9c0a1b2c3d4e5f60718293",
"repo": "string",
"revision": "string",
"integration": "string"
},
"artifact_id": "support-sft@2026-11-28-1",
"error": "…",
"error_code": "string",
"attempt": 0,
"created_at": "2026-11-28T09:30:00.000Z",
"updated_at": "2026-11-28T09:30:00.000Z"
}
],
"next_cursor": "string"
}Get an artifact import#
GET/v1/artifact-imports/{id}
Path parameters
idstringrequired
Returns
200 ArtifactImport Artifact import.
13 fields
idstringrequiredworkspace_idstringrequiredstatusArtifactImportStatusrequired"queued""running""completed""failed"namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$base_modelstringrequiredformatArtifactFormatrequired"peft_lora""merged_safetensors""prefix_kv""cartridge""encoder_safetensors""router_bundle""decision_bundle""reward_bundle""reference"sourceobjectrequired5 child fields
kindenumrequired"upload""hf"upload_idstringrequiredrepostringrequiredrevisionstringrequiredHF imports: the requested revision, then the pinned commit once imported.
integrationstringrequiredHF imports: the huggingface integration used, if any.
artifact_idstringrequiredThe artifact (name@version) once the import completed.
errorstringrequiredWhy it failed. Validation failures name the file and the problem (
adapter_config.json: ...).error_codestringrequiredinvalid_artifact (the files don't match the format spec or the base model), source_unavailable, or null.
attemptintegerrequiredcreated_atstring (date-time)requiredupdated_atstring (date-time)required
from grad import Grad
client = Grad()
job = client.artifacts.get_import("imp_3f9c0a1b2c3d4e5f60718293")
print(job.status, job.artifact_id){
"id": "imp_3f9c0a1b2c3d4e5f60718293",
"workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
"status": "queued",
"name": "support-prod",
"base_model": "qwen/qwen3-8b",
"format": "peft_lora",
"source": {
"kind": "upload",
"upload_id": "obj_3f9c0a1b2c3d4e5f60718293",
"repo": "string",
"revision": "string",
"integration": "string"
},
"artifact_id": "support-sft@2026-11-28-1",
"error": "…",
"error_code": "string",
"attempt": 0,
"created_at": "2026-11-28T09:30:00.000Z",
"updated_at": "2026-11-28T09:30:00.000Z"
}Evals#
Estimate tasks, model/judge calls, and cost before running an eval#
POST/v1/evals/plan
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body PlanEvalRequest
namestringMatches
^[a-z0-9][a-z0-9._-]{0,63}$modelsarray of stringrequiredThe models to evaluate: catalog ids, artifacts (
name@version), models your inference endpoint serves, or policy labels whenenvis set.baselinestringOne of
models; the summary reports every other model's difference from it. Mutually exclusive withbaseline_eval.baseline_evalEvalBaselineRef2 child fields
idstringrequiredCompleted eval id to pair per-task scores against.
modelstringrequiredModel label inside
idwhose scores form the baseline.
gateEvalGateInput2 child fields
max_dropnumberruleEvalGateRulesignificantfails when the paired 95% CI upper bound is below-max_drop(requires at least 30 paired tasks);deltafails when the point estimate is below-max_drop(works on any non-empty paired set)."significant""delta"
envEvalEnvConfig3 child fields
namestringrequiredDisplay name of the client environment (
module:attr).max_turnsintegerrequiredMaximum agent turns per rollout.
fingerprintstringClient-computed hash of tool schemas and optional environment version, checked when pairing against a baseline_eval.
datasetstringrequiredThe dataset whose records are the tasks.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerThe version to evaluate. Default: the current one, pinned when the eval is created.
rubricarray of EvalRubricItemDefault: the dataset's own rubric (a benchmark's answer check), else a non_empty validator.
9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
samplesintegerAnswers per task and model; 3 or more for decisions you will act on.
temperaturenumberSampling temperature of the model calls.
max_tokensintegerThe most tokens each answer may have.
limitintegerEvaluate only the first
limittasks.pass_thresholdnumberDefaults to 1.0 when every rubric item is binary (regex/validator) and 0.5 otherwise.
Returns
200 PlanEvalResponse Estimated eval plan.
10 fields
task_source_kind"dataset"required"dataset"dataset_versionintegerrequiredestimated_tasksintegerrequiredestimated_model_callsintegerrequiredestimated_judge_callsintegerrequiredestimated_cost_usdnumberrequiredjudge_modelsarray of stringrequiredlocal_scorersarray of stringrequiredpass_thresholdnumberrequiredwarningsarray of stringrequired
from grad import Grad, Judge
client = Grad()
helpful = Judge(
name="helpful",
model="qwen/qwen3-32b",
prompt="Score 1 if the answer resolves the request, else 0.",
)
plan = client.evals.plan(
name="sft-vs-base",
models=["support-sft@latest", "qwen/qwen3-8b"],
baseline="qwen/qwen3-8b",
dataset="support-prod",
rubric=[helpful],
limit=200,
)
print(plan.estimated_cost_usd){
"task_source_kind": "dataset",
"dataset_version": 1,
"estimated_tasks": 0,
"estimated_model_calls": 0,
"estimated_judge_calls": 0,
"estimated_cost_usd": 0,
"judge_models": [
"string"
],
"local_scorers": [
"string"
],
"pass_threshold": 0,
"warnings": [
"string"
]
}Queue an evaluation across models on a pinned dataset version#
POST/v1/evals
Executed by the server.
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body PlanEvalRequest
namestringMatches
^[a-z0-9][a-z0-9._-]{0,63}$modelsarray of stringrequiredThe models to evaluate: catalog ids, artifacts (
name@version), models your inference endpoint serves, or policy labels whenenvis set.baselinestringOne of
models; the summary reports every other model's difference from it. Mutually exclusive withbaseline_eval.baseline_evalEvalBaselineRef2 child fields
idstringrequiredCompleted eval id to pair per-task scores against.
modelstringrequiredModel label inside
idwhose scores form the baseline.
gateEvalGateInput2 child fields
max_dropnumberruleEvalGateRulesignificantfails when the paired 95% CI upper bound is below-max_drop(requires at least 30 paired tasks);deltafails when the point estimate is below-max_drop(works on any non-empty paired set)."significant""delta"
envEvalEnvConfig3 child fields
namestringrequiredDisplay name of the client environment (
module:attr).max_turnsintegerrequiredMaximum agent turns per rollout.
fingerprintstringClient-computed hash of tool schemas and optional environment version, checked when pairing against a baseline_eval.
datasetstringrequiredThe dataset whose records are the tasks.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$dataset_versionintegerThe version to evaluate. Default: the current one, pinned when the eval is created.
rubricarray of EvalRubricItemDefault: the dataset's own rubric (a benchmark's answer check), else a non_empty validator.
9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
samplesintegerAnswers per task and model; 3 or more for decisions you will act on.
temperaturenumberSampling temperature of the model calls.
max_tokensintegerThe most tokens each answer may have.
limitintegerEvaluate only the first
limittasks.pass_thresholdnumberDefaults to 1.0 when every rubric item is binary (regex/validator) and 0.5 otherwise.
Returns
202 EvalRun Queued evaluation run.
29 fields
idstringrequiredEval id (
eval_and 24 hex characters).workspace_idstringrequirednamestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$statusEvalStatusrequired"queued""running""awaiting_outputs""awaiting_scores""completed""failed""cancelled"modeEvalModerequiredevalgenerates outputs frommodels;score(dataset.score()) grades each record's own output (modelrecord) and writes the scores to the dataset's next version;envis a client-driven agent evaluation whose rollouts post outputs via/outputsand/complete."eval""score""env"modelsarray of stringrequiredThe models evaluated: catalog ids, artifacts (
name@version), models the inference endpoint serves, or policy labels inenvmode.baselinestringrequiredThe model the summary compares the others with (
vs_baseline); null for none.baseline_evalEvalBaselineRefrequiredenvEvalEnvConfigrequiredgateEvalGateResultrequiredtask_sourceobjectrequired3 child fields
kind"dataset"required"dataset"datasetstringrequiredversionintegerrequired
rubricarray of EvalRubricItemrequired9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
samplesintegerrequiredAnswers generated per task and model.
temperaturenumberrequiredSampling temperature of the model calls.
max_tokensintegerrequiredThe most tokens each answer may have.
pass_thresholdnumberrequiredScore at or above which a task passes.
judge_modelsarray of stringrequiredThe judge models the rubric calls.
local_scorersarray of stringrequiredCode scorers that run in the SDK process; the eval waits in
awaiting_scoresuntil they post their scores.progressobjectrequired3 child fields
total_outputsintegerrequiredgeneratedintegerrequiredpending_local_scoresintegerrequired
summaryarray of EvalModelSummaryrequired12 child fields
modelstringrequiredThe model this summary is for.
overallnumberrequiredMean task score (each task's score averages its samples).
ci_lownumberrequiredLower bound of the bootstrap 95% confidence interval on
overall.ci_highnumberrequiredUpper bound of the bootstrap 95% confidence interval on
overall.pass_at_kmap of numberrequiredUnbiased pass@k per k (
pass@1, ...): the chance that one of k samples scores at leastpass_threshold.vs_baselineobjectrequiredThe mean paired difference from the baseline over the tasks both answered, with a bootstrap 95% interval; null for the baseline itself or without one.
3 child fields
deltanumberrequiredci_lownumberrequiredci_highnumberrequired
tasksintegerrequiredTasks this model answered.
errorsintegerrequiredModel or judge calls that failed.
tokens_per_tasknumberrequiredMean tokens per task.
cost_per_1k_tasks_usdnumberrequiredCost per 1,000 tasks in USD; null when the model has no price.
by_scorermap of numberMean score per rubric scorer over outputs carrying that scorer.
mean_turnsnumberMean agent turns per rollout (present when outputs include trajectories with turns).
total_cost_usdnumberrequiredCost of the model and judge calls so far, in USD.
scored_dataset_versionintegerrequiredScoring jobs: the dataset version holding the new scores (the source version when every record was already scored); null until completed.
errorstringrequiredWhy the eval failed; null otherwise.
waiting_reasonenumrequiredWhile running: the eval's model calls are waiting for capacity (a serving pool at zero that has not woken yet), for a rate limit (a full eval lane), or for an inference endpoint that is down. The worker keeps its lease and retries; this is not counted as a failed attempt. null otherwise.
"capacity_unavailable""rate_limited""inference_unavailable"nulllast_output_atstring (date-time)requiredWhen the last client output was received in
envmode; null otherwise.created_atstring (date-time)requiredupdated_atstring (date-time)requiredcompleted_atstring (date-time)requiredWhen the eval reached a final status; null until then.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad, Judge
client = Grad()
helpful = Judge(
name="helpful",
model="qwen/qwen3-32b",
prompt="Score 1 if the answer resolves the request, else 0.",
)
ev = client.evals.create(
name="sft-vs-base",
models=["support-sft@latest", "qwen/qwen3-8b"],
baseline="qwen/qwen3-8b",
dataset="support-prod",
rubric=[helpful],
limit=200,
)
ev.wait()
print(ev.summary_table()){
"id": "eval_3f9c0a1b2c3d4e5f60718293",
"workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
"name": "support-prod",
"status": "queued",
"mode": "eval",
"models": [
"string"
],
"baseline": "string",
"baseline_eval": {
"id": "obj_3f9c0a1b2c3d4e5f60718293",
"model": "qwen/qwen3-8b"
},
"env": {
"name": "support-prod",
"max_turns": 1,
"fingerprint": "string"
},
"gate": {
"max_drop": 0,
"rule": "significant",
"passed": false,
"regressed": [
"string"
],
"paired_tasks": 0,
"min_detectable_drop": 0
},
"task_source": {
"kind": "dataset",
"dataset": "support-prod",
"version": 1
},
"rubric": [
{
"name": "support-prod",
"kind": "regex",
"weight": 1,
"pattern": "string",
"flags": "string",
"validator": "json",
"model": "qwen/qwen3-8b",
"prompt": "string",
"runtime": "local"
}
],
"samples": 1,
"temperature": 0,
"max_tokens": 1,
"pass_threshold": 0,
"judge_models": [
"string"
],
"local_scorers": [
"string"
],
"progress": {
"total_outputs": 0,
"generated": 0,
"pending_local_scores": 0
},
"summary": [
{
"model": "qwen/qwen3-8b",
"overall": 0,
"ci_low": 0,
"ci_high": 0,
"pass_at_k": {},
"vs_baseline": {
"delta": 0,
"ci_low": 0,
"ci_high": 0
},
"tasks": 0,
"errors": 0,
"tokens_per_task": 0,
"cost_per_1k_tasks_usd": 0,
"by_scorer": {},
"mean_turns": 0
}
],
"total_cost_usd": 0,
"scored_dataset_version": 1,
"error": "…",
"waiting_reason": "capacity_unavailable",
"last_output_at": "2026-11-28T09:30:00.000Z",
"created_at": "2026-11-28T09:30:00.000Z",
"updated_at": "2026-11-28T09:30:00.000Z",
"completed_at": "2026-11-28T09:30:00.000Z",
"console_url": "string"
}List evaluation runs#
GET/v1/evals
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstringstatusstringOnly these statuses, comma-separated: queued, running, awaiting_outputs, awaiting_scores, completed, failed, cancelled.
qstringOnly items whose name contains this text (any case), or whose id is exactly this.
Returns
200 object Evaluation runs.
2 fields
dataarray of EvalRunrequired29 child fields
idstringrequiredEval id (
eval_and 24 hex characters).workspace_idstringrequirednamestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$statusEvalStatusrequired"queued""running""awaiting_outputs""awaiting_scores""completed""failed""cancelled"modeEvalModerequiredevalgenerates outputs frommodels;score(dataset.score()) grades each record's own output (modelrecord) and writes the scores to the dataset's next version;envis a client-driven agent evaluation whose rollouts post outputs via/outputsand/complete."eval""score""env"modelsarray of stringrequiredThe models evaluated: catalog ids, artifacts (
name@version), models the inference endpoint serves, or policy labels inenvmode.baselinestringrequiredThe model the summary compares the others with (
vs_baseline); null for none.baseline_evalEvalBaselineRefrequiredenvEvalEnvConfigrequiredgateEvalGateResultrequiredtask_sourceobjectrequired3 child fields
kind"dataset"required"dataset"datasetstringrequiredversionintegerrequired
rubricarray of EvalRubricItemrequired9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
samplesintegerrequiredAnswers generated per task and model.
temperaturenumberrequiredSampling temperature of the model calls.
max_tokensintegerrequiredThe most tokens each answer may have.
pass_thresholdnumberrequiredScore at or above which a task passes.
judge_modelsarray of stringrequiredThe judge models the rubric calls.
local_scorersarray of stringrequiredCode scorers that run in the SDK process; the eval waits in
awaiting_scoresuntil they post their scores.progressobjectrequired3 child fields
total_outputsintegerrequiredgeneratedintegerrequiredpending_local_scoresintegerrequired
summaryarray of EvalModelSummaryrequired12 child fields
modelstringrequiredThe model this summary is for.
overallnumberrequiredMean task score (each task's score averages its samples).
ci_lownumberrequiredLower bound of the bootstrap 95% confidence interval on
overall.ci_highnumberrequiredUpper bound of the bootstrap 95% confidence interval on
overall.pass_at_kmap of numberrequiredUnbiased pass@k per k (
pass@1, ...): the chance that one of k samples scores at leastpass_threshold.vs_baselineobjectrequiredThe mean paired difference from the baseline over the tasks both answered, with a bootstrap 95% interval; null for the baseline itself or without one.
3 child fields
deltanumberrequiredci_lownumberrequiredci_highnumberrequired
tasksintegerrequiredTasks this model answered.
errorsintegerrequiredModel or judge calls that failed.
tokens_per_tasknumberrequiredMean tokens per task.
cost_per_1k_tasks_usdnumberrequiredCost per 1,000 tasks in USD; null when the model has no price.
by_scorermap of numberMean score per rubric scorer over outputs carrying that scorer.
mean_turnsnumberMean agent turns per rollout (present when outputs include trajectories with turns).
total_cost_usdnumberrequiredCost of the model and judge calls so far, in USD.
scored_dataset_versionintegerrequiredScoring jobs: the dataset version holding the new scores (the source version when every record was already scored); null until completed.
errorstringrequiredWhy the eval failed; null otherwise.
waiting_reasonenumrequiredWhile running: the eval's model calls are waiting for capacity (a serving pool at zero that has not woken yet), for a rate limit (a full eval lane), or for an inference endpoint that is down. The worker keeps its lease and retries; this is not counted as a failed attempt. null otherwise.
"capacity_unavailable""rate_limited""inference_unavailable"nulllast_output_atstring (date-time)requiredWhen the last client output was received in
envmode; null otherwise.created_atstring (date-time)requiredupdated_atstring (date-time)requiredcompleted_atstring (date-time)requiredWhen the eval reached a final status; null until then.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
for ev in client.evals.list(status="running", search="sft-vs-base"):
print(ev.id, ev.name, ev.status){
"data": [
{
"id": "eval_c13bd1724f656bf328ba0115",
"workspace_id": "ws_e2e",
"name": "support-prod-score",
"status": "completed",
"mode": "score",
"models": [
"record"
],
"baseline": null,
"baseline_eval": null,
"env": null,
"gate": null,
"task_source": {
"kind": "dataset",
"dataset": "support-prod",
"version": 1
},
"rubric": [
{
"kind": "regex",
"name": "polite",
"flags": "i",
"weight": 1,
"pattern": "thank"
}
],
"samples": 1,
"temperature": 0,
"max_tokens": 1,
"pass_threshold": 1,
"judge_models": [],
"local_scorers": [],
"progress": {
"total_outputs": 1,
"generated": 1,
"pending_local_scores": 0
},
"summary": [
{
"model": "record",
"tasks": 1,
"ci_low": 0,
"errors": 0,
"ci_high": 0,
"overall": 0,
"by_scorer": {
"polite": 0
},
"pass_at_k": {
"pass@1": 0
},
"vs_baseline": null,
"tokens_per_task": 0,
"cost_per_1k_tasks_usd": 0
}
],
"total_cost_usd": 0,
"scored_dataset_version": 2,
"error": null,
"waiting_reason": null,
"last_output_at": null,
"created_at": "2026-12-02T15:48:59.828Z",
"updated_at": "2026-12-02T15:49:00.347Z",
"completed_at": "2026-12-02T15:49:00.346Z"
}
],
"next_cursor": null
}Get an evaluation run by ID#
GET/v1/evals/{id}
Path parameters
idstringrequired
Returns
200 EvalRun Evaluation run.
29 fields
idstringrequiredEval id (
eval_and 24 hex characters).workspace_idstringrequirednamestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$statusEvalStatusrequired"queued""running""awaiting_outputs""awaiting_scores""completed""failed""cancelled"modeEvalModerequiredevalgenerates outputs frommodels;score(dataset.score()) grades each record's own output (modelrecord) and writes the scores to the dataset's next version;envis a client-driven agent evaluation whose rollouts post outputs via/outputsand/complete."eval""score""env"modelsarray of stringrequiredThe models evaluated: catalog ids, artifacts (
name@version), models the inference endpoint serves, or policy labels inenvmode.baselinestringrequiredThe model the summary compares the others with (
vs_baseline); null for none.baseline_evalEvalBaselineRefrequiredenvEvalEnvConfigrequiredgateEvalGateResultrequiredtask_sourceobjectrequired3 child fields
kind"dataset"required"dataset"datasetstringrequiredversionintegerrequired
rubricarray of EvalRubricItemrequired9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
samplesintegerrequiredAnswers generated per task and model.
temperaturenumberrequiredSampling temperature of the model calls.
max_tokensintegerrequiredThe most tokens each answer may have.
pass_thresholdnumberrequiredScore at or above which a task passes.
judge_modelsarray of stringrequiredThe judge models the rubric calls.
local_scorersarray of stringrequiredCode scorers that run in the SDK process; the eval waits in
awaiting_scoresuntil they post their scores.progressobjectrequired3 child fields
total_outputsintegerrequiredgeneratedintegerrequiredpending_local_scoresintegerrequired
summaryarray of EvalModelSummaryrequired12 child fields
modelstringrequiredThe model this summary is for.
overallnumberrequiredMean task score (each task's score averages its samples).
ci_lownumberrequiredLower bound of the bootstrap 95% confidence interval on
overall.ci_highnumberrequiredUpper bound of the bootstrap 95% confidence interval on
overall.pass_at_kmap of numberrequiredUnbiased pass@k per k (
pass@1, ...): the chance that one of k samples scores at leastpass_threshold.vs_baselineobjectrequiredThe mean paired difference from the baseline over the tasks both answered, with a bootstrap 95% interval; null for the baseline itself or without one.
3 child fields
deltanumberrequiredci_lownumberrequiredci_highnumberrequired
tasksintegerrequiredTasks this model answered.
errorsintegerrequiredModel or judge calls that failed.
tokens_per_tasknumberrequiredMean tokens per task.
cost_per_1k_tasks_usdnumberrequiredCost per 1,000 tasks in USD; null when the model has no price.
by_scorermap of numberMean score per rubric scorer over outputs carrying that scorer.
mean_turnsnumberMean agent turns per rollout (present when outputs include trajectories with turns).
total_cost_usdnumberrequiredCost of the model and judge calls so far, in USD.
scored_dataset_versionintegerrequiredScoring jobs: the dataset version holding the new scores (the source version when every record was already scored); null until completed.
errorstringrequiredWhy the eval failed; null otherwise.
waiting_reasonenumrequiredWhile running: the eval's model calls are waiting for capacity (a serving pool at zero that has not woken yet), for a rate limit (a full eval lane), or for an inference endpoint that is down. The worker keeps its lease and retries; this is not counted as a failed attempt. null otherwise.
"capacity_unavailable""rate_limited""inference_unavailable"nulllast_output_atstring (date-time)requiredWhen the last client output was received in
envmode; null otherwise.created_atstring (date-time)requiredupdated_atstring (date-time)requiredcompleted_atstring (date-time)requiredWhen the eval reached a final status; null until then.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
ev = client.evals.get("eval_3f9c0a1b2c3d4e5f60718293")
print(ev.summary_table()){
"id": "eval_3f9c0a1b2c3d4e5f60718293",
"workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
"name": "support-prod",
"status": "queued",
"mode": "eval",
"models": [
"string"
],
"baseline": "string",
"baseline_eval": {
"id": "obj_3f9c0a1b2c3d4e5f60718293",
"model": "qwen/qwen3-8b"
},
"env": {
"name": "support-prod",
"max_turns": 1,
"fingerprint": "string"
},
"gate": {
"max_drop": 0,
"rule": "significant",
"passed": false,
"regressed": [
"string"
],
"paired_tasks": 0,
"min_detectable_drop": 0
},
"task_source": {
"kind": "dataset",
"dataset": "support-prod",
"version": 1
},
"rubric": [
{
"name": "support-prod",
"kind": "regex",
"weight": 1,
"pattern": "string",
"flags": "string",
"validator": "json",
"model": "qwen/qwen3-8b",
"prompt": "string",
"runtime": "local"
}
],
"samples": 1,
"temperature": 0,
"max_tokens": 1,
"pass_threshold": 0,
"judge_models": [
"string"
],
"local_scorers": [
"string"
],
"progress": {
"total_outputs": 0,
"generated": 0,
"pending_local_scores": 0
},
"summary": [
{
"model": "qwen/qwen3-8b",
"overall": 0,
"ci_low": 0,
"ci_high": 0,
"pass_at_k": {},
"vs_baseline": {
"delta": 0,
"ci_low": 0,
"ci_high": 0
},
"tasks": 0,
"errors": 0,
"tokens_per_task": 0,
"cost_per_1k_tasks_usd": 0,
"by_scorer": {},
"mean_turns": 0
}
],
"total_cost_usd": 0,
"scored_dataset_version": 1,
"error": "…",
"waiting_reason": "capacity_unavailable",
"last_output_at": "2026-11-28T09:30:00.000Z",
"created_at": "2026-11-28T09:30:00.000Z",
"updated_at": "2026-11-28T09:30:00.000Z",
"completed_at": "2026-11-28T09:30:00.000Z",
"console_url": "string"
}Page through generated model outputs#
GET/v1/evals/{id}/outputs
Filter by model or by a code scorer that still needs a score.
Path parameters
idstringrequired
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstringmodelstringmissing_scorerstringfields"key""key"
Returns
200 object Eval outputs.
2 fields
dataarray of EvalOutputrequired16 child fields
idstringrequiredeval_idstringrequiredtask_indexintegerrequiredtask_idstringrequiredmodelstringrequiredsample_indexintegerrequiredinputarray of ChatMessagerequired7 child fields
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
outputstringrequiredexpected_outputanyrecordDatasetRecordrequired24 child fields
schema"grad.trajectory/1""grad.trajectory/1"idstringsession_idstringgroup_idstringroleenum"chosen""rejected""anchor""positive""negative""desirable""undesirable""rollout"nullsourcestringtimestampstringmessagesarray of ChatMessage7 child fields
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
toolsarray of map of anyinputTrajectoryInput5 child fields
messagesarray of ChatMessage7 child fields
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
toolsarray of map of anymediaarray of map of anyfeaturesmap of anypayloadany
outputTrajectoryOutputpromptstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
completionstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
chosenstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
rejectedstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
querystringpositivestringnegativesarray of stringstateanyquestionsmap of anyexpected_outputanyscoresmap of numbermetricsmap of numbermetadatamap of any
scorenumberCombined rubric score for this output (null until scored/finalized).
scoresmap of numberrequirederrorstringrequiredusageobjectrequired2 child fields
prompt_tokensintegerrequiredcompletion_tokensintegerrequired
trajectoryEvalTrajectorytrajectory_urlstring
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
for output in client.evals.outputs("eval_3f9c0a1b2c3d4e5f60718293", missing_scorer="sql_runs"):
print(output.id, output.model, output.output){
"data": [
{
"id": "evout_3f9c0a1b2c3d4e5f60718293",
"eval_id": "obj_3f9c0a1b2c3d4e5f60718293",
"task_index": 0,
"task_id": "obj_3f9c0a1b2c3d4e5f60718293",
"model": "qwen/qwen3-8b",
"sample_index": 0,
"input": [
{
"role": "system",
"content": "Count active users from yesterday.",
"reasoning_content": "string",
"tool_calls": [],
"tool_call_id": "obj_3f9c0a1b2c3d4e5f60718293",
"name": "support-prod",
"train": false
}
],
"output": "string",
"expected_output": null,
"record": {
"schema": "grad.trajectory/1",
"id": "obj_3f9c0a1b2c3d4e5f60718293",
"session_id": "obj_3f9c0a1b2c3d4e5f60718293",
"group_id": "obj_3f9c0a1b2c3d4e5f60718293",
"role": "chosen",
"source": "string",
"timestamp": "string",
"messages": [
{}
],
"tools": [
{}
],
"input": {
"messages": [],
"tools": [],
"media": [],
"features": {},
"payload": null
},
"output": {
"turns": [],
"payload": null
},
"prompt": "string",
"completion": "string",
"chosen": "string",
"rejected": "string",
"query": "string",
"positive": "string",
"negatives": [
"string"
],
"state": null,
"questions": {},
"expected_output": null,
"scores": {},
"metrics": {},
"metadata": {}
},
"score": 0,
"scores": {},
"error": "…",
"usage": {
"prompt_tokens": 0,
"completion_tokens": 0
},
"trajectory": {
"messages": [
{}
],
"turns": 0,
"finish_reason": "string",
"policy": {},
"error": "…"
},
"trajectory_url": "string"
}
],
"next_cursor": "string"
}Post client-side rollout outputs and trajectories for an env-mode eval#
POST/v1/evals/{id}/outputs
Idempotent per cell.
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body PostEvalOutputsRequest
outputsarray of ClientEvalOutputInputrequired12 child fields
modelstringrequiredtask_indexintegerrequiredtask_idstringrequiredsample_indexintegerrequiredrecordmap of anyrequiredinputarray of map of anyrequiredoutputstringrequiredexpected_outputanyscoresmap of numbererrorstringtrajectoryEvalTrajectoryusageobject3 child fields
prompt_tokensintegercompletion_tokensintegercost_usdnumber
Returns
200 PostEvalOutputsResponse Accepted outputs.
2 fields
acceptedintegerrequiredgeneratedintegerrequired
from grad import Grad
client = Grad()
res = client.wire.post_eval_outputs(
"eval_3f9c0a1b2c3d4e5f60718293",
{
"outputs": [
{
"model": "qwen/qwen3-8b",
"task_index": 0,
"task_id": "task-1",
"sample_index": 0,
"record": {"messages": [{"role": "user", "content": "What is 12 * 7?"}]},
"input": [{"role": "user", "content": "What is 12 * 7?"}],
"output": "84",
"scores": {"correct": 1},
}
]
},
)
print(res["accepted"]){
"accepted": 0,
"generated": 0
}Finalize an env-mode eval once all expected outputs are posted#
POST/v1/evals/{id}/complete
Or queue it for judge scoring.
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Returns
200 EvalRun Completed or queued evaluation run.
29 fields
idstringrequiredEval id (
eval_and 24 hex characters).workspace_idstringrequirednamestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$statusEvalStatusrequired"queued""running""awaiting_outputs""awaiting_scores""completed""failed""cancelled"modeEvalModerequiredevalgenerates outputs frommodels;score(dataset.score()) grades each record's own output (modelrecord) and writes the scores to the dataset's next version;envis a client-driven agent evaluation whose rollouts post outputs via/outputsand/complete."eval""score""env"modelsarray of stringrequiredThe models evaluated: catalog ids, artifacts (
name@version), models the inference endpoint serves, or policy labels inenvmode.baselinestringrequiredThe model the summary compares the others with (
vs_baseline); null for none.baseline_evalEvalBaselineRefrequiredenvEvalEnvConfigrequiredgateEvalGateResultrequiredtask_sourceobjectrequired3 child fields
kind"dataset"required"dataset"datasetstringrequiredversionintegerrequired
rubricarray of EvalRubricItemrequired9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
samplesintegerrequiredAnswers generated per task and model.
temperaturenumberrequiredSampling temperature of the model calls.
max_tokensintegerrequiredThe most tokens each answer may have.
pass_thresholdnumberrequiredScore at or above which a task passes.
judge_modelsarray of stringrequiredThe judge models the rubric calls.
local_scorersarray of stringrequiredCode scorers that run in the SDK process; the eval waits in
awaiting_scoresuntil they post their scores.progressobjectrequired3 child fields
total_outputsintegerrequiredgeneratedintegerrequiredpending_local_scoresintegerrequired
summaryarray of EvalModelSummaryrequired12 child fields
modelstringrequiredThe model this summary is for.
overallnumberrequiredMean task score (each task's score averages its samples).
ci_lownumberrequiredLower bound of the bootstrap 95% confidence interval on
overall.ci_highnumberrequiredUpper bound of the bootstrap 95% confidence interval on
overall.pass_at_kmap of numberrequiredUnbiased pass@k per k (
pass@1, ...): the chance that one of k samples scores at leastpass_threshold.vs_baselineobjectrequiredThe mean paired difference from the baseline over the tasks both answered, with a bootstrap 95% interval; null for the baseline itself or without one.
3 child fields
deltanumberrequiredci_lownumberrequiredci_highnumberrequired
tasksintegerrequiredTasks this model answered.
errorsintegerrequiredModel or judge calls that failed.
tokens_per_tasknumberrequiredMean tokens per task.
cost_per_1k_tasks_usdnumberrequiredCost per 1,000 tasks in USD; null when the model has no price.
by_scorermap of numberMean score per rubric scorer over outputs carrying that scorer.
mean_turnsnumberMean agent turns per rollout (present when outputs include trajectories with turns).
total_cost_usdnumberrequiredCost of the model and judge calls so far, in USD.
scored_dataset_versionintegerrequiredScoring jobs: the dataset version holding the new scores (the source version when every record was already scored); null until completed.
errorstringrequiredWhy the eval failed; null otherwise.
waiting_reasonenumrequiredWhile running: the eval's model calls are waiting for capacity (a serving pool at zero that has not woken yet), for a rate limit (a full eval lane), or for an inference endpoint that is down. The worker keeps its lease and retries; this is not counted as a failed attempt. null otherwise.
"capacity_unavailable""rate_limited""inference_unavailable"nulllast_output_atstring (date-time)requiredWhen the last client output was received in
envmode; null otherwise.created_atstring (date-time)requiredupdated_atstring (date-time)requiredcompleted_atstring (date-time)requiredWhen the eval reached a final status; null until then.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
ev = client.wire.complete_eval("eval_3f9c0a1b2c3d4e5f60718293", {})
print(ev["status"]){
"id": "eval_3f9c0a1b2c3d4e5f60718293",
"workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
"name": "support-prod",
"status": "queued",
"mode": "eval",
"models": [
"string"
],
"baseline": "string",
"baseline_eval": {
"id": "obj_3f9c0a1b2c3d4e5f60718293",
"model": "qwen/qwen3-8b"
},
"env": {
"name": "support-prod",
"max_turns": 1,
"fingerprint": "string"
},
"gate": {
"max_drop": 0,
"rule": "significant",
"passed": false,
"regressed": [
"string"
],
"paired_tasks": 0,
"min_detectable_drop": 0
},
"task_source": {
"kind": "dataset",
"dataset": "support-prod",
"version": 1
},
"rubric": [
{
"name": "support-prod",
"kind": "regex",
"weight": 1,
"pattern": "string",
"flags": "string",
"validator": "json",
"model": "qwen/qwen3-8b",
"prompt": "string",
"runtime": "local"
}
],
"samples": 1,
"temperature": 0,
"max_tokens": 1,
"pass_threshold": 0,
"judge_models": [
"string"
],
"local_scorers": [
"string"
],
"progress": {
"total_outputs": 0,
"generated": 0,
"pending_local_scores": 0
},
"summary": [
{
"model": "qwen/qwen3-8b",
"overall": 0,
"ci_low": 0,
"ci_high": 0,
"pass_at_k": {},
"vs_baseline": {
"delta": 0,
"ci_low": 0,
"ci_high": 0
},
"tasks": 0,
"errors": 0,
"tokens_per_task": 0,
"cost_per_1k_tasks_usd": 0,
"by_scorer": {},
"mean_turns": 0
}
],
"total_cost_usd": 0,
"scored_dataset_version": 1,
"error": "…",
"waiting_reason": "capacity_unavailable",
"last_output_at": "2026-11-28T09:30:00.000Z",
"created_at": "2026-11-28T09:30:00.000Z",
"updated_at": "2026-11-28T09:30:00.000Z",
"completed_at": "2026-11-28T09:30:00.000Z",
"console_url": "string"
}Post scores computed by local (SDK-side) code scorers; the eval completes when none are missing#
POST/v1/evals/{id}/scores
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body PostEvalScoresRequest
scoresarray of objectrequired3 child fields
output_idstringrequiredscorerstringrequiredscorenumberrequired
Returns
200 PostEvalScoresResponse Accepted scores.
3 fields
acceptedintegerrequiredstatusEvalStatusrequired"queued""running""awaiting_outputs""awaiting_scores""completed""failed""cancelled"pending_local_scoresintegerrequired
from grad import Grad
client = Grad()
result = client.evals.post_scores(
"eval_3f9c0a1b2c3d4e5f60718293",
[{"output_id": "evout_3f9c0a1b2c3d4e5f60718293", "scorer": "sql_runs", "score": 1}],
)
print(result["accepted"]){
"accepted": 0,
"status": "queued",
"pending_local_scores": 0
}Per-task, per-model results of a completed evaluation#
GET/v1/evals/{id}/results
Path parameters
idstringrequired
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstringmodelstring
Returns
200 object Task outcomes.
2 fields
dataarray of EvalTaskOutcomerequired7 child fields
task_idstringrequiredmodelstringrequiredscorenumberrequiredpassedbooleanrequiredsample_scoresarray of numberrequiredjudge_modelstringrequiredrecordDatasetRecordrequired24 child fields
schema"grad.trajectory/1""grad.trajectory/1"idstringsession_idstringgroup_idstringroleenum"chosen""rejected""anchor""positive""negative""desirable""undesirable""rollout"nullsourcestringtimestampstringmessagesarray of ChatMessage7 child fields
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
toolsarray of map of anyinputTrajectoryInput5 child fields
messagesarray of ChatMessage7 child fields
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
toolsarray of map of anymediaarray of map of anyfeaturesmap of anypayloadany
outputTrajectoryOutputpromptstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
completionstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
chosenstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
rejectedstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
querystringpositivestringnegativesarray of stringstateanyquestionsmap of anyexpected_outputanyscoresmap of numbermetricsmap of numbermetadatamap of any
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
for result in client.evals.results("eval_3f9c0a1b2c3d4e5f60718293", model="support-sft@latest"):
print(result.task_id, result.score){
"data": [
{
"task_id": "obj_3f9c0a1b2c3d4e5f60718293",
"model": "qwen/qwen3-8b",
"score": 0,
"passed": false,
"sample_scores": [
0
],
"judge_model": "string",
"record": {
"schema": "grad.trajectory/1",
"id": "obj_3f9c0a1b2c3d4e5f60718293",
"session_id": "obj_3f9c0a1b2c3d4e5f60718293",
"group_id": "obj_3f9c0a1b2c3d4e5f60718293",
"role": "chosen",
"source": "string",
"timestamp": "string",
"messages": [
{}
],
"tools": [
{}
],
"input": {
"messages": [],
"tools": [],
"media": [],
"features": {},
"payload": null
},
"output": {
"turns": [],
"payload": null
},
"prompt": "string",
"completion": "string",
"chosen": "string",
"rejected": "string",
"query": "string",
"positive": "string",
"negatives": [
"string"
],
"state": null,
"questions": {},
"expected_output": null,
"scores": {},
"metrics": {},
"metadata": {}
}
}
],
"next_cursor": "string"
}List failing task records from an evaluation run for mining#
GET/v1/evals/{id}/failures
Path parameters
idstringrequired
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstringmodelstringthresholdnumber
Returns
200 object Failing task outcomes.
3 fields
eval_idstringrequireddataarray of EvalTaskOutcomerequired7 child fields
task_idstringrequiredmodelstringrequiredscorenumberrequiredpassedbooleanrequiredsample_scoresarray of numberrequiredjudge_modelstringrequiredrecordDatasetRecordrequired24 child fields
schema"grad.trajectory/1""grad.trajectory/1"idstringsession_idstringgroup_idstringroleenum"chosen""rejected""anchor""positive""negative""desirable""undesirable""rollout"nullsourcestringtimestampstringmessagesarray of ChatMessage7 child fields
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
toolsarray of map of anyinputTrajectoryInput5 child fields
messagesarray of ChatMessage7 child fields
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
toolsarray of map of anymediaarray of map of anyfeaturesmap of anypayloadany
outputTrajectoryOutputpromptstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
completionstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
chosenstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
rejectedstring or array of ChatMessageOne of 2 shapes
- string
- array of ChatMessage
roleenumrequired"system""user""assistant""tool"contentstring or array of map of anyOne of 2 shapes
- string
- array of map of any
reasoning_contentstringtool_callsarray of map of anytool_call_idstringnamestringtrainboolean
querystringpositivestringnegativesarray of stringstateanyquestionsmap of anyexpected_outputanyscoresmap of numbermetricsmap of numbermetadatamap of any
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
failures = client.evals.failures("eval_3f9c0a1b2c3d4e5f60718293", threshold=0.8)
hard = failures.to_dataset("support-hard") # mine them into a new dataset{
"eval_id": "obj_3f9c0a1b2c3d4e5f60718293",
"data": [
{
"task_id": "obj_3f9c0a1b2c3d4e5f60718293",
"model": "qwen/qwen3-8b",
"score": 0,
"passed": false,
"sample_scores": [
0
],
"judge_model": "string",
"record": {
"schema": "grad.trajectory/1",
"id": "obj_3f9c0a1b2c3d4e5f60718293",
"session_id": "obj_3f9c0a1b2c3d4e5f60718293",
"group_id": "obj_3f9c0a1b2c3d4e5f60718293",
"role": "chosen",
"source": "string",
"timestamp": "string",
"messages": [
{}
],
"tools": [
{}
],
"input": {
"messages": [],
"tools": [],
"media": [],
"features": {},
"payload": null
},
"output": {
"turns": [],
"payload": null
},
"prompt": "string",
"completion": "string",
"chosen": "string",
"rejected": "string",
"query": "string",
"positive": "string",
"negatives": [
"string"
],
"state": null,
"questions": {},
"expected_output": null,
"scores": {},
"metrics": {},
"metadata": {}
}
}
],
"next_cursor": "string"
}Cancel a queued, running, awaiting_outputs or awaiting_scores evaluation#
POST/v1/evals/{id}/cancel
An eval that is already cancelled is returned as it is, so a retried cancel is a no-op.
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Returns
200 EvalRun Cancelled evaluation run.
29 fields
idstringrequiredEval id (
eval_and 24 hex characters).workspace_idstringrequirednamestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$statusEvalStatusrequired"queued""running""awaiting_outputs""awaiting_scores""completed""failed""cancelled"modeEvalModerequiredevalgenerates outputs frommodels;score(dataset.score()) grades each record's own output (modelrecord) and writes the scores to the dataset's next version;envis a client-driven agent evaluation whose rollouts post outputs via/outputsand/complete."eval""score""env"modelsarray of stringrequiredThe models evaluated: catalog ids, artifacts (
name@version), models the inference endpoint serves, or policy labels inenvmode.baselinestringrequiredThe model the summary compares the others with (
vs_baseline); null for none.baseline_evalEvalBaselineRefrequiredenvEvalEnvConfigrequiredgateEvalGateResultrequiredtask_sourceobjectrequired3 child fields
kind"dataset"required"dataset"datasetstringrequiredversionintegerrequired
rubricarray of EvalRubricItemrequired9 child fields
namestringrequiredMatches
^[A-Za-z0-9_.:-]+$kindenumrequired"regex""validator""code""judge"weightnumberpatternstringflagsstringMatches
^[imsu]*$validatorenum"json""non_empty""exact_match""final_number""choice""math_equivalence""ifeval"modelstringpromptstringruntime"local"Code scorers always run in the SDK process (
local); the eval waits inawaiting_scoresuntil the SDK posts their scores."local"
samplesintegerrequiredAnswers generated per task and model.
temperaturenumberrequiredSampling temperature of the model calls.
max_tokensintegerrequiredThe most tokens each answer may have.
pass_thresholdnumberrequiredScore at or above which a task passes.
judge_modelsarray of stringrequiredThe judge models the rubric calls.
local_scorersarray of stringrequiredCode scorers that run in the SDK process; the eval waits in
awaiting_scoresuntil they post their scores.progressobjectrequired3 child fields
total_outputsintegerrequiredgeneratedintegerrequiredpending_local_scoresintegerrequired
summaryarray of EvalModelSummaryrequired12 child fields
modelstringrequiredThe model this summary is for.
overallnumberrequiredMean task score (each task's score averages its samples).
ci_lownumberrequiredLower bound of the bootstrap 95% confidence interval on
overall.ci_highnumberrequiredUpper bound of the bootstrap 95% confidence interval on
overall.pass_at_kmap of numberrequiredUnbiased pass@k per k (
pass@1, ...): the chance that one of k samples scores at leastpass_threshold.vs_baselineobjectrequiredThe mean paired difference from the baseline over the tasks both answered, with a bootstrap 95% interval; null for the baseline itself or without one.
3 child fields
deltanumberrequiredci_lownumberrequiredci_highnumberrequired
tasksintegerrequiredTasks this model answered.
errorsintegerrequiredModel or judge calls that failed.
tokens_per_tasknumberrequiredMean tokens per task.
cost_per_1k_tasks_usdnumberrequiredCost per 1,000 tasks in USD; null when the model has no price.
by_scorermap of numberMean score per rubric scorer over outputs carrying that scorer.
mean_turnsnumberMean agent turns per rollout (present when outputs include trajectories with turns).
total_cost_usdnumberrequiredCost of the model and judge calls so far, in USD.
scored_dataset_versionintegerrequiredScoring jobs: the dataset version holding the new scores (the source version when every record was already scored); null until completed.
errorstringrequiredWhy the eval failed; null otherwise.
waiting_reasonenumrequiredWhile running: the eval's model calls are waiting for capacity (a serving pool at zero that has not woken yet), for a rate limit (a full eval lane), or for an inference endpoint that is down. The worker keeps its lease and retries; this is not counted as a failed attempt. null otherwise.
"capacity_unavailable""rate_limited""inference_unavailable"nulllast_output_atstring (date-time)requiredWhen the last client output was received in
envmode; null otherwise.created_atstring (date-time)requiredupdated_atstring (date-time)requiredcompleted_atstring (date-time)requiredWhen the eval reached a final status; null until then.
console_urlstringWeb console deep-link when GRAD_CONSOLE_URL is configured; null otherwise.
from grad import Grad
client = Grad()
ev = client.evals.cancel("eval_3f9c0a1b2c3d4e5f60718293"){
"id": "eval_3f9c0a1b2c3d4e5f60718293",
"workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
"name": "support-prod",
"status": "queued",
"mode": "eval",
"models": [
"string"
],
"baseline": "string",
"baseline_eval": {
"id": "obj_3f9c0a1b2c3d4e5f60718293",
"model": "qwen/qwen3-8b"
},
"env": {
"name": "support-prod",
"max_turns": 1,
"fingerprint": "string"
},
"gate": {
"max_drop": 0,
"rule": "significant",
"passed": false,
"regressed": [
"string"
],
"paired_tasks": 0,
"min_detectable_drop": 0
},
"task_source": {
"kind": "dataset",
"dataset": "support-prod",
"version": 1
},
"rubric": [
{
"name": "support-prod",
"kind": "regex",
"weight": 1,
"pattern": "string",
"flags": "string",
"validator": "json",
"model": "qwen/qwen3-8b",
"prompt": "string",
"runtime": "local"
}
],
"samples": 1,
"temperature": 0,
"max_tokens": 1,
"pass_threshold": 0,
"judge_models": [
"string"
],
"local_scorers": [
"string"
],
"progress": {
"total_outputs": 0,
"generated": 0,
"pending_local_scores": 0
},
"summary": [
{
"model": "qwen/qwen3-8b",
"overall": 0,
"ci_low": 0,
"ci_high": 0,
"pass_at_k": {},
"vs_baseline": {
"delta": 0,
"ci_low": 0,
"ci_high": 0
},
"tasks": 0,
"errors": 0,
"tokens_per_task": 0,
"cost_per_1k_tasks_usd": 0,
"by_scorer": {},
"mean_turns": 0
}
],
"total_cost_usd": 0,
"scored_dataset_version": 1,
"error": "…",
"waiting_reason": "capacity_unavailable",
"last_output_at": "2026-11-28T09:30:00.000Z",
"created_at": "2026-11-28T09:30:00.000Z",
"updated_at": "2026-11-28T09:30:00.000Z",
"completed_at": "2026-11-28T09:30:00.000Z",
"console_url": "string"
}Integrations#
Connect a provider#
POST/v1/integrations
Credentials are write-only.
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body CreateIntegrationRequest
providerIntegrationProviderrequired"langfuse""langsmith""braintrust""posthog""phoenix""huggingface""wandb""mlflow"namestringUnique per workspace; how sources, imports and loggers refer to it. Default: the provider (
langfuse), thenlangfuse-2,langfuse-3, ...Matches
^[a-z0-9][a-z0-9._-]{0,63}$hoststringThe provider's base URL (https). Defaults to its public host: https://cloud.langfuse.com, https://api.smith.langchain.com, https://api.braintrust.dev, https://us.posthog.com, https://huggingface.co, https://api.wandb.ai. Required for phoenix (your Phoenix Cloud space URL or self-hosted Phoenix) and mlflow (the tracking URI). Credentials are only ever sent to this host.
credentialsIntegrationCredentialsWrite-only: stored encrypted and never returned. Each provider takes its own fields: langfuse
public_key+secret_key; langsmith, braintrust and wandbapi_key; posthogpersonal_api_key; phoenixapi_key(optional); huggingfacetoken; mlflowtoken(optional). Any other field is 422 integration_credentials_invalid.5 child fields
public_keystringLangfuse public key (
pk-lf-...).secret_keystringLangfuse secret key (
sk-lf-...).api_keystringLangSmith, Braintrust or W&B API key; Phoenix API key (optional).
personal_api_keystringPostHog personal API key (
phx_...).tokenstringHugging Face access token; MLflow tracking-server bearer token (optional).
Returns
201 Integration The new integration (pending).
11 fields
idstringrequiredOpaque id:
int_…on a self-hosted server, a UUID on Gradiated Cloud. Never parse it.workspace_idstringrequirednamestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$providerIntegrationProviderrequired"langfuse""langsmith""braintrust""posthog""phoenix""huggingface""wandb""mlflow"hoststringrequiredWhere its credentials go: the provider's base URL.
statusIntegrationStatusrequiredpending: not verified yet (created or changed since its last connection test).active: the last connection test passed.failing: it failed (last_errorsays why)."pending""active""failing"last_errorstringrequiredWhy the last connection test failed (null otherwise).
last_checked_atstring (date-time)requiredWhen the connection was last tested.
used_byIntegrationUsagerequired4 child fields
countintegerrequiredEverything that uses the integration: sources, plus imports and runs that have not finished. At most 100 of each kind are listed.
sourcesarray of objectrequiredSources syncing through it.
2 child fields
idstringrequireddatasetstringrequired
importsarray of objectrequiredQueued or running HF imports.
1 child fields
idstringrequired
runsarray of objectrequiredQueued or running runs logging through it.
2 child fields
idstringrequirednamestringrequired
created_atstring (date-time)requiredupdated_atstring (date-time)required
import os
from grad import Grad
client = Grad()
integration = client.integrations.create(
"langfuse",
credentials={
"public_key": os.environ["LANGFUSE_PUBLIC_KEY"],
"secret_key": os.environ["LANGFUSE_SECRET_KEY"],
},
){
"id": "int_9b9df9563dcef32c3fdff892",
"workspace_id": "ws_e2e",
"name": "langfuse",
"provider": "langfuse",
"host": "https://cloud.langfuse.com",
"status": "untested",
"last_error": null,
"last_checked_at": null,
"used_by": {
"count": 0,
"sources": [],
"imports": [],
"runs": []
},
"created_at": "2026-12-02T15:48:59.946Z",
"updated_at": "2026-12-02T15:48:59.946Z"
}List integrations#
GET/v1/integrations
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstringproviderenum"langfuse""langsmith""braintrust""posthog""phoenix""huggingface""wandb""mlflow"
Returns
200 object Integrations.
2 fields
dataarray of Integrationrequired11 child fields
idstringrequiredOpaque id:
int_…on a self-hosted server, a UUID on Gradiated Cloud. Never parse it.workspace_idstringrequirednamestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$providerIntegrationProviderrequired"langfuse""langsmith""braintrust""posthog""phoenix""huggingface""wandb""mlflow"hoststringrequiredWhere its credentials go: the provider's base URL.
statusIntegrationStatusrequiredpending: not verified yet (created or changed since its last connection test).active: the last connection test passed.failing: it failed (last_errorsays why)."pending""active""failing"last_errorstringrequiredWhy the last connection test failed (null otherwise).
last_checked_atstring (date-time)requiredWhen the connection was last tested.
used_byIntegrationUsagerequired4 child fields
countintegerrequiredEverything that uses the integration: sources, plus imports and runs that have not finished. At most 100 of each kind are listed.
sourcesarray of objectrequiredSources syncing through it.
2 child fields
idstringrequireddatasetstringrequired
importsarray of objectrequiredQueued or running HF imports.
1 child fields
idstringrequired
runsarray of objectrequiredQueued or running runs logging through it.
2 child fields
idstringrequirednamestringrequired
created_atstring (date-time)requiredupdated_atstring (date-time)required
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
for integration in client.integrations.list():
print(integration.name, integration.provider, integration.status){
"data": [
{
"id": "int_9b9df9563dcef32c3fdff892",
"workspace_id": "ws_e2e",
"name": "langfuse",
"provider": "langfuse",
"host": "https://cloud.langfuse.com",
"status": "untested",
"last_error": null,
"last_checked_at": null,
"used_by": {
"count": 1,
"sources": [
{
"id": "src_1456303e7610ad38945c8487",
"dataset": "support-prod"
}
],
"imports": [],
"runs": []
},
"created_at": "2026-12-02T15:48:59.946Z",
"updated_at": "2026-12-02T15:48:59.968Z"
}
],
"next_cursor": null
}Get an integration#
GET/v1/integrations/{name}
Never its credentials.
Path parameters
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$
Returns
200 Integration The integration.
11 fields
idstringrequiredOpaque id:
int_…on a self-hosted server, a UUID on Gradiated Cloud. Never parse it.workspace_idstringrequirednamestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$providerIntegrationProviderrequired"langfuse""langsmith""braintrust""posthog""phoenix""huggingface""wandb""mlflow"hoststringrequiredWhere its credentials go: the provider's base URL.
statusIntegrationStatusrequiredpending: not verified yet (created or changed since its last connection test).active: the last connection test passed.failing: it failed (last_errorsays why)."pending""active""failing"last_errorstringrequiredWhy the last connection test failed (null otherwise).
last_checked_atstring (date-time)requiredWhen the connection was last tested.
used_byIntegrationUsagerequired4 child fields
countintegerrequiredEverything that uses the integration: sources, plus imports and runs that have not finished. At most 100 of each kind are listed.
sourcesarray of objectrequiredSources syncing through it.
2 child fields
idstringrequireddatasetstringrequired
importsarray of objectrequiredQueued or running HF imports.
1 child fields
idstringrequired
runsarray of objectrequiredQueued or running runs logging through it.
2 child fields
idstringrequirednamestringrequired
created_atstring (date-time)requiredupdated_atstring (date-time)required
from grad import Grad
client = Grad()
integration = client.integrations.get("langfuse") # never its credentials
print(integration.status, integration.used_by){
"id": "int_9b9df9563dcef32c3fdff892",
"workspace_id": "ws_e2e",
"name": "langfuse",
"provider": "langfuse",
"host": "https://cloud.langfuse.com",
"status": "untested",
"last_error": null,
"last_checked_at": null,
"used_by": {
"count": 1,
"sources": [
{
"id": "src_1456303e7610ad38945c8487",
"dataset": "support-prod"
}
],
"imports": [],
"runs": []
},
"created_at": "2026-12-02T15:48:59.946Z",
"updated_at": "2026-12-02T15:48:59.968Z"
}Rotate credentials or change the host#
PATCH/v1/integrations/{name}
Resumes paused sources that use it.
Path parameters
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$
Body UpdateIntegrationRequest
hoststringThe provider's base URL (https). Defaults to its public host: https://cloud.langfuse.com, https://api.smith.langchain.com, https://api.braintrust.dev, https://us.posthog.com, https://huggingface.co, https://api.wandb.ai. Required for phoenix (your Phoenix Cloud space URL or self-hosted Phoenix) and mlflow (the tracking URI). Credentials are only ever sent to this host. Null resets it to the provider's public host. Changing the host of an integration that holds credentials needs every credential again, in this request.
credentialsIntegrationCredentialsWrite-only: stored encrypted and never returned. Each provider takes its own fields: langfuse
public_key+secret_key; langsmith, braintrust and wandbapi_key; posthogpersonal_api_key; phoenixapi_key(optional); huggingfacetoken; mlflowtoken(optional). Any other field is 422 integration_credentials_invalid.5 child fields
public_keystringLangfuse public key (
pk-lf-...).secret_keystringLangfuse secret key (
sk-lf-...).api_keystringLangSmith, Braintrust or W&B API key; Phoenix API key (optional).
personal_api_keystringPostHog personal API key (
phx_...).tokenstringHugging Face access token; MLflow tracking-server bearer token (optional).
Returns
200 Integration The updated integration.
11 fields
idstringrequiredOpaque id:
int_…on a self-hosted server, a UUID on Gradiated Cloud. Never parse it.workspace_idstringrequirednamestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$providerIntegrationProviderrequired"langfuse""langsmith""braintrust""posthog""phoenix""huggingface""wandb""mlflow"hoststringrequiredWhere its credentials go: the provider's base URL.
statusIntegrationStatusrequiredpending: not verified yet (created or changed since its last connection test).active: the last connection test passed.failing: it failed (last_errorsays why)."pending""active""failing"last_errorstringrequiredWhy the last connection test failed (null otherwise).
last_checked_atstring (date-time)requiredWhen the connection was last tested.
used_byIntegrationUsagerequired4 child fields
countintegerrequiredEverything that uses the integration: sources, plus imports and runs that have not finished. At most 100 of each kind are listed.
sourcesarray of objectrequiredSources syncing through it.
2 child fields
idstringrequireddatasetstringrequired
importsarray of objectrequiredQueued or running HF imports.
1 child fields
idstringrequired
runsarray of objectrequiredQueued or running runs logging through it.
2 child fields
idstringrequirednamestringrequired
created_atstring (date-time)requiredupdated_atstring (date-time)required
import os
from grad import Grad
client = Grad()
integration = client.integrations.update(
"langfuse", credentials={"secret_key": os.environ["LANGFUSE_SECRET_KEY"]}
){
"id": "int_9b9df9563dcef32c3fdff892",
"workspace_id": "ws_e2e",
"name": "langfuse",
"provider": "langfuse",
"host": "https://cloud.langfuse.com",
"status": "untested",
"last_error": null,
"last_checked_at": null,
"used_by": {
"count": 0,
"sources": [],
"imports": [],
"runs": []
},
"created_at": "2026-12-02T15:48:59.946Z",
"updated_at": "2026-12-02T15:48:59.968Z"
}Delete an integration#
DELETE/v1/integrations/{name}
409 integration_in_use, with used_by, while anything uses it.
Path parameters
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$
Returns
204 Deleted.
from grad import Grad
client = Grad()
client.integrations.delete("langfuse")Deleted.
Test the connection: one cheap authenticated call to the provider; updates status#
POST/v1/integrations/{name}/test
Path parameters
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Returns
200 Integration The integration with the test's status (ok or failing, and last_error).
11 fields
idstringrequiredOpaque id:
int_…on a self-hosted server, a UUID on Gradiated Cloud. Never parse it.workspace_idstringrequirednamestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$providerIntegrationProviderrequired"langfuse""langsmith""braintrust""posthog""phoenix""huggingface""wandb""mlflow"hoststringrequiredWhere its credentials go: the provider's base URL.
statusIntegrationStatusrequiredpending: not verified yet (created or changed since its last connection test).active: the last connection test passed.failing: it failed (last_errorsays why)."pending""active""failing"last_errorstringrequiredWhy the last connection test failed (null otherwise).
last_checked_atstring (date-time)requiredWhen the connection was last tested.
used_byIntegrationUsagerequired4 child fields
countintegerrequiredEverything that uses the integration: sources, plus imports and runs that have not finished. At most 100 of each kind are listed.
sourcesarray of objectrequiredSources syncing through it.
2 child fields
idstringrequireddatasetstringrequired
importsarray of objectrequiredQueued or running HF imports.
1 child fields
idstringrequired
runsarray of objectrequiredQueued or running runs logging through it.
2 child fields
idstringrequirednamestringrequired
created_atstring (date-time)requiredupdated_atstring (date-time)required
from grad import Grad
client = Grad()
integration = client.integrations.test("langfuse")
print(integration.status, integration.last_error){
"id": "obj_3f9c0a1b2c3d4e5f60718293",
"workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
"name": "support-prod",
"provider": "langfuse",
"host": "string",
"status": "pending",
"last_error": "string",
"last_checked_at": "2026-11-28T09:30:00.000Z",
"used_by": {
"count": 0,
"sources": [
{
"id": "obj_3f9c0a1b2c3d4e5f60718293",
"dataset": "support-prod"
}
],
"imports": [
{
"id": "obj_3f9c0a1b2c3d4e5f60718293"
}
],
"runs": [
{
"id": "obj_3f9c0a1b2c3d4e5f60718293",
"name": "support-prod"
}
]
},
"created_at": "2026-11-28T09:30:00.000Z",
"updated_at": "2026-11-28T09:30:00.000Z"
}Sources#
Connect an observability provider to a dataset#
POST/v1/datasets/{name}/sources
Path parameters
namestringrequiredMatches
^[a-z0-9][a-z0-9._-]{0,63}$
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body CreateSourceRequest
providerSourceProviderrequired4 child fields
kindstringOne of langfuse, langsmith, braintrust, posthog, phoenix, gradiated; anything else is 422 source_provider_unsupported. Optional with
integration(the integration's provider); one of the two is required.integrationstringName of the integration to read through (its host and credentials). Optional when the workspace has exactly one integration of this provider; with several, 422 integration_ambiguous lists them. Not used by 'gradiated'.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$projectstringThe provider project to read. Required for braintrust (project id or name) and posthog (numeric project id); optional elsewhere (LangSmith project, Phoenix project).
filtersmap of anyWhich traces to sync; a trace must match every key. Values are a string or a list (any of which matches) unless noted:
tags(list: every tag),environment,model,version,release,name(trace name or route),user_id,session_id,metadata({key: value}, each equal),from/to(ISO 8601: the trace started in [from, to)),has_feedback(true: a score or a correction) andmin_score(a number every score must reach, or{name: number}). Score filters are judged on the merged dataset, so feedback that arrives later still counts. LangSmith also takesfilter(a LangSmith filter expression, AND-ed); gradiated takesmodels,tasksandversions. Any other key is 422 source_filter_unsupported. The response holds the effective filters (single values as lists).
schedulestringFive-field cron in UTC (
*/15 * * * *); minute resolution, so it fires at most once a minute (a seconds field is rejected). Leave it out to sync only on request.sample_ratenumberThe share of traces to sync, chosen by a hash of the trace id: re-syncs keep the same sample, and a trace's feedback follows it. Default 1.
max_records_per_syncintegerAt most this many new traces per sync; the rest are not synced (the sync's drop reasons count them). Feedback on traces already synced always lands. Null: no cap.
max_records_per_dayintegerAt most this many new traces per UTC day; the rest are not synced (the sync's drop reasons count them). Feedback on traces already synced always lands. Null: no cap.
version_intervalintegerSeconds between the dataset versions scheduled syncs commit (default 900). A scheduled sync may fetch every minute; its parts wait, staged, until the interval has passed or enough records are waiting, so a busy source doesn't add a version a minute. 0: every sync commits. Manual and full syncs always commit, and so does removing the schedule or the source, or the source pausing.
Returns
201 Source Created source.
22 fields
idstringrequiredSource id (
src_and 24 hex characters).workspace_idstringrequireddatasetstringrequiredThe dataset the source syncs into (one per source).
Matches
^[a-z0-9][a-z0-9._-]{0,63}$providerobjectrequired4 child fields
kindenumrequired"langfuse""langsmith""braintrust""posthog""phoenix""gradiated"integrationstringrequiredThe integration it reads through (null for 'gradiated').
projectstringrequiredfiltersmap of anyrequiredThe effective filters: validated, with single values as lists.
schedulestringrequiredFive-field UTC cron; null when the source syncs only on request.
sample_ratenumberrequiredThe share of traces synced (1: all).
max_records_per_syncintegerrequiredAt most this many new traces per sync; null for no cap.
max_records_per_dayintegerrequiredAt most this many new traces per UTC day; null for no cap.
records_todayintegerrequiredNew traces synced so far this UTC day (what max_records_per_day counts).
version_intervalintegerrequiredSeconds between the dataset versions scheduled syncs commit (0: every sync).
pending_recordsintegerrequiredRecords scheduled syncs fetched that wait for the next dataset version.
next_sync_atstring (date-time)requiredWhen the schedule fires next (null without a schedule or while paused). After a failed sync the schedule backs off: twice its interval per consecutive failure, at most an hour.
statusenumrequiredpausedafter 10 consecutive failed syncs: the schedule stops firing. A manual sync, or rotating its integration's credentials, resumes it."active""paused"paused_reasonstringrequiredWhy the source is paused (null while active).
last_errorstringrequiredThe error of the last failed sync (provider keys redacted); cleared by a successful sync.
last_error_atstring (date-time)requiredWhen the last sync failed; null if none has.
consecutive_failuresintegerrequiredFailed syncs since the last successful one.
pending_fullbooleanrequiredA full sync was requested while another sync ran; it is queued as soon as that one ends.
last_synced_atstring (date-time)requiredWhen the last successful sync finished.
last_syncSourceSyncrequiredThe most recent sync, running or finished.
created_atstring (date-time)requiredupdated_atstring (date-time)required
from grad import Grad
client = Grad()
source = client.datasets.get("support-prod").add_source(
integration="langfuse",
filters={"environment": "production", "has_feedback": True},
schedule="*/15 * * * *",
){
"id": "src_1456303e7610ad38945c8487",
"workspace_id": "ws_e2e",
"dataset": "support-prod",
"provider": {
"kind": "langfuse",
"integration": "langfuse",
"project": null,
"filters": {
"environment": [
"production"
],
"has_feedback": true
}
},
"schedule": "*/15 * * * *",
"sample_rate": 1,
"max_records_per_sync": null,
"max_records_per_day": null,
"records_today": 0,
"version_interval": 900,
"pending_records": 0,
"next_sync_at": "2026-12-02T16:00:00.000Z",
"status": "active",
"paused_reason": null,
"last_error": null,
"last_error_at": null,
"consecutive_failures": 0,
"pending_full": false,
"last_synced_at": null,
"last_sync": null,
"created_at": "2026-12-02T15:48:59.980Z",
"updated_at": "2026-12-02T15:48:59.980Z"
}List sources (newest first), optionally for one dataset#
GET/v1/sources
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstringdatasetstringMatches
^[a-z0-9][a-z0-9._-]{0,63}$
Returns
200 object Sources.
2 fields
dataarray of Sourcerequired22 child fields
idstringrequiredSource id (
src_and 24 hex characters).workspace_idstringrequireddatasetstringrequiredThe dataset the source syncs into (one per source).
Matches
^[a-z0-9][a-z0-9._-]{0,63}$providerobjectrequired4 child fields
kindenumrequired"langfuse""langsmith""braintrust""posthog""phoenix""gradiated"integrationstringrequiredThe integration it reads through (null for 'gradiated').
projectstringrequiredfiltersmap of anyrequiredThe effective filters: validated, with single values as lists.
schedulestringrequiredFive-field UTC cron; null when the source syncs only on request.
sample_ratenumberrequiredThe share of traces synced (1: all).
max_records_per_syncintegerrequiredAt most this many new traces per sync; null for no cap.
max_records_per_dayintegerrequiredAt most this many new traces per UTC day; null for no cap.
records_todayintegerrequiredNew traces synced so far this UTC day (what max_records_per_day counts).
version_intervalintegerrequiredSeconds between the dataset versions scheduled syncs commit (0: every sync).
pending_recordsintegerrequiredRecords scheduled syncs fetched that wait for the next dataset version.
next_sync_atstring (date-time)requiredWhen the schedule fires next (null without a schedule or while paused). After a failed sync the schedule backs off: twice its interval per consecutive failure, at most an hour.
statusenumrequiredpausedafter 10 consecutive failed syncs: the schedule stops firing. A manual sync, or rotating its integration's credentials, resumes it."active""paused"paused_reasonstringrequiredWhy the source is paused (null while active).
last_errorstringrequiredThe error of the last failed sync (provider keys redacted); cleared by a successful sync.
last_error_atstring (date-time)requiredWhen the last sync failed; null if none has.
consecutive_failuresintegerrequiredFailed syncs since the last successful one.
pending_fullbooleanrequiredA full sync was requested while another sync ran; it is queued as soon as that one ends.
last_synced_atstring (date-time)requiredWhen the last successful sync finished.
last_syncSourceSyncrequiredThe most recent sync, running or finished.
created_atstring (date-time)requiredupdated_atstring (date-time)required
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
for source in client.sources.list(dataset="support-prod"):
print(source.id, source.status, source.last_error){
"data": [
{
"id": "src_1456303e7610ad38945c8487",
"workspace_id": "ws_e2e",
"dataset": "support-prod",
"provider": {
"kind": "langfuse",
"integration": "langfuse",
"project": null,
"filters": {
"environment": [
"production"
],
"has_feedback": true
}
},
"schedule": "*/15 * * * *",
"sample_rate": 0.5,
"max_records_per_sync": null,
"max_records_per_day": null,
"records_today": 0,
"version_interval": 900,
"pending_records": 0,
"next_sync_at": "2026-12-02T16:00:00.000Z",
"status": "active",
"paused_reason": null,
"last_error": null,
"last_error_at": null,
"consecutive_failures": 0,
"pending_full": false,
"last_synced_at": null,
"last_sync": {
"import_id": "imp_2fa783bc75ee294eef1791f6",
"status": "running",
"full": false,
"dataset_version": null,
"error": null,
"created_at": "2026-12-02T15:48:59.998Z",
"finished_at": null
},
"created_at": "2026-12-02T15:48:59.980Z",
"updated_at": "2026-12-02T15:49:00.001Z"
}
],
"next_cursor": null
}Get a source and its latest sync#
GET/v1/sources/{id}
Path parameters
idstringrequired
Returns
200 Source Source.
22 fields
idstringrequiredSource id (
src_and 24 hex characters).workspace_idstringrequireddatasetstringrequiredThe dataset the source syncs into (one per source).
Matches
^[a-z0-9][a-z0-9._-]{0,63}$providerobjectrequired4 child fields
kindenumrequired"langfuse""langsmith""braintrust""posthog""phoenix""gradiated"integrationstringrequiredThe integration it reads through (null for 'gradiated').
projectstringrequiredfiltersmap of anyrequiredThe effective filters: validated, with single values as lists.
schedulestringrequiredFive-field UTC cron; null when the source syncs only on request.
sample_ratenumberrequiredThe share of traces synced (1: all).
max_records_per_syncintegerrequiredAt most this many new traces per sync; null for no cap.
max_records_per_dayintegerrequiredAt most this many new traces per UTC day; null for no cap.
records_todayintegerrequiredNew traces synced so far this UTC day (what max_records_per_day counts).
version_intervalintegerrequiredSeconds between the dataset versions scheduled syncs commit (0: every sync).
pending_recordsintegerrequiredRecords scheduled syncs fetched that wait for the next dataset version.
next_sync_atstring (date-time)requiredWhen the schedule fires next (null without a schedule or while paused). After a failed sync the schedule backs off: twice its interval per consecutive failure, at most an hour.
statusenumrequiredpausedafter 10 consecutive failed syncs: the schedule stops firing. A manual sync, or rotating its integration's credentials, resumes it."active""paused"paused_reasonstringrequiredWhy the source is paused (null while active).
last_errorstringrequiredThe error of the last failed sync (provider keys redacted); cleared by a successful sync.
last_error_atstring (date-time)requiredWhen the last sync failed; null if none has.
consecutive_failuresintegerrequiredFailed syncs since the last successful one.
pending_fullbooleanrequiredA full sync was requested while another sync ran; it is queued as soon as that one ends.
last_synced_atstring (date-time)requiredWhen the last successful sync finished.
last_syncSourceSyncrequiredThe most recent sync, running or finished.
created_atstring (date-time)requiredupdated_atstring (date-time)required
from grad import Grad
client = Grad()
source = client.sources.get("src_3f9c0a1b2c3d4e5f60718293")
print(source.status, source.last_synced_at){
"id": "src_1456303e7610ad38945c8487",
"workspace_id": "ws_e2e",
"dataset": "support-prod",
"provider": {
"kind": "langfuse",
"integration": "langfuse",
"project": null,
"filters": {
"environment": [
"production"
],
"has_feedback": true
}
},
"schedule": "*/15 * * * *",
"sample_rate": 0.5,
"max_records_per_sync": null,
"max_records_per_day": null,
"records_today": 0,
"version_interval": 900,
"pending_records": 0,
"next_sync_at": "2026-12-02T16:00:00.000Z",
"status": "active",
"paused_reason": null,
"last_error": null,
"last_error_at": null,
"consecutive_failures": 0,
"pending_full": false,
"last_synced_at": null,
"last_sync": {
"import_id": "imp_2fa783bc75ee294eef1791f6",
"status": "running",
"full": false,
"dataset_version": null,
"error": null,
"created_at": "2026-12-02T15:48:59.998Z",
"finished_at": null
},
"created_at": "2026-12-02T15:48:59.980Z",
"updated_at": "2026-12-02T15:49:00.001Z"
}Change a source's filters, sampling, record caps or schedule#
PATCH/v1/sources/{id}
From its next sync.
Path parameters
idstringrequired
Body UpdateSourceRequest
filtersmap of anyReplaces the source's filters ({} clears them). Which traces to sync; a trace must match every key. Values are a string or a list (any of which matches) unless noted:
tags(list: every tag),environment,model,version,release,name(trace name or route),user_id,session_id,metadata({key: value}, each equal),from/to(ISO 8601: the trace started in [from, to)),has_feedback(true: a score or a correction) andmin_score(a number every score must reach, or{name: number}). Score filters are judged on the merged dataset, so feedback that arrives later still counts. LangSmith also takesfilter(a LangSmith filter expression, AND-ed); gradiated takesmodels,tasksandversions. Any other key is 422 source_filter_unsupported. The response holds the effective filters (single values as lists).schedulestringFive-field cron in UTC (
*/15 * * * *); minute resolution, so it fires at most once a minute (a seconds field is rejected). Leave it out to sync only on request.sample_ratenumberThe share of traces to sync, chosen by a hash of the trace id: re-syncs keep the same sample, and a trace's feedback follows it. Default 1.
max_records_per_syncintegerAt most this many new traces per sync; the rest are not synced (the sync's drop reasons count them). Feedback on traces already synced always lands. Null: no cap.
max_records_per_dayintegerAt most this many new traces per UTC day; the rest are not synced (the sync's drop reasons count them). Feedback on traces already synced always lands. Null: no cap.
version_intervalintegerSeconds between the dataset versions scheduled syncs commit (default 900). A scheduled sync may fetch every minute; its parts wait, staged, until the interval has passed or enough records are waiting, so a busy source doesn't add a version a minute. 0: every sync commits. Manual and full syncs always commit, and so does removing the schedule or the source, or the source pausing.
Returns
200 Source The updated source.
22 fields
idstringrequiredSource id (
src_and 24 hex characters).workspace_idstringrequireddatasetstringrequiredThe dataset the source syncs into (one per source).
Matches
^[a-z0-9][a-z0-9._-]{0,63}$providerobjectrequired4 child fields
kindenumrequired"langfuse""langsmith""braintrust""posthog""phoenix""gradiated"integrationstringrequiredThe integration it reads through (null for 'gradiated').
projectstringrequiredfiltersmap of anyrequiredThe effective filters: validated, with single values as lists.
schedulestringrequiredFive-field UTC cron; null when the source syncs only on request.
sample_ratenumberrequiredThe share of traces synced (1: all).
max_records_per_syncintegerrequiredAt most this many new traces per sync; null for no cap.
max_records_per_dayintegerrequiredAt most this many new traces per UTC day; null for no cap.
records_todayintegerrequiredNew traces synced so far this UTC day (what max_records_per_day counts).
version_intervalintegerrequiredSeconds between the dataset versions scheduled syncs commit (0: every sync).
pending_recordsintegerrequiredRecords scheduled syncs fetched that wait for the next dataset version.
next_sync_atstring (date-time)requiredWhen the schedule fires next (null without a schedule or while paused). After a failed sync the schedule backs off: twice its interval per consecutive failure, at most an hour.
statusenumrequiredpausedafter 10 consecutive failed syncs: the schedule stops firing. A manual sync, or rotating its integration's credentials, resumes it."active""paused"paused_reasonstringrequiredWhy the source is paused (null while active).
last_errorstringrequiredThe error of the last failed sync (provider keys redacted); cleared by a successful sync.
last_error_atstring (date-time)requiredWhen the last sync failed; null if none has.
consecutive_failuresintegerrequiredFailed syncs since the last successful one.
pending_fullbooleanrequiredA full sync was requested while another sync ran; it is queued as soon as that one ends.
last_synced_atstring (date-time)requiredWhen the last successful sync finished.
last_syncSourceSyncrequiredThe most recent sync, running or finished.
created_atstring (date-time)requiredupdated_atstring (date-time)required
from grad import Grad
client = Grad()
source = client.sources.update("src_3f9c0a1b2c3d4e5f60718293", sample_rate=0.5){
"id": "src_1456303e7610ad38945c8487",
"workspace_id": "ws_e2e",
"dataset": "support-prod",
"provider": {
"kind": "langfuse",
"integration": "langfuse",
"project": null,
"filters": {
"environment": [
"production"
],
"has_feedback": true
}
},
"schedule": "*/15 * * * *",
"sample_rate": 0.5,
"max_records_per_sync": null,
"max_records_per_day": null,
"records_today": 0,
"version_interval": 900,
"pending_records": 0,
"next_sync_at": "2026-12-02T16:00:00.000Z",
"status": "active",
"paused_reason": null,
"last_error": null,
"last_error_at": null,
"consecutive_failures": 0,
"pending_full": false,
"last_synced_at": null,
"last_sync": null,
"created_at": "2026-12-02T15:48:59.980Z",
"updated_at": "2026-12-02T15:48:59.989Z"
}Remove a source#
DELETE/v1/sources/{id}
Sync now: queue an import of new traces and scores#
POST/v1/sources/{id}/sync
Returns the running one if a sync is in progress.
A source starts at most one sync per minute. Within a minute of the last sync's start this returns that sync with a Retry-After header (seconds until a new one may start), so a retried or repeated call is safe. A full sync asked for while an incremental one is queued or running returns the running one and starts right after it (pending_full on the source). Syncing a paused source resumes it.
Path parameters
idstringrequired
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body SyncSourceRequest
fullbooleanRebuild the dataset from the provider as a new version (ignores the stored watermark).
Returns
202 ImportJob The sync's import job: new, running, or the last one when it started under a minute ago.
15 fields
idstringrequiredImport job id (
imp_and 24 hex characters).workspace_idstringrequireddatasetstringrequiredThe dataset the records go into.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$statusImportStatusrequired"queued""running""completed""failed"sourcemap of anyrequiredWhere the records come from: an upload, a Hugging Face dataset, a benchmark, or a source sync.
connectorenumrequiredThe parser requested for the records (
autodetects it from the file)."auto""grad_trajectories""openai_chat""gradiated""otel""langfuse""posthog""braintrust""langsmith"attemptintegerrequiredAttempts started so far.
imported_countintegerrequiredRecords this import added to the dataset (score updates for existing records add none).
dropped_countintegerrequiredRows that couldn't be imported;
drop_reasonssays why.detected_scoresarray of stringrequiredScore names found on the imported records.
drop_reasonsarray of stringrequiredWhy rows were dropped, one line per row (
line 12: invalid JSON), capped at 100 entries.dataset_versionintegerrequiredThe dataset version this import produced; null until then.
errorstringrequiredWhy the import failed; null otherwise.
created_atstring (date-time)requiredupdated_atstring (date-time)required
from grad import Grad
client = Grad()
job = client.sources.sync("src_3f9c0a1b2c3d4e5f60718293", full=False)
print(job.wait().status){
"id": "imp_2fa783bc75ee294eef1791f6",
"workspace_id": "ws_e2e",
"dataset": "support-prod",
"status": "queued",
"source": {
"full": false,
"kind": "provider",
"provider": "langfuse",
"source_id": "src_1456303e7610ad38945c8487"
},
"connector": "auto",
"attempt": 0,
"imported_count": 0,
"dropped_count": 0,
"detected_scores": [],
"drop_reasons": [],
"dataset_version": null,
"error": null,
"created_at": "2026-12-02T15:48:59.998Z",
"updated_at": "2026-12-02T15:48:59.998Z"
}Models#
List trainable base models#
GET/v1/base-models
The server catalog and price source.
Returns
200 object Trainable catalog models.
1 fields
dataarray of TrainableModelrequired13 child fields
idstringrequiredhf_repostringrequiredfamilyenumrequired"llm""encoder"modalitiesarray of ModalityrequiredInput modalities the model accepts (
text,image,audio).adaptersarray of enumrequiredrecipesarray of RecipeKindrequireddefault_forarray of RecipeKindrequiredprice_per_million_tokens_usdnumberrequiredmax_context_tokensintegerrequiredtemplate_revisionstringrequiredcalibrated_lrsmap of numberrequiredmin_gpu_memory_gbnumberrequiredGPU memory (GB) training this base needs at the recipe defaults, measured on an H100 80 GB. v0 trains on one GPU, and runs.plan refuses (422 model_exceeds_gpu_memory) a run that needs more than 80 GB. Null when unknown.
default_poolingenumEncoder models only: native pooling mode used when recipe.pool is omitted ('cls' for BGE, 'mean' for mean-pooled encoders, 'last_token' for causal-architecture encoders).
"mean""cls""last_token"
from grad import Grad
client = Grad()
for model in client.models.list():
print(model.id, model.recipes){
"data": [
{
"id": "qwen/qwen3-0.6b",
"hf_repo": "Qwen/Qwen3-0.6B",
"family": "llm",
"modalities": [
"text"
],
"adapters": [
"lora"
],
"default_for": [
"router"
],
"price_per_million_tokens_usd": 0.15,
"max_context_tokens": 32768,
"template_revision": "qwen3@3",
"calibrated_lrs": {
"sft": 0.0008,
"rl": 0.00005,
"grpo": 0.00005,
"dpo": 0.00003,
"router": 0.0005,
"decision": 0.0005,
"distill": 0.0003,
"reward": 0.00015
},
"min_gpu_memory_gb": 8,
"recipes": [
"decision",
"distill"
]
},
{
"id": "qwen/qwen3-1.7b",
"hf_repo": "Qwen/Qwen3-1.7B",
"family": "llm",
"modalities": [
"text"
],
"adapters": [
"lora"
],
"default_for": [],
"price_per_million_tokens_usd": 0.22,
"max_context_tokens": 32768,
"template_revision": "qwen3@3",
"calibrated_lrs": {
"sft": 0.0007,
"rl": 0.00004,
"grpo": 0.00004,
"dpo": 0.00003,
"router": 0.0005,
"decision": 0.0004,
"distill": 0.00025,
"reward": 0.00012
},
"min_gpu_memory_gb": 12,
"recipes": [
"decision",
"distill"
]
}
]
}Keys#
Create a scoped workspace API key#
POST/v1/keys
Trainer worker keys are platform config, not keys.
Headers
Idempotency-KeystringUp to 255 visible ASCII characters (SDKs send a UUIDv4 and reuse it across retries). A create retried with the same key and body returns what the first request created, with
Idempotent-Replayed: true; the same key with a different body is rejected with 422idempotency_key_reused. The key is stored on the created resource, in the same transaction.Matches
^[\x21-\x7e]{1,255}$
Body CreateApiKeyRequest
namestringrequiredKey name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$scopesarray of ApiKeyScoperequiredThe scopes the key gets (at least one); a
:writescope includes its:read, andadminincludes every workspace scope.
Returns
201 CreatedApiKey Created API key (secret returned once).
2 fields
keyApiKeyrequired7 child fields
idstringrequiredKey id (
key_and 24 hex characters).workspace_idstringrequirednamestringrequiredKey name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$prefixstringrequiredThe first 12 characters of the secret, to tell keys apart.
scopesarray of ApiKeyScoperequiredWhat the key may do; a
:writescope includes its:read, andadminincludes every workspace scope.created_atstring (date-time)requiredrevoked_atstring (date-time)requiredWhen the key was revoked; null while it works.
secretstringrequiredThe full key (
grad_and 48 hex characters). Shown only in this response.
from grad import Grad
client = Grad()
created = client.keys.create(name="ci", scopes=["datasets:write", "runs:write"])
print(created.secret) # shown once{
"key": {
"id": "key_bd29ebeac8cb6a3f2ea88426",
"workspace_id": "ws_e2e",
"name": "ci",
"prefix": "grad_c4d858d",
"scopes": [
"datasets:write",
"runs:write"
],
"created_at": "2026-12-02T15:48:59.560Z",
"revoked_at": null
},
"secret": "grad_…"
}List workspace API keys#
GET/v1/keys
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstring
Returns
200 object Workspace keys.
2 fields
dataarray of ApiKeyrequired7 child fields
idstringrequiredKey id (
key_and 24 hex characters).workspace_idstringrequirednamestringrequiredKey name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$prefixstringrequiredThe first 12 characters of the secret, to tell keys apart.
scopesarray of ApiKeyScoperequiredWhat the key may do; a
:writescope includes its:read, andadminincludes every workspace scope.created_atstring (date-time)requiredrevoked_atstring (date-time)requiredWhen the key was revoked; null while it works.
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
for key in client.keys.list():
print(key.id, key.name, key.scopes){
"data": [
{
"id": "key_bd29ebeac8cb6a3f2ea88426",
"workspace_id": "ws_e2e",
"name": "ci",
"prefix": "grad_c4d858d",
"scopes": [
"datasets:write",
"runs:write"
],
"created_at": "2026-12-02T15:48:59.560Z",
"revoked_at": null
}
],
"next_cursor": null
}Get a workspace API key by id#
GET/v1/keys/{id}
Metadata only.
Path parameters
idstringrequired
Returns
200 ApiKey Workspace API key.
7 fields
idstringrequiredKey id (
key_and 24 hex characters).workspace_idstringrequirednamestringrequiredKey name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$prefixstringrequiredThe first 12 characters of the secret, to tell keys apart.
scopesarray of ApiKeyScoperequiredWhat the key may do; a
:writescope includes its:read, andadminincludes every workspace scope.created_atstring (date-time)requiredrevoked_atstring (date-time)requiredWhen the key was revoked; null while it works.
from grad import Grad
client = Grad()
key = client.keys.get("key_3f9c0a1b2c3d4e5f60718293")
print(key.name, key.scopes){
"id": "key_3f9c0a1b2c3d4e5f60718293",
"workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
"name": "support-prod",
"prefix": "string",
"scopes": [
"admin"
],
"created_at": "2026-11-28T09:30:00.000Z",
"revoked_at": "2026-11-28T09:30:00.000Z"
}Revoke a workspace API key#
DELETE/v1/keys/{id}
Path parameters
idstringrequired
Returns
200 ApiKey Revoked API key.
7 fields
idstringrequiredKey id (
key_and 24 hex characters).workspace_idstringrequirednamestringrequiredKey name.
Matches
^[a-z0-9][a-z0-9._-]{0,63}$prefixstringrequiredThe first 12 characters of the secret, to tell keys apart.
scopesarray of ApiKeyScoperequiredWhat the key may do; a
:writescope includes its:read, andadminincludes every workspace scope.created_atstring (date-time)requiredrevoked_atstring (date-time)requiredWhen the key was revoked; null while it works.
from grad import Grad
client = Grad()
client.keys.revoke("key_3f9c0a1b2c3d4e5f60718293"){
"id": "key_3f9c0a1b2c3d4e5f60718293",
"workspace_id": "ws_8d2e4f6a1b3c5d7e9f0a2b4c",
"name": "support-prod",
"prefix": "string",
"scopes": [
"admin"
],
"created_at": "2026-11-28T09:30:00.000Z",
"revoked_at": "2026-11-28T09:30:00.000Z"
}Usage#
List billed usage, newest first (filter by period, run, eval or kind): one record per billed increment of a run or eval attempt#
GET/v1/usage
Query parameters
limitintegerPage size (default 50). Values above 200 are clamped to 200.
cursorstringfromstringStart of the period (inclusive): YYYY-MM-DD (UTC) or an ISO 8601 timestamp.
tostringEnd of the period: a date YYYY-MM-DD covers that whole UTC day; a timestamp is exclusive.
run_idstringOnly usage billed for this run (its training and the evals it started: labeling, teacher answers, checkpoint evals) or trainer (
trn_...).eval_idstringkindenum"training""trainer""eval""scoring""labeling""teacher"
Returns
200 object Usage records.
2 fields
dataarray of UsageRecordrequired16 child fields
idstringrequiredUsage row id.
kindUsageKindrequiredWhat the tokens paid for:
training(a run's attempts),trainer(a trainer's ops),eval(evals, including a run's checkpoint evals),scoring(dataset.score),labeling(a router run's labeling eval) orteacher(an off-policy distill run's teacher answers)."training""trainer""eval""scoring""labeling""teacher"ref_idstringrequiredThe run (kind
training) or eval this usage belongs to.ref_namestringrequiredThe run's or eval's name.
run_idstringrequiredThe run the usage was billed for: the run itself, or the run whose labeling, teacher or checkpoint eval it is.
attemptintegerrequiredThe attempt the tokens belong to.
tokens_fromintegerrequiredThe attempt's tokens this row starts after (usage is billed in increments while an attempt runs).
tokens_throughintegerrequiredThe attempt's tokens this row ends at;
tokensis the difference fromtokens_from.tokensintegerrequiredTokens billed in this row.
prompt_tokensintegerPrompt tokens processed by sample ops in this row (0 for non-sample usage).
sampled_tokensintegerGenerated/completion tokens produced by sample ops in this row (0 for non-sample usage).
cost_usdnumberrequiredThe charge, in USD.
price_versionstringrequiredThe version of the catalog price the charge was computed with.
billed_byenumrequiredWho bills this usage:
grad(training, and evals on a self-hosted server) orgateway(on Gradiated Cloud, eval model and judge tokens are billed once by the inference gateway; shown here, not charged twice)."grad""gateway"idempotency_keystringrequiredrun-usage:{id}:{attempt}:{tokens_through}(eval-usage:for evals); unique, so an increment is never billed twice.created_atstring (date-time)requiredWhen the increment was billed.
next_cursorstringrequiredPass back as
cursorfor the next page; null on the last page (every list endpoint).
from grad import Grad
client = Grad()
for row in client.usage.list(from_="2026-11-01"):
print(row.created_at, row.kind, row.cost_usd){
"data": [
{
"id": "use_1",
"kind": "training",
"ref_id": "run_ed1c235f0c631d8f209e22a5",
"attempt": 1,
"tokens_from": 0,
"tokens_through": 21,
"tokens": 21,
"prompt_tokens": 0,
"sampled_tokens": 0,
"cost_usd": 0.000008,
"price_version": "p_51c1854c0003",
"billed_by": "grad",
"idempotency_key": "run-usage:run_ed1c235f0c631d8f209e22a5:1:21",
"created_at": "2026-12-02T15:49:00.151Z",
"ref_name": "support-sft",
"run_id": "run_ed1c235f0c631d8f209e22a5"
}
],
"next_cursor": null
}Total cost and tokens over a period (default: this UTC month), by kind, the top runs and evals, and optional groups#
GET/v1/usage/summary
Query parameters
fromstringStart of the period (inclusive): YYYY-MM-DD (UTC) or an ISO 8601 timestamp.
tostringEnd of the period: a date YYYY-MM-DD covers that whole UTC day; a timestamp is exclusive.
group_byenum"day""week""month""model""recipe""kind"
Returns
200 UsageSummary Usage summary.
11 fields
fromstring (date-time)requiredStart of the period (inclusive).
tostring (date-time)requiredEnd of the period (exclusive).
cost_usdnumberrequiredtokensintegerrequiredsampled_tokensintegerrequiredGenerated/completion tokens produced by trainer sample ops in this period.
recordsintegerrequiredby_kindarray of UsageKindTotalrequiredOne entry per kind with usage, costliest first.
4 child fields
kindUsageKindrequiredWhat the tokens paid for:
training(a run's attempts),trainer(a trainer's ops),eval(evals, including a run's checkpoint evals),scoring(dataset.score),labeling(a router run's labeling eval) orteacher(an off-policy distill run's teacher answers)."training""trainer""eval""scoring""labeling""teacher"cost_usdnumberrequiredtokensintegerrequiredrecordsintegerrequired
top_runsarray of UsageRefTotalrequiredThe costliest runs' training in the period (up to 5).
5 child fields
idstringrequirednamestringrequiredkindUsageKindrequiredWhat the tokens paid for:
training(a run's attempts),trainer(a trainer's ops),eval(evals, including a run's checkpoint evals),scoring(dataset.score),labeling(a router run's labeling eval) orteacher(an off-policy distill run's teacher answers)."training""trainer""eval""scoring""labeling""teacher"cost_usdnumberrequiredtokensintegerrequired
top_evalsarray of UsageRefTotalrequiredThe costliest evals, scoring, labeling and teacher jobs in the period (up to 5).
5 child fields
idstringrequirednamestringrequiredkindUsageKindrequiredWhat the tokens paid for:
training(a run's attempts),trainer(a trainer's ops),eval(evals, including a run's checkpoint evals),scoring(dataset.score),labeling(a router run's labeling eval) orteacher(an off-policy distill run's teacher answers)."training""trainer""eval""scoring""labeling""teacher"cost_usdnumberrequiredtokensintegerrequired
group_byUsageGroupByrequiredgroupsarray of UsageGrouprequiredWith group_by: one entry per group with usage, oldest first for time groups and costliest first otherwise.
4 child fields
keystringrequiredThe group: a UTC day or week start (YYYY-MM-DD), a month (YYYY-MM), a model, a recipe or a kind. Null for usage with no recipe (plain evals, scoring).
cost_usdnumberrequiredtokensintegerrequiredrecordsintegerrequired
from grad import Grad
client = Grad()
summary = client.usage.summary(from_="2026-11-01", group_by="model")
print(summary.cost_usd, summary.tokens){
"from": "2026-12-01T00:00:00.000Z",
"to": "2027-01-01T00:00:00.000Z",
"cost_usd": 0.000008,
"tokens": 21,
"records": 1,
"sampled_tokens": 0,
"by_kind": [
{
"kind": "training",
"cost_usd": 0.000008,
"tokens": 21,
"records": 1
}
],
"top_runs": [
{
"id": "run_ed1c235f0c631d8f209e22a5",
"name": "support-sft",
"kind": "training",
"cost_usd": 0.000008,
"tokens": 21
}
],
"top_evals": [],
"group_by": null,
"groups": []
}