# Custom projects

> Custom projects (custom_models in the SDK and API): train a model with the SDK, save, promote to production, call, download; the training loop in detail.

Part of the Endor docs. Index of every page: https://endor.thetokencompany.com/llms.txt. HTML version: https://endor.thetokencompany.com/docs/training.

In a custom project, you train a model yourself on your labeled data. New to Endor? Start with the [Quickstart](https://endor.thetokencompany.com/docs/quickstart).

You create custom projects and train their models with the SDK or the API. The dashboard's **Custom projects** page lists the models, and promotes, archives and downloads them. In the SDK and the API, custom projects are custom models: `client.custom_models`, `/v1/custom_models`.

## From data to a model in production

1. Upload labeled rows and measure a base model on them.
2. Create a custom project: choose a base model and a name for its model.
3. Train it with your own loop. Endor runs each step on a GPU.
4. Save it. A saved model is **archived**: you can evaluate and download it, but decisions can't call it yet.
5. Promote it to **production**, and call it by its name. It is **deploying** until Endor has loaded it onto a GPU, then **live**.

To try it without your own data, download the sample [train.jsonl](https://endor.thetokencompany.com/docs/samples/train.jsonl): 20 support tickets, each with a `department` (choice) and an `urgent` (noul) label.

```python
import endor

client = endor.EndorClient()

rows = endor.data.load_rows("train.jsonl")
train_rows, heldout_rows = endor.data.split(rows, holdout=0.2)
client.datasets.upload("heldout", heldout_rows)
print(client.evaluations.create("mapika/decider-2b", "heldout").result().results["overall"]["accuracy"])  # the baseline

train = endor.data.rows_to_datums(train_rows)
with client.custom_models.create("router-2", base_model="mapika/decider-2b") as run:  # waits for a GPU (see below)
    steps = endor.Steps()
    for epoch in range(3):
        for batch in endor.data.batches(train, 8, seed=epoch):
            steps.add(run.forward_backward(batch), run.optim_step(learning_rate=1e-4))
    steps.wait()
    run.save_checkpoint().result()  # saves "router-2", archived
# the end of the "with" block closes the run and releases the GPU

print(client.evaluations.create("router-2", "heldout").result().results["overall"]["accuracy"])
client.custom_models.promote("router-2")  # in production: decisions can call it now
row = heldout_rows[0]
res = client.system_one(row.state, row.questions, model="router-2")
```

The run takes seconds to start when a GPU for its base model is warm, and a few minutes when one has to start.

## Choosing a base model

The examples use `mapika/decider-2b` because it is small, but you can train any base model. Smaller base models are faster and cheaper per training step and per decision. Larger ones start more accurate. Before you train, evaluate a few on your held-out rows (see [Compare models](https://endor.thetokencompany.com/docs/base-models#compare-models)), and check that your questions fit their rules, such as the number of options. Every base model, with its limits and prices: [Base models](https://endor.thetokencompany.com/docs/base-models).

## Production and archive

| | Archived | Production |
|---|---|---|
| Decisions (`model="router-2"`) | `409 model_not_in_production` | Yes |
| Evaluate, `client.predict`, download | Yes | Yes |
| Expires | Only if you give it a TTL | Never |
| Delete | Yes | Archive it first (`409 model_in_production`) |

- Promoting a model removes its TTL, so it never expires, also after you archive it again. To give it one again, archive it and call `client.custom_models.set_ttl`.

- An organization can have 3 models from custom projects in production. Need more? Email rasmus@thetokencompany.com.
- When every production slot is taken, promote with `replace`: `client.custom_models.promote("router-3", replace="router-2")` archives `router-2` in the same step. Without `replace`, the promote fails with `409 production_full`, and the message names the models in production. In the dashboard, **Promote** asks you to type the name of the model it replaces.
- A promoted model is **deploying** until Endor has loaded it onto a GPU, then **live**: `serving` in `GET /v1/custom_models/{name}`, and in the dashboard Deploying, then Serving traffic. Decisions can call it while it deploys, but the first ones wait for it to load. If it can't be loaded, `serving` is `failed` (`serving_error` says why): promote it again to retry.
- `client.custom_models.archive("router-2")` takes a model out of production and frees its slot. Decisions refuse it at once.
- `client.custom_models.list()` gives the models in production first, then the archived ones.
- While a save runs, `GET /v1/custom_models/{name}` shows the model with `state` `saving`. Every other call that names it answers `409 model_not_ready` until the save completes.

## Names

Each save is a new model, and its name is used once: a name that a saved model already has fails with `409 conflict`, and one a continuous model has with `409 name_taken`. The models of custom projects and continuous models share one list of names in the organization, and a name can't be a base model's name (the part of its id after `owner/`). To improve a model, train again, save under a new name (`router-3`), and promote it with `replace` to switch your traffic. Calls then use the new name.

## The loop

```python
import endor

client = endor.EndorClient()

rows = endor.data.load_rows("train.jsonl")
train_rows, heldout_rows = endor.data.split(rows, holdout=0.1)
train = endor.data.rows_to_datums(train_rows)
heldout = endor.data.rows_to_datums(heldout_rows)

with client.custom_models.create("router-4", base_model="mapika/decider-2b", rank=16) as run:
    steps = endor.Steps()  # keeps 2 steps in flight
    for batch in endor.data.batches(train, 16):
        fb = run.forward_backward(batch)
        opt = run.optim_step(learning_rate=1e-4)
        for out, step in steps.add(fb, opt):  # the results of the step before
            print(step.step, out.loss)
    for out, step in steps.wait():  # the results of the last step
        print(step.step, out.loss)

    scored = run.forward(heldout).result()
    metrics = endor.metrics.decision_metrics(scored.probabilities, [d.target for d in heldout])
    run.log({"heldout/accuracy": metrics["accuracy"]})

    print(run.save_checkpoint().result())  # "router-4"
```

1. `client.custom_models.create(name, base_model=...)` starts a run on a GPU and loads the base model. This takes seconds when a GPU for the base model is warm, and a few minutes when one has to start. Use `wait=False` to continue immediately, then wait on `run.ready`. `client.runs.create(base_model, model=name)` does the same.
2. `run.forward_backward(batch)` calculates the loss and adds the gradients. You make the datums on your machine (`rows_to_datums`), and each call sends its batch: up to 1,024 datums and 32 MB. Training needs no dataset upload. Only a server evaluation reads a stored dataset, or rows sent with it.
3. `run.optim_step(learning_rate=...)` applies the gradients (AdamW) and sets them to zero. Give the learning rate at each step.
4. `endor.Steps()` sends each step before the results of the step before are back. Thus the GPU starts the next step immediately and does not wait for your round trip, which is most of a second per step. `steps.add(fb, opt)` returns the results of the step before. `steps.wait()` returns the results of the last step.
5. `run.forward(data)` gives the probabilities and the loss without training.
6. `run.save_checkpoint()` saves the model under the name the run was created with; `run.save_checkpoint("router-4b")` saves under another name. It returns a future, and the model exists only after the save completes: call `.result()` before you use it. Until then, calls to the model fail with `409 model_not_ready`.
7. The `with` block closes the run at the end, also after an error. Closing releases the GPU.

`run.log(metrics)` adds your metrics to the run. `forward_backward` and `optim_step` record loss, accuracy, gradient norm and learning rate automatically. Read them with `run.metrics()`, or in [Weights & Biases](#weights-biases).

For a standard fine-tune, `endor.recipes.supervised` does all of this in one call (see [Recipes](https://endor.thetokencompany.com/docs/sdk#recipes)).

## Score a candidate before saving

`run.predict(rows)` answers decision rows with the adapter as it is now, on the run's GPU. You get the answers of a decision without saving a model first.

```python
with client.custom_models.create("router-5", base_model="mapika/decider-2b", rank=16) as run:
    ...  # train
    answers = run.predict(heldout_rows).result()  # one {question name: answer} per row, in order
    print(answers[0]["department"].choice, answers[0]["department"].probabilities)
    run.save_checkpoint().result()  # save the candidate that you keep
```

- A row is a decision: `{"state": ..., "questions": {...}}`, as in a [dataset](https://endor.thetokencompany.com/docs/data-format). Labels, ids and weights are ignored. A row can have 64 questions. The SDK splits lists of more than 1,024 questions into several calls.
- The answers have the format of `client.system_one`: choice, noul and score answers with their probabilities.
- They match a decision on the model saved at the same point within the usual difference between training and serving: a few hundredths at most in a probability.
- The call does not change the run: no gradients, the same step. It runs in order with your other calls.
- Endor bills it as training GPU time, like `forward`. A decision on a saved model is billed per input token instead.
- States can be text or JSON. Images are not supported yet.
- For a saved model, use `client.predict(model, rows)` (see [predict](https://endor.thetokencompany.com/docs/sdk#predict)).

## Calibration

A calibrated model that says 90% is right about 90% of the time. Compare `mean_confidence` (the mean probability of the top option) with `accuracy` on held-out rows, in `decision_metrics` or an evaluation. With a high `ece`, confidence well above accuracy (0.99 against 0.90) means the model is overconfident, and well below (0.64 against 0.82) means it is underconfident.

- Overconfident: fewer epochs or a lower learning rate, or slightly soft targets, for example 0.9 on the label and the rest spread over the other options.
- Underconfident: hard labels. A model learns to give its targets' probabilities, so targets flatter than how often the top answer is right make it unsure. Vote shares of annotators who disagree do this: in one test they gave the same accuracy as the winning labels, with an `ece` of 0.176 against 0.016.

A model cannot learn an option that has no training examples, and learns a rare one poorly. Count the labels of each option before you train, and give a rare option more examples or a higher `weight`.

## Progress

You drive a run step by step, so Endor only knows its length if you tell it. Give `total_steps=500` when you create the run, or call `run.set_total_steps(500)` later, and the dashboard shows a progress bar with an ETA from the recent pace. Without a total, it shows the step count and the steps per minute. `recipes.supervised` sets the total from the data size and the epochs, and prints a progress line. `run.info()` gives `step`, `total_steps`, `seconds_per_step` (the median of the last 20 steps), `progress` and `eta_seconds`.

## Weights & Biases

Endor can log your runs to [Weights & Biases](https://wandb.ai) from its servers. Nothing changes in your training code.

1. Connect once: in the dashboard, **Settings → Integrations → Connect Weights & Biases**. Paste a W&B API key (from wandb.ai/authorize) and, optionally, a default entity. Endor checks the key with W&B before it saves it.
2. Every run then logs to W&B. To turn it off for one run, create it with `wandb=False`.

Each run becomes a W&B run with the same id and name, and a config with the base model, the LoRA settings and your `config` (hyperparameters). Endor logs every run metric against the Endor step: `train/loss`, `train/accuracy`, `train/grad_norm`, `train/lr`, what you send with `run.log`, and `progress` when the run has a total. New points reach W&B within about a minute. When the run is closed, Endor finishes the W&B run. `run.info().wandb_url` links to it. If W&B is down, Endor logs later; training never waits for W&B.

Endor keeps the key encrypted in AWS Secrets Manager, never shows it again, and only its logging service can read it. **Disconnect** in Settings → Integrations deletes the key at once.

## Losses

Set `loss_fn` on `forward` and `forward_backward`:

- `cross_entropy` (default): log loss for a hard label, cross-entropy for soft `probs`.
- `brier`: squared error on all option probabilities.

The update is the weighted mean of all datums since the last `optim_step`. Thus two calls with half a batch each give the same step as one call with the full batch. `optim_step` with no gradients fails with `no_gradients`.

To change other AdamW settings, give `endor.AdamParams`: `beta1` (0.9), `beta2` (0.95), `eps` (1e-12), `weight_decay` (0), `grad_clip_norm` (0 = off).

## Order of calls

Training calls return a future immediately. You can send the next call before the last call finishes. The run executes the calls in the order you sent them. Each call has a sequence number (`seq_id`). The SDK sets it, so a retried call never runs two times.

Thus a call that you send after `steps.add(...)`, for example `run.forward(heldout)` or `run.save_checkpoint()`, sees the adapter after that step. If a step failed, the `add` or `wait` that reads it raises the error. Keep a few steps in flight, not all of them: a run holds at most 64 pending calls, then answers `429 queue_full`.

## Save and resume

```python
import endor

client = endor.EndorClient()
with client.custom_models.create("router-6", from_model="router-2", include_optimizer=True) as run:
    print(run.info().step)  # continues from the step of router-2
```

- A run with `from_model` starts from that model's weights, on its base model and LoRA settings. A different explicit setting fails with `422`.
- `include_optimizer=True` continues the optimizer state. The model must have it: save it with `save_checkpoint(include_optimizer=True)`.
- `save_checkpoint(ttl_seconds=...)` deletes an archived model after that time (1 hour to 10 years). Without it, Endor keeps the model. Models in production never expire, and promoting a model removes its TTL.
- For checkpoints during a long run, save each one under its own name with a TTL, for example `run.save_checkpoint(f"router-ckpt-{step}", ttl_seconds=86_400)`. The `with` block closes the run on any exception that your code doesn't catch.
- To continue an open run from another process, for example after your script stopped, get it again with `client.runs.get(run_id)`: `run.info_.step` is its step. The run you get keeps the run open as one from `create` does: it sends a heartbeat every minute until you close it, so use it in a `with` block too.

## Run limits

- Runs share GPUs with other runs on the same base model. Your calls always run alone, so the results are the same as on a GPU of your own.
- Endor bills the GPU time that your calls use, at $7.00 per GPU-hour, by the second. Each run session costs at least 60 GPU-seconds. Waiting between calls is free.
- After 2 minutes without calls, Endor parks the run: it saves the state and frees the GPU (`idle`). The next call resumes the run in a few seconds, at the same step. While the run is open, the SDK sends a heartbeat every minute (for a run from `create` or `client.runs.get`), so you can wait as long as you need between calls. After an hour without calls or heartbeats, for example when your process ended without closing the run, Endor closes it. Saved models are kept; unsaved progress is lost.
- A run starts in seconds when a GPU for its base model is warm. If nobody trained on the base model for a while, the run waits a few minutes for a GPU to start (`provisioning`).
- An organization can have 25 open runs by default, idle runs included; `max_active_runs` in `GET /v1/whoami` gives your organization's limit. One more fails with `409 limit_reached`.
- A run that fails gets `closed_at`, like a closed run. A run that ends before it ever had a GPU reports `step` 0.
- Close a run with `run.close()` or `endor runs close RUN_ID`. Endor keeps saved models. Progress that you did not save is lost.
- If the GPU stops or is taken back, the run continues on another GPU at the same step, usually within a few minutes; your pending calls wait (`provisioning`) and then run. Endor rebuilds the run from its last saved state and replays your calls since then; that time isn't billed. In the rare case it can't do that exactly, pending calls fail with `trainer_lost` and the run is `failed`. Start a new run with `from_model`.

## Run a model outside Endor

Download a model from a custom project with `client.custom_models.download("router-2", "./router-2")`, `endor custom-models download router-2 -o ./router-2`, or **Download** in its menu on the **Custom projects** page. A continuous model's version downloads the same way: `project.download("v3", "./v3")`. The files are:

| File | Content |
|---|---|
| `adapter_model.safetensors` | The LoRA weights in PEFT format (fp32): `lora_A` and `lora_B` for each trained layer. |
| `adapter_config.json` | The PEFT `LoraConfig`: `r`, `lora_alpha`, `target_modules`. `base_model_name_or_path` is the base model's `hf_repo` and `revision` its `hf_revision`. |
| `endor_manifest.json` | `base_model`, `hf_repo`, `hf_revision`, `contract`, `contract_version`, `option_ids`, `lora` (the run's LoRA settings), `training_run_id`, `parent_model`, `step`. |
| `readout.safetensors` | Only for `perplexity-ai/pplx-decider-v1.2-27b` with `train_readout=True`: the trained readout head, which replaces the head of the base model. |
| `optimizer.pt` | Only with `include_optimizer=True`: the AdamW state, to resume training. You do not need it to run the model. |

The adapter is a LoRA for the base model's `hf_repo` at the pinned `hf_revision`. `GET /v1/base_models` gives both. The `contract` names how Endor uses the base model for a decision: the prompt that it makes from the state and the question, and the readout that gives one probability for each option (the option codes, the head or the output rows that it reads, and the temperature).

The weights alone do not give Endor's probabilities. You also need the contract, and Endor's contract code is not published. Thus, to get the same answers outside Endor, you must make the contract again from the reference code of the base model's publisher (on its Hugging Face page). Also:

- The layer names in the adapter are the names in the model that Endor loads. For `perplexity-ai/pplx-decider-v1.2-27b`, they are under `language_model` of the bare Qwen3.5 model, not of `AutoModelForCausalLM`.
- For `autotrust/jev-9b` and `autotrust/gev-26b`, Endor first merges the publisher's own LoRA (the `adapter/` folder of `hf_repo`) into the base weights. Merge it before you apply the Endor adapter.
- For `jaredpalmer/kev-9b` and `bespokelabs/nimble-9b-v2`, the publisher's model is itself a LoRA on a stock Qwen3.5-9B. Endor keeps that LoRA as it is (not merged) and trains your adapter on top of it. Apply the publisher's LoRA first, then yours.
- For `fastino/gliner2.5-decide`, the adapter is for the DeBERTa encoder of the `gliner2` package. It is not a causal language model.

## Other pages

- [Overview](https://endor.thetokencompany.com/docs/index.md): What Endor does: you train decision models on your labeled data in custom projects with the SDK, Endor runs the GPUs, and you call them by name. Continuous models are for invited organizations.
- [Quickstart](https://endor.thetokencompany.com/docs/quickstart.md): Start here: install the SDK, measure base models on your data, train a model in a custom project, evaluate it, promote it and call it.
- [Core concepts](https://endor.thetokencompany.com/docs/concepts.md): Organizations, continuous models and their production and preview versions, names, base models, custom projects, datasets, runs, evaluations and futures.
- [Continuous models](https://endor.thetokencompany.com/docs/continuous-learning.md): Continuous models (projects in the SDK and API), only available to invited organizations: create one, call its production version or its preview, auto-promote, promote and roll back versions, feedback, price.
- [Decisions](https://endor.thetokencompany.com/docs/decisions.md): Decisions with the SDK and over HTTP, model names, giving feedback on them, TypeSafe clients, cold starts, errors.
- [Base models](https://endor.thetokencompany.com/docs/base-models.md): The 18 base models: limits, rules, prices and cold starts.
- [Billing & limits](https://endor.thetokencompany.com/docs/billing.md): Prices, the prepaid balance, usage and limits.
- [Data format](https://endor.thetokencompany.com/docs/data-format.md): Decision rows, question types, hard and soft labels, datums and limits: the data for custom projects.
- [API reference](https://endor.thetokencompany.com/docs/api.md): Each /v1 endpoint: method, path, body fields, response fields and errors.
- [Python SDK](https://endor.thetokencompany.com/docs/sdk.md): The Python SDK (0.9.0): client, continuous models (client.projects) and versions, custom projects (client.custom_models), datasets, runs, evaluations, futures, data helpers, recipes, errors, CLI.
- [Updates](https://endor.thetokencompany.com/docs/updates.md): Changes to the API and SDK, newest first, and when old names and endpoints stop working.
- [Index](https://endor.thetokencompany.com/llms.txt): every page and the API schema.
