# index.md ![](_static/arena-logo.svg) # Arena documentation Arena post-trains open-weight language models on your data and serves the result as an agent you can call. You can work in the web app, from the `arena` CLI, or from Python, on Arena’s GPUs or on your own. - [Quickstart](get-started/quickstart.md): train a model on grade-school maths problems, start to finish. - [Guides](guides/create-a-project.md): one page per task, from creating a project to deploying an agent. - [CLI and Python reference](cli/install.md): install `agilerl`, sign in, and look up any command. - [Arena for partners](partners.md): offer Arena training to your own customers. # account/account.md # Profile and organizations Manage your profile, your CLI key, the organizations you belong to, their members and the secrets their training jobs use. Everything on this page is in **Settings**. Click your initials in the top right to open the profile menu, then click **Settings**. The page has five tabs: **Profile management**, **Billing**, **Organization**, **Usage** and **Bring your own compute**. Billing and usage are on [Billing and credits](account/billing.md). Bring your own compute is on [How BYOC works](compute/byoc.md). ## Roles Each organization gives you one of two roles. The members table shows it. | Role | What they can do | |------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **Admin** | Everything a Member can, plus: add balance, change billing details, invite and remove members, change roles, view the activity log, rename or delete the organization. On **Enterprise**, set up bring your own compute. | | **Member** | Create projects, upload data, train and deploy in the organization. Read every **Settings** tab. Add and replace organization secrets. | Roles are per organization. You can be an **Admin** in one and a **Member** in another. ## Profile Open **Settings** → **Profile management**. - **Account details** shows your name and email. Your name, email and password are kept in your sign-in account, not in Arena. Click **Update profile** to change them in a new tab. - **Notifications** has four switches. **Low credit alerts** (called **Usage alerts** on Enterprise) and **Storage alerts** send email. **Product updates** sends newsletters, new features and announcements. **Cookies and analytics** saves as soon as you flip it. Click **Save preferences** for the others. These settings are yours, not the organization’s. ## CLI API key A CLI API key lets the `arena` CLI and the Python client act as you without a browser sign-in. Use one in CI, on remote machines and in coding agents. 1. Open **Settings** → **Profile management** and find **CLI API key**. 2. Click **Create key**. The **Save Your CLI API Key** dialog shows the full key once. Click **Copy key** before you close it. 3. Set it as `ARENA_API_KEY` where the CLI runs. See [Sign in with an API key](cli/install.md#sign-in-with-an-api-key). After that the card shows only the key’s last four characters, its **Key ID** and when it was **Last used**. You have one key at a time. - **Rotate key** replaces it. The old key stops working at once, so update anything that uses it. - **Revoke key** turns it off. The CLI stops accepting it until you create a new key or run `arena login`. ## Organizations An organization holds projects, experiments, environments, datasets, agents, secrets and a balance. You work in one organization at a time, and every list in Arena shows only that organization’s data. **Switch.** Open the profile menu and click **Switch organisation**. Pick another organization from the list. Arena reloads your workspace and the balance in the menu updates. **Create.** In the same panel, click **Create organisation**. Give it a **Name**, and optionally a **Long name** and **Description**. You are its **Admin**. **Rename or delete.** **Admins** see two icons on the organization’s row in **Switch organisation**: the settings icon opens **Manage organisation**, and the trash icon deletes it. You can delete an organization only while you belong to at least one other. ## Members Open **Settings** → **Organization**. The **Members** card shows how many seats are used and lists everyone in the organization with their role. An **Admin** can: - **Invite.** Click **Invite member**, enter an email and send. The person gets an email with a link to join. Invites join as **Member**. Change the role after they join. - **Change a role.** Pick **Admin** or **Member** in the member’s row. - **Resend or cancel an invite.** An expired invite has a resend button. A pending invite has a cancel button. - **Remove a member.** Use the remove button on their row. To remove an **Admin**, change them to **Member** first. **Members** see the card without the list, and **Invite member** is turned off. **Admins** also see **Activity log** on this tab. **View activity log** opens a record of what users in the organization did. ## Organization secrets Organization secrets hold API keys and tokens that your training jobs need, such as `WANDB_API_KEY`, `HF_TOKEN`, or the provider key an LLM judge calls. A job reads each secret as an environment variable with the secret’s name. In a manifest, a judge’s `api_key_env` names the secret that holds its key, so the key itself never goes in the manifest. See [Write prompts and reward functions](guides/prompts-and-rewards.md) for the judge setup. Any member of the organization can add, replace and delete secrets, and every member’s jobs can read them. Arena encrypts each value and never shows it again. You see only the name, when it last changed and who changed it. ### Web app 1. Open **Settings** → **Organization** and find **Organization secrets**. 2. Click **Add secret**. 3. Enter a **Name** in uppercase letters, digits and underscores, for example `OPENAI_API_KEY`. This is the environment variable name the job sees. 4. Paste the **Value** and click **Add secret**. To change a value, click **Replace** on the row. Jobs that start after that get the new value. To delete a secret, click the trash icon and confirm **Delete secret**. Running jobs keep the value they started with. ### CLI ```bash # Prompts for the value without echoing it arena secrets set OPENAI_API_KEY # Or read it from a local environment variable arena secrets set OPENAI_API_KEY --from-env OPENAI_API_KEY arena secrets list arena secrets delete OPENAI_API_KEY --yes ``` `arena secrets set` creates the secret or replaces its value. It also reads the value from stdin when you pipe one in. It never takes the value as an argument, so the value stays out of your shell history. Flags are in the [command reference](cli/command-reference.md). ## Delete your account 1. Open **Settings** → **Profile management** and find **Delete account**. 2. Click **Request deletion**. 3. Type `DELETE` and click **Delete account**. Arena schedules the deletion for 30 days later and emails you the date. Until then the card reads **Deletion scheduled for** with the date, and **Cancel deletion request** stops it. On that date your account is anonymized, and 30 days later its data is removed for good. It can’t be recovered after the scheduled date. # account/billing.md # Billing and credits Arena charges training, deployments and storage to your organization’s balance. This page covers the two ways to pay, how charges work, adding balance and reading your usage. Open the profile menu (your initials, top right) and click **Settings**. Billing is on the **Billing** tab and spend is on the **Usage** tab. The profile menu also shows the balance under **Credits**. ## Pay as you go and Enterprise Every new organization is on **Pay as you go**. **Enterprise** is a contract you agree with AgileRL. The badge next to your name in the profile menu shows which one you are on. | | Pay as you go | Enterprise | |-----------------------------------------------------------------------|-----------------------------------------------------|---------------------------------------------------------------| | How you pay | Buy credits up front. Charges come off the balance. | Contract. Usage is recorded at the agreed rates and invoiced. | | Balance in the profile menu | The amount left, for example `$110.00` | **Unlimited credits remaining** | | Starting new runs | Only while the balance is above `$10.00` | Always | | Add balance | Yes, an **Admin** | No | | Arena cloud GPUs | Yes | Yes, same catalog | | [Bring your own compute](compute/byoc.md) | No | Yes, after an **Admin** sets it up | To move to Enterprise, an **Admin** clicks **Talk to us about Enterprise** on the **Billing** tab. AgileRL changes the organization once the contract is signed. Enterprise contracts come in two forms. One is billed through Stripe: the **Billing** tab shows the renewal day, the payment method and invoices. The other is billed off-platform: the plan line reads **Enterprise — contract billing (invoices handled off-platform)**, and the tab shows your **Contract**, the **Usage rates** agreed in it and how to reach billing about **Invoices**. ## Who can do what | Action | Member | Admin | |---------------------------------------------|----------|--------------------| | Train and deploy while the balance allows | Yes | Yes | | See the **Billing** and **Usage** tabs | Yes | Yes | | Add balance | No | Yes | | Edit the payment method and billing details | No | Yes | | Open invoices | No | Yes | | Invite and remove members | No | Yes | | Set up bring your own compute | No | Yes, on Enterprise | Members see the **Billing** tab with the note **Billing changes require an organization admin.** Roles are on [Profile and organizations](account/account.md#roles). ## How charges work - **Opening balance.** Your first organization gets `$110.00` once. Organizations you create after that start at `$0.00`. - **Training.** A run is charged for the GPUs it uses, per hour, while its machines exist. Time spent waiting for capacity or in a queue is free, so a run that never starts costs nothing. Charging stops once the machines are released, a few minutes after the run ends. The **Training resources** bar in the wizard shows the hourly price and an estimated cost before you train. See [Choose compute](guides/choose-compute.md). - **Deployments.** A deployed agent is charged by the hour while it is **Deployed**. When the balance cannot cover the next hour, Arena stops the agent and its status turns **Stopped**. Add balance, then deploy it again. - **Your own cluster.** On a cluster your organization registered itself ([BYOC](compute/byoc.md)), Arena charges a flat platform fee: `$2.00` for each hour a training run runs and `$1.00` for each hour a deployment is up, whatever the number of nodes or GPUs. It is charged by the second, like other runs. The **Training resources** bar, the CLI cost estimate and the CLI resource list include it. Runs and deployments started before the fee was introduced are not charged it. A run that fails on Arena’s side gets its fee back with the rest of its charges. - **Storage.** Datasets, checkpoints and other files count toward storage, which is also charged. - **Refunds.** If a run fails because of an error on Arena’s side, everything it was charged goes back to the balance as one **Refund: run failed on our side** entry, a few minutes after its machines are released. A run that fails because of your code, data, model choice or settings, or that runs out of GPU memory, is not refunded. The run’s failure reason says which it was. ### When the balance runs low On Pay as you go: - You cannot start a new run once the balance is `$10.00` or less. - A running job stops when the balance falls below `$5.00`. A charge that was already under way can still take the balance below zero. **Low credit alerts** on **Profile management** email you as the balance runs low. They do not change these limits. On Enterprise, runs keep going and usage keeps being recorded. ## Add balance An **Admin** on Pay as you go adds balance by buying training credits. 1. Open **Settings** → **Billing**. 2. Under **Credit balance**, click **Add balance**. 3. In **Buy training credits**, pick **Basic** (100 credits), **Standard** (500) or **Premium** (1,000), or enter a **Custom amount**. 4. Click **Purchase** and pay in Stripe. One credit is one US dollar of balance, and Stripe charges in US dollars. You come back to Arena and the balance updates. Credits you buy stay until you spend them. On the same tab, **Edit in Stripe** changes the payment method, **Edit information** changes the name and email on **Billed to**, and **Invoices** lists past and upcoming invoices. **View invoices** opens them all in Stripe. ## Usage and statements The **Usage** tab shows what the organization has spent. ### Web app The top of the tab shows **Month to date**, **Balance**, **Storage**, **Deployments** and **Member seats**. Below that is the billing period. It starts on **Billing period - Current month**. Pick a past month from the dropdown to see its statement. Each period shows **Balance brought forward**, **Purchased**, **Consumed** and **Closing balance**, then one row per day with **Top Up**, **Amount** and **Balance**. Expand a day to see each job that day, with its project, user, resource and credits used, plus any other entries such as refunds and adjustments. To download the ledger as CSV, click the download icon and confirm **Export** in **Export Ledger Data**. Use it to split spend across projects or teams. On Enterprise, job lines show **Included** next to the amount: the usage is recorded but does not come off a balance. ### CLI ```bash # Balance, and what running jobs have accrued but not yet been charged arena user credits # Each charge and credit, newest first, with the balance after each arena user credits --ledger ``` `--ledger` can narrow to one job or one deployment. Flags are in the [command reference](cli/command-reference.md). # cli/coding-agents.md # Using Arena from a coding agent Set up Claude Code, Cursor, Codex or another coding agent so it can upload data, write a manifest and submit experiments with the `arena` CLI. ## Prerequisites - An Arena account and a CLI API key. See [Install and sign in](cli/install.md#sign-in-with-an-api-key). ## Give the coding agent the CLI and a key The coding agent runs commands in a terminal with no browser, so it can’t use `arena login`. Install the CLI with `uv tool install agilerl` and give the coding agent your key through `ARENA_API_KEY`. `uv tool` gives the CLI its own environment, so it doesn’t replace the `agilerl` 2.x RL framework if the project uses it. ```bash uv tool install agilerl export ARENA_API_KEY='arena_pat_...' ``` Put the export in the shell profile or `.env` file your coding agent’s terminal loads, not in a file you commit. The key acts as you, so anything the coding agent submits is billed to your organization. `arena experiments submit` and `arena experiments resume` print the price and ask you to confirm before billing starts. With no terminal attached, they refuse to go on unless you pass `--yes`. Leave `--yes` out of your instructions if you want to approve each run yourself, and have the coding agent run `--dry-run` first to show you the price. ## Get JSON output Put `--json` before the command name to get one JSON document on stdout with every field. Progress, logs and errors go to stderr, so the coding agent can parse stdout directly: ```bash arena --json experiments list --project gsm8k arena --json experiments status gsm8k-cispo ``` `ARENA_JSON=1` turns it on for every command. `arena agent run`, `arena agent generate` and the `arena agent sessions` commands stream text and ignore it. `arena --json experiments logs` prints one object per log line, then one with the final status and failure reason. A few commands also take `--json` after the command name: - `arena manifest validate run.yaml --json` prints the verdict and exits 0 whether the manifest is valid or not. A non-zero exit means the check itself failed. - `arena memory estimate run.yaml --gpu h100-80 --json` and `arena memory solve max_model_len run.yaml --gpu h100-80 --json` print the full GPU memory result. Without `--num-gpus`, Arena sizes the run at the GPU count a submit on that GPU type would pick; pass `--num-gpus` to check another count. ## Point the coding agent at these docs Every page on this site has a Markdown copy at the same address plus `.md`, for example `https://docs.arena.agilerl.com/cli/install.md`. Two files at the site root collect them: - [`llms.txt`](https://docs.arena.agilerl.com/llms.txt) lists every page with a one-line description. Give the coding agent this first so it can fetch only the pages it needs. - [`llms-full.txt`](https://docs.arena.agilerl.com/llms-full.txt) is the whole site in one file, for coding agents that can hold it. The CLI also documents itself. `arena --help` prints every flag, and `arena manifest schema` prints the manifest’s JSON Schema. ## Add Arena to your project instructions Paste this into the project’s `AGENTS.md`, `CLAUDE.md` or Cursor rules file and edit the project name: ```markdown ## Arena We train models on Arena with the `arena` CLI from the `agilerl` package. - Install: `uv tool install agilerl`, which keeps the CLI out of the project's environment. Upgrade with `uv tool upgrade agilerl`. Auth comes from the `ARENA_API_KEY` environment variable, which is already set. Never print, echo, log or commit its value, and never pass it on the command line. Do not run `arena login`. - Docs: fetch https://docs.arena.agilerl.com/llms.txt, then the `.md` page you need. Use `arena --help` for flags. - Put `--json` before the command name when you need to read the output (`arena --json experiments list`). - Our project is `my-project`. Pass `--project my-project` to commands that take it. - To start a run, begin from Arena's default manifest instead of writing one: `arena manifest template --model --dataset > run.yaml` - Validate before every submit and fix every error it reports: `arena manifest validate run.yaml` - Show me the price with `arena experiments submit run.yaml --dry-run` and wait for my OK before submitting for real. - Follow a run with `arena experiments status ` and `arena experiments logs `. ``` ## Related - [Command reference](cli/command-reference.md) - [Run spec and manifest schema](cli/manifest-schema.md) - [Train a model](guides/train-a-model.md) # cli/command-reference.md # Command reference Every `arena` command, subcommand and flag, with the same text `arena --help` prints. The pages are generated from the version of `agilerl` that Arena currently supports. For how to use a command, start from the guide for the task. ## Commands Each command has its own page with its subcommands and their flags. - [arena agent](cli/commands/agent.md): List, deploy, run, and generate with Arena agents. - [arena cluster](cli/commands/cluster.md): Manage Arena enterprise clusters. - [arena datasets](cli/commands/datasets.md): Manage your language model datasets in Arena. - [arena env](cli/commands/env.md): Manage your custom GEM environments. - [arena experiments](cli/commands/experiments.md): Manage experiments (training jobs) by name. - [arena login](cli/commands/login.md): Sign in through the browser. - [arena logout](cli/commands/logout.md): Log out and clear persisted credentials. - [arena manifest](cli/commands/manifest.md): Validate a training manifest, or print its JSON Schema. - [arena memory](cli/commands/memory.md): Estimate GPU memory, or solve one setting against a card. - [arena models](cli/commands/models.md): List HuggingFace models in the Arena catalog. - [arena projects](cli/commands/projects.md): Manage your projects in Arena. - [arena resources](cli/commands/resources.md): List the GPU types and GPU counts you can train on. - [arena secrets](cli/commands/secrets.md): Manage your organization’s secrets in Arena. - [arena user](cli/commands/user.md): Retrieve user / account information. `arena cluster` only appears in `arena --help` once you sign in to an Enterprise organization. Its `providers` subcommands come from your organization’s settings at run time, so they are not listed here. ## Global options These go between `arena` and the command, for example `arena --json experiments list`. ### Usage ```shell arena [OPTIONS] COMMAND [ARGS]... ``` ### Options ### --json Print each result as one JSON document on stdout, with every field. Progress, logs and errors go to stderr. Commands that stream text (agent run/generate, sessions) stay as text. ### --api-key Bearer secret: profile CLI PAT (arena_pat_…) or access token. ### --org-key Organisation API key (arena_org_…). Requires --external-user-id. ### --external-user-id Partner user id sent as X-External-User-Id. Requires --org-key. ### --base-url Override Arena API base URL (for local/dev environments). ### --keycloak-url Override Keycloak URL for authentication. ### --realm Override Keycloak realm. ### --client-id Override Keycloak client ID. ### --request-timeout Default timeout in seconds for API requests. * **Default:** `30` ### --upload-timeout Timeout in seconds for file uploads and cluster register. * **Default:** `300` ### --module-catalog-url Base URL of the signed Terraform module catalog. ### --module-catalog-public-key Ed25519 public key PEM used to verify the module catalog. ### -h, --help Show this message and exit. # cli/commands/agent.md # arena agent List, deploy, run, and generate with Arena agents. ### Usage ```shell arena agent [OPTIONS] COMMAND [ARGS]... ``` ## arena agent delete Archive a deployment. ### Usage ```shell arena agent delete [OPTIONS] NAME ``` ### Options ### --yes Archive without an interactive prompt. ### --experiment-name Experiment name when several deployments share this name. ### --project-name Project name when several deployments share this name. ### Arguments ### NAME Required argument ## arena agent deploy Deploy an agent from an experiment checkpoint. A deployment’s memory scope is fixed once it exists, so `--memory-scope` only takes effect on the first deploy. Without `--num-gpus` and `--gpu-type`, a redeploy keeps the agent’s resources and a new deployment uses Arena’s default. ### Usage ```shell arena agent deploy [OPTIONS] EXPERIMENT_NAME ``` ### Options ### --checkpoint Steps of the checkpoint to deploy, from arena experiments checkpoints. Omit to deploy the checkpoint with the most steps. ### --memory-scope Who the deployment keeps chat sessions for. New deployments default to ‘user’. Redeploying without this flag keeps the stored scope. * **Options:** user | organization ### --num-gpus GPUs on the deployment’s node. ### --gpu-type Short GPU name such as h100-80, b200 or l4. ### Arguments ### EXPERIMENT_NAME Required argument ## arena agent generate Stream a completion from a prompt through a deployed agent. Omit *deployment_name* to use the agent set by `arena agent run`. Prompts continue the current conversation, starting one on the first prompt, so a deployment that keeps chat history remembers what you asked. ### Usage ```shell arena agent generate [OPTIONS] [DEPLOYMENT_NAME] ``` ### Options ### --project-name Project name (exact) — narrows duplicate deployment names. ### --experiment-name Experiment name (exact) — narrows duplicate deployment names. ### --refresh Refetch the deployment URL from Arena instead of using the local cache. ### --prompt **Required** Prompt text for the deployment. ### --session-id Chat session to continue. Overrides a session set by ‘arena agent sessions resume’. ### --new-session Start a new conversation and continue it in later prompts. ### --max-tokens Most tokens the answer may run to. A longer answer is cut off. * **Default:** `512` ### Arguments ### DEPLOYMENT_NAME Optional argument ## arena agent list List deployed agents. ### Usage ```shell arena agent list [OPTIONS] ``` ### Options ### --name Exact deployment name filter. ### --experiment-name Exact experiment name filter. ### --project-name Exact project name filter. ## arena agent run Select a deployment as the active agent to use for inference. ### Usage ```shell arena agent run [OPTIONS] DEPLOYMENT_NAME ``` ### Options ### --project-name Project name (exact) — narrows duplicate deployment names. ### --experiment-name Experiment name (exact) — narrows duplicate deployment names. ### --refresh Refetch the deployment URL from Arena instead of using the local cache. ### Arguments ### DEPLOYMENT_NAME Required argument ## arena agent sessions Browse chat sessions held by a deployed agent. ### Usage ```shell arena agent sessions [OPTIONS] COMMAND [ARGS]... ``` ### arena agent sessions clear Clear the current session, so the next prompt starts a new conversation. Omit *deployment_name* to use the agent set by `arena agent run`. Only the local pointer is cleared; the session itself stays on the deployment and `arena agent sessions resume` can pick it up again. ### Usage ```shell arena agent sessions clear [OPTIONS] [DEPLOYMENT_NAME] ``` ### Arguments ### DEPLOYMENT_NAME Optional argument ### arena agent sessions delete Delete a chat session and its history from the deployment. Omit *deployment_name* to use the agent set by `arena agent run`. Unlike `arena agent sessions clear`, this cannot be undone: the messages are gone from the deployment, not just from this machine. ### Usage ```shell arena agent sessions delete [OPTIONS] SESSION_ID [DEPLOYMENT_NAME] ``` ### Options ### --project-name Project name (exact) — narrows duplicate deployment names. ### --experiment-name Experiment name (exact) — narrows duplicate deployment names. ### --refresh Refetch the deployment URL from Arena instead of using the local cache. ### --yes Confirm deletion without interactive prompt. ### Arguments ### SESSION_ID Required argument ### DEPLOYMENT_NAME Optional argument ### arena agent sessions get Show one chat session and its messages. Omit *deployment_name* to use the agent set by `arena agent run`. ### Usage ```shell arena agent sessions get [OPTIONS] SESSION_ID [DEPLOYMENT_NAME] ``` ### Options ### --project-name Project name (exact) — narrows duplicate deployment names. ### --experiment-name Experiment name (exact) — narrows duplicate deployment names. ### --refresh Refetch the deployment URL from Arena instead of using the local cache. ### Arguments ### SESSION_ID Required argument ### DEPLOYMENT_NAME Optional argument ### arena agent sessions list List your chat sessions with a deployed agent. Omit *deployment_name* to use the agent set by `arena agent run`. The session being resumed, if any, is marked in the first column. ### Usage ```shell arena agent sessions list [OPTIONS] [DEPLOYMENT_NAME] ``` ### Options ### --project-name Project name (exact) — narrows duplicate deployment names. ### --experiment-name Experiment name (exact) — narrows duplicate deployment names. ### --refresh Refetch the deployment URL from Arena instead of using the local cache. ### Arguments ### DEPLOYMENT_NAME Optional argument ### arena agent sessions resume Continue a chat session in later commands without repeating its id. Omit `--session-id` to choose one with the arrow keys. The session is remembered per deployment, so `arena agent generate --prompt '...'` carries on the conversation until you run `arena agent sessions clear`. ### Usage ```shell arena agent sessions resume [OPTIONS] [DEPLOYMENT_NAME] ``` ### Options ### --project-name Project name (exact) — narrows duplicate deployment names. ### --experiment-name Experiment name (exact) — narrows duplicate deployment names. ### --refresh Refetch the deployment URL from Arena instead of using the local cache. ### --session-id Session to resume. Omit to pick one from a list. ### Arguments ### DEPLOYMENT_NAME Optional argument ## arena agent update Rename, describe, or enable a deployment. ### Usage ```shell arena agent update [OPTIONS] NAME ``` ### Options ### --new-name Replacement display name. ### --description Replacement description. ### --enabled, --disabled Enable or disable the deployment. ### --experiment-name Experiment name when several deployments share this name. ### --project-name Project name when several deployments share this name. ### Arguments ### NAME Required argument # cli/commands/cluster.md # arena cluster Manage Arena enterprise clusters. ### Usage ```shell arena cluster [OPTIONS] COMMAND [ARGS]... ``` ## arena cluster connect Connect a Kubernetes cluster to Arena in one step. Runs preflight and stops on a failed check, then registers the cluster (an existing name keeps its token), installs the agent, and waits until it connects and reports its health after the install finishes. Lists the resource classes Arena suggests from the cluster’s nodes and creates them on --yes or after a prompt. ### Usage ```shell arena cluster connect [OPTIONS] ``` ### Options ### --name **Required** Arena cluster name. ### --kubeconfig Kubeconfig for the agent cluster. Defaults to arena-cluster-NAME/kubeconfig when that file exists. ### --context Kubernetes context to use. Without it or --kubeconfig, the command shows the current context and asks first. ### --agent-namespace Kubernetes namespace for the agent Helm release. * **Default:** `'arena'` ### --storage-endpoint Object storage endpoint. ### --storage-bucket Object storage bucket. ### --storage-prefix Object storage prefix. ### --storage-secret-name Secret in the agent namespace that holds the storage credentials. ### --ray-data-storage-class-name StorageClass for Ray data. Defaults to the cluster’s default StorageClass. ### --rotate-token Issue a new agent token for a cluster that is already registered. The previous token keeps working for 24 hours. ### --wait-timeout Seconds to wait for the agent to connect and send its health report. * **Default:** `900.0` ### --yes Create the resource classes Arena suggests without prompting. ## arena cluster destroy Destroy the cloud cluster recorded in the selected Terraform state. ### Usage ```shell arena cluster destroy [OPTIONS] ``` ### Options ### --spec Cloud cluster provisioning YAML file. ### --name Cluster name in Arena. Used when --spec is omitted. ### --state-dir Terraform state directory (default: ./arena-cluster-NAME/terraform). ### --delete-storage Force-delete experiment object storage (data, metrics, and checkpoints). Kept otherwise. ### --delete-storage-project Delete experiment object storage, the Terraform state bucket, and the Nebius storage project that provisioning created. ### --all Delete this cluster’s buckets and IAM, including its Nebius region projects. The Terraform state bucket is deleted last. ### --module-version Terraform module release to install. Upgrades a cluster that already has a pin. ### --yes Destroy without prompting. ## arena cluster generate-spec Write a default cluster spec YAML with placeholder cloud IDs. ### Usage ```shell arena cluster generate-spec [OPTIONS] ``` ### Options ### --provider Cloud provider for the generated spec. * **Default:** `'nebius'` * **Options:** nebius | aws ### --name Cluster name written into the spec (default: arena-PROVIDER). ### --output Destination YAML path (default: ./NAME.yaml). ### --force Overwrite an existing file. ## arena cluster manifest Write the GitOps manifest for the agent at this Arena release. The manifest pins the agent chart and holds no secrets. On a new cluster, run the install package’s bootstrap command first. To upgrade, commit the new manifest. ### Usage ```shell arena cluster manifest [OPTIONS] ``` ### Options ### --name **Required** Registered cluster name. ### --format **Required** argocd: an Argo CD Application. flux: a Flux HelmRepository and HelmRelease. * **Options:** argocd | flux ### -o, --output File to write. Standard output when omitted. ### --platform Target AgileRL’s own platform clusters, which needs AgileRL staff access. ## arena cluster plan Create a cloud cluster plan without applying it. ### Usage ```shell arena cluster plan [OPTIONS] ``` ### Options ### --spec **Required** Cloud cluster provisioning YAML file. ### --state-dir Terraform state directory (default: OUTPUT_DIR/terraform). ### --module-version Terraform module release to install. Upgrades a cluster that already has a pin. ### --byoc-scope customer keeps this org’s bucket. platform shares the Arena catalog and bucket and requires a platform admin. Choosing platform uses ephemeral placement unless --placement is set. * **Options:** customer | platform ### --placement Override values.placement. in-cluster runs jobs in this cluster; ephemeral hunts capacity outside it. * **Options:** in-cluster | ephemeral ### --ray-data-pvc-size Override the Ray data PVC size. ### --ray-data-storage-class-name Override the Ray data storage class. ### --preprocessing-resource-class Override the preprocessing resource class name. ### --tls-secret-name Override the inference TLS secret. ### --gateway-api-parent-refs Override Gateway API parent refs JSON. ### --hostname-template Override the inference hostname template. ### --domain Override the inference DNS domain. ### --ingress-class-name Override the inference ingress class. ### --storage-secret-name Override the object storage secret name. ### --storage-prefix Override the object storage prefix. ### --storage-bucket Override the object storage bucket. ### --storage-endpoint Override the object storage endpoint. ### --name Override the cluster name from --spec. ### --create-state-bucket Create the Terraform state bucket if it is missing. ## arena cluster preflight Check that a Kubernetes cluster can run the Arena agent. Read-only: changes nothing in Arena or the cluster. Exits non-zero when a check fails. ### Usage ```shell arena cluster preflight [OPTIONS] ``` ### Options ### --name Arena cluster name. When Arena already has this cluster, its own agent does not count as a second one. ### --kubeconfig Kubeconfig for the agent cluster. Defaults to arena-cluster-NAME/kubeconfig when that file exists. ### --context Kubernetes context to use. Without it or --kubeconfig, the command shows the current context and asks first. ### --agent-namespace Kubernetes namespace for the agent Helm release. * **Default:** `'arena'` ### --ray-data-storage-class-name StorageClass for Ray data. Defaults to the cluster’s default StorageClass. ### --json Print the report as one JSON document, for the Arena web wizard. ## arena cluster provision Provision a cloud Kubernetes cluster from a YAML spec. ### Usage ```shell arena cluster provision [OPTIONS] [nebius|aws] ``` ### Options ### --spec **Required** Cloud cluster provisioning YAML file. ### --state-dir Terraform state directory (default: OUTPUT_DIR/terraform). ### --module-version Terraform module release to install. Upgrades a cluster that already has a pin. ### --byoc-scope customer keeps this org’s bucket. platform shares the Arena catalog and bucket and requires a platform admin. Choosing platform uses ephemeral placement unless --placement is set. * **Options:** customer | platform ### --placement Override values.placement. in-cluster runs jobs in this cluster; ephemeral hunts capacity outside it. * **Options:** in-cluster | ephemeral ### --ray-data-pvc-size Override the Ray data PVC size. ### --ray-data-storage-class-name Override the Ray data storage class. ### --preprocessing-resource-class Override the preprocessing resource class name. ### --tls-secret-name Override the inference TLS secret. ### --gateway-api-parent-refs Override Gateway API parent refs JSON. ### --hostname-template Override the inference hostname template. ### --domain Override the inference DNS domain. ### --ingress-class-name Override the inference ingress class. ### --storage-secret-name Override the object storage secret name. ### --storage-prefix Override the object storage prefix. ### --storage-bucket Override the object storage bucket. ### --storage-endpoint Override the object storage endpoint. ### --name Override the cluster name from --spec. ### --output-dir Directory for kubeconfig and generated Helm values. ### --register-and-install Register the cluster with Arena and install the Helm agent. ### --agent-namespace Kubernetes namespace for the agent Helm release when installing. * **Default:** `'arena'` ### --yes Apply without prompting. ### --create-state-bucket Create the Terraform state bucket if it is missing. ### Arguments ### PROVIDER Optional argument ## arena cluster register Register a Kubernetes cluster and write Helm install bundles. Re-running with the same `--name` updates the existing cluster (upsert) and keeps its agent token; `--rotate-token` issues a new one. Object storage is optional. `--install` deploys the agent chart. `--install-storage` requests bundled MinIO and installs that chart. `--lab` is `--install-storage --narrow-allowed-ips`. `--byoc-scope platform` shares the Arena catalog and bucket. ### Usage ```shell arena cluster register [OPTIONS] [nebius|aws] ``` ### Options ### -v, --verbose Show detailed command traces. ### --yes Provision and create suggested classes without prompting. ### --create-state-bucket Create the Terraform state bucket when provisioning a missing cluster. terraform_state.create_bucket in the spec does the same. ### --module-version Terraform module release to install. Upgrades a cluster that already has a pin. ### --state-dir Terraform state directory (default: ./arena-cluster-NAME/terraform). ### --agent-namespace Kubernetes namespace for the agent Helm release. * **Default:** `'arena'` ### --no-helm-wait Do not wait for Helm storage resources or the agent Deployment. ### --charts-dir Platform development only: path to agilerl-platform/resources/helm-setup instead of downloading charts from Arena. ### --rotate-token Issue a new agent token for a cluster that is already registered. The previous token keeps working for 24 hours. ### --no-write Do not persist Helm values or token files under --output-dir. ### --lab Lab k3d profile: same as --install-storage --narrow-allowed-ips. ### --narrow-allowed-ips Omit 10.0.0.0/8 from WireGuard AllowedIPs (k3d/k3s ClusterIP). ### --install-storage Mint bundled MinIO values and install the storage chart. ### --install Run helm upgrade --install for the agent chart. ### --force Overwrite existing output files. ### --skip-enable Skip enabling the BYOC provider (use when it is already enabled). ### --output-dir Directory for Helm values and token (default: ./arena-cluster-NAME). ### --kubeconfig Kubeconfig for the agent cluster. Defaults to arena-cluster-NAME/kubeconfig when that file exists. ### --context Kubernetes context to use. Without it or --kubeconfig, the command shows the current context and asks first. ### --byoc-scope customer keeps this org’s bucket. platform shares the Arena catalog and bucket and requires a platform admin. Choosing platform uses ephemeral placement unless --placement is set. * **Options:** customer | platform ### --placement Override values.placement. in-cluster runs jobs in this cluster; ephemeral hunts capacity outside it. * **Options:** in-cluster | ephemeral ### --ray-data-pvc-size Override the Ray data PVC size. ### --ray-data-storage-class-name Override the Ray data storage class. ### --preprocessing-resource-class Override the preprocessing resource class name. ### --tls-secret-name Override the inference TLS secret. ### --gateway-api-parent-refs Override Gateway API parent refs JSON. ### --hostname-template Override the inference hostname template. ### --domain Override the inference DNS domain. ### --ingress-class-name Override the inference ingress class. ### --storage-secret-name Override the object storage secret name. ### --storage-prefix Override the object storage prefix. ### --storage-bucket Override the object storage bucket. ### --storage-endpoint Override the object storage endpoint. ### --name Override the cluster name from --spec. ### --spec Cloud cluster YAML file that supplies registration settings. ### Arguments ### PROVIDER Optional argument ## arena cluster register-classes Register Nebius GPU presets as Arena resource classes on an existing cluster. ### Usage ```shell arena cluster register-classes [OPTIONS] ``` ### Options ### --spec **Required** Cloud cluster provisioning YAML file. ### --state-dir Terraform state directory (default: OUTPUT_DIR/terraform). ### --module-version Terraform module release to install. Upgrades a cluster that already has a pin. ### --output-dir Directory for the kubeconfig written when new node groups are applied. ### --all Register every GPU preset in the Nebius project. ### --preset Register one preset, as platform:preset. Repeat to register several. ### --yes Apply without prompting. ### --register-node-group Create the Nebius node group for each selected preset, then register the class. ## arena cluster revoke-token Revoke every credential of the cluster now, for a leaked one. The agent is refused until you run arena cluster connect again. ### Usage ```shell arena cluster revoke-token [OPTIONS] ``` ### Options ### --name **Required** Registered cluster name. ### --yes Do not ask first. ### --platform Target AgileRL’s own platform clusters, which needs AgileRL staff access. ## arena cluster rotate-token Ask the cluster’s agent to renew its credential. The current one keeps working until the agent uses the new one. ### Usage ```shell arena cluster rotate-token [OPTIONS] ``` ### Options ### --name **Required** Registered cluster name. ### --yes Do not ask first. ### --platform Target AgileRL’s own platform clusters, which needs AgileRL staff access. ## arena cluster smoke Check that a BYOC cluster can run jobs. The cluster’s agent installs a small train release as its own ServiceAccount, the way it installs a job, waits until its Ray head is Ready, and removes it. The release mounts no storage and asks for no GPU. The command fails with the agent’s reason when the release does not come up. ### Usage ```shell arena cluster smoke [OPTIONS] ``` ### Options ### --name **Required** Registered cluster name. ### --kubeconfig Kubeconfig for the agent cluster. Defaults to arena-cluster-NAME/kubeconfig when that file exists. ### --context Kubernetes context to use. Without it or --kubeconfig, the command shows the current context and asks first. ### --timeout Seconds to wait for the result. * **Default:** `3600.0` ### --platform Target AgileRL’s own platform clusters, which needs AgileRL staff access. ## arena cluster status Show Terraform outputs for a provisioned cluster. ### Usage ```shell arena cluster status [OPTIONS] ``` ### Options ### --spec **Required** Cloud cluster provisioning YAML file. ### --state-dir Terraform state directory (default: OUTPUT_DIR/terraform). ### --module-version Terraform module release to install. Upgrades a cluster that already has a pin. ## arena cluster unregister Remove a BYOC cluster from Arena by name. Arena refuses a cluster with runs unless --stop-runs stops them. Its agent then deletes the job namespaces it created and Arena archives the cluster and its classes and revokes its tokens. The agent Helm release is uninstalled after that, unless declined. ### Usage ```shell arena cluster unregister [OPTIONS] ``` ### Options ### --name **Required** Registered cluster name. ### --kubeconfig Kubeconfig for the agent cluster. Defaults to arena-cluster-NAME/kubeconfig when that file exists. ### --context Kubernetes context to use. Without it or --kubeconfig, the command shows the current context and asks first. ### --stop-runs Stop the cluster’s experiments and deployments first. ### --force Archive the cluster now without waiting for its agent, for an agent that is offline. Arena ends its runs. Uninstalling the agent release removes its job namespaces; if the release stays, run the printed command. ### --uninstall-helm Uninstall the agent Helm release without prompting. Does not uninstall MinIO. ### --keep-agent Leave the agent Helm release installed. ### --uninstall-storage Uninstall the MinIO storage Helm release without prompting. Deletes checkpoints, metrics, and datasets. ### --wait-timeout Seconds to wait for the agent to clean up. * **Default:** `600.0` ### --yes Unregister without prompting. Uninstalls nothing without --uninstall-helm. ### --platform Target AgileRL’s own platform clusters, which needs AgileRL staff access. ## arena cluster upgrade Upgrade the BYOC agent chart without changing cluster credentials. ### Usage ```shell arena cluster upgrade [OPTIONS] ``` ### Options ### --name **Required** Registered cluster name. ### --kubeconfig Kubeconfig for the agent cluster. Defaults to arena-cluster-NAME/kubeconfig when that file exists. ### --context Kubernetes context to use. Without it or --kubeconfig, the command shows the current context and asks first. ### --agent-namespace Kubernetes namespace for the agent Helm release. Defaults to the namespace Helm reports for this cluster. ### --no-helm-wait Do not wait for the agent Deployment. ### --yes Apply agent ClusterRole changes without prompting. ### --platform Target AgileRL’s own platform clusters, which needs AgileRL staff access. # cli/commands/datasets.md # arena datasets Manage your language model datasets in Arena. ### Usage ```shell arena datasets [OPTIONS] COMMAND [ARGS]... ``` ## arena datasets create Create a dataset on Arena. ### Usage ```shell arena datasets create [OPTIONS] NAME ``` ### Options ### --category **Required** Dataset category. traces is OpenAI chat messages, one session segment per messages row or one call per prompt-completion row; it takes no column mapping and is checked locally before upload. * **Options:** preference | reasoning | sft | traces ### --column-mapping Column mapping as a JSON object string. Not used with traces. ### --column-mapping-file Path to a JSON file containing the column mapping. ### --description Optional description. ### --file Local CSV, JSONL or parquet file, or a Hugging Face parquet folder. ### --config Parquet config when --file is a folder with more than one config. ### --hf-dataset HuggingFace dataset id to import. ### --hf-config HuggingFace dataset config (default on the server: default). ### --hf-split HuggingFace split (required when using --hf-dataset). ### Arguments ### NAME Required argument ## arena datasets delete Archive a dataset by name. ### Usage ```shell arena datasets delete [OPTIONS] NAME ``` ### Options ### --yes Confirm deletion without interactive prompt. ### Arguments ### NAME Required argument ## arena datasets exists Check whether a dataset name exists in Arena. ### Usage ```shell arena datasets exists [OPTIONS] NAME ``` ### Arguments ### NAME Required argument ## arena datasets list List datasets registered for your organization. ### Usage ```shell arena datasets list [OPTIONS] ``` ### Options ### --search Search HuggingFace datasets. # cli/commands/env.md # arena env Manage your custom GEM environments. ### Usage ```shell arena env [OPTIONS] COMMAND [ARGS]... ``` ## arena env delete Delete an environment version (or all versions if version is None) from Arena. ### Usage ```shell arena env delete [OPTIONS] NAME ``` ### Options ### --version Version to delete. Omit to delete every version. ### --yes Confirm deletion without interactive prompt. ### Arguments ### NAME Required argument ## arena env duplicate Copy an existing environment version to a new version name. If no version is provided, the latest version will be duplicated. ### Usage ```shell arena env duplicate [OPTIONS] NAME NEW_VERSION ``` ### Options ### --version Version to copy. Omit for the latest. ### Arguments ### NAME Required argument ### NEW_VERSION Required argument ## arena env entrypoints List available entrypoints for an existing environment version. ### Usage ```shell arena env entrypoints [OPTIONS] NAME ``` ### Options ### --version Version to inspect. Omit for the latest. ### Arguments ### NAME Required argument ## arena env exists Check if an environment version exists in Arena. ### Usage ```shell arena env exists [OPTIONS] NAME ``` ### Options ### --version Version to check. Omit for the latest. ### Arguments ### NAME Required argument ## arena env list List all available environments in Arena, and whether they have been validated. ### Usage ```shell arena env list [OPTIONS] ``` ### Options ### --name Only list this environment. ### --include-arena, --no-include-arena Also list the environments Arena provides. * **Default:** `False` ## arena env validate Validate a GEM environment on Arena. Pass NAME to validate an already-registered environment. Pass --source to register and validate in one step. NAME is always required and is never inferred from --source. ### Usage ```shell arena env validate [OPTIONS] NAME ``` ### Options ### --version Version to validate. Omit for the latest, or v1 when --source registers a new environment. ### --source Path to environment source directory or .tar.gz archive. ### --env-config Path to env_config.yaml file. ### --requirements Path to requirements.txt file. ### --entrypoint Optional entrypoint override. Useful when multiple entrypoints exist. ### --description Optional description of the environment. ### --do-rollouts, --no-do-rollouts Also run sample episodes against the environment and report them. * **Default:** `False` ### Arguments ### NAME Required argument # cli/commands/experiments.md # arena experiments Manage experiments (training jobs) by name. ### Usage ```shell arena experiments [OPTIONS] COMMAND [ARGS]... ``` ## arena experiments checkpoints List checkpoints for an experiment. ### Usage ```shell arena experiments checkpoints [OPTIONS] EXPERIMENT_NAME ``` ### Options ### --project Project, when the experiment name exists in more than one; the default project is used only then. ### Arguments ### EXPERIMENT_NAME Required argument ## arena experiments list List experiments in a project. ### Usage ```shell arena experiments list [OPTIONS] ``` ### Options ### --project Project whose experiments should be listed (defaults to the default project in ~/.arena/config.json). ## arena experiments logs Print an experiment’s training logs, then why it failed if it did. With --json, prints one JSON object per log line, then one object with the experiment’s final status and failure_reason. ### Usage ```shell arena experiments logs [OPTIONS] EXPERIMENT_NAME ``` ### Options ### --tail Show only the newest N lines. ### -f, --follow Keep printing new lines until the experiment ends. ### --level Lowest severity to show (default info). * **Options:** info | warning | error ### --project Project, when the experiment name exists in more than one; the default project is used only then. ### Arguments ### EXPERIMENT_NAME Required argument ## arena experiments metrics Download metrics for an experiment by name. ### Usage ```shell arena experiments metrics [OPTIONS] EXPERIMENT_NAME ``` ### Options ### --metric Metric to download. Omit to request all metrics. Repeat for multiple. ### --output-file Destination file path. Defaults to a name derived from the experiment. ### --overwrite Replace the destination file if it already exists. ### --preview-rows When CSV is returned, preview this many rows in a rich table. * **Default:** `5` ### --project Project, when the experiment name exists in more than one; the default project is used only then. ### Arguments ### EXPERIMENT_NAME Required argument ## arena experiments resume Resume an experiment by name. Prints the hardware, hourly rate and estimated total first, then asks to go on. --yes skips the question; without a terminal on stdin, --yes is required. --dry-run prints the price and resumes nothing. ### Usage ```shell arena experiments resume [OPTIONS] EXPERIMENT_NAME ``` ### Options ### --max-steps **Required** Total training steps, counted from the start of the original run; must be greater than the checkpoint’s step. ### --checkpoint Checkpoint to resume from. Omit it to use the best checkpoint. ### --new-name Name for the resumed experiment. ### --project Project, when the experiment name exists in more than one; the default project is used only then. ### -y, --yes Resume without asking to confirm the price. ### --dry-run Print the hardware and estimated price, then stop without resuming. ### Arguments ### EXPERIMENT_NAME Required argument ## arena experiments status Show an experiment’s status and, if it failed, why. ### Usage ```shell arena experiments status [OPTIONS] EXPERIMENT_NAME ``` ### Options ### --project Project, when the experiment name exists in more than one; the default project is used only then. ### Arguments ### EXPERIMENT_NAME Required argument ## arena experiments stop Stop a running experiment by name (same as the platform training job name). ### Usage ```shell arena experiments stop [OPTIONS] EXPERIMENT_NAME ``` ### Options ### --project Project, when the experiment name exists in more than one; the default project is used only then. ### Arguments ### EXPERIMENT_NAME Required argument ## arena experiments submit Submit an experiment from a manifest. Prints the hardware, hourly rate and estimated total first, then asks to go on. --yes skips the question; without a terminal on stdin, --yes is required. --dry-run prints the price and submits nothing. ### Usage ```shell arena experiments submit [OPTIONS] MANIFEST ``` ### Options ### --num-gpus Total GPUs. Arena uses the fewest nodes that fit the run’s memory estimate. Omit both GPU flags to let Arena pick the cheapest fit. ### --gpu-type Short GPU name such as h100-80, b200 or l4. Omit both GPU flags to let Arena pick the cheapest fit. ### --project Project to submit the experiment to (defaults to the default project in ~/.arena/config.json). ### --experiment-name Name of the experiment. ### --reward-file Python rubric or reward function scoring a rollout job (multipart submit). Required when the manifest targets a reasoning dataset. ### --completion Model completion for reward validation. Defaults to the reference answer from the first dataset row when omitted. ### --idempotency-key Reuse this key to replay the same submit instead of starting another job. ### -y, --yes Submit without asking to confirm the price. ### --dry-run Print the hardware and estimated price, then stop without submitting. ### Arguments ### MANIFEST Required argument # cli/commands/login.md # arena login Sign in through the browser. Ends the saved login, so it also switches user or environment. ### Usage ```shell arena login [OPTIONS] ``` ### Options ### --timeout Maximum seconds to wait for device authorization. * **Default:** `300` # cli/commands/logout.md # arena logout Log out and clear persisted credentials. ### Usage ```shell arena logout [OPTIONS] ``` # cli/commands/manifest.md # arena manifest Validate a training manifest, or print its JSON Schema. ### Usage ```shell arena manifest [OPTIONS] COMMAND [ARGS]... ``` ## arena manifest schema Print the training manifest JSON Schema. ### Usage ```shell arena manifest schema [OPTIONS] ``` ## arena manifest template Print Arena’s default manifest for ALGORITHM as YAML, ready to edit. ### Usage ```shell arena manifest template [OPTIONS] ALGORITHM ``` ### Options ### --model Catalog model id (Hugging Face) to fine-tune. ### --dataset Dataset name to fill in. ### --env Arena environment name to fill in, from arena env list. ### --env-version Environment version; required with --env-entrypoint. Omit for the latest. ### --env-entrypoint Entrypoint to fill in, from arena env entrypoints. ### --section
Print one section instead of the whole manifest. * **Options:** algorithm | environment | network | replay_buffer | training ### Arguments ### ALGORITHM Required argument ## arena manifest validate Validate MANIFEST (a path, or - for stdin) against the contract. ### Usage ```shell arena manifest validate [OPTIONS] MANIFEST ``` ### Options ### --payload Print the resolved manifest. ### --json Report the verdict as one JSON document on stdout and exit 0 for either verdict; a non-zero exit then means the tool itself failed. ### Arguments ### MANIFEST Required argument # cli/commands/memory.md # arena memory Estimate GPU memory, or solve one setting against a card. ### Usage ```shell arena memory [OPTIONS] COMMAND [ARGS]... ``` ## arena memory estimate Size MANIFEST (a training manifest path) against a GPU. Run settings come from the manifest; name the device with --gpu (a GPU type from arena resources list) or --device-gb. MANIFEST - reads stdin. Arena runs the estimate, so this needs a login. ### Usage ```shell arena memory estimate [OPTIONS] MANIFEST ``` ### Options ### --gpu Training GPU: a GPU type from arena resources list such as ‘h100-80’, or a name such as ‘NVIDIA L4’. ### --device-gb Training GPU memory in GiB, for a GPU the catalogue does not know. ### --num-gpus GPUs on the node the run gets. Needed when the run picks tensor_parallel_size or max_num_seqs from it. ### --json Emit the full estimate as JSON instead of the report. ### --no-color Plain glyphs instead of colour (also honours NO_COLOR). ### Arguments ### MANIFEST Required argument ## arena memory solve Solve max_model_len for MANIFEST: the largest context that still fits, given everything else. Arena runs the solve for models in its catalog, so this needs a login. ### Usage ```shell arena memory solve [OPTIONS] {max_model_len} MANIFEST ``` ### Options ### --gpu GPU: a GPU type from arena resources list such as ‘h100-80’, or a name such as ‘NVIDIA L4’. ### --device-gb GPU memory in GiB, for a GPU the catalogue does not know. ### --num-gpus GPUs on the node the run gets. Needed when the run picks tensor_parallel_size or max_num_seqs from it. ### --hi Search ceiling; also capped at the checkpoint’s RoPE limit. ### --json Emit the solve result as JSON instead of the report. ### --no-color Plain glyphs instead of colour (also honours NO_COLOR). ### Arguments ### FIELD Required argument ### MANIFEST Required argument # cli/commands/models.md # arena models List HuggingFace models in the Arena catalog. ### Usage ```shell arena models [OPTIONS] COMMAND [ARGS]... ``` ## arena models info Fetch LoRA modules and catalog metadata for a model. ### Usage ```shell arena models info [OPTIONS] MODEL_NAME ``` ### Arguments ### MODEL_NAME Required argument ## arena models list List HuggingFace models in the Arena catalog. LoRA modules and ranks for one model: `arena models info MODEL_NAME`. ### Usage ```shell arena models list [OPTIONS] ``` ## arena models supported Print every supported model’s static info as JSON (no server call). ### Usage ```shell arena models supported [OPTIONS] ``` # cli/commands/projects.md # arena projects Manage your projects in Arena. ### Usage ```shell arena projects [OPTIONS] COMMAND [ARGS]... ``` ## arena projects create Create a new LLM project in Arena. * **param name:** The name of the project. * **type name:** str * **param description:** The description of the project. * **type description:** str | None * **returns:** A dictionary containing the created project. * **rtype:** dict[str, Any] ### Usage ```shell arena projects create [OPTIONS] NAME ``` ### Options ### --description Description of the project. ### Arguments ### NAME Required argument ## arena projects delete Delete a project in Arena. ### Usage ```shell arena projects delete [OPTIONS] NAME ``` ### Options ### --yes Confirm deletion without interactive prompt. ### Arguments ### NAME Required argument ## arena projects get-default Show the current default project. ### Usage ```shell arena projects get-default [OPTIONS] ``` ## arena projects list List all projects in Arena. ### Usage ```shell arena projects list [OPTIONS] ``` ## arena projects set-default Set the default project for commands that accept --project. ### Usage ```shell arena projects set-default [OPTIONS] NAME ``` ### Arguments ### NAME Required argument # cli/commands/resources.md # arena resources List the GPU types and GPU counts you can train on. ### Usage ```shell arena resources [OPTIONS] COMMAND [ARGS]... ``` ## arena resources list List the GPU types you can train on, with the --num-gpus values each takes. ### Usage ```shell arena resources list [OPTIONS] ``` ### Options ### --algorithm The run’s algorithm.name, e.g. GRPO. Lists only the GPU counts it trains on. Without it, lists what LLM training accepts, single GPUs included. # cli/commands/secrets.md # arena secrets Manage your organization’s secrets in Arena. A manifest’s `judge.api_key_env` names one of these secrets; Arena passes it to the training job as an environment variable of that name. ### Usage ```shell arena secrets [OPTIONS] COMMAND [ARGS]... ``` ## arena secrets delete Delete secret NAME. ### Usage ```shell arena secrets delete [OPTIONS] NAME ``` ### Options ### --yes Confirm deletion without interactive prompt. ### Arguments ### NAME Required argument ## arena secrets list List your organization’s secrets. Values are never shown. ### Usage ```shell arena secrets list [OPTIONS] ``` ## arena secrets set Create or replace secret NAME. The value comes from --from-env, from stdin when piped, or from a hidden prompt. It is never accepted as an argument. ### Usage ```shell arena secrets set [OPTIONS] NAME ``` ### Options ### --from-env Read the value from this local environment variable. ### Arguments ### NAME Required argument # cli/commands/user.md # arena user Retrieve user / account information. ### Usage ```shell arena user [OPTIONS] COMMAND [ARGS]... ``` ## arena user credits Show the balance and the cost running jobs have accrued but not been charged. --ledger lists each charge by job and deployment instead. ### Usage ```shell arena user credits [OPTIONS] ``` ### Options ### --ledger List charges and credits, newest first, with the balance after each. ### --job With --ledger: one job only. ### --deployment With --ledger: one deployment only. ### --limit With --ledger: most entries. ## arena user profile Get current authenticated user profile. ### Usage ```shell arena user profile [OPTIONS] ``` # cli/install.md # Install and sign in Install the `arena` command and the Python client, then sign in so they act as you in your organization. ## Install `agilerl` supports Python 3.10 to 3.13. From 3.0, `agilerl` is the Arena CLI and Python client. It no longer contains the open-source AgileRL reinforcement learning framework (`agilerl` 2.x), and installing it replaces that framework in the same environment. Install the CLI with [uv](https://docs.astral.sh/uv/getting-started/installation/). `uv tool install` puts the `arena` command in its own environment, so it leaves an `agilerl` 2.x framework you have elsewhere alone: ```bash uv tool install agilerl arena --help ``` For the Python client inside a project, run `uv add agilerl`. That installs into the project’s environment, so in a project that uses the framework, keep it pinned to `agilerl<3` and use the client from a separate project. If you don’t use uv, `pip install -U agilerl` in a new virtual environment still works. ### Moving from agilerl-arena `agilerl` replaces the `agilerl-arena` package. Both ship the `arena` command, so remove `agilerl-arena` before you install `agilerl`. If you installed it as a uv tool: ```bash uv tool uninstall agilerl-arena && uv tool install agilerl ``` In a uv project: ```bash uv remove agilerl-arena && uv add agilerl ``` If you installed it with pip, run this in the environment that has `agilerl-arena`. Uninstalling `agilerl-arena` removes the `arena` command; `--force-reinstall` puts it back even when `agilerl` is already installed. This replaces an `agilerl` 2.x framework in that environment. ```bash pip uninstall -y agilerl-arena && pip install -U --force-reinstall agilerl ``` Then change Python imports from `agilerl.arena` to `agilerl` (`from agilerl import ArenaClient`). ## Sign in Sign in one of two ways: - **`arena login`** on a machine with a browser. Use this on your laptop. - **`ARENA_API_KEY`** where there is no browser: CI, scheduled jobs, remote machines and coding agents. ### Sign in with the browser ```bash arena login ``` The CLI opens a browser sign-in and saves the session in `~/.arena/credentials.json`, so you sign in once per machine. One login is kept at a time: running `arena login` again replaces it, which is also how you switch user. `arena logout` clears it. Run `arena login` again when a command fails with a sign-in error. ### Sign in with an API key Create a key in the web app under **Settings** → **Profile management** → **CLI API key** (steps in [CLI API key](account/account.md#cli-api-key)), then export it wherever the CLI runs: ```bash export ARENA_API_KEY='arena_pat_...' ``` The key acts as you, in the organization you have selected in the web app. When `ARENA_API_KEY` is set, every command uses it, even after `arena login`. Unset it to go back to your browser session. ### Sign in from Python `ArenaClient` finds credentials the same way the CLI does: an `api_key` argument first, then `ARENA_API_KEY`, then the login saved by `arena login`. ```python from agilerl import ArenaClient client = ArenaClient() # ARENA_API_KEY or the saved login client = ArenaClient(api_key="arena_pat_...") # an explicit key client.login() # browser sign-in, saved for later runs ``` The methods are listed in [Python client](cli/python-client.md). ## Check you’re signed in ```bash arena user profile ``` This prints your name and email. In Python, call `client.get_current_user()`. ## Upgrade ```bash uv tool upgrade agilerl ``` With pip, run `pip install -U agilerl` instead. When Arena needs a newer client than the one you have, the CLI offers to upgrade and then runs your command again. Set `ARENA_AUTO_UPGRADE=1` to upgrade without the question, for example in CI. The automatic upgrade uses pip, which a `uv tool` environment doesn’t have, so if it fails there, run `uv tool upgrade agilerl` yourself. ## Next Each guide shows the CLI command next to the web app steps, and the [command reference](cli/command-reference.md) lists every command. To have a coding agent run them for you, see [Using Arena from a coding agent](cli/coding-agents.md). # cli/manifest-schema.md # Run spec and manifest schema Every field of the training manifest that `arena experiments submit` and `ArenaClient.submit_experiment` take. The page is generated from the `agilerl` version Arena currently supports. `arena manifest template` prints a manifest with Arena’s defaults to start from, and `arena manifest validate` checks one before you submit. `arena manifest schema` prints the same contract as JSON Schema. A manifest is a YAML or JSON file with these top-level sections: | Section | What it holds | |-----------------------------------|---------------------------------------------------------------------------------| | `apiVersion` | Contract version the manifest is written against. Defaults to `agilerl.com/v1`. | | [`algorithm`](#algorithm) | Which algorithm trains (`name`, for example `GRPO`) and its hyperparameters. | | [`environment`](#environment) | The dataset or environment the model trains on. | | [`training`](#training) | How long to train, evaluation, checkpoints and rollout layout. | | [`network`](#network) | The base model and its LoRA settings. | | [`replay_buffer`](#replay-buffer) | Where rollouts wait before the trainer learns from them. | Fields a model leaves out take the defaults shown. Fields marked as picked from the memory estimate are set by Arena; a manifest cannot set them. ## algorithm `algorithm.name` picks the algorithm: `GRPO`, `GSPO`, `CISPO`, `LLMPPO`, `LLMREINFORCE`, `OPD`, `DPO` or `SFT`. Which one fits which data is on [Algorithms](reference/algorithms.md). Every algorithm takes the common fields below. The model itself goes under [`network`](#network): `pretrained_model_name_or_path`, `max_context_length` and `lora_config`. ### *class* LLMAlgorithmSpec LLM fine-tuning algorithms. `pretrained_model_name_or_path`, `weights_path`, `max_model_len` and `lora_config` are written under the manifest’s `network` section and lifted onto the algorithm when the manifest is validated. #### *field* answer_continuation *: bool* *= False* After the thinking budget runs out, continue into the answer instead of ending the episode. #### *field* batch_size *: int* *= 16* Prompts sampled per step; the rollout batch is batch_size x group_size. #### *field* beta *: float* *= 0.001* Weight on the KL penalty holding the policy near the reference model. 0 disables the penalty entirely. #### *field* calc_position_embeddings *: bool* *= True* Compute position embeddings in the forward pass. Turn off only for models that build their own. #### *field* constrain_answer_pattern *: str | None* *= None* Regex grammar for vLLM structured outputs on each turn, or on an answer continuation when answer_continuation is enabled. #### *field* fsdp *: Annotated[FSDPConfig | None, WithJsonSchema(FSDP_JSON_SCHEMA)]* *= None* FSDP2 shard config. Omitted, true or {}: the run trains the faster plan that fits, DDP when the model fits one GPU with an equal-or-cheaper plan, else FSDP. Setting ep or tp above 1 keeps FSDP. #### *field* gradient_checkpointing *: bool | None* *= None* Recompute block activations during the backward pass instead of storing them. Affects only memory and speed, not what the run learns. Picked from the memory estimate together with the micro-batch and fsdp.checkpoint_every_n_blocks, least recompute that fits; on when the run has no estimate. Manifests cannot set it. #### *field* max_grad_norm *: float* *= 0.1* Gradients are clipped to this global norm before each step. #### *field* micro_batch_size_per_gpu *: int | None* *= None* Trajectories per backward pass, per GPU. Affects only memory: it changes what fits, not what the run learns. Picked from the memory estimate as the largest that fits; manifests cannot set it. #### *field* mini_batch_size *: int | None* *= None* Trajectories one optimizer step covers, per rank. Must be a whole number of micro-batches. This is a learning-cadence decision, not a memory one: it sets how often the policy moves. #### *field* quantization *: str | dict[str, Any] | None* *= None* Trainer-side bitsandbytes quantization: a preset name such as ‘nf4’, or BitsAndBytesConfig keyword arguments. #### *field* routed_expert_chunk_mib *: int | None* *= None* MiB of the widest activation of one routed-expert row chunk under DDP; FSDP runs use fsdp.routed_expert_chunk_mib. Picked from the memory estimate; manifests cannot set it. None on a MoE model picks the largest of 512/256/128/64 whose estimated training peak fits; unpicked, the trainer uses 64. #### *field* seed *: int* *= 42* Seed for sampling, data order and initialization. #### *field* thinking_token_budget *: int | None* *= None* Tokens the model may spend reasoning before it has to answer. Unset leaves reasoning length unconstrained. #### *field* update_epochs *: int* *= 1* Optimizer passes over each batch of collected rollouts. #### *field* use_separate_reference_adapter *: bool* *= True* Hold the reference policy in its own frozen LoRA adapter rather than the base weights. #### *field* vllm_engine_args *: dict[str, Any]* *[Optional]* Engine arguments forwarded to vLLM verbatim. #### *field* vllm_lora_export_dir *: str | None* *= None* Directory the trainer writes LoRA adapters to for vLLM to pick up. Unset uses the run’s default adapter root. ### Reinforcement learning algorithms GRPO, GSPO, CISPO, OPD, LLMPPO and LLMREINFORCE generate answers and learn from their rewards. They share these fields on top of the common ones. ### *class* RolloutLLMSpec Bases: [`LLMAlgorithmSpec`](cli/manifest-schema.md#agilerl.models.algorithms.base.LLMAlgorithmSpec) Shared surface for the LLM algorithms that generate their own rollouts. #### *field* beta *: float* *= 0.001* Weight on the KL penalty holding the policy near the reference model. 0 disables the penalty entirely. #### *field* cosine_lr_schedule_config *: [CosineLRScheduleConfig](cli/manifest-schema.md#agilerl.models.networks.CosineLRScheduleConfig) | None* *= None* Learning-rate schedule stepped once per training step: linear warmup to each learning rate (actor and critic alike), then cosine decay to min_lr_ratio of it. The LLMPPO actor’s schedule starts after critic_warmup_steps. On the cluster, unset or null warms up over 5% of training.max_steps and decays to 10%. For a constant learning rate, set warmup_proportion 0 and min_lr_ratio 1.0. #### *field* max_output_tokens *: int | None* *= None* Hard cap on tokens generated per completion. #### *field* max_row_tokens *: int | None* *= None* Longest training row, prompt plus completion, that the trainer’s memory estimate sizes for. Unset uses max_model_len. An environment with segment_prompt_tokens sets it to segment_prompt_tokens plus max_output_tokens (twice max_output_tokens with answer_continuation), capped at max_model_len; rollouts never produce a longer row. #### *field* micro_batch_size_per_gpu *: int | None* *= None* Trajectories per backward pass, per GPU. Affects only memory: it changes what fits, not what the run learns. Picked from the memory estimate as the largest that fits; manifests cannot set it. #### *field* micro_batch_tokens_per_gpu *: int | None* *= None* Tokens per packed backward pass, per GPU, when the forward packs sequences. Rows fill each pass up to this many tokens; a longer row runs alone. Affects only memory and speed, not what the run learns. Picked from the memory estimate as the fastest budget that fits; manifests cannot set it. #### *field* min_output_tokens *: int | None* *= None* Floor on tokens generated per completion. Unset lets the model stop as soon as it emits an end-of-sequence token. #### *field* min_p *: float* *= 0.0* Drop tokens whose probability is below this fraction of the most likely token’s probability. #### *field* mini_batch_size *: int | None* *= None* Trajectories one optimizer step covers, per rank. Must be a whole number of micro-batches. This is a learning-cadence decision, not a memory one: it sets how often the policy moves. #### *field* reference_update_interval *: int | None* *= None* Optimizer steps between copies of the policy onto the reference model the KL penalty holds it near. Unset keeps the reference fixed. #### *field* repetition_penalty *: float* *= 1.0* Penalty applied to tokens already generated, to discourage loops. #### *field* temperature *: float* *= 0.9* Sampling temperature for generation. Higher values diversify rollouts. The trainer divides logits by this, so it has to be above 0. #### *field* top_k *: int* *= 50* Keep only the K most likely next tokens at each generation step. #### *field* top_p *: float* *= 1.0* Nucleus sampling: keep the smallest set of tokens whose probability sums to this value. #### *field* vllm_config *: [VLLMConfig](cli/manifest-schema.md#agilerl.models.networks.VLLMConfig) | None* *= None* vLLM engine settings for generation. #### *field* vllm_importance_sampling_cap *: float* *= 2.0* Trainer/vLLM ratio at which the sampling-mismatch metrics count a token as clipped. #### *field* vllm_max_clip_fraction *: float* *= 0.02* Warn when the share of tokens whose trainer/vLLM ratio reaches the importance-sampling cap exceeds this. bf16 engines usually stay under 0.01. #### *field* vllm_max_logprob_gap *: float* *= 0.1* Warn when the mean per-token log-prob gap between vLLM and the trainer exceeds this, in nats. bf16 engines usually sit near 0.01-0.03. ### *class* CosineLRScheduleConfig Model specification for cosine LR schedule configuration. #### *field* min_lr_ratio *: float* *= 0.1* Floor as a fraction of the peak learning rate, held after num_steps. #### *field* num_steps *: int* *[Required]* Training steps (learn calls) from the start of warmup to the floor. #### *field* warmup_proportion *: float* *= 0.0* Fraction of num_steps spent ramping the learning rate up to its peak. ### *class* VLLMConfig Model specification for vLLM configuration. #### *field* dtype *: str | None* *= None* Weight dtype for generation, e.g. bfloat16. Unset lets vLLM choose. #### *field* frequency_penalty *: float* *= 0.0* Penalty on tokens in proportion to how often they appeared. #### *field* gpu_memory_utilization *: float | None* *= None* Share of GPU memory vLLM reserves for weights and KV cache. When generation is colocated with training, this has to leave room for the trainer. Unset is 0.9 on a rollout engine, which has its GPUs to itself, and 0.3 colocated. #### *field* kv_cache_dtype *: str | None* *= None* KV cache dtype, e.g. fp8. Fits a longer context into the same memory. #### *field* limit_mm_per_prompt *: dict[str, Annotated[int, Field(ge=0)]] | None* *= None* Most items of each modality one prompt may carry, e.g. {image: 4, video: 0}. Unset keeps vLLM’s limit. #### *field* lora_staging_dir *: str | None* *= None* Directory the engine reads LoRA adapters from. #### *field* max_num_batched_tokens *: int | None* *= None* Tokens vLLM may process in one scheduler pass. Unset lets the trainer size it; raising it speeds up long prefills but costs memory. #### *field* max_num_seqs *: int | None* *= None* Sequences vLLM decodes concurrently. Set it to at least group_size so a GRPO group does not queue. Unset gives colocated generation 16 and each rollout engine one sequence per episode it runs at once (rollout_batch_size / rollout_engines_per_agent, rounded up, x group_size). #### *field* presence_penalty *: float* *= 0.0* Penalty on tokens that already appeared, at any count. #### *field* quantization *: str | None* *= None* Quantization applied to the generation engine, e.g. fp8. Unset or none serves unquantized weights. #### *field* stop_sequences *: list[str] | None* *= None* Strings that end a completion when generated. #### *field* tensor_parallel_size *: int | None* *= None* GPUs the model is sharded across for generation. Unset until the allocation’s memory estimate chooses a width. An explicit integer is kept. #### *field* vllm_model_name_or_path *: str | None* *= None* Serve generation from a different checkpoint than the trainer fine-tunes. ### Fields for each algorithm Each algorithm adds the fields below to those of the class it builds on. ### *class* GRPOSpec Bases: [`RolloutLLMSpec`](cli/manifest-schema.md#agilerl.models.algorithms.rollout_llm.RolloutLLMSpec) Group Relative Policy Optimization. #### *field* adv_clip_range *: float | None* *= None* Clip advantages to +/- this value. Unset leaves them unclipped. #### *field* adv_filter_eps *: float* *= 0.0* With filter_zero_adv, also drop groups whose largest absolute advantage is below this threshold. #### *field* adv_norm *: Literal['mean_only', 'mean_std']* *= 'mean_only'* How group advantages are normalized. ‘mean_only’ subtracts the group mean; ‘mean_std’ also divides by its standard deviation. #### *field* advantage_granularity *: Literal['auto', 'trajectory', 'turn']* *= 'auto'* Level the advantage is computed at. ‘auto’ follows the environment: per-turn for multi-turn, per-trajectory otherwise. #### *field* clip_coef *: float* *= 0.2* Clipping range of the policy-ratio surrogate. Caps how far one update may move the policy from the behaviour that collected the data. #### *field* filter_zero_adv *: bool* *= False* Drop groups whose completions all scored the same. They contribute no gradient, so training on them only costs compute. #### *field* group_size *: int* *= 8* Completions sampled per prompt. The group is what the advantage is computed relative to, so this is the main GRPO setting to tune. #### *field* importance_sampling_level *: Literal['token', 'turn', 'trajectory'] | None* *= None* Level the importance-sampling ratio is computed at. Coarser levels are lower variance but a blunter correction. Turn-level uses a geometric-mean ratio per reply. #### *field* kl_clamp *: float | None* *= 10.0* Per-token bound on the K3 KL penalty. 10 is the policy about 2.6 nats below the reference on a token; tokens further below get no KL gradient, so one diverged token cannot set the step’s gradient norm. Tokens above the reference keep their KL pull. Unset removes the bound. #### *field* loss_norm *: Literal['micro_batch', 'accumulation_window', 'episode']* *= 'accumulation_window'* Token count the loss is averaged over: the whole accumulation window across all data-parallel ranks (default), or each micro-batch on its own. The window is the unbiased choice when micro-batches have uneven lengths. ‘episode’ gives every episode of the window the same total policy weight, averaging tokens within an episode, so long episodes do not outweigh short ones. #### *field* loss_type *: Literal['grpo', 'gspo', 'cispo']* *= 'grpo'* Policy-gradient loss variant. GSPO and CISPO pin this on their own specs. #### *field* lr *: float* *= 5e-07* Optimizer learning rate. #### *field* off_policy_sequence_mask_threshold *: float | None* *= 0.03* Drop the policy and KL gradient of negative-advantage completions whose mean log(sampling / current) log-prob gap exceeds this (DeepSeek-V3.2 off-policy sequence masking). Set null to mask nothing. GSPO leaves this unset. #### *field* off_policy_token_mask_bounds *: tuple[float, float] | None* *= (0.5, 5.0)* (low, high) band on each token’s ratio of the current policy to the policy that sampled it. Tokens outside get no policy or KL gradient (IcePop). Set null to mask nothing. GSPO leaves this unset. #### *field* profiling_config *: ProfilingConfig | None* *= None* Opt-in learn profiling: CUDA memory snapshot on OOM and a torch.profiler trace of one micro-batch. Unset profiles nothing. #### *field* turn_advantage_trajectory_fallback *: bool* *= True* Fall back to a trajectory-level advantage when per-turn credit cannot be assigned. #### *field* use_bias_correction_kl *: bool* *= True* Weight the per-token KL by the importance ratio to the old policy so its gradient is unbiased off-policy (DeepSeek-V3.2). #### *field* use_kl_advantage_shaping *: bool* *= False* Fold the KL penalty into the advantage instead of adding it as a separate loss term. #### *field* whiten_advantages *: bool* *= False* Normalize advantages to zero mean and unit variance across the batch. ### *class* GSPOSpec Bases: [`GRPOSpec`](cli/manifest-schema.md#agilerl.models.algorithms.grpo.GRPOSpec) GRPO with the GSPO sequence-level loss. #### *field* loss_type *: Literal['gspo']* *= 'gspo'* GSPO’s sequence-level loss. ### *class* CISPOSpec Bases: [`GRPOSpec`](cli/manifest-schema.md#agilerl.models.algorithms.grpo.GRPOSpec) GRPO with the CISPO loss and asymmetric clip bounds. #### *field* loss_type *: Literal['cispo']* *= 'cispo'* CISPO’s clipped importance-sampling loss. ### *class* LLMPPOSpec Bases: [`RolloutLLMSpec`](cli/manifest-schema.md#agilerl.models.algorithms.rollout_llm.RolloutLLMSpec) Proximal policy optimization for LLM fine-tuning, with a value head. #### *field* advantage_granularity *: Literal['turn', 'token', 'auto']* *= 'auto'* Level the advantage is computed at. ‘turn’ enforces turn-level updates, ‘token’ token-level, and ‘auto’ uses token-level only when every sample is single-turn. #### *field* beta *: float* *= 0.001* Weight on the KL penalty holding the policy near the reference model. 0 disables the penalty entirely. #### *field* clip_coef *: float* *= 0.2* Clipping range of the policy-ratio surrogate. Caps how far one update may move the policy from the behaviour that collected the data. #### *field* critic_warmup_steps *: int* *= 0* Learn steps at the start of training that train only the critic, on Monte Carlo returns of the fixed initial policy, before LLMPPO updates the policy. Resuming from a checkpoint continues the count. #### *field* gae_lambda *: float* *= 1.0* Generalized advantage estimation trace decay, trading bias against variance. 1.0 is plain Monte-Carlo returns. #### *field* gamma *: float* *= 1.0* Discount factor applied across turns. #### *field* importance_sampling_level *: Literal['auto', 'token', 'turn', 'trajectory']* *= 'auto'* Level the importance-sampling ratio is computed at. Coarser levels are lower variance but a blunter correction. Turn-level uses a geometric-mean ratio per reply. #### *field* kl_clamp *: float | None* *= 10.0* Per-token bound on the K3 KL penalty. 10 is the policy about 2.6 nats below the reference on a token; tokens further below get no KL gradient, so one diverged token cannot set the step’s gradient norm. Tokens above the reference keep their KL pull. Unset removes the bound. #### *field* lr_actor *: float* *= 1e-05* Optimizer learning rate for the actor (policy) network. #### *field* lr_critic *: float | None* *= 0.0001* Optimizer learning rate for the critic (value) network. #### *field* max_grad_norm *: float* *= 1.0* Actor and critic gradients are each clipped to this norm before each step. #### *field* off_policy_token_mask_bounds *: tuple[float, float] | None* *= (0.5, 5.0)* (low, high) band on each token’s ratio of the current policy to the rollout policy that sampled it. Tokens outside get no policy gradient (IcePop). Set null to mask nothing. #### *field* share_grad_clip *: bool* *= False* Clip actor and critic gradients by one coefficient from their combined norm. #### *field* temperature *: float* *= 1.0* Sampling temperature for generation. Higher values diversify rollouts. The trainer divides logits by this, so it has to be above 0. #### *field* top_p *: float* *= 1.0* Nucleus sampling: keep the smallest set of tokens whose probability sums to this value. #### *field* turn_level_clip *: bool* *= True* Apply the surrogate clip per turn rather than per token. #### *field* vf_coef *: float* *= 0.5* Weight on the value-function loss in the combined objective. #### *field* whiten_advantages *: bool* *= True* Normalize advantages to zero mean and unit variance across the batch. ### *class* LLMREINFORCESpec Bases: [`RolloutLLMSpec`](cli/manifest-schema.md#agilerl.models.algorithms.rollout_llm.RolloutLLMSpec) REINFORCE with return batch normalization. #### *field* advantage_granularity *: Literal['turn', 'token', 'auto']* *= 'auto'* Level the advantage is computed at. ‘turn’ enforces turn-level updates, ‘token’ token-level, and ‘auto’ uses token-level only when every sample is single-turn. #### *field* beta *: float* *= 0.001* Weight on the KL penalty holding the policy near the reference model. 0 disables the penalty entirely. #### *field* clip_coef *: float* *= 0.2* Clipping range of the policy-ratio surrogate. Caps how far one update may move the policy from the behaviour that collected the data. #### *field* gamma *: float* *= 1.0* Discount factor applied across turns. #### *field* importance_sampling_level *: Literal['token', 'turn', 'trajectory']* *= 'token'* Level the importance-sampling ratio is computed at. Coarser levels are lower variance but a blunter correction. Turn-level uses a geometric-mean ratio per reply. #### *field* lr *: float* *= 1e-05* Optimizer learning rate. #### *field* max_grad_norm *: float* *= 1.0* Gradients are clipped to this global norm before each step. #### *field* off_policy_token_mask_bounds *: tuple[float, float] | None* *= (0.5, 5.0)* (low, high) band on each token’s ratio of the current policy to the rollout policy that sampled it. Tokens outside get no policy gradient (IcePop). Set null to mask nothing. #### *field* temperature *: float* *= 1.0* Sampling temperature for generation. Higher values diversify rollouts. The trainer divides logits by this, so it has to be above 0. #### *field* top_p *: float* *= 1.0* Nucleus sampling: keep the smallest set of tokens whose probability sums to this value. ### *class* OPDSpec Bases: [`GRPOSpec`](cli/manifest-schema.md#agilerl.models.algorithms.grpo.GRPOSpec) GRPO whose per-token advantage adds the teacher’s log-prob gap to the policy’s. #### *field* beta *: float* *= 0.0* Weight on the KL penalty holding the policy near the reference model. 0 disables the penalty entirely. #### *field* group_size *: int* *= 4* Completions sampled per prompt. The group is what the advantage is computed relative to, so this is the main GRPO setting to tune. With no task reward the teacher term is the whole update, and a group of 1 spends the same samples on more prompts. #### *field* teacher *: [DistillationTeacherConfig](cli/manifest-schema.md#agilerl.models.distillation.DistillationTeacherConfig)* *[Optional]* The model that scores every rollout: by default the live policy, given each task’s reference trace; else teacher.adapter, teacher.base or teacher.model. The per-token gap is added to the task advantage. #### *field* temperature *: float* *= 1.0* Sampling temperature. The teacher scores the unmodified policy, so this stays 1. #### *field* top_k *: int* *= 0* Keep only the K most likely next tokens at each generation step. ### *class* DistillationTeacherConfig The model that scores each rollout; the per-token gap is the distillation advantage. By default the teacher is the live policy, given each task’s reference trace in a leading system message. With `adapter` it is the student’s base model under that frozen LoRA adapter, served beside the policy’s adapter in the rollout engines. With `base` it is the student’s base weights without any LoRA, which keeps the policy close to the model it started from. With `model` it is that model, in its own vLLM engine beside each rollout engine. A `context_key` gives any of them the reference. #### *field* adapter *: str | None* *= None* LoRA adapter of the student’s base model that scores rollouts, such as a GRPO run’s checkpoint: a local or s3:// directory holding adapter_config.json, or a checkpoint holding it under actor/. Its rank must fit the student’s network.lora_config.lora_r. The rollout engines serve it frozen beside the policy’s adapter, so weight sync always sends the adapter. #### *field* base *: bool* *= False* Score rollouts with the student’s base weights, without any LoRA, so the policy is pulled back towards the model it started from, such as to recover behaviour an SFT checkpoint lost. Needs no extra GPUs; weight sync always sends the adapter. #### *field* coef *: float* *= 1.0* Weight of the per-token teacher-minus-student log-prob on the advantage. #### *field* context_key *: str | None* *= None* Key of the env reset info holding the task’s reference trace. A dataset-backed rollout reads the dataset column of that name. Unset is ‘reference_trace’ for the live policy, and no reference with a teacher model, adapter or base. #### *field* max_context_tokens *: int* *= 8192* Token budget of the teacher’s system message. A longer reference is cut to fit, and rollout engines reserve this much extra context. #### *field* max_token_gap *: float | None* *= 10.0* Bound, in nats, on each token’s teacher-minus-student log-prob before coef scales it. Tokens the teacher finds near impossible otherwise outweigh the rest of the batch. Null leaves it unbounded. #### *field* model *: [DistillationTeacherModel](cli/manifest-schema.md#agilerl.models.distillation.DistillationTeacherModel) | None* *= None* A separate, usually larger, teacher model. Unset scores in the rollout engines, with teacher.adapter, teacher.base or the live policy. #### *field* template *: str* *= 'A reference solution to the task that follows is given below. Solve the task as that reference does.\\n\\n{reference}'* System message the teacher reads before the rollout; ‘{reference}’ is replaced with the reference trace. ### *class* DistillationTeacherModel A separately hosted model that scores the student’s rollouts. #### *field* pretrained_model_name_or_path *: str* *[Required]* Hub id of the teacher, from the model catalog. It must share the student’s tokenizer vocabulary, since it scores the student’s token ids. #### *field* vllm_config *: [VLLMConfig](cli/manifest-schema.md#agilerl.models.networks.VLLMConfig)* *[Optional]* vLLM settings of the teacher engine. tensor_parallel_size is the GPUs each rollout engine’s teacher adds to the run; unset, the run sizes it from the teacher and the GPU. #### *field* weights_path *: str | None* *= None* Local or s3:// directory to load the teacher’s weights and tokenizer from. pretrained_model_name_or_path then names the catalog model with the same architecture. ### *class* DPOSpec Bases: [`LLMAlgorithmSpec`](cli/manifest-schema.md#agilerl.models.algorithms.base.LLMAlgorithmSpec) Direct Preference Optimization. #### *field* answer_continuation *: bool* *= False* Unused: DPO trains on dataset rows, with no rollout to continue. #### *field* beta *: float* *= 0.1* Weight on the KL penalty holding the policy near the reference model. 0 disables the penalty entirely. #### *field* lr *: float* *= 5e-06* Optimizer learning rate. #### *field* nll_alpha *: float* *= 1.0* Weight on the auxiliary likelihood term over chosen responses, which keeps the model fluent while preferences are optimized. #### *field* reference_update_interval *: int | None* *= None* Optimizer steps between copies of the policy onto the reference model the KL penalty holds it near. Unset keeps the reference fixed. ### *class* SFTSpec Bases: [`LLMAlgorithmSpec`](cli/manifest-schema.md#agilerl.models.algorithms.base.LLMAlgorithmSpec) Supervised fine-tuning. No reference model, so no KL penalty. #### *field* answer_continuation *: bool* *= False* Unused: SFT trains on dataset rows, with no rollout to continue. #### *field* beta *: float* *= 0.001* Unused: SFT has no reference policy to penalise against. #### *field* lr *: float* *= 5e-05* Optimizer learning rate. #### *field* use_separate_reference_adapter *: bool* *= False* Always off: SFT has no reference policy to hold in an adapter. ## environment When you submit, `dataset` names the registered dataset Arena trains on. Without `dataset`, Arena trains on whatever `name` names: a dataset, or an environment. With `dataset` set, `name` is only a label, unless it names a different registered dataset, which submit refuses. Set `name` to the same dataset, or leave it out. ### *class* LLMEnvSpec The dataset or interactive environment an LLM algorithm fine-tunes against. A `rollout` env is generative and comes from exactly one source: * dataset rows plus a rubric — a single-turn env over labelled rows; * `entrypoint` — a callable returning a text env, run where training runs (or on env hosts under the hosting fields, which need the Ray runtime); * `env_url` — an OpenEnv service someone else hosts; * `env_image` — a prebuilt env image the Ray runtime runs as its own Pod. A built-in (`BUNDLED_ENVIRONMENTS`) may name no source. A `dataset` env is teacher-forced over the rows; `objective` picks the loss. #### *field* action_error_field *: str* *= ''* Observation field holding the error text of the action just taken. A restarted context lists it after that action. Empty lists the actions alone. #### *field* action_field *: str | None* *= None* The action field an env receives the model’s text in — message by default, but code or action_str elsewhere; for an MCP tool it is the argument name. #### *field* action_processor *: str | None* *= None* module:fn entrypoint that turns the post- action text into what the env receives. Unset sends that text unchanged. #### *field* adaptive_task_sampling *: bool* *= True* Draw each group’s task row in proportion to how often that row’s recent groups had differing rewards, so tasks that keep giving tied groups are drawn less (Ray async rollouts over task rows only). false keeps the per-epoch shuffle. #### *field* answer_tool *: str | None* *= None* For an MCP-backed env, one of its real tools receiving a turn’s prose when the turn has no tool call. Unset answers such a turn with retry feedback. #### *field* apply_chat_template *: bool* *= True* Render prompts through the tokenizer chat template. Digit-token multi-turn probes set this false and encode observations raw. #### *field* chat_template_kwargs *: dict[str, Any]* *[Optional]* Defaults injected into apply_chat_template, e.g. {‘enable_thinking’: false}. #### *field* chat_template_path *: str | None* *= None* Jinja file whose template replaces the tokenizer’s own. #### *field* columns *: dict[str, str] | None* *= None* Maps your dataset’s column names onto the ones the run expects (question, answer; prompt, target, or multi-turn messages and tools for SFT). Unset assumes they already match. #### *field* cpus_per_env_host *: float | None* *= None* CPUs reserved per env host; an env_image Pod requests them with no CPU limit. #### *field* dataset *: str | None* *= None* HuggingFace dataset id, or a Parquet or JSONL path, for the dataset sources. #### *field* dataset_format *: Literal['traces'] | None* *= None* traces: rows are recorded session segments, OpenAI chat messages in a messages column with optional tools. A rollout renders each target assistant turn’s history as a single-turn prompt and needs no prompt_template; with no rubric_file_path it scores 0, which OPD trains on as pure distillation. objective sft trains every target assistant turn. Takes no columns mapping. #### *field* dataset_path *: str | None* *= None* Object-store path to a user-supplied dataset. #### *field* entrypoint *: str | None* *= None* The env to build: a registry id, or module:Class (or module:attr constructor) for a custom upload. #### *field* env_config *: dict[str, Any] | None* *= None* Keyword arguments forwarded to the factory or constructor after the env id. Not a place for env_id. system_prompt is reserved and set on the built env. #### *field* env_host_memory_bytes *: int | None* *= None* Memory reserved per env host. #### *field* env_host_memory_limit_bytes *: int | None* *= None* Memory limit per env_image Pod. Unset sets no limit. #### *field* env_host_ready_timeout_s *: float | None* *= None* Seconds each env_image session Pod may take to become ready, image pull included. Unset is 600. #### *field* env_host_resource *: str | None* *= None* Where env hosts land: a custom Ray resource, or (for env_image) the Pod nodeSelector — key=value, or a bare pool name. #### *field* env_hosts *: int | None* *= None* Number of env hosts to serve the env on (Ray runtime only). Unset with no image or packages runs an entrypoint in-process in each rollout slot, unless cpus_per_env_host, env_host_memory_bytes or env_host_resource is set, which asks for one host. #### *field* env_image *: str | None* *= None* Prebuilt env image run verbatim as its own Pod per host, serving on env_port (Ray runtime only). #### *field* env_packages *: dict[str, Any] | None* *= None* What the entrypoint needs installed, as {‘uv’: […]} or {‘pip’: […]}. Installed where the env runs the first time the entrypoint is not importable. #### *field* env_port *: int | None* *= None* TCP port the env_image server listens on. #### *field* env_services *: list[[EnvServiceSpec](cli/manifest-schema.md#agilerl.models.env.EnvServiceSpec)]* *[Optional]* Backing services the env_image sessions share, started with the job and deleted with it (Ray runtime on Kubernetes only). #### *field* env_session_ports *: dict[str, int]* *[Optional]* Container environment set to base + session index in each session container, so sessions sharing a Pod bind distinct ports. #### *field* env_sessions_per_host *: int | None* *= None* Sessions per env_image Pod: one container each, serving on env_port, env_port + 1, … Unset is 1. More than 1 needs env_session_ports. #### *field* env_type *: Literal['rollout', 'dataset']* *[Required]* Which LLM regime drives the run: a generative environment the model acts in (rollout), or teacher-forced learning over dataset rows (dataset). #### *field* env_url *: str | list[str] | None* *= None* URL of an already-hosted OpenEnv service. A list is a set of interchangeable replicas dealt across rollout slots. #### *field* env_vars *: dict[str, str]* *[Optional]* Container environment for each env_image Pod. #### *field* factory *: str | None* *= None* Optional module:attr callable that receives the entrypoint as its first argument, e.g. gem:make. Unset constructs entrypoint as a class or callable. #### *field* goal_images_field *: str | None* *= None* Observation field holding the task images that follow the first prompt. Empty or unset reads none. #### *field* group_rubric_name *: str | None* *= None* Name of a GroupRubric in the rubric_file_path module. It scores each finished group of completions together, and each score is added to that completion’s final-turn reward. Leave rubric_name unset to keep the env’s own turn reward. Group replay is off with a group rubric. #### *field* hf_dataset_id *: str | None* *= None* HuggingFace dataset id, when set apart from dataset. #### *field* include_reasoning *: bool | None* *= None* Send the env each turn’s reasoning with its markers, not only the text after the reasoning ends; a Rubric class reads that text as TurnAction.message. Unset sends it over dataset rows and not to an env that runs the action. A reward function gets the whole turn as completion either way. #### *field* judge *: [JudgeSpec](cli/manifest-schema.md#agilerl.models.env.JudgeSpec) | None* *= None* LLM judge handed to the rubric: a Rubric class whose \_\_init_\_ takes judge is built with it. Needs rubric_file_path. #### *field* max_concurrent_resets *: int | None* *= None* Env resets one rollout engine runs at once (Ray runtime only). Unset runs every reset at once; set it to what the env’s backing services can serve. #### *field* max_reward *: float | None* *= None* Reward at which a rollout counts as solved, used for the success metric. #### *field* max_turns *: int | None* *= None* Turn budget per episode. Unset puts no cap on turns: the episode ends when the env terminates or truncates, or when the next prompt no longer fits the model’s context. Required with env_url, segment_prompt_tokens or segment_max_images. #### *field* min_reward *: float | None* *= None* Lowest reward the env gives. Scores a turn whose tool calls are malformed or missing, which never reaches the env. Unset scores 0. #### *field* modality *: Literal['text', 'vision'] | None* *= None* What the env’s observations carry: text only, or text and images (vision). text lets a vision-language model’s rollout engine skip its multimodal towers. Unset is unknown and keeps them. #### *field* name *: str | None* *= None* Catalog / dataset label only. Not the env id. #### *field* num_envs *: int | None* *= None* Ignored for LLM runs: rollout concurrency comes from the batch and group size. #### *field* objective *: Literal['preference', 'sft'] | None* *= None* Teacher-forced loss, required with env_type dataset: sft, or preference (DPO) over chosen/rejected pairs. #### *field* observation_field *: str | None* *= None* The field an env’s observation carries its text in. Unset reads the standard shapes, or the single text field the observation carries. #### *field* observation_processor *: str | None* *= None* module:fn entrypoint rendering an observation payload to prompt text, for envs that need more than a field lookup. Mutually exclusive with observation_field. #### *field* prompt_template *: dict[str, Any] | None* *= None* Conversation template, keyed ‘role_index’ (system_0, user_1, …) so ordering is explicit. Values may use {question} and {answer}, filled from the mapped columns; other braces are literal. Required for a rollout over dataset rows, except traces. #### *field* repeat_system_prompt *: bool* *= False* Also put env_config.system_prompt after the first observation and after each image observation, ahead of a trailing ‘Question:’ block. False sends each observation unchanged. #### *field* request_timeout_s *: float | None* *= None* Per-message client timeout in seconds for an env reached over HTTP. Unset applies a 300 s bound; 0 disables the bound. #### *field* response_column *: str | None* *= None* Column holding the target response. SFT only. #### *field* restart_keep_turns *: int* *= 0* Turns a restarted context repeats word for word (the model’s tokens and the observation after each), oldest dropped to leave room for one more turn under segment_prompt_tokens. Must be below segment_max_images. 0 keeps only the list of past actions. #### *field* restart_older_images *: bool* *= True* Whether kept turns before the latest keep their images in a restarted context. False needs restart_keep_turns of 2 or more. #### *field* restart_older_obs_field *: str* *= ''* Observation field a restarted context shows, as ‘field: value’, for each kept turn before the latest, in place of that turn’s full observation text. Needs restart_keep_turns of 2 or more. Empty repeats every kept observation in full. #### *field* reward *: RewardSpec | None* *= None* Built-in reward scoring each turn, in place of rubric_file_path. #### *field* rubric_file_path *: str | None* *= None* Path to the Python module holding the rubric (or reward function) that scores every turn. Required for a rollout over dataset rows, except under OPD, where unset scores every turn 0; on an env, its score replaces the env’s reward, which it can read as an input. #### *field* rubric_name *: str | None* *= None* Name of the rubric (or reward callable) to import from that module. #### *field* screenshot_field *: str | None* *= None* Observation field holding the page image. Empty or unset reads no page image. A field named image is always read when present. #### *field* segment_max_images *: int | None* *= None* Restart the episode’s context when the next prompt would carry more than this many images; set it to the engine’s limit_mm_per_prompt image count. Unset puts no image limit on a segment. #### *field* segment_prompt_tokens *: int | None* *= None* Restart the episode’s context when the next prompt would exceed this many tokens; each segment trains as its own row. Unset keeps one row per episode. #### *field* strict_chat_template_boundary *: bool | None* *= None* Fail when the chat template cannot render a clean multi-turn boundary, rather than falling back to ChatML markers. #### *field* task_family_field *: str | None* *= None* Field of each env_config.tasks row naming the row’s family, such as a template id. Under adaptive_task_sampling, a row with few groups is drawn by its family’s pooled rate of differing rewards. The field is not sent to the env. Unset puts no row in a family. #### *field* task_family_prior_strength *: float* *= 1.0* Groups’ worth of weight a family’s rate carries in a row’s estimate; a row with more groups than this is drawn mostly by its own rate. #### *field* train_test_split *: float | None* *= None* Fraction of the dataset used for training; the rest is held out for evaluation. ### *class* JudgeSpec The LLM a rubric’s judge calls: provider, model, endpoint and limits. #### *field* api_key_env *: str | None* *= None* Name of the environment variable holding the API key; never the key itself. Unset sends no key (a local endpoint). #### *field* base_url *: str | None* *= None* http(s) endpoint. A URL with a path is the API root, used as given ([https://openrouter.ai/api/v1](https://openrouter.ai/api/v1)); a bare host gets the client’s default path. Unset uses the provider’s hosted API, which needs api_key_env. #### *field* max_concurrency *: int* *= 16* Judge requests in flight per process. #### *field* max_tokens *: int* *= 4096* Verdict token budget. A thinking judge spends it on its thinking too, so a low budget cuts the verdict off. #### *field* model *: str* *[Required]* Judge model id; for bedrock, the Bedrock model id (deepseek.v3.2). #### *field* provider *: Literal['openai', 'anthropic', 'bedrock']* *= 'openai'* API the judge speaks. openai covers any OpenAI-compatible endpoint: OpenRouter, Together, Groq or self-hosted vLLM, through base_url. bedrock calls Amazon Bedrock’s Converse API with the machine’s own AWS credentials. #### *field* region *: str | None* *= None* AWS region a bedrock judge’s model runs in (us-east-1). #### *field* temperature *: float* *= 0.0* Judge sampling temperature. Anthropic judges take none: leave it unset. #### *field* timeout_s *: float* *= 120.0* Seconds one request attempt may take; the provider SDK retries it. ### *class* EnvServiceSpec A backing service the env sessions share: one Pod behind a stable DNS name. #### *field* containers *: list[[EnvContainerSpec](cli/manifest-schema.md#agilerl.models.env.EnvContainerSpec)]* *[Required]* Containers of the service Pod; they share its network. #### *field* host_volumes *: list[[EnvHostVolume](cli/manifest-schema.md#agilerl.models.env.EnvHostVolume)]* *[Optional]* Node directories mounted read-only into every container, for data the node provides (a disk the cluster attaches) rather than the image. #### *field* name *: str* *[Required]* Service name, unique within the environment. #### *field* port *: int* *[Required]* Port clients dial; the service URL is [http:/](http:/)/:. #### *field* ready_timeout_s *: float* *= 600.0* How long the service may take to become ready. #### *field* url_env *: str* *[Required]* Environment variable carrying the service URL into every env session and service container. ### *class* EnvContainerSpec One container of an `env_services` Pod. #### *field* command *: list[str] | None* *= None* Replaces the image ENTRYPOINT. Required with memory_rootfs. #### *field* cpu *: str* *= '10m'* CPU request, as a Kubernetes quantity. No CPU limit is set. #### *field* env *: dict[str, str]* *[Optional]* Container environment, in order. A value may reference an earlier variable or any service’s url_env as $(NAME). #### *field* ephemeral_storage *: str | None* *= None* Ephemeral-storage request, so the Pod lands on a node with room for a large image. #### *field* image *: str* *[Required]* Container image. #### *field* memory *: str | None* *= None* Memory request. #### *field* memory_limit *: str | None* *= None* Memory limit. #### *field* memory_rootfs *: str | None* *= None* Size of a memory-backed volume the image is unpacked into, for an image larger than a node’s disk. The container then runs command under chroot in a privileged container: the image’s ENTRYPOINT, ENV and WORKDIR do not apply, so set command and env. The unpack uses the Pod’s image pull secrets. #### *field* name *: str* *[Required]* Container name, unique within its service. #### *field* port *: int | None* *= None* Port this container serves the service on. Exactly one container of a service sets it. #### *field* readiness_command *: list[str] | None* *= None* Exec readiness probe. Unset probes TCP on port, if set. #### *field* readiness_path *: str | None* *= None* HTTP GET readiness probe on port. #### *field* setup_command *: list[str] | None* *= None* Runs once the container starts; the service is not ready until it exits 0, and a failure restarts the container. Output goes to the container log. ### *class* EnvHostVolume A node directory mounted read-only into every container of a service. #### *field* host_path *: str* *[Required]* Directory on the node under /var/cache/agilerl-, where the platform mounts the data it provides. The Pod does not start on a node without it. #### *field* mount_path *: str* *[Required]* Where the containers see the directory. #### *field* name *: str* *[Required]* Volume name, unique within its service. ## training ### *class* TrainingSpec The manifest’s `training` section. #### *field* checkpoint_export *: [CheckpointExportSpec](cli/manifest-schema.md#agilerl.models.training.CheckpointExportSpec) | None* *= None* Adapter-only save by default, or a merged Hugging Face export when format is merged and trigger matches. #### *field* checkpoint_optimizer *: bool* *= True* Store the optimizer state in LLM checkpoints so a resumed run keeps its Adam moments. Adds about twice the adapter’s size. #### *field* checkpoint_path *: str | None* *= None* Where checkpoints are written. #### *field* checkpoint_steps *: int | None* *= None* Steps between checkpoints. Unset never writes. #### *field* env_resource_ratio *: float | None* *= None* Share of each node’s CPU reserved for environment workers. #### *field* eval_greedy *: bool* *= True* Also run eval_loop near-greedy passes over the held-out tasks under async rollout. With eval_samples_per_task set they report as eval_score_greedy and eval_accuracy_greedy. #### *field* eval_loop *: int* *= 1* Evaluation passes averaged into each eval score. More passes give a steadier score. #### *field* eval_max_concurrent_episodes *: int | None* *= None* Held-out episodes one rollout engine runs at once; the rest wait in a queue. They share the engine’s episode slots with training. Unset lets them take every free slot. #### *field* eval_samples_per_task *: int* *= 0* Held-out episodes per task sampled at the algorithm’s temperature and top_p under async rollout. Their mean is eval_score and eval_accuracy. 0 reports the near-greedy pass there instead. #### *field* eval_steps *: SkipJsonSchema[int | None]* *= None* Steps per evaluation episode. Unset runs a full episode. #### *field* evaluation_interval *: int | None* *= None* Steps between evaluations during LLM fine-tuning. #### *field* evo_steps *: int | None* *= None* Steps between evaluation rounds, also spelled metrics_interval. Unset resolves to the algorithm’s own cadence. #### *field* max_steps *: int* *= 1000000* Total steps to train for. The run stops here. Unset on an LLM run over dataset rows trains one pass over the dataset. #### *field* max_wall_seconds *: float | None* *= None* Wall-clock limit for the run. Unset trains to max_steps. #### *field* name *: str | None* *= None* Label for the training loop in logs. #### *field* num_epochs *: SkipJsonSchema[int | None]* *= None* Passes over the dataset, when the loop is epoch-driven rather than step-driven. Not for LLM runs: they set max_steps. #### *field* overwrite_checkpoints *: bool* *= False* Overwrite the previous checkpoint instead of keeping each one. #### *field* reporting_interval *: int* *= 1024* Steps between metric reports. #### *field* rollout_batch_size *: int | None* *= None* Rollout groups per cycle, in total across all of a member’s rollout engines, rounded up to a multiple of the engine count; each engine runs an equal share. Must divide evenly by training_gpus_per_agent so every learner shard gets data. Unset is the algorithm’s batch_size rounded up to a multiple of both training_gpus_per_agent and the engine count, so the engines keep one learn step of groups in flight. #### *field* rollout_engines_per_agent *: int | Literal['auto']* *= 0* Generation engines per trainer, one GPU each. ‘auto’ takes every GPU the trainers leave over. Unset under async rollout with training_gpus_per_agent also unset, the trainer / engine split is picked by the throughput model; unset otherwise is ‘auto’. #### *field* rollout_mode *: RolloutMode* *= 'colocated'* Where generation runs. ‘colocated’ alternates generation and learning on the same GPU, for local runs; ‘async’ moves generation onto dedicated rollout engines that run continuously. Arena runs every rollout LLM job async. replay_buffer.max_rollout_version_lag bounds staleness. #### *field* rollout_version_stamp *: RolloutVersionStamp | None* *= None* Which weight version a published group is fenced by. ‘oldest_turn’ ages a group by how long it ran, so long episodes are dropped first; ‘publish’ makes buffer residency independent of episode duration. #### *field* target_score *: float | None* *= None* Stop early once the eval score reaches this. Unset trains to max_steps. #### *field* training_gpus_per_agent *: int* *= 1* Data-parallel trainer GPUs. The replay buffer shards rollouts across them. #### *field* weight_sync_interval *: int | None* *= None* Learn chunks between rollout weight syncs under async rollout. Unset resolves to 1: fresh weights every cycle. ### *class* CheckpointExportSpec When to write a merged Hugging Face package next to adapter checkpoints. * **Parameters:** * **format** – `adapter` writes LoRA weights only; `merged` also writes `merged/` after a durable adapter save when `trigger` matches. * **trigger** – `final` (last durable save of the run), `best` (best checkpoint if the trainer marks one, otherwise `final`), `on_demand` (no merge during train), or `every` (after every adapter save). #### *field* format *: CheckpointExportFormat* *= 'adapter'* adapter writes LoRA weights only; merged also writes merged/ after a durable adapter save when trigger matches. #### *field* trigger *: CheckpointExportTrigger* *= 'final'* final (last durable save of the run), best (best checkpoint if the trainer marks one, otherwise final), on_demand (no merge during train), or every (after every adapter save). ## network ### *class* FinetuningNetworkSpec Model specification for LLM finetuning networks. #### *field* lora_config *: [LoraConfigDict](cli/manifest-schema.md#agilerl.models.networks.LoraConfigDict)* *[Optional]* LoRA adapter configuration. Unset or null trains the model’s catalog default adapter; Arena has no full finetune. #### *field* max_context_length *: int* *[Required]* Context window the run is sized for, prompt plus completion. #### *field* pretrained_model_name_or_path *: str* *[Required]* HuggingFace model id or local path to fine-tune. #### *field* weights_path *: str | None* *= None* Local or s3:// directory to load the weights and tokenizer from. pretrained_model_name_or_path then names the catalog model with the same architecture, which sizes and configures the run. ### *class* LoraConfigDict Model specification for LLM LoRA configuration. It names no modules: Arena trains LoRA on the catalog’s modules for the model (`catalog_lora_modules()`). #### *field* lora_alpha *: int* *= 32* LoRA scaling. Conventionally set to twice the rank. #### *field* lora_dropout *: float* *= 0.0* Dropout on the adapter. Must be 0 when target_parameters is set. Rollout algorithms (GRPO, CISPO, GSPO, LLMPPO, LLMREINFORCE) sample with vLLM, which applies no dropout. #### *field* lora_r *: int* *= 16* LoRA rank. Higher adapts more of the model, at proportional memory cost. #### *field* target_parameters *: list[str] | None* *= None* Packed MoE expert parameter paths to adapt, e.g. block_sparse_moe.experts.gate_up_proj. Requires lora_dropout=0. #### *field* task_type *: str* *= 'CAUSAL_LM'* PEFT task type for the adapter. ## replay_buffer ### *class* LLMRolloutBufferSpec LLM branch of the `replay_buffer` section: the async rollout deque. #### *field* drop_uninformative_groups *: bool* *= True* Discard groups whose completions all got identical rewards before they reach a learner, and wait until each learner’s batch is full of groups whose rewards differ. Tied groups have zero advantage, so training on them only costs compute, but each trained step then generates more groups than it trains. No effect when group_size is 1. #### *field* group_replay_max_age *: int* *= 20* Policy versions (weight syncs) a stored completion stays eligible for group replay; 0 turns group replay off. Group replay keeps each task’s most recent completion for each episode return seen (up to 4 returns per task). When every completion in a new group for that task gets the same return, swap one of them for the stored completion with the highest other return, so the group still has a reward difference to learn from: a group that all failed gets a past success, one that all succeeded gets a past failure. The replayed completion keeps the token log-probabilities it was sampled with, and the algorithm’s ratio clipping bounds its update. Applies to async rollout over a dataset-backed task list; no effect when group_size is 1. The store is in memory only and refills from new rollouts after a resume. #### *field* max_rollout_version_lag *: int* *= 2* Weight-sync versions a group may fall behind before it is dropped as too off-policy: the sync to version v keeps groups generated at version v - lag or later. 0 is strictly on-policy; the default 2 also keeps groups started under the two previous weight versions. #### *field* max_size *: int* *= 10000* Rollout groups queued per learner shard before the oldest is evicted. Counts generated groups, not RL transitions. #### *field* name *: str | None* *= None* Label for the buffer in logs. # cli/python-client.md # Python client The `ArenaClient` class, the inference `Agent` for calling deployed agents, and the errors they raise. The page is generated from the docstrings of the `agilerl` version Arena currently supports. To set up credentials, see [Install and sign in](cli/install.md). ### *class* ArenaClient(\*, api_key=None, org_key=None, external_user_id=None, request_timeout=30, upload_timeout=300, verbose=True) Client for the Arena RLOps platform. Handles authentication, environment management, and training job submission. Authentication is resolved in priority order: 1. *org_key* plus *external_user_id* (constructor or `ARENA_ORG_KEY` / `ARENA_EXTERNAL_USER_ID`). Sends `Authorization: Bearer ` and `X-External-User-Id`. 2. *api_key* constructor argument 3. `ARENA_API_KEY` environment variable 4. Stored OAuth credentials from `~/.arena/credentials.json` 5. Interactive [`login()`](cli/python-client.md#agilerl.client.ArenaClient.login) (device authorization flow) For PAT / OAuth credentials, the value is sent as `Authorization: Bearer `. Use a **personal access token** from your Arena account profile (`arena_pat__`) to skip OAuth device login. You can also pass a Keycloak access token in the same way if you obtain one elsewhere. Organisation keys (`arena_org_…`) are for partner servers and must be paired with an external user id. * **Parameters:** * **api_key** (*str* *|* *None*) – Bearer token material (profile PAT or OAuth access token). When set, device login is not required. * **org_key** (*str* *|* *None*) – Organisation API key (`arena_org_…`). Requires *external_user_id*. * **external_user_id** (*str* *|* *None*) – Partner user id sent as `X-External-User-Id`. Requires *org_key*. * **request_timeout** (*int*) – Default timeout in seconds for API requests. * **upload_timeout** (*int*) – Timeout in seconds for file uploads and cluster register. * **verbose** (*bool*) – Whether to enable verbose logging. * **Returns:** None * **Return type:** None ## ArenaClient ### Sign-in and account #### *classmethod* ArenaClient.configure(\*, base_url=None, keycloak_url=None, realm=None, client_id=None) Override default URLs for local development or testing. An explicit `base_url` / `keycloak_url` takes precedence over the `ARENA_BASE_URL` / `ARENA_KEYCLOAK_URL` environment variables. Returns the class so calls can be chained with instantiation: ```default client = ArenaClient.configure( base_url="http://localhost:3001", keycloak_url="http://localhost:8023", )() ``` * **Parameters:** * **base_url** (*str* *|* *None*) * **keycloak_url** (*str* *|* *None*) * **realm** (*str* *|* *None*) * **client_id** (*str* *|* *None*) * **Return type:** type[[*ArenaClient*](cli/python-client.md#agilerl.client.ArenaClient)] #### ArenaClient.login(timeout=300) Sign in through the browser, then end the previously saved login. Only one login is kept in `~/.arena/credentials.json`, so this is also how to switch user or environment. Organisation-key credentials skip it. An API key stays on this client until the browser sign-in succeeds. * **Parameters:** **timeout** (*int*) – Maximum seconds to wait for browser authorization. * **Return type:** None #### ArenaClient.logout() End the saved login and remove stored credentials. * **Return type:** None #### *property* ArenaClient.is_authenticated *: bool* `True` when the client holds an org key, API key, or access token. #### ArenaClient.get_current_user() Get the authenticated user’s profile details. Includes account fields such as email and name. When the Arena server exposes them, the payload may also contain entitlement flags (e.g. enterprise / BYOC access) relevant to CLI feature gating. * **Return type:** dict[str, *Any*] #### ArenaClient.get_user_credits() Get the authenticated user’s credit information. * **Return type:** None | bool | int | float | str | list[JSONValue] | dict[str, JSONValue] #### ArenaClient.get_credit_balance() Get the active organization’s balance and its accrued, uncharged cost. * **Returns:** `balance` (spendable credits), `accrued_cost` (run up by running jobs and deployments but not charged yet), `balance_after_accrued` and `accrued`, one entry per running item with `kind`, `id`, `experiment_id`, `name`, `since`, `hourly_cost` and `accrued_cost`. * **Return type:** dict[str, Any] * **Raises:** [**ArenaAPIError**](cli/python-client.md#agilerl.exceptions.ArenaAPIError) – With status 404 from an Arena server without accrued cost. #### ArenaClient.get_credit_ledger(\*, job_id=None, deployment_id=None, limit=None) List the active organization’s charges and credits, newest first. * **Parameters:** * **job_id** (*int* *|* *None*) – Only charges for this job. * **deployment_id** (*int* *|* *None*) – Only charges for this deployment. * **limit** (*int* *|* *None*) – Most entries to return (the server caps it at 1000). * **Returns:** Entries with `time`, `kind`, `job_id`, `deployment_id`, `experiment_id`, `item`, `description`, `amount` (negative for charges) and `balance` (after the entry). * **Return type:** list[dict[str, Any]] * **Raises:** [**ArenaAPIError**](cli/python-client.md#agilerl.exceptions.ArenaAPIError) – With status 404 from an Arena server without the ledger. #### ArenaClient.close() Close the underlying HTTP connection pool. * **Return type:** None ### Projects #### ArenaClient.list_projects() List all projects in Arena for the authenticated user. * **Returns:** A list of projects. * **Return type:** list[dict[str, Any]] #### ArenaClient.create_project(name, description=None, llm_based=True) Create a new LLM project in Arena. * **Parameters:** * **name** (*str*) – The name of the project to create. * **description** (*str* *|* *None*) – The description of the project to create. * **llm_based** (*bool*) – Accepted for agilerl-arena 1.x callers; must be True. * **Returns:** A dictionary containing the project creation result. * **Return type:** dict[str, Any] * **Raises:** [**ArenaValidationError**](cli/python-client.md#agilerl.exceptions.ArenaValidationError) – When `llm_based` is False. #### ArenaClient.delete_project(name) Delete a project in Arena. * **Parameters:** **name** (*str*) – The name of the project to delete. * **Return type:** None #### ArenaClient.get_default_project() Return the default project name from `~/.arena/config.json`, or None if unset. * **Return type:** str | None #### ArenaClient.set_default_project(name) Validate that *name* exists and persist it as the default project. * **Parameters:** **name** (*str*) – The project name to set as default. * **Raises:** [**ArenaConfigError**](cli/python-client.md#agilerl.exceptions.ArenaConfigError) – If the project does not exist. * **Return type:** None ### Environments #### ArenaClient.list_environments(name=None, include_arena=False) List environments available to the authenticated user. * **Parameters:** * **name** (*str* *|* *None*) – Environment name. If None, list all environments. * **include_arena** (*bool*) – Whether to include the built-in environments available in Arena. * **Returns:** A nested dictionary keyed by environment name, then version: ```python { "": { "": { "validated": True, } } } ``` * **Return type:** dict[str, dict[str, dict[str, bool]]] #### ArenaClient.environment_exists(name, version=None) Check whether an environment name/version is registered. * **Parameters:** * **name** (*str*) – Environment name. * **version** (*str* *|* *None*) – Environment version. Defaults to None, which resolves to the latest version. * **Returns:** True if the environment exists, False otherwise. * **Return type:** bool #### ArenaClient.list_environment_entrypoints(name, version=None) List available entrypoints for an environment version. * **Parameters:** * **name** (*str*) – Environment name, as specified in Arena. * **version** (*str* *|* *None*) – Environment version. Defaults to None, which resolves to the latest version. * **Returns:** A list of entrypoints. * **Return type:** list[str] #### ArenaClient.validate_environment(\*, name, version=None, source=None, env_config=None, requirements=None, entrypoint=None, description=None, do_rollouts=False) Validate a custom GEM environment on Arena. When source is provided the environment is uploaded, created, and validated in a single step. When source is None an already-registered environment is validated by name/version. * **Parameters:** * **name** (*str*) – Environment name. * **version** (*str* *|* *None*) – Environment version. If creating an environment from scratch, defaults to “v1”, if validating an already-registered environment, defaults to None, which resolves to the latest version. * **source** (*str* *|* *os.PathLike* *[**str* *]* *|* *bytes* *|* *None*) – Environment source — a directory path (compressed automatically), a `.tar.gz` file path, or raw `bytes`. * **env_config** (*str* *|* *os.PathLike* *[**str* *]* *|* *None*) – Path to the environment configuration file containing the environment parameters. When *source* is a directory and this is None, a top-level `env_config.yaml`, `env_config.yml`, or `env_config.json` (in that order) is picked up automatically. Default is None. * **requirements** (*str* *|* *os.PathLike* *[**str* *]* *|* *None*) – Path to additional dependencies needed for the environment. When *source* is a directory and this is None, a top-level `requirements.txt` is picked up automatically. Default is None. * **entrypoint** (*str* *|* *None*) – Optional entrypoint override. Default is None. * **description** (*str* *|* *None*) – Optional description of the environment. Default is None. * **do_rollouts** (*bool*) – Whether to also run sample episodes against the environment and include them in the result. Default is False. * **Returns:** A dictionary containing the validation result. * **Return type:** dict[str, Any] #### ArenaClient.delete_environment(\*, name, version=None, confirm=False) Delete an environment version (or all versions if version is None). * **Parameters:** * **name** (*str*) – Environment name, as specified in Arena. * **version** (*str* *|* *None*) – Environment version. If None, delete all environment versions. * **confirm** (*bool*) – Whether to confirm the deletion. * **Return type:** dict[str, *Any*] | None #### ArenaClient.duplicate_environment_version(\*, name, new_version, version=None) Duplicate a custom environment version to a new version name. * **Parameters:** * **name** (*str*) – Environment name. * **new_version** (*str*) – New `version` for the duplicate (e.g. `v2`). * **version** (*str* *|* *None*) – Source version; when omitted, the latest version is used. * **Return type:** dict[str, *Any*] ### Datasets #### ArenaClient.list_datasets(\*, search=None) List datasets or search HuggingFace datasets. * **Parameters:** **search** (*str* *|* *None*) – HuggingFace dataset search query. * **Returns:** List of datasets or search results from Arena. * **Return type:** list[dict[str, Any]] #### ArenaClient.dataset_exists(name) Check whether a dataset name is registered for the active org. * **Parameters:** **name** (*str*) – Dataset name. * **Returns:** `exists`, and `datasetType` when the name is registered. * **Return type:** dict[str, bool | str] #### ArenaClient.create_dataset(\*, name, category, column_mapping=None, description=None, file=None, config=None, hf_dataset_name=None, hf_config=None, hf_split=None) Create an LLM dataset on Arena. Upload a local CSV, a parquet file, a Hugging Face parquet folder, import from HuggingFace, or create metadata only. Validation is performed by the Arena API; a local `traces` file is also checked against the traces spec before upload. * **Parameters:** * **name** (*str*) – Dataset name. * **category** (*str*) – Dataset category (`reasoning`, `preference`, `sft`, or `traces`). * **column_mapping** (*str* *|* *dict* *[**str* *,* *Any* *]* *|* *None*) – Column mapping as a JSON string or dict. Required except for `traces`, whose column names are the spec. * **description** (*str* *|* *None*) – Optional description. * **file** (*str* *|* *os.PathLike* *[**str* *]* *|* *bytes* *|* *None*) – Local CSV, JSONL or parquet path, a directory of parquet shards, or raw CSV bytes (bytes are uploaded as `dataset.csv`). * **config** (*str* *|* *None*) – Parquet config name when *file* is a folder with more than one config (e.g. gsm8k `main` vs `socratic`). * **hf_dataset_name** (*str* *|* *None*) – HuggingFace dataset id for import. * **hf_config** (*str* *|* *None*) – HuggingFace dataset config name. * **hf_split** (*str* *|* *None*) – HuggingFace split (required when importing from HF). * **Returns:** Created dataset metadata from Arena. * **Return type:** dict[str, Any] * **Raises:** [**ArenaValidationError**](cli/python-client.md#agilerl.exceptions.ArenaValidationError) – If a `traces` file breaks the spec. #### ArenaClient.delete_dataset(name, \*, confirm=False) Archive a dataset by name. * **Parameters:** * **name** (*str*) – Dataset name. * **confirm** (*bool*) – When `True`, skip the interactive confirmation prompt. * **Returns:** Archive result, or `None` if the user declined confirmation. * **Return type:** dict[str, Any] | None ### Models and GPUs #### ArenaClient.list_models() List HuggingFace models in the Arena catalog. * **Returns:** Catalog rows including `model_name`, `num_params`, `lora_info`, `max_context_length`, `lora_ranks`, and `enabled`. * **Return type:** list[dict[str, Any]] #### ArenaClient.get_model_info(model_name) Fetch LoRA modules and catalog metadata for a model. * **Parameters:** **model_name** (*str*) – HuggingFace model id as stored in the catalog. * **Returns:** `modules`, `parameters`, `lora_info`, `num_params`, `max_context_length`, and `lora_ranks`. * **Return type:** dict[str, Any] #### ArenaClient.list_resources(algorithm=None) List the GPU types and GPU counts a submit accepts. Each `gpuType` is a value `ArenaClient.submit_experiment` accepts as `gpu_type`, and each of its `numGpus` a value for `num_gpus`. An older platform returns resource `tiers` instead. * **Parameters:** **algorithm** (*str* *|* *None*) – The run’s `algorithm.name`. Arena then lists only the GPU counts that algorithm trains on: a GRPO-family run generates on its own GPU, so it needs at least two. Without it the list is for LLM training and includes single GPUs. * **Returns:** `{"gpuTypes": [{"gpuType": str, "gpusPerNode": list[int], "numGpus": list[int], "devOnly": bool}]}`. * **Return type:** dict[str, Any] #### ArenaClient.estimate_memory(manifest, gpu=None, device_gb=None, num_gpus=None, gpus_per_node=None) Size a training manifest’s GPU memory on one device. * **Parameters:** * **manifest** (*dict* *[**str* *,* *Any* *]*) – The raw manifest document. * **gpu** (*str* *|* *None*) – GPU type from `arena resources list`, or a GPU name. * **device_gb** (*float* *|* *None*) – GPU memory in GiB; overrides the GPU’s when both are set. * **num_gpus** (*int* *|* *None*) – GPUs in the allocation, for the engine layout the run picks. * **gpus_per_node** (*int* *|* *None*) – GPUs on one node; `None` puts all `num_gpus` on one. * **Returns:** The exit code (0 fits, 3 over budget, 2 usage error) and report. * **Return type:** *MemoryEstimate* #### ArenaClient.solve_memory(manifest, field, gpu=None, device_gb=None, num_gpus=None, hi=None) Solve the largest value of one manifest setting that fits on one device. * **Parameters:** * **manifest** (*dict* *[**str* *,* *Any* *]*) – The raw manifest document. * **field** (*str*) – The setting to solve; only `max_model_len`. * **gpu** (*str* *|* *None*) – GPU type from `arena resources list`, or a GPU name. * **device_gb** (*float* *|* *None*) – GPU memory in GiB; overrides the GPU’s when both are set. * **num_gpus** (*int* *|* *None*) – GPUs on the node, for the engine layout the run picks. * **hi** (*int* *|* *None*) – Search ceiling; the checkpoint’s RoPE limit also caps it. * **Returns:** The exit code (0 solved, 3 nothing fits, 2 usage error) and report. * **Return type:** *MemoryEstimate* ### Experiments #### ArenaClient.get_default_run_spec(algorithm, \*, env_name=None, env_version=None, env_entrypoint=None, dataset_name=None, field=None, pretrained_model_name_or_path=None) Fetch a default RunSpec for an algorithm. `field` returns one section instead of the full spec. * **Parameters:** * **algorithm** (*str*) – Catalog algorithm name. * **env_name** (*str* *|* *None*) – Arena environment name. * **env_version** (*str* *|* *None*) – Environment version. Required with `env_entrypoint` (`v1` and `1` are both accepted). * **env_entrypoint** (*str* *|* *None*) – Environment entrypoint. * **dataset_name** (*str* *|* *None*) – Dataset name. * **field** (*str* *|* *None*) – RunSpec section to return (`algorithm`, `environment`, `network`, `replay_buffer`, or `training`). * **pretrained_model_name_or_path** (*str* *|* *None*) – HuggingFace model name in the catalog. * **Returns:** A filled RunSpec, or one section when `field` is set. * **Return type:** dict[str, Any] * **Raises:** [**ArenaValidationError**](cli/python-client.md#agilerl.exceptions.ArenaValidationError) – When `algorithm` is a classic RL algorithm. #### ArenaClient.quote_experiment(manifest, \*, num_gpus=None, gpu_type=None, project=None, experiment_name=None, reward_file=None, completion=None) Price an experiment without starting it. Arena runs the submit checks and picks the class exactly as [`submit_experiment()`](cli/python-client.md#agilerl.client.ArenaClient.submit_experiment) would, then stops before creating anything. Arguments match [`submit_experiment()`](cli/python-client.md#agilerl.client.ArenaClient.submit_experiment). * **Returns:** `resource_id`, `resource_name`, `gpu_type`, `num_gpus`, `num_nodes`, `hourly_cost` (credits per hour), `max_steps`, `step_seconds`, `estimated_hours` and `estimated_cost`. The last two are `None` when Arena has no duration estimate. `reward_error` says why the reward fails the check [`submit_experiment()`](cli/python-client.md#agilerl.client.ArenaClient.submit_experiment) runs, else `None`. * **Return type:** dict[str, Any] * **Raises:** [**ArenaAPIError**](cli/python-client.md#agilerl.exceptions.ArenaAPIError) – With status 404 from an Arena server that cannot price a run before it starts. * **Parameters:** * **manifest** (*str* *|* *Path* *|* *dict* *[**str* *,* *Any* *]*) * **num_gpus** (*int* *|* *None*) * **gpu_type** (*str* *|* *None*) * **project** (*str* *|* *None*) * **experiment_name** (*str* *|* *None*) * **reward_file** (*str* *|* *PathLike* *[**str* *]* *|* *bytes* *|* *None*) * **completion** (*str* *|* *None*) #### ArenaClient.submit_experiment(manifest, \*, num_gpus=None, gpu_type=None, project=None, experiment_name=None, reward_file=None, completion=None, idempotency_key=None) Submit an experiment (a training job). * **Parameters:** * **manifest** (*str* *|* *Path* *|* *dict* *[**str* *,* *Any* *]*) – Training manifest as a YAML/JSON file path, raw YAML string, or a pre-parsed dict. * **num_gpus** (*int* *|* *None*) – Total GPUs for the job. Arena uses the fewest nodes that fit the run’s memory estimate. * **gpu_type** (*str* *|* *None*) – Short GPU name such as `h100-80`, `b200` or `l4`. * **project** (*str* *|* *None*) – The project to submit the experiment to. * **experiment_name** (*str* *|* *None*) – The name of the experiment to submit. * **reward_file** (*str* *|* *os.PathLike* *[**str* *]* *|* *bytes* *|* *None*) – Python rubric or reward module scoring a rollout job. When set, the request is sent as `multipart/form-data` and a rollout manifest without `environment.rubric_file_path` gets the file’s basename (`reward.py` for bytes). * **completion** (*str* *|* *None*) – Optional model completion for reward validation. When omitted, the server uses the reference answer from the first dataset row. * **idempotency_key** (*str* *|* *None*) – Reuse this key to replay the same submit instead of starting another job. The key is org-wide. * **Raises:** [**ArenaValidationError**](cli/python-client.md#agilerl.exceptions.ArenaValidationError) – When `num_gpus` is below 1, the manifest turns on HPO, or the manifest’s rubric path names a different file than `reward_file`, or a local file when `reward_file` is unset. * **Return type:** dict[str, *Any*] #### ArenaClient.list_experiments(project=None) List all experiments in a project. * **Parameters:** **project** (*str* *|* *None*) – The name of the project. Falls back to the default project from `~/.arena/config.json` if not provided. * **Returns:** A list of experiments. * **Return type:** list[dict[str, Any]] #### ArenaClient.get_experiment_status(experiment_name, project=None) Return an experiment’s status and, when it failed, why. * **Parameters:** * **experiment_name** (*str*) – Experiment name (latest match in scope). * **project** (*str* *|* *None*) – Project, when the experiment name exists in more than one. * **Returns:** `experiment_name`, `status`, `failure_reason` (`None` unless the run failed) and `last_modified`. * **Return type:** dict[str, Any] #### ArenaClient.get_experiment_logs(experiment_name, \*, tail=None, after=None, limit=None, level=None, project=None) Return one page of an experiment’s training logs (the web Log view). * **Parameters:** * **experiment_name** (*str*) – Experiment name (latest match in scope). * **tail** (*int* *|* *None*) – Return the newest `tail` lines (1-1000). Not with `after`. * **after** (*int* *|* *None*) – Return lines after this line `timestamp` (Unix microseconds), oldest first. Pass the previous page’s `next_after`. * **limit** (*int* *|* *None*) – Lines per page when not tailing (1-1000, server default 500). * **level** (*Literal* *[* *"info"* *,* *"warning"* *,* *"error"* *]* *|* *None*) – Lowest severity to return. * **project** (*str* *|* *None*) – Project, when the experiment name exists in more than one. * **Returns:** The status fields of [`get_experiment_status()`](cli/python-client.md#agilerl.client.ArenaClient.get_experiment_status) plus `lines` (`timestamp`, `severity`, `message`, `event_type`), `next_after` and `has_more`. * **Return type:** dict[str, Any] #### ArenaClient.iter_experiment_logs(experiment_name, \*, tail=None, follow=False, level=None, project=None, poll_interval=5.0) Yield pages of an experiment’s training logs until there are no more. With `follow`, keep polling while the experiment is pending or running, and stop once it has ended and a poll brings no new lines. * **Parameters:** * **experiment_name** (*str*) – Experiment name (latest match in scope). * **tail** (*int* *|* *None*) – Start with the newest `tail` lines instead of the first line. * **follow** (*bool*) – Keep polling for new lines while the experiment runs. * **level** (*Literal* *[* *"info"* *,* *"warning"* *,* *"error"* *]* *|* *None*) – Lowest severity to return. * **project** (*str* *|* *None*) – Project, when the experiment name exists in more than one. * **poll_interval** (*float*) – Seconds between polls when following. * **Returns:** Pages as returned by [`get_experiment_logs()`](cli/python-client.md#agilerl.client.ArenaClient.get_experiment_logs); the last one carries the final `status` and `failure_reason`. * **Return type:** Iterator[dict[str, Any]] #### ArenaClient.set_stream_handler(handler) Register a callback invoked for each `StreamEvent` during streaming. Set to `None` to clear the handler. * **Parameters:** **handler** (*Callable* *[* *[**StatusEvent* *|* *CheckEvent* *|* *ErrorEvent* *|* *LogEvent* *]* *,* *None* *]* *|* *None*) * **Return type:** None #### ArenaClient.stop_experiment(experiment_name, project=None) Stop a running experiment in Arena. * **Parameters:** * **experiment_name** (*str*) – Experiment name to halt. * **project** (*str* *|* *None*) – Project, when the experiment name exists in more than one. * **Return type:** None | bool | int | float | str | list[JSONValue] | dict[str, JSONValue] #### ArenaClient.quote_resume(experiment_name, max_steps=None, checkpoint=None, new_name=None, project=None) Price a resume without starting it. A resume runs on the experiment’s own hardware. Arguments match [`resume_experiment()`](cli/python-client.md#agilerl.client.ArenaClient.resume_experiment). * **Returns:** The fields [`quote_experiment()`](cli/python-client.md#agilerl.client.ArenaClient.quote_experiment) returns, for the steps left between the checkpoint and `max_steps` on that hardware. * **Return type:** dict[str, Any] * **Raises:** [**ArenaAPIError**](cli/python-client.md#agilerl.exceptions.ArenaAPIError) – With status 404 from an Arena server that cannot price a resume before it starts. * **Parameters:** * **experiment_name** (*str*) * **max_steps** (*int* *|* *None*) * **checkpoint** (*str* *|* *None*) * **new_name** (*str* *|* *None*) * **project** (*str* *|* *None*) #### ArenaClient.resume_experiment(experiment_name, max_steps=None, checkpoint=None, new_name=None, project=None) Resume an experiment (a training job). * **Parameters:** * **experiment_name** (*str*) – The name of the experiment to resume. * **max_steps** (*int* *|* *None*) – Total training steps, counted from the start of the original run; must be greater than the checkpoint’s step. Omit to keep the stored total. * **checkpoint** (*str* *|* *None*) – Checkpoint to resume from. Omit to use the best checkpoint. * **new_name** (*str* *|* *None*) – Name for the resumed experiment. * **project** (*str* *|* *None*) – Project, when the experiment name exists in more than one. * **Returns:** A dictionary containing the resume result. * **Return type:** dict[str, Any] #### ArenaClient.list_checkpoints(experiment_name, project=None) List all checkpoints for an experiment. * **Parameters:** * **experiment_name** (*str*) – The name of the experiment to list checkpoints for. * **project** (*str* *|* *None*) – Project, when the experiment name exists in more than one. * **Returns:** A list of checkpoints. * **Return type:** list[dict[str, Any]] #### ArenaClient.list_experiment_metric_names(experiment_name, \*, project=None, details=False) List metric catalog rows recorded for an experiment (JSON). For a **CSV preview** with `--metric` / `--preview-rows`-style filters, use [`preview_experiment_metrics_csv()`](cli/python-client.md#agilerl.client.ArenaClient.preview_experiment_metrics_csv). * **Parameters:** * **experiment_name** (*str*) – Experiment name (latest updated match in scope). * **project** (*str* *|* *None*) – Optional exact project name in the current org. * **details** (*bool*) – When True, the API returns `{\"metrics\": […catalog…]}`. * **Returns:** Catalog rows `{display_name, category}`, or that object when `details` is True. * **Return type:** list[dict[str, Any]] | dict[str, Any] #### ArenaClient.preview_experiment_metrics_csv(experiment_name, \*, preview_rows, metrics=None, project=None) Fetch a capped CSV snippet (Arena CLI `--metric` / `--preview-rows`). Uses `GET /api/cli/v1/experiments/metrics` with `preview_rows` set. Omit `metrics` to include all columns. * **Parameters:** * **experiment_name** (*str*) – Experiment name (latest match in scope). * **preview_rows** (*int*) – Maximum number of **data** rows in the CSV (server-capped). * **metrics** (*Sequence* *[**str* *]* *|* *None*) – Metric column names to include (repeat query param `metric`). * **project** (*str* *|* *None*) – Optional exact project name. * **Returns:** A tuple of the metrics payload, content type, and disposition. * **Return type:** tuple[bytes, str | None, str | None] #### ArenaClient.download_experiment_metrics(experiment_name, output_path=None, metrics=None, project=None, overwrite=False) Download experiment metrics to a local file. * **Parameters:** * **experiment_name** (*str*) – The name of the experiment to download metrics for. * **output_path** (*str* *|* *os.PathLike* *[**str* *]* *|* *None*) – Destination file path or directory. If a directory, the filename is inferred from the server response. Defaults to `{experiment_name}_metrics.csv` in the current directory. * **metrics** (*list* *[**str* *]* *|* *None*) – The metrics to download. If None, download all metrics. * **project** (*str* *|* *None*) – Project name; defaults to the saved default project. * **overwrite** (*bool*) – Replace the file at the resolved output path if it exists. * **Returns:** The path to the written file. * **Return type:** Path * **Raises:** * **FileExistsError** – If the resolved output path is a directory, or is an existing file and `overwrite` is False. * **NotADirectoryError** – If the parent path exists but is not a directory. ### Secrets #### ArenaClient.list_secrets() List your organization’s secrets without their values. * **Returns:** One row per secret with `name`, `created_at`, `updated_at` and `updated_by`. * **Return type:** list[dict[str, Any]] #### ArenaClient.set_secret(name, value) Create or replace an organization secret. * **Parameters:** * **name** (*str*) – Secret name, such as `ANTHROPIC_API_KEY`. * **value** (*str*) – Secret value. Sent once and never returned. * **Returns:** The stored row’s `name`, `created_at`, `updated_at` and `updated_by`. * **Return type:** dict[str, Any] #### ArenaClient.delete_secret(name) Delete an organization secret. * **Parameters:** **name** (*str*) – Secret name. * **Returns:** `{"deleted": True, "name": name}`. * **Return type:** dict[str, Any] ### Deployments #### ArenaClient.deploy_agent(experiment_name, checkpoint=None, memory_scope=None, num_gpus=None, gpu_type=None) Create an inference deployment from an experiment checkpoint. Without `num_gpus` or `gpu_type`, a redeploy keeps the agent’s resources. A new deployment runs on the cluster the agent was trained on if that is your own cluster, else on the cheapest node type that can serve the model. If Arena can’t size the model, it uses its default node type and rejects `num_gpus` and `gpu_type`. * **Parameters:** * **experiment_name** (*str*) – The name of the experiment to deploy. * **checkpoint** (*str* *|* *None*) – Steps of the checkpoint to deploy, as listed by [`list_checkpoints()`](cli/python-client.md#agilerl.client.ArenaClient.list_checkpoints) (e.g. `"500"`). If None, deploy the checkpoint with the most steps. * **memory_scope** (*MemoryScope* *|* *None*) – Who the deployment keeps chat sessions for. `"user"` gives every caller their own conversations, `"organization"` shares them across the organisation. A new deployment defaults to `"user"`. Redeploying with `None` keeps the scope already stored, it does not reset it, and the scope cannot be changed after the deployment exists. * **num_gpus** (*int* *|* *None*) – GPUs on the agent’s node. * **gpu_type** (*str* *|* *None*) – Short GPU name such as `h100-80`, `b200` or `l4`. * **Returns:** A dictionary containing the deployment result. * **Return type:** dict[str, Any] * **Raises:** [**ArenaValidationError**](cli/python-client.md#agilerl.exceptions.ArenaValidationError) – When `num_gpus` is below 1 or `memory_scope` is unknown. #### ArenaClient.update_inference_deployment(name, new_name=None, description=None, enabled=None, experiment_name=None, project_name=None) Rename, describe, or enable a deployment. * **Parameters:** * **name** (*str*) – Current deployment name. * **new_name** (*str* *|* *None*) – Replacement display name. * **description** (*str* *|* *None*) – Replacement description. * **enabled** (*bool* *|* *None*) – `True` enables the deployment, `False` disables it. * **experiment_name** (*str* *|* *None*) – Experiment name when several deployments share `name`. * **project_name** (*str* *|* *None*) – Project name when several deployments share `name`. * **Returns:** The updated deployment. * **Return type:** dict[str, Any] #### ArenaClient.list_inference_deployments(\*, name=None, experiment_name=None, project_name=None) List inference deployments available to the user. * **Parameters:** * **name** (*str* *|* *None*) – The name of the deployment to list. * **experiment_name** (*str* *|* *None*) – The name of the experiment to list deployments for. * **project_name** (*str* *|* *None*) – The name of the project to list deployments for. * **Returns:** A list of deployments. * **Return type:** list[dict[str, Any]] #### ArenaClient.delete_inference_deployment(name, experiment_name=None, project_name=None) Archive a deployment. * **Parameters:** * **name** (*str*) – Deployment name. * **experiment_name** (*str* *|* *None*) – Experiment name when several deployments share `name`. * **project_name** (*str* *|* *None*) – Project name when several deployments share `name`. * **Returns:** `{"success": true}` when the deployment is archived. * **Return type:** dict[str, Any] #### ArenaClient.open_inference_agent(deployment_name, \*, refresh=False, experiment_name=None, project_name=None, timeout=None) Build an `Agent` for a named deployment. Attempts to load the deployment from the cache, and if not found, fetches it from the API. The agent carries this client’s own credential, so run [`login()`](cli/python-client.md#agilerl.client.ArenaClient.login) or set `ARENA_API_KEY` before using a deployment that keeps memory per user. It reads the credential on each request, so a login’s access token is refreshed before it expires. * **Parameters:** * **deployment_name** (*str*) – The name of the deployment to open. * **refresh** (*bool*) – Whether to refresh the deployment metadata. * **experiment_name** (*str* *|* *None*) – Experiment name to disambiguate when multiple deployments share the same deployment name. * **project_name** (*str* *|* *None*) – Project name to disambiguate when multiple deployments share the same deployment name. * **timeout** (*int* *|* *None*) * **Return type:** [*Agent*](cli/python-client.md#agilerl.inference.Agent) A redeploy moves the deployment to a new URL, which leaves the cached one answering 404. Rather than make you pass *refresh* to find that out, a 404 from the cached URL refetches it once and retries. * **Parameters:** * **timeout** (*int* *|* *None*) – HTTP timeout in seconds for the returned agent’s inference requests. * **deployment_name** (*str*) * **refresh** (*bool*) * **experiment_name** (*str* *|* *None*) * **project_name** (*str* *|* *None*) * **Returns:** An `Agent` instance. * **Return type:** [Agent](cli/python-client.md#agilerl.inference.Agent) ## Inference `ArenaClient.open_inference_agent` returns an `Agent` bound to one deployment. ### *class* Agent(endpoint, \*, api_key=None, org_key=None, external_user_id=None, timeout=30, generate_params=None, probe_on_init=True, assertion_source=None) HTTP client for a deployed Arena inference endpoint. When *probe_on_init* is `True` (default), [`status()`](cli/python-client.md#agilerl.inference.Agent.status) runs once at construction and stores `metadata`. Wrong endpoint for the deployment type returns HTTP 400 from the server. Every request carries your own Arena credential as `Authorization: Bearer`. A deployment that keeps memory per user works out who is calling from it, so there is nothing else to pass. Organisation-key clients also send `X-External-User-Id`. The credential is never logged, shown in `repr()`, or written to disk. * **Parameters:** * **endpoint** (*str*) – Base URL of the Arena inference deployment. * **api_key** (*str* *|* *Callable* *[* *[* *]* *,* *str* *|* *None* *]* *|* *None*) – Profile PAT (`arena_pat__`) or access token, or a callable that returns one for each request. A login’s access token expires within minutes, so [`open_inference_agent()`](cli/python-client.md#agilerl.client.ArenaClient.open_inference_agent) passes a callable that refreshes it. Falls back to the `ARENA_API_KEY` environment variable. * **org_key** (*str* *|* *None*) – Organisation API key (`arena_org_…`). Requires *external_user_id*. Falls back to `ARENA_ORG_KEY`. * **external_user_id** (*str* *|* *None*) – Partner user id sent as `X-External-User-Id`. Requires *org_key*. Falls back to `ARENA_EXTERNAL_USER_ID`. * **timeout** (*int*) – Request timeout in seconds. * **generate_params** ([*LLMParams*](cli/python-client.md#agilerl.inference.LLMParams) *|* *None*) – Default LLM sampling parameters; defaults to [`LLMParams`](cli/python-client.md#agilerl.inference.LLMParams) when `None`. * **probe_on_init** (*bool*) – If `True`, fetch `GET /status` during `__init__`. * **assertion_source** (*Callable* *[* *[**str* *]* *,* *DeploymentAssertion* *]* *|* *None*) – Mints a `DeploymentAssertion` for the deployment id in `metadata`. #### status(\*, refresh=False) Return deployment metadata. * **Parameters:** **refresh** (*bool*) – Whether to refresh the metadata. * **Returns:** The deployment metadata. * **Return type:** StatusResponse #### generate(prompts, \*, params=None, session_id=None) Generate LLM completions. * **Parameters:** * **prompts** (*str* *|* *list* *[**str* *]*) – The prompts to the agent. * **params** ([*LLMParams*](cli/python-client.md#agilerl.inference.LLMParams) *|* *dict* *[**str* *,* *Any* *]* *|* *None*) – The parameters to the agent. * **session_id** (*str* *|* *None*) – Chat session to continue, as listed by [`list_sessions()`](cli/python-client.md#agilerl.inference.Agent.list_sessions). When omitted, a new session id is sent, so the call starts a new conversation. * **Returns:** The LLM results. * **Return type:** LLMResults #### generate_stream(prompt, \*, params=None, session_id=None) Stream generated tokens for a single prompt. * **Parameters:** * **prompt** (*str*) – The prompt to the agent. * **params** ([*LLMParams*](cli/python-client.md#agilerl.inference.LLMParams) *|* *dict* *[**str* *,* *Any* *]* *|* *None*) – The parameters to the agent. * **session_id** (*str* *|* *None*) – Chat session to continue, as listed by [`list_sessions()`](cli/python-client.md#agilerl.inference.Agent.list_sessions). When omitted, a new session id is sent, so the call starts a new conversation. * **Returns:** An iterator of strings. * **Return type:** Iterator[str] #### list_sessions() List the chat sessions the calling user has with this deployment. * **Returns:** The sessions, most recently updated first as ordered by the deployment. Empty when the user has no conversations yet. * **Return type:** list[SessionInfo] #### get_session(session_id) Fetch one chat session and its messages. * **Parameters:** **session_id** (*str*) – The ID of the session to fetch. * **Returns:** The session and its messages. * **Return type:** SessionDetail #### delete_session(session_id) Delete a chat session and every turn the deployment stored for it. Deleting is idempotent: a session that is already gone, or that belongs to someone else under the deployment’s memory scope, answers the same way, so this reports whether there was anything to delete rather than raising. * **Parameters:** **session_id** (*str*) – The ID of the session to delete. * **Returns:** `True` if the session was deleted, `False` if the deployment has no such session visible to you. * **Return type:** bool #### close() Close the underlying HTTP connection pool. * **Return type:** None ### *class* LLMParams LLM sampling parameters model. * **Parameters:** * **max_new_tokens** (*int*) – The maximum number of new tokens to generate. * **temperature** (*float*) – The temperature of the LLM. * **top_p** (*float*) – The top-p value of the LLM. * **do_sample** (*bool*) – Whether to sample the LLM. #### *field* do_sample *: bool* *= True* #### *field* max_new_tokens *: int* *= 100* #### *field* temperature *: float* *= 0.7* #### *field* top_p *: float* *= 0.9* ## Errors Every error the client raises is an `ArenaError`. ### *exception* ArenaError Base exception for all Arena client errors. ### *exception* ArenaAuthError(message, \*, sdk_hint='', cli_hint='') Raised when authentication fails or credentials are missing/expired. * **Parameters:** * **message** (*str*) * **sdk_hint** (*str*) * **cli_hint** (*str*) * **Return type:** None ### *exception* ArenaTimeoutError(message, \*, sdk_hint='', cli_hint='') Raised when the device-flow login times out waiting for user authorization. * **Parameters:** * **message** (*str*) * **sdk_hint** (*str*) * **cli_hint** (*str*) * **Return type:** None ### *exception* ArenaAPIError(detail, \*, status_code=0, extras=None, sdk_hint='', cli_hint='') Raised when the Arena API returns a non-2xx response. * **Parameters:** * **detail** (*str*) – Human-readable error description. * **status_code** (*int*) – HTTP status code from the API response. * **extras** (*dict* *[**str* *,* *Any* *]* *|* *None*) – Supplementary context from the error body. * **sdk_hint** (*str*) – Guidance shown when running from the Python SDK. * **cli_hint** (*str*) – Guidance shown when running from the CLI. * **Return type:** None ### *exception* ArenaValidationError(detail, \*, status_code=0, extras=None, sdk_hint='', cli_hint='') Raised when environment validation fails or client arguments are invalid. * **Parameters:** * **detail** (*str*) * **status_code** (*int*) * **extras** (*dict* *[**str* *,* *Any* *]* *|* *None*) * **sdk_hint** (*str*) * **cli_hint** (*str*) * **Return type:** None ### *exception* ArenaInferenceError(detail, \*, status_code=0, extras=None, sdk_hint='', cli_hint='') Raised when an Arena inference deployment request fails or inputs are invalid. * **Parameters:** * **detail** (*str*) * **status_code** (*int*) * **extras** (*dict* *[**str* *,* *Any* *]* *|* *None*) * **sdk_hint** (*str*) * **cli_hint** (*str*) * **Return type:** None ### *exception* ArenaTrainingError(detail, \*, status_code=0, extras=None, sdk_hint='', cli_hint='') Raised when a training job submission or execution fails. * **Parameters:** * **detail** (*str*) * **status_code** (*int*) * **extras** (*dict* *[**str* *,* *Any* *]* *|* *None*) * **sdk_hint** (*str*) * **cli_hint** (*str*) * **Return type:** None ### *exception* ArenaClientUpgradeRequiredError(detail, \*, status_code=0, extras=None, sdk_hint='', cli_hint='') Raised when Arena refuses this agilerl release as below its minimum (HTTP 426). * **Parameters:** * **detail** (*str*) * **status_code** (*int*) * **extras** (*dict* *[**str* *,* *Any* *]* *|* *None*) * **sdk_hint** (*str*) * **cli_hint** (*str*) * **Return type:** None ### *exception* ArenaEnvironmentNotFoundError(detail, \*, status_code=0, extras=None, sdk_hint='', cli_hint='') Raised when a referenced environment does not exist in Arena. * **Parameters:** * **detail** (*str*) * **status_code** (*int*) * **extras** (*dict* *[**str* *,* *Any* *]* *|* *None*) * **sdk_hint** (*str*) * **cli_hint** (*str*) * **Return type:** None ### *exception* ArenaConfigError(message, \*, sdk_hint='', cli_hint='') Raised when required configuration (e.g. default project) is missing. * **Parameters:** * **message** (*str*) * **sdk_hint** (*str*) * **cli_hint** (*str*) * **Return type:** None # compute/byoc.md # How BYOC works Training runs on Arena’s cloud by default. Bring your own compute (BYOC) runs it on Kubernetes you control instead: your own hardware, a cluster you run on any cloud (GKE included), or one the Arena CLI creates for you on Nebius or AWS. Arena still holds your projects, experiments and results. The training jobs, checkpoints and deployments run on your cluster and write to your storage bucket. BYOC needs an **Enterprise** organization. Hours on your clusters are billed at your BYOC contract rates, shown on the **Billing** tab. For runs on your clusters Arena charges a flat platform fee, `$2.00` for each hour a training run runs and `$1.00` for each hour a deployment is up, whatever the number of nodes or GPUs; see [How charges work](account/billing.md#how-charges-work). To move an organization to **Enterprise**, contact AgileRL; see [Billing and credits](account/billing.md). ## Who does what An org **Admin** sets BYOC up once: 1. Open the profile menu, click **Settings**, then the **Bring your own compute** tab. 2. Connect a cluster: `arena cluster connect` checks the cluster, registers it, installs the agent and waits until the agent reports its health. The agent is a service in your cluster that runs Arena’s training jobs there; it is not a deployed agent from the **Agents** page. The install needs cluster-admin, and so do later upgrades that change the agent’s permissions. See [Install a BYOC cluster](compute/install-byoc-cluster.md). 3. Add a resource class for each pool of worker machines. Arena suggests one for each kind of GPU node the agent found, and you create them with one click or one prompt. See [Resource classes](compute/resource-classes.md). 4. Keep it healthy. The agent reports its health every 10 minutes. Agent upgrades that change its Kubernetes permissions wait for a cluster admin to approve them. Rotating the agent’s credential asks the agent to renew it; the current one keeps working until it does, so there is nothing to install. The same **Admin** approves agent upgrades, rotates or revokes the agent’s credential and edits classes later. **Members** don’t change anything on that tab. Once a class is enabled on a connected cluster, they pick it like any other GPU type when they build an experiment: under **Training resources**, BYOC rows end in **(BYOC)**, for example **A100 80GB (BYOC)**. See [Choose compute](guides/choose-compute.md). ## What runs where - The agent connects out to Arena and sets up a private tunnel, so the cluster needs outbound network access to Arena and no inbound access. Its nodes also pull Arena’s images from a private registry, with a login the agent renews itself. - Checkpoints, metrics and datasets for runs on your cluster go to the bucket you register with it. They don’t go to Arena’s cloud storage. - Deployments from those checkpoints can serve on the same cluster. One cluster can hold several resource classes, one per hardware pool. Each class shows up as its own row under **Training resources**. ## Turn BYOC off for some or all runs There is no single off switch. To keep classes out of new runs: - Turn a class off with its **On** toggle. It stays in the table. - **Disable** a cluster to stop all of its classes at once. This also revokes the agent’s credentials. **Restore** brings it back; then issue a new agent token and install the agent again. - **Archive** a cluster you are finished with. Its classes are archived with it. ## Classes from the older per-class install Before clusters, BYOC installed Ray once per resource class. If your organization still has classes from that setup, they appear under **Resource classes without a registered cluster** and new experiments can’t use them. To move across: 1. Register a cluster and install the agent ([Install a BYOC cluster](compute/install-byoc-cluster.md)). 2. Add new classes to that cluster, with new names. The agent sets up Ray for each one; there is no per-class install. 3. Start new experiments on the new classes. Let jobs on the old classes finish. 4. Remove the old per-class Ray installs from your machines, then delete the old classes. To reuse the same machines, stop starting jobs on the old classes and wait for running jobs to finish before step 1. Checkpoints from old runs stay in Arena’s cloud storage. New runs write to your bucket. A deployment on your cluster needs a checkpoint that is already in your bucket, so an old cloud-trained checkpoint can’t be deployed there yet. If several teams share the hardware the old classes run on, contact AgileRL and we’ll plan the cutover with you. # compute/install-byoc-cluster.md # Install a BYOC cluster Connect a Kubernetes cluster to Arena and install the agent into it, so your organization can train on it. On a cluster you already run, one command does it: `arena cluster connect` checks the cluster, registers it, installs the agent, waits for the agent to report its health and offers resource classes for the GPUs it found. Training runs on Arena’s cloud unless you do this; see [How BYOC works](compute/byoc.md) for what changes. ## Prerequisites Everyone needs: - An **Enterprise** organization and the org **Admin** role. - The Arena CLI, recent enough to have `arena cluster connect`, signed in (`uv tool install --upgrade agilerl`, then `arena login`, or set `ARENA_API_KEY`). See [Install and sign in](cli/install.md). The web app path can skip it if you install with Helm. - `kubectl` and Helm 3 on the machine that runs the install. - A kubeconfig context for the cluster with cluster-admin rights. The install creates ClusterRoles and admission policies, so it needs those rights once. Later, only agent upgrades that change the agent’s permissions need them again. The cluster needs: - Kubernetes 1.30 or later. - GPU nodes that advertise `nvidia.com/gpu`, from the NVIDIA GPU Operator or device plugin. Resource classes pick GPU nodes by the `nvidia.com/gpu.product` label, which NVIDIA GPU Feature Discovery (part of the GPU Operator) sets. - One default StorageClass, or a StorageClass you name for Ray data. - A namespace for the agent (`arena` by default) that allows privileged pods. The agent’s tunnel container and storage sidecar run privileged. - No other Arena agent. Arena runs one agent per Kubernetes cluster. - Outbound HTTPS to Arena, and outbound UDP to the Arena tunnel gateway. The gateway host is `wireguard.gatewayHost` in the agent Helm values Arena generates. The cluster needs no inbound access. - Outbound HTTPS from the nodes to Arena’s private image registry, `761296822462.dkr.ecr.us-east-1.amazonaws.com`, and to the S3 endpoint it serves image layers from, `prod-us-east-1-starport-layer-bucket.s3.us-east-1.amazonaws.com`. Arena’s images are not public; see [Image pulls](#image-pulls). What else depends on the **Cloud provider** you pick: | Cloud provider | You bring | You also need | |-----------------------|--------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------| | **Custom** | A Kubernetes cluster you already run (self-managed, EKS, GKE or similar), and an S3-compatible bucket it can reach | A Secret with the bucket’s credentials (Step 1) | | **Nebius** or **AWS** | A cloud account. The Arena CLI creates the cluster and its bucket. | `terraform`, and the cloud’s own CLI (`nebius` or `aws`) signed in on the same machine | Arena never creates a cluster from the browser. For **Nebius** and **AWS**, registering in the web app gives you the command to run. Arena doesn’t provision clusters on Google Cloud. To use GKE or any other Kubernetes, create the cluster yourself and register it as **Custom**. ## Step 1: Create the storage Secret (Custom only) The agent reads your bucket’s credentials from a Secret in its namespace, `arena`. Put the keys in a file, `arena-storage.env`: ```text AWS_ACCESS_KEY_ID= AWS_SECRET_ACCESS_KEY= ``` Then create the namespace and the Secret. Both commands are safe to re-run: ```bash kubectl --context '' create namespace arena --dry-run=client -o yaml \ | kubectl --context '' apply -f - kubectl --context '' create secret generic arena-storage -n arena \ --from-env-file=arena-storage.env \ --dry-run=client -o yaml | kubectl --context '' apply -f - ``` No bucket yet and just trying BYOC out? The CLI can install a bundled MinIO into the cluster instead; add `--install-storage` to `arena cluster register` in Step 3. ## Step 2: Run preflight (optional) Preflight tells you what would stop the install before anything changes. It only reads the cluster, and it changes nothing in Arena. ```bash arena cluster preflight --context '' ``` It prints one row per check, each with `PASS`, `WARN` or `FAIL`, and a fix for anything that is not a pass: | Check | What it looks at | |------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------| | `kubernetes_version` | Kubernetes 1.30 or later | | `can_create_*` | You may create namespaces, ClusterRoles, ClusterRoleBindings, and validating admission policies and bindings. A `no` here fails | | `can_escalate_clusterroles`, `can_bind_clusterroles` | Warns without these. cluster-admin has both | | `node_inventory` | GPU nodes by product and GPU count. Warns when no node has GPUs, or when a GPU node has no `nvidia.com/gpu.product` label | | `storage_class` | One default StorageClass, or that the class you passed with `--ray-data-storage-class-name` exists | | `privileged_pods` | A dry run of a privileged pod in the agent namespace (or `default` if that namespace does not exist yet). Kubernetes admits or refuses it without creating it | | `one_agent` | No other Arena agent is installed in the cluster | The command exits non-zero when any check fails. Warnings do not stop it. `--name` names an Arena cluster you already registered, so its own agent does not count as a second one. `--agent-namespace` checks a namespace other than `arena`. `--json` prints the whole report as one JSON document: the context, the API server, the cluster’s ID, whether it passed, and every check, each with its name, status, detail and fix. `arena cluster connect` runs the same checks first. Run preflight on its own when someone else will do the install: without cluster-admin the permission rows fail, but the other rows still show what the cluster is missing. ## Step 3: Register the cluster and install the agent Cluster names are unique in your organization. Registering a name that already exists updates that cluster. ### Web app 1. Open the profile menu, click **Settings**, then the **Bring your own compute** tab. 2. Click **Register cluster**. 3. Enter a **Name** and pick a **Cloud provider**: **Custom**, **Nebius** or **AWS**. You can’t change the provider later. 4. Fill in the provider’s fields: - **Custom**: under **Checkpoint storage**, the **Storage endpoint** (the S3 API the agent can reach, such as `https://s3.corp.example.com`), **Bucket**, and **Secret name** from Step 1. **Prefix** is optional. - **Nebius**: **Tenant ID** and **Region**, and optionally **Project ID** and **Subnet ID**. An empty **Project ID** creates a compute project, and an empty **Subnet ID** creates a VPC and subnet. A **Subnet ID** needs a **Project ID**. **Storage project ID** under **Networking and advanced** names an existing project for object storage and Terraform state; leave it empty to create one. The bucket is named after the cluster. - **AWS**: **Region**, **Kubernetes version** and **Arena instance type** (the CPU nodes the agent runs on). The form has no GPU workers: add them under `workers` in the spec file before you provision, or the cluster has no GPU nodes. The bucket is named after the cluster. 5. Leave **Networking and advanced** alone unless you need the settings described [below](#networking-and-advanced-settings). 6. Click **Register and continue**. The install dialog opens. 7. Install: - **Custom**: copy the `arena cluster register … --install` command under **Install the agent** and run it where `kubectl` points at your cluster. Without the Arena CLI, open **Install with Helm instead**: download the **Install package (.tar.gz)**, which has the charts, values, GitOps manifests and an `INSTALL.md` to follow on a bastion, or copy the **Helm install command** and `agent-helm-values.yaml`. The Helm command from the install package is safe to re-run. A new agent token is shown only once, so click **Copy agent token** before you close the dialog. - **Nebius** or **AWS**: under **Provision the cluster**, download the spec file and run the command shown. It creates the cluster, registers it and installs the agent. If the CLI rejects the file with `values and registration are not accepted`, write the spec with `arena cluster generate-spec` instead and keep the cluster name; see the CLI tab. 8. The steps at the top of the dialog (**Register**, **Install agent**, **Agent connects**, **Health checks**) and the status at the bottom fill in as the agent reports, so you can leave the dialog open while you run the command. Click **Done**. The cluster shows **Pending install** until the agent first checks in, then **Connected**. To open the install dialog again later, select the cluster and click **Install agent**, which reads **Reinstall** once the agent has checked in. ### CLI **Custom.** One command checks, registers and installs: ```bash arena cluster connect --name corp-k8s --context '' \ --storage-endpoint https://s3.corp.example.com \ --storage-bucket arena-data \ --storage-secret-name arena-storage ``` `connect`: 1. Runs preflight and stops on a failed check. Nothing has changed in Arena or the cluster at that point. 2. Registers the cluster in Arena, and turns on BYOC for your organization if it is not on yet. 3. Records which Kubernetes cluster it installed into. Every later command for this cluster checks that it is pointed at the same one. 4. Installs the agent with Helm as release `arena-byoc-agent` in namespace `arena`. 5. Waits for the agent’s first heartbeat, then for its first health report, and prints the health checks. 6. Lists the resource classes Arena suggests from the GPU nodes the agent found, and asks whether to create them. See [Step 5](#step-5-add-resource-classes). It ends with `Cluster 'corp-k8s' is connected`. If the health report has a failing check, the command says so and exits non-zero. The cluster is still connected: fix the check and the agent reports again within 10 minutes. `--wait-timeout` sets how long it waits for the heartbeat and the health report (default 900 seconds), `--ray-data-storage-class-name` names a StorageClass for Ray data, and `--yes` creates the suggested classes without asking. Running `connect` again with the same name updates the cluster, upgrades the agent in place and keeps its token. Use that to change storage settings or to repair an install. `--rotate-token` issues a new agent token for a cluster that is already registered. `arena cluster register --install` also registers and installs, without the preflight and the wait. It takes the same flags as `connect`, plus the flags for the [networking and advanced settings](#networking-and-advanced-settings) and `--install-storage`. It writes the Helm values and agent token to `./arena-cluster-corp-k8s`; add `--no-write` to keep them off disk. Without `--install`, it only registers and writes those files. After the install it offers the suggested classes if the agent has already reported its nodes; right after a first install it usually hasn’t, and the CLI says so. If the agent namespace has no token Secret yet, for example because you registered the cluster in the web app and haven’t installed it, `--install` stops and asks for `--rotate-token`. The install command the web app shows after it issues a token already has `--rotate-token`. **Nebius.** Start from a spec file, fill in your cloud IDs, check the plan, then provision: ```bash arena cluster generate-spec --provider nebius --name lab-cluster arena cluster plan --spec lab-cluster.yaml --create-state-bucket arena cluster provision nebius --spec lab-cluster.yaml \ --create-state-bucket --register-and-install ``` The spec needs a dedicated bucket for Terraform state, separate from the experiment-data bucket. `--create-state-bucket` creates it if it’s missing; without the flag, `plan` and `provision` ask before creating it. `--register-and-install` registers the cluster with Arena and installs the agent once the cluster is up. If you already registered the cluster in the web app, the spec file you downloaded there has the same name; run `provision` without `--register-and-install`, then install the agent with the command from **Install agent** on the cluster. **AWS.** See [Provision on AWS](#provision-on-aws) below. `arena cluster status --spec lab-cluster.yaml` prints the cluster’s endpoints and node groups afterwards. Every flag is listed in the [command reference](cli/commands/cluster.md). The `arena cluster` commands, and their `--help`, only appear once you’re signed in to an **Enterprise** organization. ### GitOps install (Argo CD or Flux) If you manage the cluster with Argo CD or Flux, let it install and upgrade the agent from Arena’s chart registry instead of running Helm yourself. The install package has a `gitops/` folder: | File | What | |----------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `gitops/argocd-application.yaml` | An Argo CD `Application` in namespace `argocd` | | `gitops/flux.yaml` | A Flux `HelmRepository` and `HelmRelease` in namespace `arena` (Flux 2.7.5 or later, the first release that accepts this HelmRelease and limits the status a failed upgrade records) | Both install the chart `arena-byoc-agent` at the version this Arena release ships, as release `arena-byoc-agent` in namespace `arena`, with the same values as the Helm install plus `upgrade.mode: gitops`. The values name each Secret the agent reads and hold no token, key or password, so the files can go in git. 1. **Create the Secrets once.** `INSTALL.md` in the package has a bootstrap command. It creates namespace `arena`, the Secrets from the package’s `secrets/` folder (the agent token, the 12-hour registry login, and the WireGuard keys on a tunnel cluster), and the provisioner’s SSH key and token, which it generates only when they do not exist yet. Run it before the manifest, and again only with a new install package. Keep the Secrets out of git and out of your GitOps tool: after its first poll the agent replaces the token with its own credential (`arena-byoc-agent-credential`) and renews its registry login (`arena-byoc-agent-image-pull`) itself. 2. **Apply the manifest.** Commit one of the files to the repository your Argo CD or Flux syncs, or `kubectl apply -f` it. Flux pulls the chart with the agent’s registry login. Argo CD needs a repository Secret for `/charts` (the `repoURL` in the Application), with user name `AWS` and the password from the agent’s login. The login lasts 12 hours and the agent renews it every few hours, so copy it again on a schedule: ```bash kubectl -n arena get secret arena-byoc-agent-image-pull -o jsonpath='{.data.\.dockerconfigjson}' \ | base64 -d | jq -rj '.auths[].password' > password kubectl -n argocd create secret generic arena-charts \ --from-literal=type=helm --from-literal=name=arena-charts --from-literal=enableOCI=true \ --from-literal=url=/charts --from-literal=username=AWS --from-file=password \ --dry-run=client -o yaml \ | kubectl label --local -f - argocd.argoproj.io/secret-type=repository -o yaml \ | kubectl apply -f - rm password ``` 3. **Check health** as in [Step 4](#step-4-check-health). To upgrade, change the chart version in the manifest (`targetRevision` for Argo CD, `chart.spec.version` for Flux) to the one a newer install package shows, or write the new manifest with `arena cluster manifest --name --format argocd|flux`. Arena does not upgrade a GitOps install itself and offers no upgrade button for it. Before each upgrade the chart’s drain hook holds new runs and waits until nothing is running on the cluster, for up to 30 minutes; a sync that times out is retried up to an hour later, until it succeeds. In Argo CD, a sync that is still retrying keeps the chart version and values it started with: change them, then terminate it (`argocd app terminate-op arena-byoc-agent`). Flux reads the HelmRelease again on each retry, and a new chart version upgrades straight away. If the new version changes the agent’s ClusterRoles, your GitOps tool needs the rights to apply them. If you re-register the cluster with a new token, run the new package’s bootstrap command, then restart the agent with `kubectl -n arena delete pod -l app.kubernetes.io/name=arena-byoc-agent`. To move an agent installed with Helm to GitOps, keep the provisioner’s SSH key: running job VMs accept only that key. Don’t `helm uninstall`, which deletes it. 1. Run the bootstrap command. It keeps the existing provisioner Secrets. 2. Detach those Secrets from the Helm release, so that neither Helm nor your GitOps tool deletes them: ```bash kubectl -n arena label secret arena-byoc-provisioner-ssh arena-byoc-provisioner-token \ app.kubernetes.io/instance- app.kubernetes.io/managed-by- helm.sh/chart- kubectl -n arena annotate secret arena-byoc-provisioner-ssh arena-byoc-provisioner-token \ meta.helm.sh/release-name- meta.helm.sh/release-namespace- ``` 3. Delete Helm’s release records: `kubectl -n arena delete secret -l owner=helm,name=arena-byoc-agent`. 4. Apply the manifest. Argo CD or Flux adopts the agent’s other objects. ### Image pulls Arena’s images (the agent, the validators, training and inference) are in a private registry. The agent Helm values Arena generates carry a registry login that lasts 12 hours (`imagePull.credential`), and the chart keeps it in the Secret `arena-byoc-agent-image-pull`. Keep the values file private, like the token. After that the agent renews the login itself every few hours, signing in to Arena with its own token, and copies it into each job and deployment namespace as the Secret `arena-image-pull`. Nothing else is needed. If the agent cannot renew the login, the **Image pull credential** health check turns red and says why. Pods that are already running keep running. A cluster that was offline for more than 12 hours may not be able to start the agent’s pods on a new node; run `arena cluster upgrade` to install a fresh login. When a GitOps tool installs the agent, the values in git hold no login: the bootstrap command creates `arena-byoc-agent-image-pull` from the install package, and the agent renews it from then on. If your own tooling keeps a login Secret fresh, set `imagePull.mode: external` and `imagePull.secretName` to that Secret, and the agent only copies it. ## Step 4: Check health The agent sends a health report when it starts and every 10 minutes. On the **Bring your own compute** tab, select the cluster and look at **Health**. Each check shows **OK**, **Warning** or **Failing**, with the fix underneath: | Check | OK when | |---------------------------|-------------------------------------------------------------------------------------------------------------------------| | **Health report** | The last report is 25 minutes old or less | | **Kubernetes version** | 1.30 or later | | **Nodes** | At least one node advertises `nvidia.com/gpu`. The table under the checks lists GPU model, GPUs per node and node count | | **StorageClass** | One default StorageClass, or the cluster’s Ray data StorageClass exists | | **Tunnel** | The tunnel’s last handshake was within 5 minutes of the report | | **Storage** | The agent reached your bucket | | **Credential** | The cluster has an active agent token | | **Image pull credential** | The agent renewed its registry login and it has not expired | | **Agent permissions** | The agent’s ClusterRoles match this Arena release | | **One agent** | No other Arena agent runs in the cluster | **Classes with no matching nodes** lists any resource class whose node placement labels match no node the agent reported. Jobs on those classes stay pending. The status next to the cluster name, with **Last poll** under it: | Status | Meaning | |---------------------|--------------------------------------------------------------------------------------------------------------------| | **Pending install** | Registered, but the agent has not checked in yet | | **Connected** | The agent checks in every minute | | **Degraded** | The agent has not checked in for 3 minutes, or its last check-in reported an error. The error shows below the name | | **Disabled** | Credentials are revoked and the cluster takes no runs. **Restore** brings it back | | **Removing** | The agent is deleting its job namespaces before Arena archives the cluster | The cluster’s details also show its **Provider**, **Agent token** (whether it has an active one), **Token last used**, **Enabled capacity** (nodes and GPUs across enabled classes), and the **Storage bucket**, **Storage prefix** and **Storage endpoint** the agent stores checkpoints and datasets in. Notices above the details, such as **Needs your approval** or **Credential renewal pending**, are covered under [Approve and apply agent upgrades](#approve-and-apply-agent-upgrades) and [Rotate or revoke the agent credential](#rotate-or-revoke-the-agent-credential). ## Step 5: Add resource classes A resource class is one pool of worker machines that jobs can run on. Once the agent has reported its nodes, Arena suggests one class for each GPU model and GPU count it found, with the CPUs, memory, node count and node placement label filled in from the nodes. ### Web app Select the cluster on the **Bring your own compute** tab and find **Suggested classes** below **Resource classes**. Click **Create** on each one you want. For hardware Arena didn’t suggest, click **Add resource class**. See [Resource classes](compute/resource-classes.md). ### CLI `arena cluster connect` and `arena cluster register` list the suggestions and ask `Create these classes?`. Pass `--yes` to create them without asking. In a script without `--yes`, they print the suggestions and create nothing. On **Nebius** and **AWS**, `--register-and-install` already added a class for each GPU worker group in the spec, named `-`, and skips suggestions. Add more only for hardware outside the spec. On Nebius, `arena cluster register-classes` adds more from the CLI; see [Resource classes](compute/resource-classes.md#from-the-cli). A created suggestion is an ordinary class: edit, turn off or delete it like any other. Arena doesn’t suggest a shape that an existing class already selects. When **Suggested classes** asks you to upgrade the agent, run `arena cluster upgrade`: older agents don’t report node CPU and memory. ## Step 6: Check that it works 1. The cluster shows **Connected**, and **Health** has no **Failing** check. 2. Run a smoke test (see [Check that the cluster can run jobs](#check-that-the-cluster-can-run-jobs)): ```bash arena cluster smoke --name corp-k8s --context '' ``` 3. In a test experiment, open **Training resources**. A row ending in **(BYOC)** appears for the GPU type of each enabled class. 4. Pick it, train, and check the experiment leaves **Pending**. If it doesn’t, see [Troubleshooting](#troubleshooting). ## Provision on AWS The CLI creates an EKS cluster, its network and its storage in your AWS account with Terraform, then registers it and installs the agent. ### What you need - The `aws` CLI, signed in as an IAM user or role in the account you want to use. The account root user doesn’t work, because EKS can’t authenticate it. - Permission for that identity to create IAM users, policies and access keys. The CLI uses it to create an IAM user named `byoc-provisioner` with a policy named `byoc-provision`, stores that user’s access key in the AWS CLI profile `byoc`, and runs Terraform as that user. The policy allows EC2, EKS, EFS, Elastic Load Balancing, Auto Scaling and S3, plus the IAM actions the cluster’s roles need. `plan` sets this up too. - `terraform` 1.10 or later, `kubectl` and Helm 3. ### Write the spec ```bash arena cluster generate-spec --provider aws --name lab-aws ``` This writes `lab-aws.yaml`. The parts to check: ```yaml provider: aws name: lab-aws # also the EKS cluster name arena: storage: bucket: lab-aws-data # experiment data; Terraform creates it endpoint: https://s3.eu-west-1.amazonaws.com # change to match aws.region inference: domain: lab-aws.inference.agilerl.rlops.ai terraform_state: bucket: lab-aws-tfstate # must differ from arena.storage.bucket aws: region: eu-west-1 system: {min_node_count: 2, max_node_count: 10, instance_type: t3.xlarge} workers: - name: gpu min_node_count: 0 max_node_count: 4 instance_type: g6.xlarge num_cpus: 16 num_gpus: 1 memory_gib: 64 gpu_type: l4 vram_gib: 24 object_storage: size_gib: 1024 ``` - **Region.** If you change `aws.region`, change the region in `arena.storage.endpoint` too. The template doesn’t do it for you. - **Workers.** `workers` is empty in the template, which gives a cluster with no GPUs. Add a group for each kind of GPU machine. A GPU group needs `num_cpus`, `memory_gib`, `gpu_type` and `vram_gib` as well as the instance type. Each GPU group becomes a resource class named `lab-aws-`, sized to `max_node_count`. - **Network.** There are no VPC or subnet fields. Terraform creates a VPC with two public subnets in the region. The account is the one your `aws` credentials belong to. `kubernetes_version` defaults to `1.36`. Set `aws.shared_filesystem.provision: true` to add an EFS file system and a StorageClass named `arena-shared`. ### Plan and provision ```bash arena cluster plan --spec lab-aws.yaml --create-state-bucket arena cluster provision aws --spec lab-aws.yaml \ --create-state-bucket --register-and-install ``` `--create-state-bucket` creates the state bucket if it’s missing. The positional `aws` is optional, but if you give it, it must match `provider` in the spec. Run every `arena cluster` command for this cluster from the same folder. The CLI keeps its Terraform state, the state bucket’s credentials and the kubeconfig in `./arena-cluster-lab-aws/`, or in the folder you pass with `--state-dir`. ### Use the cluster with kubectl The CLI writes the cluster’s kubeconfig to `./arena-cluster-lab-aws/kubeconfig`. It doesn’t change `~/.kube/config`. To point `kubectl` and `helm` at the new cluster: ```bash export KUBECONFIG=$PWD/arena-cluster-lab-aws/kubeconfig ``` The kubeconfig gets its credentials from the `aws` CLI, so keep the CLI installed on that machine. Without `--register-and-install`, `provision` stops after creating the cluster and prints the register command to run next, with this `KUBECONFIG` set. ### Tear it down ```bash arena cluster destroy --spec lab-aws.yaml ``` This keeps the experiment-data bucket. `--delete-storage` deletes it too, and `--all` also removes the state bucket. If the cluster is registered in Arena, the CLI asks whether to unregister it. ## Networking and advanced settings All optional. They sit under **Networking and advanced** on the form, and have matching flags on `arena cluster register`. **Domain** is where deployments on this cluster are served. The form fills in `-.byoc.agilerl.com`. Keep it and Arena handles DNS and HTTPS for you: it publishes a wildcard record for the domain once your Gateway or Ingress controller has an address, and issues and renews the certificate. The records track the address the agent reports and are removed when you disable or archive the cluster. Type your own domain instead and you point `*.` at your load balancer yourself, and set **TLS secret name** to a certificate you manage. Clear both **Domain** and **Hostname template** to skip inference DNS. **Hostname template** is the host part only. It defaults to `inference-{deploymentId}`, and Arena joins it to the domain as `.`. Route with Gateway API (**Gateway name**, **Gateway namespace**, **Gateway section name**) or with Ingress (**Ingress class name**). With Ingress, set `routing.ingressControllers` in the agent’s Helm values to the Service in front of your Ingress controller, or there is no address to publish. **Ray data storage class** and **Ray data PVC size** give every node in a run the same volume. Use a `ReadWriteMany` StorageClass your platform team already runs (NFS, CephFS or similar). Leave them empty to use the cluster’s default. **Preprocessing resource class** pins dataset preprocessing to one of this cluster’s classes. ## Choose the Kubernetes cluster Every command that touches Kubernetes (`preflight`, `connect`, `register --install`, `upgrade`, `smoke`, `unregister`) takes `--kubeconfig` and `--context`. Without `--context` it uses the current context of `--kubeconfig`, of `./arena-cluster-NAME/kubeconfig`, or of your default kubeconfig. For the default kubeconfig it shows the context and API server and asks first; in a script it stops and asks for `--context`. Arena remembers each cluster by the UID of its `kube-system` namespace, taken at `connect` or `register --install`, or from the agent’s first check-in for a cluster registered earlier. A command pointed at a different Kubernetes cluster stops before it changes anything, with `Kubernetes context … is not Arena cluster '…'`. Pass `--context` for the right cluster, or register the other cluster under its own name. ## Move a cluster to another Kubernetes cluster To keep an Arena cluster, its resource classes and its history while it runs somewhere else, move it rather than registering a new one. Only an Arena platform admin can move a cluster: AgileRL support on Arena at agilerl.com, or whoever runs your self-hosted Arena. Move it when no runs or deployments are active on the cluster. Arena refuses the move while an experiment, a Ray cluster, or an enabled deployment is still active. 1. Cut off and remove the agent on the old Kubernetes cluster: ```bash arena cluster revoke-token --name corp-k8s helm uninstall arena-byoc-agent --namespace arena --kube-context '' ``` Revoke first: an old agent that still checks in would tie the cluster to the old Kubernetes cluster again. 2. Ask your Arena platform admin to move `corp-k8s`. Arena forgets the old Kubernetes cluster, and your organization’s **Activity log** shows **Cluster Moved To Another Kubernetes Cluster**. 3. Connect the new Kubernetes cluster: ```bash arena cluster connect --name corp-k8s --context '' ``` This issues a new enrollment token and installs the agent. Arena records the new Kubernetes cluster on the agent’s first check-in, and from then on refuses any other one. An agent already installed on the new cluster before the move stopped with `Arena refused this cluster's identity: conflict`. Its pod restarts by itself within a few minutes; to pick up the move at once, restart it: ```bash kubectl rollout restart deployment/arena-byoc-agent --namespace arena --context '' ``` The agent keeps its credential in the Secret `-credential` in its namespace (`arena-byoc-agent-credential` for the default release). Reconnecting with a new token, as above, needs nothing from the old cluster. If you copy the credential Secret from the old cluster instead of reconnecting, give it the name that matches the new Helm release, or the agent falls back to its spent enrollment token and Arena refuses it. ## Approve and apply agent upgrades Arena upgrades the agent from the web app when the new release keeps the same Kubernetes permissions. When a release adds or removes ClusterRole rules, Arena holds the upgrade until a cluster admin applies it, so you choose what the agent may do in your cluster. A held upgrade shows on the cluster as **Needs your approval**, with the badge **Agent upgrade held**. The card lists each change: the ClusterRole, **Added** or **Removed**, the resource, and the verbs. Apply it one of two ways: - **With the Arena CLI.** As a cluster admin, run: ```bash arena cluster upgrade --name corp-k8s --context '' ``` The CLI prints each change, one block per ClusterRole with `+` for added and `-` for removed rules, asks `Apply these ClusterRole changes?`, then runs the Helm upgrade. In a script, pass `--yes` once you have read the changes; without it the command stops and asks you to run it in a terminal. - **Without the Arena CLI.** Open **Apply without the Arena CLI** on the card. Download the ClusterRole manifest (`arena-byoc-agent-rbac-.yaml`), apply it with the `kubectl --context '' apply -f …` command shown, then click **ClusterRoles applied, upgrade agent**. Arena then upgrades the agent from inside the cluster. When the card has no such option, use the CLI. An upgrade that keeps the same permissions shows as **Agent update available** (**A newer agent release is available for this cluster.**). Click **View update** to see the component versions, then **Upgrade agent**. On older agents it shows the `arena cluster upgrade` command instead. While an upgrade request is open, the cluster shows **Upgrading agent** and new runs on it wait, showing **Waiting for cluster upgrade**. Deployments already serving keep serving. The request closes when the agent reports the new release, or after 70 minutes, when Arena drops it and the waiting runs start. If an upgrade attempt fails, the agent rolls back to the release it had and reports `agent upgrade failed:` with Helm’s error. It starts another upgrade Job on its next poll, within a minute, during the first 20 minutes of the request. After that it starts no new Job, though one already running can still be in the cluster when **Upgrading agent** goes. When the message says `stopped after … upgrade Jobs failed`, three Jobs failed because the chart does not render or Kubernetes refused a write, and the agent starts no further Job for this release. **Upgrade agent** asks for the same release, so it doesn’t start one either. Wait until the Job `arena-byoc-agent-upgrade` has finished, then run `arena cluster upgrade` from a machine with cluster access. You can also upgrade from the terminal with `arena cluster upgrade` whenever no `arena-byoc-agent-upgrade` Job is running. It downloads the current chart and runs `helm upgrade --install` for the agent release only, and leaves the token, the tunnel Secret and the storage chart alone. It upgrades an agent that is already installed; to install one, use `connect`. An agent installed by Argo CD or Flux is upgraded from git; see [GitOps install](#gitops-install-argo-cd-or-flux). ## Rotate or revoke the agent credential The agent signs in to Arena with its own credential, kept in the Secret `arena-byoc-agent-credential` in its namespace. The install gives it a one-time enrollment token, which it trades for that credential on its first call, and it renews the credential itself. **Rotate** when a policy asks you to. Arena asks the agent to renew, and the agent picks the new credential up on its next poll, within a minute. The current credential keeps working until the agent uses the new one, so nothing goes down and there is nothing to install. **Revoke now** when you think a credential leaked. Every credential of the cluster stops working at once, and the agent’s next call to Arena is refused. Training and inference on the cluster stop reconciling until you reconnect it. ### Web app Select the cluster and open its actions menu (**⋯**): - **Rotate agent credential** asks the agent to renew. - **Revoke credentials now**, then confirm, cuts the agent off. To reconnect, choose **Issue agent token** and run the install the dialog shows. The new enrollment token is shown once, in that dialog. ### CLI Ask the agent to renew. The command needs no kubeconfig and the agent does not restart, but the agent must have connected at least once: ```bash arena cluster rotate-token --name corp-k8s ``` Cut the agent off: ```bash arena cluster revoke-token --name corp-k8s ``` Reconnect it with `arena cluster connect --name corp-k8s --context ''`, which issues a new enrollment token and installs it. Both commands take `--yes` to skip the confirmation prompt. A CLI older than this behaviour stops with `this arena CLI is too old` on `rotate-token`; upgrade it with `uv tool upgrade agilerl`. If the agent has not picked a renewal up a day later, the cluster shows **Credential renewal pending** and org admins get an email. Its current credential still works. Check that the agent is running, and upgrade it if it is older than the release that renews its own credential. **Agent token** shows whether the cluster has an active credential, and **Token last used** shows when the agent last signed in with one. If Arena refuses the agent’s credential, the cluster says **Agent is using an expired credential** or **Agent is using a revoked credential**, with what to do. Re-registering a cluster keeps its token. `arena cluster connect` and `arena cluster register` issue a new token only with `--rotate-token`; the previous one then keeps working for 24 hours, and the cluster shows **Token renewal pending** with the time it stops. That is for an agent too old to renew its own credential. `arena cluster register --name corp-k8s --rotate-token`, without `--install`, leaves it to you to put the new token in the cluster within those 24 hours. **Disable** in the actions menu also revokes every credential, and stops training and inference on the cluster’s classes. To bring the cluster back, click **Restore**, then issue a new token and reinstall. ## Check that the cluster can run jobs ```bash arena cluster smoke --name corp-k8s --context '' ``` The agent installs a small training release with its own ServiceAccount, the same way it installs a job, waits until the release’s Ray head is Ready, and removes it. The release asks for no GPU and mounts no storage, so it reads and writes none of your data. The command prints whether the smoke passed. When it fails, it prints the reason the agent saw, such as an RBAC rule Kubernetes refused or an image the node could not pull. The agent picks the smoke up on its next poll, within a minute. The release uses the training image of the cluster’s oldest resource class, so add a class first. An agent older than this Arena release does not run smokes: run `arena cluster upgrade` first. Arena runs one smoke per cluster at a time; running the command again while one runs waits for that one. A smoke fails when the agent reports nothing on it for 90 minutes. A new smoke starts only once the agent has confirmed that the last one’s release is removed. `--timeout` is how long the CLI waits (default 3600 seconds). `--kubeconfig` and `--context` select the cluster, which must be the one Arena has on record. ## Remove a cluster ```bash arena cluster unregister --name corp-k8s --context '' ``` Arena stops giving the cluster new runs and marks it **Removing**. A cluster that still has experiments, deployments or Ray clusters is refused, and the error lists them; add `--stop-runs` to stop them first. Once nothing is running, the agent deletes the job namespaces it created. Arena then archives the cluster and its classes, revokes its tokens and deletes its DNS records, and the CLI uninstalls the agent. The CLI waits up to 10 minutes (`--wait-timeout`); if that runs out, run the same command again. An agent that is offline, or too old to clean up after itself, is archived straight away and the CLI prints a command that removes its job namespaces once you can reach the cluster. If that cluster still has runs, Arena asks for `--force`, which ends them without the agent. Add `--uninstall-storage` to also remove a bundled MinIO; that deletes the checkpoints, metrics and datasets in it. `--keep-agent` leaves the agent installed, and `--yes` skips the prompts without uninstalling anything you didn’t ask for. For a cluster the CLI provisioned, `arena cluster destroy --spec lab-cluster.yaml` tears down the cloud resources. The experiment-data bucket is kept unless you pass `--delete-storage`. From the web app, **Archive** the cluster. It does the same as `unregister` without flags, except that it doesn’t uninstall the agent: the cluster shows **Removing** until the agent has cleaned up, and its tokens stay until then. An agent that can’t clean up, or is offline, is archived at once and the response has the cleanup command. Afterwards, remove the agent yourself with `helm uninstall arena-byoc-agent --namespace arena`. ## Troubleshooting These are the messages the CLI and the cluster show, and what to do about each. ### Preflight and connect | Message | What to do | |--------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `helm is not on PATH. Install Helm 3, then run this again.` | Install Helm 3 on the machine running the CLI | | `No --context or --kubeconfig given. Pass --context … to use the current context` | The CLI will not guess the cluster in a script. Pass `--context` | | `No Kubernetes context to use from …` | The kubeconfig has no such context. Check `kubectl config get-contexts` and pass `--kubeconfig` and `--context` | | `Could not read the kube-system namespace UID` | The context cannot reach the cluster, or you may not read namespaces. Check `kubectl --context '' get namespace kube-system` | | `Preflight failed: … Fix them and run again; nothing was changed in Arena or the cluster.` | Fix each `FAIL` row using its fix column, then run again | | `You may not create …` | Use a kubeconfig with cluster-admin | | `Kubernetes 1.x` with `FAIL` | Upgrade the cluster to 1.30 or later | | `A privileged pod is refused in namespace …` | Label the agent namespace `pod-security.kubernetes.io/enforce=privileged` (create it first if needed), or exempt it from the policy that refused the pod | | `StorageClass …, set for Ray data, does not exist` | Create that StorageClass, or pass another `--ray-data-storage-class-name` | | `Arena agents already in this cluster: …` | Unregister the cluster that agent belongs to, or remove it with `helm uninstall --namespace ` | | `The agent has not reached Arena after …s` | Check the agent pod runs (`kubectl get pods -n arena`). Check the cluster can reach the Arena gateway over UDP and Arena over HTTPS. The message ends with the agent’s last error | | `The agent is connected but sent no health report within …s` | The agent is older than the chart Arena serves. Run `arena cluster upgrade` | | `… is connected, but its health report has failing checks` | Fix the failing checks shown above the message. The agent reports again within 10 minutes | | `Re-run with --yes to create them, or create them on the cluster page in Arena.` | The CLI did not create the suggested classes because it could not ask. Run again with `--yes`, or click **Create** under **Suggested classes** | ### Wrong cluster | Message | What to do | |----------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `Kubernetes context … is not Arena cluster '…', which runs in cluster UID …. Pass --context for that cluster.` | Your context points at a different Kubernetes cluster than the one this Arena cluster was installed in. Pass `--context` for the right one. Nothing was changed | | `Kubernetes cluster … is not Arena cluster …. Point kubectl at that cluster, or register this one under a new name.` | Arena refused a register, rotation or smoke for the same reason. To connect a second cluster, give it its own name. To run this Arena cluster here instead, [move it](#move-a-cluster-to-another-kubernetes-cluster) | | Agent log: `Arena refused this cluster's identity: conflict` | The agent runs in a Kubernetes cluster other than the one Arena recorded, and stops. [Move the cluster](#move-a-cluster-to-another-kubernetes-cluster) and restart the agent, or reinstall the agent where it ran before | | `Arena has no cluster UID for '…' yet. Its agent records one on its next heartbeat.` | The cluster was registered before Arena recorded cluster identities. Nothing to do: the next heartbeat records it | ### Token | Message | What to do | |--------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `Arena kept the agent token of cluster …, but namespace … has no token Secret …. Re-run with --rotate-token` | The cluster is registered but the agent was never installed here. Run the same command with `--rotate-token` | | `Cannot --install without an agent token` | Your Arena CLI is too old. Run `uv tool upgrade agilerl` | | **Token renewal pending** on the cluster | A re-register with `--rotate-token` issued a new token; the previous one still works until the time shown. Check the agent’s token Secret holds the new token before then, or run `arena cluster connect --rotate-token` again. The notice clears when the previous token expires | | **Credential renewal pending** on the cluster | The agent has not picked up a renewal Arena asked for a day ago. Its current credential still works. Check the agent is running, and upgrade it if it is older than the release that renews its own credential | | **Agent is using an expired credential** | The agent can no longer renew it. Run `arena cluster connect --name ` again: it installs a new token when the cluster has none, and with `--rotate-token` when the cluster still has one the agent lost | | **Agent is using a revoked credential** | The credential was revoked, with **Revoke credentials now** or by disabling the cluster. Run `arena cluster connect` again, or issue a new agent token and reinstall | ### Health checks | Check shows | What to do | |----------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **Nodes**: `none with allocatable nvidia.com/gpu` | Install the NVIDIA GPU Operator or device plugin | | **Nodes** or **StorageClass**: `unavailable: needs approval upgrade` | The agent cannot read nodes or StorageClasses yet. [Approve the held upgrade](#approve-and-apply-agent-upgrades) | | **StorageClass**: `no default StorageClass` | Mark one StorageClass default (annotation `storageclass.kubernetes.io/is-default-class: "true"`) or set the cluster’s **Ray data storage class** | | **Tunnel**: `the tunnel has not completed a handshake` | Check the cluster can send UDP to the gateway host and port, and that the agent pod’s `wireguard` container is running | | **Storage**: `the agent could not reach its storage` | Check the storage Secret’s keys, the endpoint, and the bucket policy | | **Credential**: `the cluster has no active agent token` | Connect the cluster again with `arena cluster connect --name `, which issues a new enrollment token and installs it | | **Image pull credential** failing | The agent could not renew its registry login; the detail says why. Check the agent can reach Arena and read its log. If the login has already expired, run `arena cluster upgrade` | | **Agent permissions**: `the agent's ClusterRoles differ from this release` | [Approve the held upgrade](#approve-and-apply-agent-upgrades) | | **One agent**: `other Arena agents in this cluster` | Keep one agent per cluster: `helm uninstall -n ` for the others | | `the agent could not read …` | Read the agent’s log: `kubectl logs deploy/arena-byoc-agent -c operator -n arena` | ### Smoke test and upgrades | Message | What to do | |--------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `This cluster has no resource class.` | Create a class first; the smoke uses its training image | | `The agent of cluster … has not reported that it runs smokes.` | Run `arena cluster upgrade`, then wait for the next heartbeat | | `Smoke failed on cluster …: …` | The reason is the agent’s. Fix it (often an RBAC rule or an image pull) and run the smoke again | | `This upgrade changes the agent's ClusterRoles and needs your approval. Run it in a terminal to confirm, or pass --yes.` | Run `arena cluster upgrade` in a terminal, or add `--yes` once you have read the changes | | `Helm release … is not installed in namespace ….` | `upgrade` only upgrades an installed agent. Install it with `arena cluster connect` | | `agent upgrade failed: …` on the cluster | The agent rolled back that attempt. It starts another Job on its next poll, within a minute, for the first 20 minutes of the request. After that it starts no new Job. Leave a running `arena-byoc-agent-upgrade` Job to finish | | `agent upgrade failed: …; stopped after … upgrade Jobs failed` | Three Jobs failed because the chart does not render or Kubernetes refused a write, and the agent starts no further Job for this release. **Upgrade agent** asks for the same release, so it does not start one either. Wait until the Job `arena-byoc-agent-upgrade` has finished, then run `arena cluster upgrade` | | **Degraded** with no error shown | The agent has not checked in for 3 minutes. Check its pod and its network access to Arena | # compute/resource-classes.md # Resource classes A resource class describes one pool of worker machines on a BYOC cluster: how many nodes, and the CPUs, GPUs and memory on each. Members pick classes when they train. Add one class per kind of hardware, for example `nvidia-l4-east` and `nvidia-a100-west` on the same cluster. The cluster’s agent sets up each class, so there is nothing to install per class. ## Prerequisites - A registered cluster. See [Install a BYOC cluster](compute/install-byoc-cluster.md). - The org **Admin** role. ## Create suggested classes The quickest way to get classes is to let Arena suggest them. Once the agent has reported its nodes, Arena suggests one class for each GPU model and GPU count it found. Each suggestion has the CPUs, memory and node count of those nodes, and a node selector on `nvidia.com/gpu.product` (plus `nvidia.com/gpu.count` when one GPU model comes in several counts). ### Web app Select the cluster on the **Bring your own compute** tab. **Suggested classes** lists the suggestions, with the node selector each would use. Click **Create** on each one you want. ### CLI `arena cluster connect` and `arena cluster register` list the suggestions and ask `Create these classes?`. Pass `--yes` to create them without asking. A created suggestion is an ordinary class: edit, turn off or delete it like any other. Arena leaves out a shape an existing class already selects. Memory is rounded down so a class never asks for more than the node has. If **Suggested classes** asks you to upgrade the agent, run `arena cluster upgrade`: older agents don’t report node CPU and memory. ## Add a class 1. Open the profile menu, click **Settings**, then the **Bring your own compute** tab. 2. Select the cluster and click **Add resource class**. A disabled cluster has no button; **Restore** it first. 3. Fill in the form and click **Add**. | Field | What to enter | |--------------------------------|------------------------------------------------------------------------------------------------| | **Name** | Shown to everyone in the experiment wizard, so name the hardware: GPU model, site or rack. | | **Enabled** | On by default. A class that isn’t enabled stays in the table but can’t be picked for new runs. | | **Description** | Optional notes, such as the GPU SKU. | | **Enterprise cluster** | The cluster that runs the class. Already set when you add from a cluster. | | **Number of nodes** | How many worker nodes the agent runs for this class. At least 1. | | **CPUs**, **GPUs**, **Memory** | Per worker node, under **Compute resource (per worker node)**. Match the machines. | | **GPU type** | Required when **GPUs** is above 0, for example `L4` or `A100`. | | **VRAM per GPU (GB)** | Required when **GPUs** is above 0. Arena uses it to check that a model fits. | | **Worker node placement** | Kubernetes node labels that pick which machines the class runs on. Required for GPU classes. | ## From the CLI Apart from the [suggested classes](#create-suggested-classes), the CLI adds classes only to clusters it provisioned from a spec file: - `arena cluster provision ... --register-and-install` adds a class for each GPU worker group in the spec, named `-`. - On **Nebius**, `arena cluster register-classes` adds a class for each GPU preset you pick from your Nebius project, on a cluster that is already registered: ```bash arena cluster register-classes --spec lab-cluster.yaml --preset gpu-h100-sxm:1gpu-16vcpu-200gb ``` Repeat `--preset platform:preset` for more, or pass `--all` for every preset. `--register-node-group` also creates the Nebius node group for each one. Flags are in the [command reference](cli/commands/cluster.md). For **Custom** and **AWS** clusters, add any class that isn’t a suggestion in the web app. Editing, turning off and deleting classes are web-only too. ## Pin a class to the right GPUs Kubernetes only sees a GPU count. On a cluster with mixed hardware, an A100 class can land on an L4 node unless you say otherwise. **Worker node placement** fixes that: add a **Label key** and **Label value** that your GPU nodes already carry, and the class’s workers only run on nodes with that label. Arena doesn’t create or apply labels. If the cluster runs the NVIDIA GPU Operator, each node has an `nvidia.com/gpu.product` label. List them with: ```bash kubectl get nodes -L nvidia.com/gpu.product ``` Then use, for example, key `nvidia.com/gpu.product` and value `NVIDIA-A100-80GB-PCIe`. If no node carries a class’s labels, its jobs stay pending. The cluster’s **Health** section names such classes under **Classes with no matching nodes**. ## Change or remove a class The class table on the cluster lists **Name**, **GPU**, **CPU**, **VRAM**, **Memory**, **Nodes** and **On**. On a narrow window some columns fold into the name. Use the filter to find a class by name or GPU type, and sort by any column. - Flip **On** to take a class out of new runs, or put it back. The row stays. - Open the row’s actions menu and click **Edit resource class** to change any field. - **Delete** removes the class from Arena for good. Clean up anything left on your machines yourself. Next to a class name, **Update** means the image stored on that class differs from the current training image. The image is saved when the class is created. **Reinstall** reinstalls the agent and leaves the badge in place. Jobs still run the current training image. A GPU class missing a field is flagged: **GPU type not set** in the **GPU** column, and **Not set** in the **VRAM** column. When the **GPU** column is folded away, **GPU type not set** shows under the name and the **VRAM** column still says **Not set**. **VRAM not set** under the name shows only in the narrowest layout, which has no **VRAM** column. Edit the class to fill them in. ## How classes appear in the wizard Under **Training resources** in the experiment wizard, each BYOC GPU type is a row ending in **(BYOC)**, such as **A100 80GB (BYOC)**. A class shows up there when: - its cluster is registered and not disabled or archived, - the class is enabled, and - it has at least one GPU per worker node. CPU-only classes are never offered for training. The GPU counts you can pick come from the class’s size. A class with **Number of nodes** 2 and 4 **GPUs** per node offers 4 or 8 GPUs. Arena runs on the fewest nodes that give the count you pick. For a language model, a count without enough GPU memory shows **–**. See [Choose compute](guides/choose-compute.md) for the rest of the picker. If no **(BYOC)** row appears, check that the organization is on **Enterprise**, the cluster isn’t disabled, and the class is enabled and has GPUs. If the row is there but runs stay **Pending**, check that the cluster shows **Connected** and that **Classes with no matching nodes** doesn’t name the class. # compute/snowflake-native-app-rewards.md # Snowflake Native App rewards GRPO and other reinforcement learning over table rows need a reward: a score for each completion the model writes. In the Arena Native App you set it in the manifest’s `environment.reward`. Pick a built-in reward, or write the reward as a Snowflake function in your account and bind it to the app. The app takes no reward file. Snowflake does not let a Native App run code from outside its package, so the app does not load Python files you pass to it. The examples on this page call the app `arena_app`. Replace it with the name you gave the app at install. For installing the app, binding a table and submitting runs, see [Snowflake Native App](compute/snowflake-native-app.md). ## Prerequisites - The app is installed and connected to Arena, and it has compute pools. - A table or view is bound to the app. Each row has a prompt column and an answer column, such as `QUESTION` and `ANSWER`. - To bind your own function: a role that holds `app_admin` and can grant `USAGE` on the function, such as the function’s owner. ## Choose a reward | Use | When | |-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------| | A built-in reward | The answer column holds the right answer, and a fixed check is enough: equal text, the same number, a pattern, valid JSON, or the right tool call. | | Your own function | The check needs your own logic, other data in your account, or an LLM grader. | ## Built-in rewards A built-in reward runs inside the app. It scores the model’s final answer, which is the text of its last reply after any reasoning. It compares that answer with the row’s `answer` column and gives 1 or 0. Map your answer column onto `answer` in `environment.columns`. This GRPO run reads `QUESTION` and `ANSWER` from the bound table and scores with `numeric`: ```postgresql CALL arena_app.app_code.submit( $$ algorithm: name: GRPO batch_size: 8 group_size: 4 environment: env_type: rollout columns: question: QUESTION answer: ANSWER prompt_template: system_0: Think step by step, then give the final number inside . user_1: "{question}" reward: type: numeric answer_pattern: "(.*)" max_reward: 1.0 network: pretrained_model_name_or_path: Qwen/Qwen3.5-0.8B max_context_length: 2048 training: max_steps: 200 $$, 2, 'source_table', '', 'GPU_NV_S' ); ``` `max_reward` is the reward at which a completion counts as solved in the success metric. With a built-in reward, use `1.0`. The five types are below. Patterns are Python regular expressions. They are case-sensitive, and `.` also matches a new line. Put `(?i)` at the very start of a pattern to ignore case. ### Read the answer out of a longer reply `exact_match` and `numeric` take an optional `answer_pattern`. It is a regular expression whose first capturing group is the answer, such as `"Answer: (.*)"` or `"(.*)"`. When the pattern matches more than once, the last match counts. A reply with no match scores 0. Without `answer_pattern`, `exact_match` compares the whole reply, and `numeric` reads the number as described in [numeric](#numeric). A pattern without a capturing group is refused when you submit. ### exact_match Scores 1 when the answer equals the row’s `answer`. | Parameter | Meaning | Default | |------------------|----------------------------------------------------------------------------------------------------------------------------------|-------------| | `normalize` | Ignore case, extra spaces and one trailing full stop before comparing. With `false` the text must match character for character. | `true` | | `answer_pattern` | Reads the answer out of the reply. See [Read the answer out of a longer reply](#read-the-answer-out-of-a-longer-reply). | Whole reply | ```yaml reward: type: exact_match answer_pattern: "Answer: (.*)" ``` Use it for short text answers such as a label, a name or a yes or no. For numbers, use `numeric`, so that `42`, `42.0` and `42.` all count. ### numeric Scores 1 when the answer is a number within `tolerance` of the row’s `answer`. | Parameter | Meaning | Default | |------------------|----------------------------------------------------------------------------------------|-----------| | `tolerance` | Largest absolute difference that still counts as correct. | `1e-6` | | `answer_pattern` | Reads the answer out of the reply. The last number in the captured text is the answer. | See below | Without `answer_pattern`, the answer is the last number inside the last `\boxed{...}` in the reply. A reply with no `\boxed{...}` uses its last number. Commas between digits are ignored, so `1,250` reads as 1250. The row’s `answer` can be a number, or text that holds one. Its last number is used. A row with no number scores 0. ```yaml reward: type: numeric tolerance: 0.01 ``` ### regex Scores 1 when the reply matches `pattern`. It does not read the row’s `answer`. | Parameter | Meaning | Default | |--------------|----------------------------------------------------------------------|-----------| | `pattern` | Python regular expression. | Required | | `full_match` | Match the whole reply instead of finding the pattern anywhere in it. | `false` | ```yaml reward: type: regex pattern: "(?i)(positive|negative|neutral)" full_match: true ``` Use it to reward a format, such as one label from a fixed list. ### json_schema Scores 1 when the first JSON object in the reply is valid against `schema`. It does not read the row’s `answer`. | Parameter | Meaning | Default | |-------------|--------------------------------------|-----------| | `schema` | JSON Schema the object must satisfy. | Required | The object starts at the first `{` in the reply. Text before it is ignored. If the JSON that starts there does not parse, the reply scores 0. ```yaml reward: type: json_schema schema: type: object required: [name, email] properties: name: {type: string} email: {type: string} additionalProperties: false ``` Use it for structured extraction, where the shape of the output is what you train for. ### tool_call Scores 1 when the first tool call in the reply is the expected one. A tool call is a JSON object with `name` and `arguments`, written bare or inside `` tags. The tags are read first when the reply has them. | Parameter | Meaning | Default | |----------------------|-------------------------------------------------|-----------| | `name` | Tool the call must use. | Unset | | `required_arguments` | Argument keys the call must pass. Needs `name`. | `[]` | With `name` set, the call scores 1 when it uses that tool and passes every key in `required_arguments`. The argument values are not checked, and the row’s `answer` is not read: ```yaml reward: type: tool_call name: get_weather required_arguments: [city] ``` Without `name`, the row’s `answer` holds the expected call as JSON text, such as `{"name": "get_weather", "arguments": {"city": "Paris"}}`. The call scores 1 when both its name and its arguments equal that call: ```yaml reward: type: tool_call ``` ## Your own reward function Write the reward as a function in your Snowflake account and bind it to the app’s `reward_function` reference. Snowflake runs the function in your account, as your object. The app calls it with SQL and never reads its code. You can use any Snowflake function with the right signature: Python, SQL, Java, or one that calls `AI_COMPLETE` to grade with an LLM. ### The function’s inputs and output The function takes three `STRING` arguments, in this order, and returns `FLOAT`: | Argument | Value | |--------------|----------------------------------------------------------------------------------------------------------------------| | `prompt` | The row’s `question` column. With no `question` mapped, the first prompt of the episode. | | `completion` | The model’s final answer: the text of its last reply after any reasoning. | | `answer` | The row’s `answer` column as text. A value that is not text arrives as JSON text. `NULL` when the row has no answer. | Return a finite number for every row. The score can be any number, not just 0 or 1. Set `max_reward` in the manifest to the score at which a completion counts as solved. ### A Python function This function gives 1 when the last number in the completion equals the answer: ```postgresql CREATE OR REPLACE FUNCTION my_db.rewards.score_answer( prompt STRING, completion STRING, answer STRING) RETURNS FLOAT LANGUAGE PYTHON RUNTIME_VERSION = '3.12' HANDLER = 'score' AS $$ import re def score(prompt, completion, answer): numbers = re.findall(r"-?\d+(?:\.\d+)?", completion or "") if not numbers or answer is None: return 0.0 try: expected = float(answer) except ValueError: return 0.0 return 1.0 if abs(float(numbers[-1]) - expected) < 1e-6 else 0.0 $$; ``` An empty answer, or one that is not a plain number, scores 0. `float` raises on that input, and a function that raises stops the run. ### A SQL function A SQL function is the fastest to call. This one gives 1 when the completion contains the answer, ignoring case: ```postgresql CREATE OR REPLACE FUNCTION my_db.rewards.contains_answer( prompt STRING, completion STRING, answer STRING) RETURNS FLOAT AS $$ IFF(CONTAINS(LOWER(completion), LOWER(answer)), 1.0, 0.0)::FLOAT $$; ``` Cast the result to `FLOAT`. `IFF(..., 1.0, 0.0)` on its own is a `NUMBER`, and `CREATE FUNCTION` fails. When `answer` is `NULL`, `CONTAINS` returns `NULL` and `IFF` gives 0.0, so the function never returns `NULL`. ### Bind the function to the app Bind the function to `reward_function`. Name the function with its argument types: ```text CALL arena_app.app_code.register_reference( 'reward_function', 'ADD', SYSTEM$REFERENCE('FUNCTION', 'my_db.rewards.score_answer(STRING, STRING, STRING)', 'PERSISTENT', 'USAGE') ); ``` For the SQL function above, name it the same way: ```text CALL arena_app.app_code.register_reference( 'reward_function', 'ADD', SYSTEM$REFERENCE('FUNCTION', 'my_db.rewards.contains_answer(STRING, STRING, STRING)', 'PERSISTENT', 'USAGE') ); ``` Run either call as a role that holds `app_admin` and can grant `USAGE` on the function, such as the function’s owner. You can also bind the function in Snowsight, on the app’s references. The reference holds one function. Binding another replaces it. Check the binding with: ```sql SHOW REFERENCES IN APPLICATION arena_app; ``` ### Use the function in a run Set `environment.reward` to `snowflake_function`: ```postgresql CALL arena_app.app_code.submit( $$ algorithm: name: GRPO batch_size: 8 group_size: 4 environment: env_type: rollout columns: question: QUESTION answer: ANSWER prompt_template: system_0: Think step by step, then give the final number. user_1: "{question}" reward: type: snowflake_function max_reward: 1.0 network: pretrained_model_name_or_path: Qwen/Qwen3.5-0.8B max_context_length: 2048 training: max_steps: 200 $$, 2, 'source_table', '', 'GPU_NV_S' ); ``` `submit` checks that a function is bound before it starts anything. ### How the app calls the function - The app scores each group of completions once the whole group has finished. Each group is one prompt with `group_size` completions. - Each training process sends groups to the function in one query on the app’s XSMALL warehouse. Groups that finish while a query runs go into the next query together. One query costs about the same whatever its size: about 1.3 seconds for a Python function and 0.15 seconds for a SQL function, from 64 to 2,048 rows. - Each GPU worker runs its own training process, so several queries can run at once and queue on the warehouse. - The first query after the warehouse resumes takes about 20 seconds, so the first training step is that much slower. - The queries run on the app’s warehouse in your account, and Snowflake bills them to your account like any other query. - If the connection to Snowflake drops, the app reconnects and tries the query again, up to 4 times. A function that fails, returns `NULL`, or returns a value that is not a finite number stops the run with that error. To keep training fast, prefer a SQL function, and keep slow work such as an LLM grader for when you need it. ## Common messages | Message | What to do | |-------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------| | `reward_file is not available in the Snowflake app.` | Leave `reward_file` out of `submit`, and set `environment.reward` in the manifest instead. | | `environment.rubric_file_path is not available in the Snowflake app.` | Remove `rubric_file_path` from the manifest, and set `environment.reward` instead. | | `A dataset-backed rollout needs reward or rubric_file_path` | Add `environment.reward` to the manifest. | | `environment.reward is snowflake_function, but no function is bound to the app's reward_function reference.` | [Bind the function](#bind-the-function-to-the-app), then submit again. | | `reward replaces the rubric file; drop ...` | Remove the fields the message lists from the manifest. | | `reward scores rollouts; a dataset environment trains on its rows.` | Use `environment.reward` only with `env_type: rollout`. | | `answer_pattern needs a capturing group, for example 'Answer: (.*)'.` | Put the answer part of the pattern in parentheses. | | `required_arguments needs name; without it answer is the expected call.` | Add `name` to the `tool_call` reward, or remove `required_arguments`. | | `The function bound to reward_function returned None for completion . It must return a finite FLOAT for every completion.` | Make the function return a number for every input, including a `NULL` answer or an empty completion. | | `The function bound to reward_function returned rewards for completions.` | Use a scalar function that returns one value per row. | `submit` refuses each of these before it starts anything, except the last two. Those stop a run that is already training. ## Related - [Snowflake Native App](compute/snowflake-native-app.md) # compute/snowflake-native-app.md # Snowflake Native App Install Arena from Snowflake Marketplace and post-train an open-weight model on your own Snowflake tables, all from SQL. Training normally runs on Arena’s cloud; with the app it runs on Snowpark Container Services in your account, and your rows, checkpoints and trained models stay there. It runs supervised fine-tuning, distillation, preference optimisation and reinforcement learning, scored by a built-in reward or by a Snowflake function of yours. The examples here call the app `arena_app`; use the name you give it at install. ## Prerequisites - A paid Snowflake account. On a trial account the install stops with Snowflake error 509009. - GPU instance families in your region. Run `SHOW COMPUTE POOL INSTANCE FAMILIES;` and look for one such as `GPU_NV_S` on AWS or `GPU_GCP_NV_L4_1_24G` on Google Cloud. - `ACCOUNTADMIN`, or a role with `IMPORT SHARE`, `CREATE APPLICATION` and `PURCHASE DATA EXCHANGE LISTING` on the account. - A warehouse in the session you call the app from. - An Arena sign-in, or an email address to create one. ## Step 1: Install from Marketplace Find **AgileRL Arena: post-training for open-weight models and agents** in Snowflake Marketplace, install it and choose its name. The app asks for five account privileges: `CREATE COMPUTE POOL`, `CREATE WAREHOUSE`, `CREATE EXTERNAL ACCESS INTEGRATION`, `EXECUTE TASK` and `EXECUTE MANAGED TASK`. Snowflake grants them at install. Install creates a warehouse and two external access integrations named `AGILERL_APP__...`, where `` is the app name in upper case. It creates no compute pools yet. If a second result row starts with `Reference register_callback 'APP_CODE.REGISTER_REFERENCE(...)' does not exist`, ignore it. Approve the app’s two connections out of your account, on the app’s page in Snowsight or in SQL, as `ACCOUNTADMIN` or `SECURITYADMIN`. `HF_ACCESS` downloads base model weights from Hugging Face. `ARENA_ACCESS` reaches `arena.agilerl.com` to check the licence and record run start, check-ins and end. ```sql SHOW SPECIFICATIONS IN APPLICATION arena_app; -- Use each request's sequence_number from the SHOW output. ALTER APPLICATION arena_app APPROVE SPECIFICATION HF_ACCESS SEQUENCE_NUMBER = 1; ALTER APPLICATION arena_app APPROVE SPECIFICATION ARENA_ACCESS SEQUENCE_NUMBER = 1; ``` ## Step 2: Give people access The app has two roles. `app_admin` connects to Arena, creates pools, binds tables, stages and reward functions, trains, publishes, exports models and cleans up. `app_user` checks status, reads logs and metrics, and calls served models. `app_admin` includes `app_user`. The example grants them to roles named `ml_engineer` and `ml_viewer`. Use your own roles, or create these first with `CREATE ROLE IF NOT EXISTS ml_engineer;` and `CREATE ROLE IF NOT EXISTS ml_viewer;` and grant them to your users: ```sql GRANT APPLICATION ROLE arena_app.app_admin TO ROLE ml_engineer; GRANT APPLICATION ROLE arena_app.app_user TO ROLE ml_viewer; ``` ## Step 3: Connect to Arena Each run checks its licence with Arena, so the app needs an Arena org key. It fetches the key itself; nobody sees or pastes it. As `app_admin`: ```sql CALL arena_app.app_code.connect_arena(); ``` It returns a link. Open it within an hour, sign up or sign in, and create the organization. Each Snowflake account gets a new Arena organization of its own. Then run `connect_arena()` again, or wait up to an hour for the app to collect the key by itself. When it has it, you see: ```text Connected to the Arena organisation Acme ML. ``` Once the app is connected, `connect_arena()` changes nothing and returns: ```text This app is already connected to Arena. Use app_code.rotate_arena_key() for a new key. ``` In some regions Snowflake takes a minute or two to deliver Arena’s check to your account. If `connect_arena()` says it’s still waiting, run it again in a few minutes. An organization connected this way trains inside Snowflake only. It can’t run training or deployments hosted by Arena. If AgileRL gave you an org key directly, connect with `CALL arena_app.app_code.configure('arena_org_...', 'your-external-user-id');` instead. The app rotates its key every 90 days. `CALL arena_app.app_code.rotate_arena_key();` rotates it now. Neither happens while a run is going. ## Step 4: Create compute pools List the GPU families your region has and Arena prices, then create pools for the ones you want: ```sql CALL arena_app.app_code.gpu_families(); CALL arena_app.app_code.set_pools(['GPU_NV_S', 'GPU_NV_M'], 4); ``` The second argument is the most GPUs each GPU pool can hold. Pass every family you want each time: `set_pools` drops the app’s pools for families you leave out. It won’t shrink or drop a GPU pool that a queued or running run still needs, or take a `max_gpus` that isn’t a multiple of a listed family’s GPUs per node. Pools start when a job starts and suspend after 5 idle minutes. A suspended pool has no Snowflake compute charge, but any month in which a pool runs counts as a month of use for the monthly fee ([Costs](#costs)). ## Step 5: Bind a table The app reads only tables and views you bind to it. As a role with `app_admin` that can grant `SELECT` on the table: ```text CALL arena_app.app_code.register_reference( 'source_table', 'ADD', SYSTEM$REFERENCE('TABLE', 'analytics.public.sft_examples', 'PERSISTENT', 'SELECT') ); SHOW REFERENCES IN APPLICATION arena_app; ``` `SHOW REFERENCES` gives each binding an alias; runs name the alias they read. For a view, use `source_view` and `'VIEW'`. To train on custom SQL, put it in a view and bind that. Snowflake stores unquoted column names in upper case. A table created as `(prompt STRING, response STRING)` has columns `PROMPT` and `RESPONSE`, and the manifest must use those names. ## Step 6: Train Pass the manifest, the GPU count, and the binding to read: ```postgresql CALL arena_app.app_code.submit( $$ algorithm: name: SFT environment: env_type: dataset objective: sft columns: prompt: PROMPT target: RESPONSE network: pretrained_model_name_or_path: Qwen/Qwen3.5-0.8B max_context_length: 2048 training: max_steps: 200 $$, 1, 'source_table', '' ); ``` `columns` maps the trainer’s names (left) to your columns (right). `submit` returns a run ID such as `arena-20261119013316-d15e04`; keep it. After the alias, `submit` takes optional arguments in this order: `gpu_family`, `reward_file`, `checkpoint_steps` and `resume_from`. Without a family it picks the one with the least GPU memory that fits. Leave `reward_file` unset: the app takes no reward file. To continue a cancelled run, pass its ID as `resume_from`. The GPU count must be a multiple of the family’s GPUs per node. Reinforcement learning (CISPO, GRPO) needs at least 2 GPUs: one trains while another generates answers. For reinforcement learning over table rows, add a `prompt_template` and a reward to the manifest’s `environment`. CISPO is the recommended default and usually trains better than GRPO; GRPO is also supported: change `name: CISPO` to `name: GRPO` and keep the rest. With `QUESTION` and `ANSWER` columns, on two A10G GPUs of `GPU_NV_S`: ```postgresql CALL arena_app.app_code.submit( $$ algorithm: name: CISPO batch_size: 8 group_size: 4 environment: env_type: rollout columns: question: QUESTION answer: ANSWER prompt_template: system_0: Think step by step, then give the final number inside . user_1: "{question}" reward: type: numeric answer_pattern: "(.*)" max_reward: 1.0 network: pretrained_model_name_or_path: Qwen/Qwen3.5-0.8B max_context_length: 2048 training: max_steps: 200 $$, 2, 'source_table', '', 'GPU_NV_S' ); ``` `numeric` is a built-in reward. It reads the number inside `` and gives 1 when it equals the row’s `ANSWER`, else 0. The app has five built-in rewards, and you can also write the reward as a Snowflake function in your account and bind it to the app. See [Snowflake Native App rewards](compute/snowflake-native-app-rewards.md). The app trains only models in the Arena catalog, and refuses ones that need to run code from their Hugging Face repo. `submit` refuses before anything starts when: - the trial has ended and the listing is not bought; - the manifest has a missing, misspelled or wrong-typed field, such as an unknown `algorithm.name` or reward type. The message names each field, what is wrong and what to change; - the app has no compute pools yet; - nothing is bound to `source_table` (or `source_view`) with that alias. The message lists the aliases that are bound and how to bind one; - the app has no pool for the GPU family. The message gives the `set_pools` call that adds one and keeps your other pools; - Arena has no price for the GPU family; - the GPU count is not a multiple of the family’s GPUs per node, or is more than the pool holds. The message lists the counts the pool can run; - the run needs more GPUs than you asked for, such as CISPO or GRPO on 1 GPU. The message gives the GPU count to ask for; - an OPD run with a separate teacher model asks for a GPU family with 1 GPU per node. Each rollout engine and its teacher run together on one node, so pick a family with at least 2 GPUs per node; - the run does not fit in the GPU memory of any pool. Each of these messages ends with `Nothing was started.` and says what to change. The messages and fixes are under [Common messages](#common-messages). GPU nodes come from Snowflake. When Snowflake has little GPU capacity in your region, they can take a long time to start. A run waits up to 45 minutes for them: `status` shows its containers as PENDING, and training starts once every GPU node has joined. If they have not all joined after 45 minutes, the run stops before training. It removes its worker service and suspends the GPU pool if nothing else is using it, so the pool is freed at once. `status` then says that not all of its nodes became available within 45 minutes and that Arena does not charge for the run. Snowflake still bills the compute pools for the time they ran, as usual. Submit the run again later, or try another GPU family. A run that fails for another reason before training starts, for example because its message broker did not start, frees the GPU pool in the same way. So does a run you cancel before training starts. `status` gives the reason, and Arena does not charge for the run. Check the run, read its logs and metrics, or stop it: ```sql CALL arena_app.app_code.status('arena-20261119013316-d15e04'); CALL arena_app.app_code.logs('arena-20261119013316-d15e04'); SELECT seq, time, metrics FROM arena_app.app_state.arena_metrics WHERE run_id = 'arena-20261119013316-d15e04' ORDER BY seq; CALL arena_app.app_code.cancel('arena-20261119013316-d15e04'); ``` `status` prints the state of the broker, head and workers, then one line for the run: `state: running`, `succeeded`, `failed`, `cancelling`, `cancelled` or `gone`. `cancel` drops the run’s services, so a run you cancel reads `gone`. `cancelled` means Snowflake cancelled a service, for example during node maintenance. A run whose head or worker service is gone before the run finished reads `failed`, because it cannot make progress; cancel it to free the nodes its other services still hold. When a run stopped before training started, `status` adds a `reason` line that says why. `logs` prints one service’s log, at INFO level and above. It reads the head by default; pass `'worker', 0` for the first worker. A new node can take several minutes to start, and GPU nodes take longest. Until it has started, `logs` says the container has not started yet; check `status` and try again. Logs of finished jobs need an active event table. If your account has none, run `ALTER ACCOUNT SET EVENT_TABLE = SNOWFLAKE.TELEMETRY.EVENTS;`. Snowflake can cancel jobs during its weekend node maintenance windows. Plan long runs around them, or resume. ## Step 7: Publish and serve Log the run’s newest checkpoint to the Model Registry inside the app, and serve it: ```sql CALL arena_app.app_code.publish('arena-20261119013316-d15e04', 'support_bot', NULL, NULL, TRUE); ``` The arguments after the model name are the version name, the checkpoint step, and whether to serve. The service is named `_`, so this example serves `SUPPORT_BOT_CHECKPOINT_200`. With serving on, `publish` returns once the model answers. First it logs the model, which can take 20 minutes or more. Then the inference service waits for a GPU node from Snowflake and loads the model. When Snowflake has few GPUs free in your region, the node alone can take half an hour or more. `publish` waits up to 60 minutes for the service. If it is still waiting after that, `publish` does not fail and drops nothing: it returns the chat function and says the service is still waiting for a GPU node. The app’s hourly task finishes the job once the service is ready. Arena starts charging for the served model only once it is ready; run `endpoint` ([Step 8](#step-8-call-the-model)) to check. If the service fails to start, `publish` raises an error with Snowflake’s status message. `publish` can run for up to about two hours and holds your warehouse while it runs. Snowflake stops any statement that runs longer than `STATEMENT_TIMEOUT_IN_SECONDS`, which is two days unless your account, user or warehouse sets it lower. If it stops `publish`, the model keeps publishing and serving, and `endpoint` says when it is ready. The publish job runs on the app’s CPU head pool, so a training run does not hold it up. The served model runs on the GPU pool: if training is using every node there, the model starts once a node is free. To serve while training, call `set_pools` again with a higher `max_gpus` to give the pool more nodes. List every GPU family you still want, because `set_pools` drops the app’s pools for families you leave out. ## Step 8: Call the model A served model has no endpoint outside Snowflake. Roles with `app_user` call it from SQL through a chat function. `endpoint` prints the function’s name, a `state:` line and an example call: ```sql CALL arena_app.app_code.endpoint('support_bot'); SELECT arena_app.app_state.SUPPORT_BOT_CHECKPOINT_200_CHAT( PARSE_JSON('[{"role": "user", "content": "Hello"}]')::ARRAY, 0.7, 256 ):choices[0]:message:content::STRING AS reply; ``` The `state:` line reads `ready`, `starting` (the service has its GPU node and is loading the model), `waiting for a GPU node`, `suspended` or `failed`, with Snowflake’s status message when it has one. The example `SELECT` works once it reads `ready`. The function takes the chat messages (an `ARRAY` in the OpenAI format), a temperature and a token limit, and returns the OpenAI chat completion as an `OBJECT`. Run it over a table of prompts to answer them all in one query. For the other chat options, call the Model Registry’s own method on the service, which `app_user` can also use. It takes all ten arguments in this order: messages, temperature, max_completion_tokens, stop, n, stream, top_p, frequency_penalty, presence_penalty and response_format: ```sql SELECT arena_app.app_state.SUPPORT_BOT_CHECKPOINT_200!__CALL__( PARSE_JSON('[{"role": "user", "content": "Hello"}]')::ARRAY, 0.7, 256, NULL, 1, FALSE, 1.0, 0.0, 0.0, NULL ); ``` To serve the model over HTTPS outside Snowflake, copy it to a stage of yours with `export_model` (see [Step 9](#step-9-clean-up)) and serve it yourself. Snowflake suspends a service that gets no calls. `endpoint` then says `suspended`. The next call waits while it starts again, which can take a few minutes. ## Step 9: Clean up Stop serving, which also stops the serving charges: ```sql CALL arena_app.app_code.unpublish('support_bot'); ``` This also drops the model’s chat function. Pass the version name and `TRUE` as well to delete the registry version. Uninstalling deletes everything the app holds, including checkpoints, metrics and models, and your roles can’t read those directly. To keep a model, bind a stage of your own and export to it first: ```text CREATE STAGE my_db.my_schema.arena_models; CALL arena_app.app_code.register_reference('export_stage', 'ADD', SYSTEM$REFERENCE('STAGE', 'my_db.my_schema.arena_models', 'PERSISTENT', 'READ', 'WRITE')); CALL arena_app.app_code.export_model('arena-20261119013316-d15e04'); ``` That copies the run’s newest merged checkpoint, as Hugging Face files, to `/checkpoint_/` on your stage. Pass a step number as the second argument for an earlier checkpoint. Files of the same name are overwritten. `export_model` starts no service and Arena charges nothing for it; Snowflake bills the copy to your account and caps each file at 5 GB. To keep the metrics, copy them into a table of your own: ```sql CREATE TABLE analytics.public.arena_metrics_copy AS SELECT * FROM arena_app.app_state.arena_metrics; ``` Then drop the app as the role that owns it: ```sql DROP APPLICATION arena_app CASCADE; ``` Arena keeps your organization for 30 days. Reinstall within that time and `connect_arena()` offers to reconnect to it. ## Costs Snowflake bills you for the app’s pools, warehouse and storage as usual. AgileRL bills through the Marketplace listing: a monthly fee for each calendar month you use the app, plus usage. Usage is GPUs × hours × the family’s price per GPU-hour, for training from the first GPU node starting to the end of the run, and for serving once the model is ready to answer. A run that never reaches its first training step is not charged at all (see below). One usage unit is 1 cent; one `GPU_NV_S` GPU for 3 hours at $2.28 an hour is 684 units. The listing shows the fee and the price per family. Any query that references the app in a month counts as use, `status` included. To skip the fee for a month, unpublish your models and make no calls to the app until the next month, or uninstall it. A run that ends before its first training step is not charged by Arena, for example because it failed while starting up, its nodes did not all become available within 45 minutes, or you cancelled it before training started. Its row in `app_state.usage_items` settles with `unbilled_reason` set to `The run ended before training started.` A run that fails partway through training is charged up to the failure. A served model is charged only once it is ready to answer. An `app_admin` can audit charges in `app_state.usage_items`, `app_state.billed_hours` and `app_state.served_models`. Usage reaches your Snowflake bill about an hour after it happens. The first 7 days after install are a free trial. An hour before it ends, `submit` and `publish` stop working and the app drops anything still running, until you buy the listing. `export_model` still works, so you keep what you trained. ## What leaves your account To connect, the app sends Arena your account locator, region, account and organization names, the app’s name and version, and whether you bought the listing. For each run it sends the run ID, GPU count and family, and start and end times; for a served model, the model and version names. It sends no rows, prompts, metrics or weights. The only other connection out is to Hugging Face, for base model weights. ## Common messages | Message | What to do | |------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------| | `Arena is not connected. An app_admin calls app_code.connect_arena first.` | Run [Step 3](#step-3-connect-to-arena). | | `Arena no longer accepts this app's org key.` | Run `connect_arena()` and open the new link. It offers to reconnect to the same organization. | | `The app has no compute pools yet.` | An `app_admin` runs [`set_pools`](#step-4-create-compute-pools). | | `Arena has no Snowflake price for ` | Pick a family that `gpu_families()` lists. | | `Nothing is bound to source_table with the alias .` (or `source_view`) | Pass an alias that `SHOW REFERENCES IN APPLICATION arena_app;` lists, or [bind the table or view](#step-5-bind-a-table) first. | | `The app has no GPU pool for .` | An `app_admin` runs the `set_pools` call that the message gives. | | ` has GPUs per node, so it cannot run GPUs.` | Pass one of the GPU counts that the message lists. | | ` needs at least GPUs on ` | Ask for the GPU count that the message gives. | | `The pool holds GPUs, so it cannot run GPUs.` | Pass a smaller GPU count, or have an `app_admin` raise `max_gpus` with `set_pools`. | | `The head container has not started yet (state: PENDING).` | The node is still starting. When Snowflake has little GPU capacity in your region, this can take a long time. Check `status` and call `logs` again later. | | `Not all of the nodes this run needs became available within 45 minutes, so it stopped before training started.` | Snowflake had too few GPU nodes free in your region. Arena does not charge for the run. Submit it again later, or try another GPU family. | | `The run's message broker did not start, so it stopped before training started.` | Arena does not charge for the run. Submit it again. | | `The run failed while starting up, so it stopped before training started.` | Arena does not charge for the run. Read the head’s log with `logs` for the error. | | ` is published, but its service is still waiting for a GPU node.` | `publish` waited 60 minutes. The model keeps starting; run `endpoint` until its `state:` line reads `ready`. | | ` is in the Model Registry, but its service failed.` | The message gives Snowflake’s status message and a statement to check the service. For help, email [arena@agilerl.com](mailto:arena@agilerl.com) with both. | | `This app has no run .` | Check the run ID. It comes from `submit`. | | `The free trial of AgileRL Arena has ended.` | Buy the listing in Snowflake Marketplace. | | `Snowflake training is not enabled for this organization.` | Contact [arena@agilerl.com](mailto:arena@agilerl.com). | | `reward_file is not available in the Snowflake app.` | Set `environment.reward` in the manifest. See [Snowflake Native App rewards](compute/snowflake-native-app-rewards.md). | For pricing, billing or help with a run, email [arena@agilerl.com](mailto:arena@agilerl.com) with your account locator and the run ID. # get-started/how-arena-works.md # How Arena works Everything in Arena belongs to an organization. Inside it, you bring training data as a dataset or an environment, train a base model on it in an experiment, and deploy one of the experiment’s checkpoints as an agent. ## The pieces **Organization.** Your workspace. Members of an organization share its projects, datasets, environments, agents, balance and secrets. You can belong to more than one and switch with **Switch organisation** in the profile menu at the top right. Org **Admins** also manage members and billing. See [Profile and organizations](account/account.md). **Project.** A folder for experiments that work towards the same goal. Every experiment lives in one project. Projects also hold [pipelines](guides/pipelines.md). **Dataset.** Rows of training data, shared across the organization. The type decides which algorithms can use it: **SFT** for prompt and target pairs, **Preference** for a prompt with a chosen and a rejected reply, **Reasoning** for questions with a checkable answer, and **Traces** for recorded conversations. See [Upload a dataset](guides/upload-a-dataset.md). **Environment.** Code the model acts in over one or more turns, for tasks a fixed dataset can’t capture, such as a game or a support simulator. Arena validates each version before you can train on it. See [Upload an environment](guides/upload-an-environment.md). **Experiment.** A training setup (a dataset or environment, a base model, an algorithm and its settings, and the GPUs) together with the one training run it starts. You set it up in the experiment wizard or submit a manifest from the CLI. An experiment trains once: resuming from a checkpoint creates a new experiment. The docs say *run* for the training itself. While it runs, it spends balance and writes metrics and checkpoints. See [Train a model](guides/train-a-model.md). **Checkpoint.** The model’s weights saved at a training step. You resume from one or deploy one. See [Results and checkpoints](guides/results-and-checkpoints.md). **Agent.** A deployed checkpoint you can send prompts to, from the web app, the CLI or your own code. Agents are listed under **Agents** in the sidebar; the CLI also calls them deployments. See [Deploy an agent](guides/deploy-an-agent.md). ## How they connect ```text Organization ├── Datasets ─────┐ ├── Environments ─┤ pick one per experiment │ ▼ ├── Projects │ └── Experiments ──► Checkpoints ──► Agents └── Members, billing, secrets ``` A dataset or environment can feed any number of experiments, in any project. An experiment can produce many checkpoints, and you choose which one to deploy. ## Where to find them The sidebar on the left has one entry per kind of object: - **Home**: recent projects and experiments. - **Environments**: your organization’s environments and their versions. - **Datasets**: your organization’s datasets. - **Experiments**: your projects, also listed under it in the sidebar. Open one for its **Experiments**, **Pipelines** and **Results** tabs. - **Agents**: your deployed agents. Your profile and CLI key, billing, members, usage and organization secrets are under **Settings** in the profile menu at the top right. See [Profile and organizations](account/account.md). From the terminal, the same objects have their own command groups: `arena projects`, `arena datasets`, `arena env`, `arena experiments` and `arena agent`. See [Install and sign in](cli/install.md). # get-started/quickstart.md # Quickstart Arena is AgileRL’s post-training platform for open-weight language and vision-language models. It runs supervised fine-tuning, preference optimisation (DPO), on-policy distillation and reinforcement learning, including multi-turn RL against an environment. You bring the datasets and environments; Arena works out how many GPUs a run needs and how to lay it out on them, on Arena’s GPUs or on a cluster of your own. Train `Qwen/Qwen3.5-0.8B` with **CISPO** on GSM8K, a dataset of grade-school maths word problems. By the end you have a running experiment whose checkpoints you can deploy as an agent. CISPO is a reinforcement learning algorithm for problems with a checkable answer. For each question it samples a group of answers, scores each one with your reward function, and pushes the model towards the answers that beat the group average. ## What you need - An Arena account. Sign up at [arena.agilerl.com](https://arena.agilerl.com). Training spends your organization’s balance; see [Billing](account/billing.md). - For the CLI tab: [uv](https://docs.astral.sh/uv/getting-started/installation/). It uses or downloads a supported Python (3.10 to 3.13). - Some balance and a little time. The example stops after 30 training steps: enough for the reward to start climbing, without paying for a full pass over GSM8K (about 900 steps, several hours on one GPU). Arena shows the estimated time and cost before the run starts, and you can stop it at any point. The two files this page uses: - [`gsm8k_cispo.yaml`](/_downloads/b3de7108d540c16690dda685ef21f374/gsm8k_cispo.yaml), the manifest: model, dataset, prompt and algorithm settings. - [`reward.py`](/_downloads/549fc2d8943f592c34a27a56fb413b12/reward.py), the reward function. ## 1. Sign in ### Web app Sign in at [arena.agilerl.com](https://arena.agilerl.com). You land on **Home**. ### CLI ```bash uv tool install agilerl arena login ``` `uv tool install` puts the `arena` command in its own environment, so it leaves the open-source AgileRL framework (`agilerl` 2.x) alone. If you have `agilerl-arena` installed, remove it first; see [Moving from agilerl-arena](cli/install.md#moving-from-agilerl-arena). To install without uv, see [Install and sign in](cli/install.md#install). `arena login` opens a browser sign-in and saves the session on this machine. Where there is no browser, sign in with an API key instead; see [Install and sign in](cli/install.md#sign-in-with-an-api-key). ## 2. Create a project A project holds your experiments. Project and dataset names are shared across your organization. If a teammate already uses `gsm8k`, add a suffix such as `gsm8k-sam` to both, use those names in place of `gsm8k` in the commands below, and put the dataset name in the manifest’s `environment.dataset` and `environment.name`. ### Web app Open **Experiments** in the sidebar, click **New project**, name it `gsm8k` and click **Create Project**. ### CLI ```bash arena projects create gsm8k arena projects set-default gsm8k ``` With a default project set, later commands don’t need `--project`. More in [Create a project](guides/create-a-project.md). ## 3. Register the dataset Import GSM8K from Hugging Face as a **reasoning** dataset. Each row has a `question` and an `answer`, and the answer ends with the final number after `####`: ```text question: Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did she sell altogether in April and May? answer: Natalia sold 48/2 = 24 clips in May. Altogether she sold 48+24 = 72 clips. #### 72 ``` ### Web app 1. Open **Datasets** in the sidebar and click **New dataset**. 2. Name it `gsm8k` and choose **Reasoning** as the **Type**. 3. In **Select dataset**, search for `openai/gsm8k`, pick it, then choose the `main` configuration. Click **Create**. 4. On the dataset page, click **Question** and then the `question` column, then **Answer** and the `answer` column. Click **Confirm Selection**. ### CLI ```bash arena datasets create gsm8k \ --category reasoning \ --hf-dataset openai/gsm8k \ --hf-config main \ --hf-split train \ --column-mapping '{"question": "question", "answer": "answer"}' ``` The mapping keys are Arena’s names; the values are the columns in your data. GSM8K already uses Arena’s names. Arena imports the dataset in the background. Before you submit a run, wait until `arena datasets list` shows a number in the `rows` column for `gsm8k`. The column stays empty until the import finishes. ```bash arena datasets list ``` More in [Upload a dataset](guides/upload-a-dataset.md). ## 4. Read the reward function The reward function scores every answer the model writes during training. Arena calls `reward_fn` with the model’s `completion` and the row’s `answer` and `question`, and expects a number back. This one ignores anything inside the model’s thinking block and adds two scores: - **Correctness**: 1 when the number in the last `` tag matches the number after `####`. - **Format**: 1 when the reply ends with one `` tag that holds only a number. ```python # Copyright 2026 AgileRL # SPDX-License-Identifier: Apache-2.0 """GSM8K reward: the right final number, in the ```` tags the prompt asks for.""" import re ANSWER_BLOCK = re.compile(r"(.*?)", re.DOTALL) NUMBER = re.compile(r"-?\d[\d,]*(?:\.\d+)?") def final_text(completion: str) -> str: """Return the text after the last ````, or the whole completion when there is none.""" return completion.rpartition("")[2].strip() def to_number(text: str) -> float | None: """Return the first number in ``text``, ignoring thousands separators.""" match = NUMBER.search(text) return float(match.group(0).replace(",", "")) if match else None def gold_answer(answer: str) -> float | None: """Return a GSM8K row's final answer: the number after ``####``.""" _, marker, final = answer.rpartition("####") return to_number(final) if marker else None def correctness_reward(text: str, answer: str) -> float: """Return 1.0 when the last ```` block holds the gold number.""" blocks = ANSWER_BLOCK.findall(text) if not blocks: return 0.0 predicted = to_number(blocks[-1]) return 1.0 if predicted is not None and predicted == gold_answer(answer) else 0.0 def format_reward(text: str) -> float: """Return 1.0 when the text ends with one ```` block holding only a number.""" blocks = ANSWER_BLOCK.findall(text) if len(blocks) != 1 or not text.endswith(""): return 0.0 return 1.0 if NUMBER.fullmatch(blocks[0].strip()) else 0.0 def reward_fn(completion: str, answer: str, question: str) -> float: """Score one completion: correctness plus format, at most 2.0. Both parts read only the text after the reasoning, so a number the model tries while thinking does not count. :param completion: The model's turn, reasoning included when it has any. :param answer: The row's GSM8K answer, ending ``#### ``. :param question: The row's question. :return: The reward. """ text = final_text(completion) return correctness_reward(text, answer) + format_reward(text) ``` The manifest’s prompt asks the model for those `` tags. A reward that checks for tags the prompt never asks for scores almost every answer 0. [Write prompts and reward functions](guides/prompts-and-rewards.md) covers what the function receives and how the prompt is built. ## 5. Submit the run ### Web app 1. Open the `gsm8k` project and click **New experiment**. Name it `gsm8k-cispo` and click **Create Experiment**. The experiment wizard opens. 2. On **Environment**, pick the `gsm8k` dataset. 3. Under **Prompts**, expand **System prompt** and enter `Reason step by step. End with the final number in tags, like 42.` Set **User prompt** to `{question}`. 4. Under **Reward Function**, replace the code in the editor with `reward.py`, set **Maximum reward** to 2, and click **Validate**. **Next** turns on when **Prompts** and **Reward Function** are both done. 5. On **Agent**, choose **CISPO** and the base model `Qwen/Qwen3.5-0.8B`. 6. On **Training**, enter 30 in **Maximum Number of Training Steps** for a short run, or leave it empty for one full pass over the dataset. Keep the other defaults. The **Training resources** bar shows the GPUs Arena picked, with the estimated time and cost. 7. On **Summary**, click **Train**. Each step is described in [Train a model](guides/train-a-model.md). ### CLI Download the manifest and the reward function into one folder: ```bash curl -fsSLO https://docs.arena.agilerl.com/_static/examples/gsm8k_cispo.yaml curl -fsSLO https://docs.arena.agilerl.com/_static/examples/gsm8k-cispo/reward.py ``` Check your balance and the manifest, then submit it with the reward file: ```bash arena user credits arena manifest validate gsm8k_cispo.yaml arena experiments submit gsm8k_cispo.yaml --reward-file reward.py --experiment-name gsm8k-cispo ``` Before the run starts, Arena checks the reward function on a sample answer (see [Validate the reward function](guides/prompts-and-rewards.md#validate-the-reward-function)), then prints the GPUs it picked with the hourly rate and estimated total for you to confirm. Add `--dry-run` to see that price without submitting. `--yes` skips the confirmation; scripts and CI need it, because the command can’t ask without a terminal. Flags for choosing GPUs yourself are in the [command reference](cli/command-reference.md). The manifest: ```yaml --- algorithm: name: CISPO batch_size: 8 beta: 0.0 lr: 0.000005 clip_coef: 0.2 max_grad_norm: 0.1 update_epochs: 1 group_size: 8 temperature: 0.9 calc_position_embeddings: true environment: name: gsm8k env_type: rollout dataset: gsm8k rubric_file_path: reward.py prompt_template: system_0: Reason step by step. End with the final number in tags, like 42. user_1: '{question}' chat_template_kwargs: enable_thinking: false max_reward: 2.0 replay_buffer: kind: llm training: max_steps: 30 metrics_interval: 5 eval_loop: 1 evaluation_interval: 50 network: pretrained_model_name_or_path: Qwen/Qwen3.5-0.8B max_context_length: 1024 lora_config: lora_r: 16 lora_alpha: 64 task_type: CAUSAL_LM ``` `environment.dataset` names the dataset you registered, and Arena trains on it. `environment.name` is used only when `dataset` is missing; here it repeats the dataset’s name. `rubric_file_path` names the reward file. `prompt_template` turns each row into the chat the model sees. `network` names the base model and trains a LoRA adapter on top of it. `training.max_steps: 30` stops the run after 30 steps. Remove `max_steps` to train one full pass over the dataset. The [manifest schema](cli/manifest-schema.md) describes every field. ## 6. Watch it train ### Web app After **Train**, Arena returns you to the project’s **Experiments** tab. The `gsm8k-cispo` row shows the run’s status. Open the **⋮** menu on the row and choose **View logs** to follow it. ### CLI ```bash arena experiments status gsm8k-cispo arena experiments logs gsm8k-cispo --follow ``` `--follow` keeps printing new lines until the run ends. Without it, the command prints the lines so far and exits. The run takes a little while to start while Arena brings up its GPUs. [Monitor, halt and resume](guides/monitor-halt-resume.md) explains the statuses and how to stop a run early. ## Next steps - [Results and checkpoints](guides/results-and-checkpoints.md): read the reward and accuracy charts and pick a checkpoint. - [Deploy an agent](guides/deploy-an-agent.md): serve a checkpoint and send it a maths problem. - [Write prompts and reward functions](guides/prompts-and-rewards.md): swap the code check for an LLM judge. # guides/choose-compute.md # Choose compute Pick the GPU type and count for a training run, and read Arena’s time and cost estimate before you start. You don’t have to pick anything. Arena estimates how much GPU memory the run needs and selects the cheapest GPU type and count that fits and has capacity. Change it only when you want faster or cheaper training. ## How Arena sizes a run The estimate depends on the model, the algorithm and the training settings. Arena runs it again a moment after you change one of them, such as the model, LoRA rank, batch size or context length. If your choice still fits, Arena keeps it. If it no longer fits, Arena moves to the cheapest choice that does, and a toast tells you when that costs more per hour. You only choose GPU type and count. Arena works out the nodes, the split between training GPUs and rollout engines, the parallel layout, micro-batch size and offload. L4, A100 and H100 GPUs all train language models. Arena cloud doesn’t offer 8×A100 for language models; use 8×H100. ## Pick GPUs ### Web app The **Training resources** bar sits at the bottom of the **Agent** and **Training** steps. 1. Click the button under **Training resources**. It shows the current choice, for example **H100 80GB, 4 GPUs**, and the cluster price per hour. 2. In the **GPU type and count** grid, rows are GPU types (cheapest first) and columns are GPU counts. Each cell shows the estimated total cost and run time. 3. Click a cell to pick it. The legend explains the cells: - **Lowest total**: the cheapest choice for the whole run. - **Not enough memory**: the run doesn’t fit. The cell shows **–**. - **Unavailable**: it fits, but there is no capacity right now. Hover for the reason. When the main provider has no capacity, Arena can offer a secondary provider. The bar then shows **Secondary provider**, and the estimate uses that provider’s price. **Cost comparison** in the middle of the bar shows how far your choice is from the cheapest. Click **Switch to lowest** to go back to it. The **Resources** card on **Summary** repeats the GPU type, count, estimated time and price. Click **Edit** there to change them. ### CLI List the GPU types and counts you can train on: ```bash arena resources list --algorithm CISPO ``` Check whether a manifest fits a GPU before you submit. If it doesn’t fit, the report suggests settings that would: ```bash arena memory estimate run.yaml --gpu h100-80 --num-gpus 4 ``` Find the longest context that still fits: ```bash arena memory solve max_model_len run.yaml --gpu h100-80 --num-gpus 4 ``` Submit on the GPUs you chose: ```bash arena experiments submit run.yaml --project my-project --reward-file reward.py --num-gpus 4 --gpu-type h100-80 ``` [Train a model](guides/train-a-model.md) says which runs need it. How submit picks GPUs depends on which flags you pass: | You pass | Arena uses | |-------------------|-------------------------------------------------------| | Neither flag | The cheapest GPU type at the smallest count that fits | | `--num-gpus` only | The cheapest GPU type at that count | | `--gpu-type` only | The smallest count of that type that fits | | Both | That many GPUs of that type, on the fewest nodes | If the run doesn’t fit at your `--num-gpus`, submit stops and names the smallest larger count that does. When it refuses a GPU type or count, it says why and lists the types and counts you can use. Arena also sets the training layout and the split between training GPUs and rollout engines. It ignores these manifest fields if you set them: `algorithm.fsdp`, `algorithm.vllm_config.tensor_parallel_size`, `training.training_gpus_per_agent`, `training.rollout_engines_per_agent` and `training.rollout_batch_size`. Submit names the ones it dropped: ```text Arena sets the training layout and GPU split; ignoring algorithm.fsdp, training.rollout_batch_size. ``` The exception is OPD with a separate teacher model. Arena keeps that run’s `tensor_parallel_size`, `training_gpus_per_agent` and `rollout_engines_per_agent`, because its own split doesn’t count the teacher’s GPUs. Flags are in the [command reference](cli/command-reference.md). ## Estimated time and cost **Est. time** and **Est. training cost** sit on the right of the bar, with a likely cost range under the cost. Both depend on how long the model’s generations turn out to be, which is mostly settled once training begins. When one of your earlier runs used the same setup, the estimate comes from its real step time. The info icon next to the cost opens **How this estimate is built**: GPU compute, the head node, and about 15 minutes plus 10% of training time for startup, checkpoints and evaluation. With a step limit set, run time is the predicted time per step times the number of steps. A dataset run with no step limit trains one pass over the data: rows divided by batch size, rounded up. You pay for the time the cluster actually runs, so stopping early costs less. Some runs get **No estimate**, for example a dataset whose row count isn’t known yet. A notice says why. ## When the bar blocks training These messages turn off **Next** on **Training** and **Train** on **Summary** until they clear: | Message | What to do | |-------------------------------------------------------------------|-------------------------------------------------------------------------| | *Memory estimation failed. Please try again.* | Click **Retry**. | | *No resource class fits this configuration.* | Pick a smaller model, or lower LoRA rank, batch size or context length. | | *No GPU capacity right now.* | Every GPU type that fits is busy. Click **Retry** later. | | *The selected GPUs don’t fit this configuration.* | Pick another GPU type or count. | | *The selected GPUs have no capacity right now.* | Pick another GPU type or count. | | *Arena cloud 8×A100 is not available for LLM training. Use H100.* | Pick H100 for 8 GPUs. | ## Your own GPUs On an **Enterprise** organization, the grid also lists GPUs from your own clusters, marked **(BYOC)**. See [Bring your own compute](compute/byoc.md). # guides/create-a-project.md # Create a project Create a project to hold a set of related experiments, their results and their pipelines. Datasets and environments belong to the organization, not to a project, so any project can use them. ## Steps ### Web app 1. Click **Experiments** in the sidebar. Your projects show as cards. 2. Click **New project**. When you have no projects yet, the button reads **Create Project**. 3. Enter a **Name** and, if you like, a **Description**. Click **Create Project**. ![The Create Project panel with Name and Description fields](tutorials/_images/create-project/02-new-project.png)The **Create Project** panel. The project opens on its **Experiments** tab, with **Pipelines** and **Results** beside it. It is also listed under **Experiments** in the sidebar. To rename a project or change its description, open the **⋮** menu on its card and choose **Edit**. ### CLI ```bash arena projects create support-agent --description "Fine-tunes for the support bot" ``` Make it the default so later commands don’t need `--project`: ```bash arena projects set-default support-agent arena projects list ``` Flags are in the [command reference](cli/command-reference.md). ## Next steps - [Upload a dataset](guides/upload-a-dataset.md) or [upload an environment](guides/upload-an-environment.md) to train on. - [Train a model](guides/train-a-model.md) in the new project. # guides/deploy-an-agent.md # Deploy an agent Turn a training checkpoint into an agent with a live endpoint you can send prompts to. ## Prerequisites - An experiment with at least one checkpoint. See [Results and checkpoints](guides/results-and-checkpoints.md). ## Deploy a checkpoint ### Web app 1. On the project’s **Experiments** tab, click **Deploy** on the experiment’s card. 2. In **Deploy Agent**, enter a **Name** and, if you like, a **Description**. 3. Select a checkpoint. Arena preselects the one with the best evaluation score. 4. Check **GPUs** and **GPU type** (see [Inference GPUs](#inference-gpus) below). 5. Click **Deploy**. Arena opens **Agents**, where the new agent shows **Deploying**. When the status changes to **Deployed**, the agent has an endpoint. This usually takes a minute or two, longer for large checkpoints. You can also start from **Agents** in the sidebar: click **New Agent**, fill in **Setup** (name, source experiment, GPUs) and **Checkpoint** (**Best**, **Final** or **Custom**), then click **Create**. An agent made this way starts as **Not deployed**. Click **Connect** on its card, or **Deploy** on its page, to start it. Org **Admins** also set **Memory scope** here. ### CLI ```bash arena experiments checkpoints gsm8k-cispo arena agent deploy gsm8k-cispo --checkpoint 500 arena agent list ``` `--checkpoint` takes a `steps` value from the checkpoint list. Leave it out to deploy the checkpoint with the most steps. That differs from the web app, which preselects the best evaluation score. The deployment takes the experiment’s name. Leave out `--num-gpus` and `--gpu-type` to let Arena pick. `--memory-scope` sets who the agent keeps chat sessions for: `user` (the default for a new agent) or `organization`. Redeploying without it keeps the current scope; passing it on a redeploy changes it. Only org **Admins** can set `organization`. Flags are in the [command reference](cli/command-reference.md). ## Inference GPUs **GPUs** is the GPU count on the node, and each **GPU type** shows its price per hour. Arena hides options that can’t run the model and picks a default: the cheapest option that can serve 8 requests at full context, or failing that, the cheapest that runs the model at all. - An option with a warning, such as **Only holds 3/8 sequences in KV cache**, runs the model but queues extra requests. - If Arena can’t check a GPU type, the option says why. You can still pick it, but Arena can’t tell whether the model fits. - **No GPU fits** means nothing can serve this model. Retrain with a shorter context length or a smaller model. - An agent trained on your own cluster lists only that cluster’s GPUs, marked **BYOC**. See [Bring your own compute](compute/byoc.md). If Arena can’t size the model at all, you get a single **Resources** field instead. ## Statuses | Status | Meaning | |-----------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------| | **Not deployed** | The agent exists but isn’t serving. Click **Connect** (the wifi icon on its card) or **Deploy**. | | **Deploying** | Arena is starting the endpoint. On your own cluster it shows **Copying** first, while the weights are copied. | | **Deployed** | The endpoint is live. | | **Stopped** | Someone stopped it, or Arena stopped it because the organization couldn’t pay for the next hour. The agent page says which. Click **Deploy** to start it again. | | **Deployment failed** | The endpoint didn’t start. Click **Deploy** to try again. | ## Stop or remove an agent - **Disconnect** (the crossed-out wifi icon) on the card, or **Stop agent** on the agent’s page, stops the endpoint and keeps the agent. While it is still **Deploying**, the page button reads **Cancel**. - **Delete** in the card’s menu removes the agent and its deployment. From the CLI, run `arena agent delete gsm8k-cispo`. To send prompts to a deployed agent, see [Invoke an agent](guides/invoke-an-agent.md). # guides/invoke-an-agent.md # Invoke an agent Send prompts to a deployed agent from the Chat Playground, the terminal, Python, or any HTTP client. ## Prerequisites - An agent with status **Deployed**. See [Deploy an agent](guides/deploy-an-agent.md). - For the CLI, Python or HTTP: the `arena` CLI signed in, or a CLI API key in `ARENA_API_KEY`. See [Install and sign in](cli/install.md). ## Send a prompt ### Web app 1. Open **Agents** in the sidebar and click the agent’s card. 2. The agent page opens on **Chat Playground**. Type a message and send it. The reply streams in as it is generated. The playground keeps each conversation as a session. Start a new one, search, rename or reopen earlier ones from the session list beside the chat. If the agent’s memory scope is **Organization**, you also see sessions other members started. The other tabs hold code to copy, already filled in with this agent’s name and endpoint: | Tab | What it shows | |------------------|---------------------------------------------------------------------------| | **Arena client** | Python, using `ArenaClient` from `agilerl` | | **Arena CLI** | The `arena agent generate` command | | **Manual HTTP** | Python `requests` call to the endpoint, with your key as a `Bearer` token | The **Endpoint** row in the left panel has a copy button for the endpoint URL. ### CLI ```bash arena agent generate gsm8k-cispo --prompt "Natalia sold 48 clips in April and half as many in May. How many in total?" ``` The completion streams to your terminal. Later prompts continue the same conversation, so the agent remembers what you asked. Add `--new-session` to start over. To skip the name on every call, select the agent once with `arena agent run gsm8k-cispo`, then run `arena agent generate --prompt "..."`. `arena agent sessions list` lists your conversations with the agent, and `arena agent sessions resume` picks one up again. Flags are in the [command reference](cli/command-reference.md). ### Python ```python from agilerl import ArenaClient with ArenaClient() as client: with client.open_inference_agent("gsm8k-cispo") as agent: result = agent.generate("Your prompt here") if result.results: print(result.results[0].completion) ``` `ArenaClient()` uses your `arena login` session, or `ARENA_API_KEY` when it is set. More methods are on the [Python client](cli/python-client.md) page. ## Call the endpoint from your own code Anything that can send HTTPS requests can call the agent. Copy the **Manual HTTP** snippet from the agent page: it has the full URL and request body. Authenticate with your CLI API key as a `Bearer` token. The key belongs to you, not to the agent, so the same key works for every agent you can see. Request and response fields, streaming, and chat sessions over HTTP are in the [Inference contract](reference/inference-contract.md). ## If calls fail Calls only succeed while the agent shows **Deployed**. If it shows **Deploying**, wait. If it shows **Stopped**, **Not deployed** or **Deployment failed**, start it again with **Deploy** on its page. Statuses are explained in [Deploy an agent](guides/deploy-an-agent.md#statuses). # guides/monitor-halt-resume.md # Monitor, halt and resume Follow a training run’s status and logs, stop it early, and continue a finished run from one of its checkpoints. A run goes **Pending** → **Running** → **Succeeded**, **Failed** or **Stopped**. It can sit in **Queued** while it waits for GPUs, and shows **Stopping** while a stop takes effect. Every status is described in [Experiment statuses](reference/experiment-statuses.md). ## Check status and logs ### Web app Each card on the project’s **Experiments** tab shows the run’s status under its name. To read the logs, open the card’s **⋮** menu and choose **View logs**. It is off for a draft that has never run. On the logs page you can: - Search the log text. - Filter by log level. - Set a start and end time, then click **Query logs**. - Click **Refresh** to load new lines while the run is going. If the run failed or was stopped, a notice at the top says why (**Why this run failed** or **Why this run stopped**). Charts of the run’s metrics are on the **Results** tab. See [Results and checkpoints](guides/results-and-checkpoints.md). ### CLI ```bash arena experiments list --project my-project arena experiments status gsm8k-cispo arena experiments logs gsm8k-cispo --follow ``` `status` prints the status and, for a failed run, the reason. `logs --follow` keeps printing new lines until the run ends, then prints why it failed if it did. For output a script can parse, put `--json` before the command group: `arena --json experiments status gsm8k-cispo`. Flags are in the [command reference](cli/command-reference.md). ## Stop a run You can stop a run that is **Pending**, **Queued**, **Running** or **Stopping**. The status moves to **Stopping**, then **Stopped**. Checkpoints the run already saved are kept. ### Web app 1. Open the card’s **⋮** menu and choose **Stop training**. You can also click the stop button on the run’s row under **Running** on the **Results** tab. 2. In **Stop Experiment**, click **Stop**. ### CLI ```bash arena experiments stop gsm8k-cispo ``` ## Resume from a checkpoint Resuming starts a new experiment that picks up from a checkpoint of a run that has finished, failed or been stopped. The original run stays as it is. ### Web app 1. On the project’s **Experiments** tab, click **Resume** on the run’s card. It replaces **Train** once the run has checkpoints and is no longer **Draft**, **Pending** or **Running**. 2. In **Resume Experiment**, select a checkpoint. The table lists **Steps**, **Training Score** and **Evaluation Score** for each. 3. Enter a **Name** for the new experiment and click **Resume**. If the experiment is a stage in a pipeline, a warning says that resuming also triggers that stage. ### CLI ```bash arena experiments resume gsm8k-cispo --max-steps 2000 --new-name gsm8k-cispo-more ``` `--max-steps` counts from the start of the original run, so it has to be greater than the checkpoint’s step. Leave out `--checkpoint` to resume from the best checkpoint. Like submit, `resume` shows the price and asks before it starts. # guides/pipelines.md # Pipelines Chain experiments and deployments in one project, so each stage starts from the previous stage’s checkpoint. A pipeline is an ordered list of stages. An **Experiment** stage trains an experiment from the project. A **Deployment** stage deploys a checkpoint from the experiment stage before it to **Agents**. Pipelines are only in the web app. ## Prerequisites - A project with the experiments you want to chain, already set up in the wizard. See [Train a model](guides/train-a-model.md). ## Build a pipeline 1. Open your project and click the **Pipelines** tab. 2. Click **New Pipeline**, enter a name and an optional description, and save. 3. Expand the pipeline’s row to open the builder, then add stages to the graph. 4. For each **Experiment** stage, pick an experiment from the project and where it starts: - The first stage starts from scratch (**Start from scratch**) or from an agent you saved (**Use saved Agent**). - Later stages start from the previous stage’s **Best checkpoint** or **Final checkpoint**. - Tick **Auto-add checkpoint to Agents when complete** to save the result as an agent. 5. For each **Deployment** stage, choose **Best checkpoint** or **Final checkpoint** from the experiment stage before it. A pipeline can’t start with a deployment. 6. Set each stage’s trigger: - **Manual** runs only when you click **Trigger stage**. The first stage is always manual. - **Auto** starts when the previous stage succeeds. Arena only lists experiments that fit after the previous stage’s algorithm. If an experiment has already run, or is used elsewhere in the pipeline, Arena asks you to duplicate it first. ## Run and follow it Click **Trigger stage** on the first stage. Each stage shows its status, and the builder refreshes about every five seconds. An experiment stage links to its **Results**. A stage marked **Stale** ran before an earlier stage was run again. Resuming an experiment that belongs to a pipeline also triggers its stage. ## Manage pipelines Each pipeline’s **⋮** menu has **Edit name**, **Duplicate** and **Delete**. A pipeline stays inside its project. # guides/prompts-and-rewards.md # Write prompts and reward functions Turn each row of a reasoning dataset into a prompt, and score what the model writes back, so a reinforcement learning run such as CISPO or GRPO can learn from it. You need a [reasoning dataset](guides/upload-a-dataset.md#reasoning). The examples use GSM8K from the [Quickstart](get-started/quickstart.md). ## How the prompt is built In a manifest, `environment.prompt_template` holds the chat messages. In the experiment wizard, the **Prompts** step writes the same thing from its system prompt and **User prompt** fields. ```yaml prompt_template: system_0: Solve the problem. Put the final number in tags. user_1: '{question}' ``` For each row, Arena: 1. **Turns each key into one chat message.** The text before the first `_` is the role: `system_0` is a system message, `user_1` a user message, `assistant_2` an assistant message. 2. **Orders the messages by the number at the end of each key.** Number every key. Arena doesn’t keep the order you wrote them in, so keys without a number come out alphabetically. Numbering only some keys, or using a number twice, is an error. 3. **Fills `{question}` and `{answer}`** from the row’s mapped columns. Nothing else is filled: other braces, such as `{"n": 1}`, stay as written. Putting `{answer}` in the prompt shows the model the answer. 4. **Applies the model’s chat template**, with `chat_template_kwargs` from the manifest’s `environment` section. The chat template decides the rest: - **System prompt.** There is one only if you add a `system_*` key, or the model’s template adds its own. `Qwen/Qwen2.5-0.5B-Instruct` adds one; Qwen3.5 models don’t. - **Thinking.** For Qwen3.5 the template opens the assistant turn with a thinking block. `Qwen/Qwen3.5-0.8B` and `Qwen/Qwen3.5-2B` close it at once (thinking off); `Qwen/Qwen3.5-4B` and `Qwen/Qwen3.5-9B` leave it open (thinking on). Set `chat_template_kwargs: {enable_thinking: true}` or `false` to choose. - **Assistant prefill.** When the last message is an assistant message with text, the model continues that text. The prefill is part of the prompt, not the completion. ## What the reward function receives Arena calls your function once per completion, passing arguments by name, and expects a number back: ```python def reward_fn(completion: str, answer, question) -> float: ... ``` - **`completion`** is everything the model wrote in its turn: reasoning, the `` that ends it, and the answer. The end-of-turn token is dropped and surrounding whitespace is stripped. It starts where the prompt ends, so anything already in the prompt, such as Qwen3.5’s opening `` or an assistant prefill, is not in it. - **`answer`** is the row’s answer column, unchanged. For GSM8K that is the whole worked answer ending `#### 72`. Columns keep their types, so a numeric answer arrives as a number. - **`question`** is the row’s question column, unchanged. It is not the rendered prompt. A completion counts as solved when its reward reaches `max_reward` in the manifest, or **Maximum reward** in the wizard. The default is 1. Set it to the most your function can return. For the same prompt and the row `question: What is 2 + 3?`, `answer: '#### 5'`, here is what `completion` looks like: | Model and setting | `completion` | |--------------------------------------------------------|-----------------------------------------------------| | `Qwen/Qwen3.5-0.8B`, `enable_thinking: true` | `2 plus 3 is 5.\n\n\n5` | | `Qwen/Qwen3.5-0.8B`, thinking off (the default) | `2 plus 3 is 5.\n5` | | `Qwen/Qwen2.5-0.5B-Instruct`, asked for `` tags | `2 plus 3 is 5.\n5` | ## Write a reward that fits - **Score the answer after the reasoning**, so a number the model tries while thinking doesn’t count. Take the text after the last ``, or the last `` match. - **Match what your model and template produce.** With Qwen3.5 thinking on, the opening `` is in the prompt and `` is followed by a blank line. A pattern that needs `` at the start of `completion`, or one newline after ``, never matches. - **Ask for every tag you check.** A reward that needs `` tags scores 0 when the prompt never asks for them. The Quickstart’s [`reward.py`](/_downloads/549fc2d8943f592c34a27a56fb413b12/reward.py) follows all three: one point for the right number, one for the format. ## Check a template before you submit Render the prompt on your own machine with the model’s tokenizer. This builds the same messages Arena does for a two-key template: ```python from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3.5-0.8B") row = {"question": "What is 2 + 3?", "answer": "#### 5"} messages = [ {"role": "system", "content": "Solve the problem. Put the final number in tags."}, {"role": "user", "content": row["question"]}, ] print(tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True, enable_thinking=False, )) ``` Then call your reward function with completions shaped like the table above. ## Validate the reward function ### Web app In the wizard’s **Environment** step, a reasoning dataset has two required steps: **Prompts** and **Reward Function**. **Next** stays disabled until both are done. 1. Under **Reward Function**, write `reward_fn` in the **Editor**, or click **Generate** to have Arena draft one from your prompt and some sample rows. 2. Set **Maximum reward**. 3. **Sample row** shows one row of your dataset, with the rendered prompt in the question cell. The **Answer** cell is the completion the check scores. It starts as the row’s answer; edit it to try other replies, and click **Reset** to go back. Your dataset is not changed. The shuffle button picks another row. 4. Click **Validate**. **Validation Results** shows the **Syntax check** and **Execution test**, and **Calculated reward** shows the score. ### CLI `arena experiments submit` runs the reward file once before it starts the run, using the reference answer from the dataset’s first row as the completion. Pass `--completion` to test with your own text instead: ```bash arena experiments submit gsm8k_cispo.yaml --reward-file reward.py --completion "72" ``` If the reward file fails to import or doesn’t return a number, nothing is submitted. `--dry-run` runs the same check before it prints the price, so a broken reward file shows up there too. Leave `environment.rubric_file_path` out of the manifest and the CLI fills it in from `--reward-file`. If you set it, it must name the same file. ## Use an LLM as the judge A judge is another LLM, called through its provider’s API, that reads each completion and scores it against criteria you write. It suits rewards that are hard to code, such as whether the working is clear. Keep a code check for the parts you can verify exactly. The example keeps GSM8K and CISPO and scores each completion as 0.6 × correctness plus 0.4 × the judge’s score for the working. Judges are set up from the CLI. The files: - [`reward.py`](/_downloads/65a2e6d80294f0d99dc52c6d7b0990b6/reward.py) - [`manifest.yaml`](/_downloads/15a0331d57e72fa638141d3cfbaf30b2/manifest.yaml) - [`manifest_ruler.yaml`](/_downloads/67e8064db5100e19d4e4604a3851b08e/manifest_ruler.yaml) ### Store the judge’s API key The training job calls the judge, so it needs your provider key. Store it as an organization secret: the manifest names the secret, and Arena passes it to the job as an environment variable of that name. The key never goes in the manifest. ```bash arena secrets set OPENAI_API_KEY --from-env OPENAI_API_KEY arena secrets list ``` Without `--from-env`, `arena secrets set` prompts for the value. In the web app, add secrets under **Settings** → **Organization**; see [Organization secrets](account/account.md#organization-secrets). ### The reward file A judge needs the reward written as an OpenEnv `Rubric` class instead of a `reward_fn`. Arena calls it on every turn with the model’s reply (`action.message`) and the dataset row (`observation.question`, `observation.answer`). ```python # Copyright 2026 AgileRL # SPDX-License-Identifier: Apache-2.0 import re from openenv.core.rubrics.base import Rubric from openenv.core.rubrics.containers import WeightedSum from agilerl.llm_envs.rubrics import LLMGroupJudgeRubric, LLMJudgeRubric CRITERIA = """\ The reply solves the math word problem. Each step of the working follows from the problem or the step before it, and a student could follow it. The reply ends with one final number inside tags, and that number matches the reference answer. Penalise wrong arithmetic, skipped steps, repetition and padding.""" def extract_gold_answer(answer: str) -> str | None: """Return the final numeric answer from a GSM8K answer (the value after ``####``).""" match = re.search(r"####\s*(-?[\d,]+)", answer) return match.group(1).replace(",", "").strip() if match else None def extract_model_answer(completion: str) -> str | None: """Return the final number inside the model's last ``...`` block.""" blocks = re.findall(r"([\s\S]*?)", completion) if not blocks: return None number = re.search(r"-?[\d,]+", blocks[-1]) return number.group(0).replace(",", "").strip() if number else None class Correctness(Rubric): """1.0 when the number in ```` matches the GSM8K gold answer.""" component_name = "correct" def forward(self, action, observation) -> float: gold = extract_gold_answer(str(observation.answer)) predicted = extract_model_answer(action.message) if gold is None or predicted is None: return 0.0 return 1.0 if predicted == gold else 0.0 class RUBRIC(WeightedSum): """Correct final answer, plus a judge's score for the working.""" def __init__(self, judge) -> None: super().__init__( [Correctness(), LLMJudgeRubric(judge, CRITERIA)], weights=[0.6, 0.4], ) class RULER(LLMGroupJudgeRubric): """One judge call ranks every completion in a group against the criteria.""" def __init__(self, judge) -> None: super().__init__(judge, CRITERIA) ``` - `Correctness` is a plain rubric: 1.0 when the number in `` matches the number after `####`. Its `component_name` names its metric. - `LLMJudgeRubric` shows the judge the question, the reply and the row’s answer, with your criteria, and asks for a score from 0 to 1. A reply it can’t read scores 0. - `RUBRIC` adds them with `WeightedSum`. The weights must add up to 1. - `RUBRIC` takes a `judge` argument in `__init__`. Arena builds the class with the run’s judge client, so it must be a class, not an instance made when the file is imported. Write the criteria the way you would brief a human grader: what a good reply does, and what to mark down. The judge sees the reply without its reasoning. Pass `include_reasoning=True` to `LLMJudgeRubric` to show it the reasoning too; that trains the model to write reasoning the judge likes. ### The manifest ```yaml --- algorithm: name: CISPO batch_size: 16 beta: 0.001 lr: 0.0000005 clip_coef: 0.2 max_grad_norm: 0.1 update_epochs: 1 group_size: 8 temperature: 0.9 calc_position_embeddings: true environment: name: gsm8k env_type: rollout dataset: gsm8k rubric_file_path: reward.py rubric_name: RUBRIC judge: provider: openai model: gpt-4.1-mini api_key_env: OPENAI_API_KEY max_tokens: 512 prompt_template: system_0: >- Solve the problem. Show your working step by step, then give the final number inside tags. user_1: '{question}' replay_buffer: kind: llm training: max_steps: 100_000 metrics_interval: 5 eval_loop: 1 evaluation_interval: 5 network: pretrained_model_name_or_path: Qwen/Qwen3.5-0.8B max_context_length: 1024 lora_config: lora_r: 16 lora_alpha: 64 task_type: CAUSAL_LM ``` Three things in `environment` set up the judge: - `rubric_name: RUBRIC` is the class to load from the reward file. Without it, Arena looks for `reward_fn`. - `judge.provider` is `openai`, which covers any OpenAI-compatible endpoint, or `anthropic`. `judge.model` is the judge’s model id. - `judge.api_key_env` is the name of the organization secret, not the key. `judge.max_tokens` is the judge’s reply budget. A judge that thinks before it answers spends this budget on thinking too, so raise it for thinking models. To reach a judge somewhere other than OpenAI, such as OpenRouter or your own vLLM server, set `judge.base_url`. The [manifest schema](cli/manifest-schema.md) lists every judge field and its default. Submit it like any other run: ```bash arena experiments submit manifest.yaml --reward-file reward.py --experiment-name gsm8k-judge ``` Every completion now costs a judge call, so each prompt costs `group_size` calls. Check your provider’s rate limits and spend before a long run. A judge call that still fails after the provider SDK’s retries drops that group, and the run stops after 8 failed episodes in a row. ### Watch the judge Besides the usual metrics, a judge run logs `reward_correct` and `reward_judge` (each part before weighting), `judge_calls`, `judge_parse_failure_rate` (replies with no readable score, each scored 0) and `judge_mean_latency_s`. If the parse failure rate is high, raise `max_tokens` first. If latency climbs, the judge is slowing training: raise `judge.max_concurrency` or use a faster model. Accuracy counts a completion as solved when its reward reaches `max_reward`, which here only a correct answer the judge also scores 1 can reach. Read `reward_correct` for how often the model gets the number right. To see why the judge gave a score, open the project’s **Results** tab and click **View sampled outputs** on the experiment. The **Judge notes** column shows the judge’s one-sentence reason for each completion. Read some early in the run. If the judge rewards something you didn’t mean, such as long answers, tighten the criteria and resubmit. ### Score a group together with RULER CISPO already compares the completions in a group. **RULER** gives the judge the same view: one call shows the judge every completion for a prompt and asks for a score for each. Comparing replies side by side is often easier for a judge than scoring each alone, and a group costs one call instead of one per completion. `reward.py` already defines `RULER`, a subclass of `LLMGroupJudgeRubric` with the same criteria. To use it, name it as `group_rubric_name` and point `rubric_name` at `Correctness` alone: ```yaml environment: rubric_file_path: reward.py rubric_name: Correctness group_rubric_name: RULER max_reward: 2.0 ``` ```bash arena experiments submit manifest_ruler.yaml --reward-file reward.py --experiment-name gsm8k-ruler ``` How it differs from the per-completion judge: - The group score is added to `Correctness`, so a completion can score up to 2; set `max_reward` to match. It is logged as `reward_group_judge`, and its judge notes are labelled `group_judge`. - Leave `rubric_name` out and the group score is the whole reward. - The judge sees the completions in a new random order on every call, so a judge that favours one position adds noise rather than bias. - A reply it can’t read, or with the wrong number of scores, scores the whole group 0. - The judge writes one reason per completion, so raise `max_tokens` with `group_size`. - Held-out evaluation episodes get no group score. # guides/results-and-checkpoints.md # Results and checkpoints Compare training runs on charts, read what the model produced, and find the checkpoints you can deploy or resume from. ## Compare runs on charts ### Web app 1. Open your project and click the **Results** tab. You can also click **Results** on an experiment’s card; that run is selected for you. 2. On the left, runs are split into **Running** (running or stopping) and **Completed** (succeeded, stopped or failed, with metrics). Click the eye icon on a run to add it to the charts. Select several to compare them. 3. On the right, the **Training** section charts the run’s metrics, such as reward and loss. Switch the horizontal axis between **Steps** and **Time** at the top of it. **System Resources** appears when the run reports hardware metrics. 4. Under **Custom Charts**, build your own chart: pick metrics for each axis, **Line** or **Scatter**, and **Steps** or **Time**. 5. Below the charts, the settings of the selected runs sit side by side under **Resources**, **Environment**, **Agent** and **Training**. Switch to **Display Differences** to see only what differs. Charts fill in once a run starts reporting metrics. While a running run is selected, the tab refreshes about every five seconds. Each run row also has **View logs**, and for language model runs **View sampled outputs**. Sampled outputs list prompts and completions from training with their **Step**, **Reward**, **Turns** and **Tokens**. Narrow them with **From step** and **To step**. ### CLI Download a run’s metrics as CSV: ```bash arena experiments metrics gsm8k-cispo --output-file gsm8k-cispo-metrics.csv ``` Leave out `--metric` to get every metric, or repeat it to pick some. Flags are in the [command reference](cli/command-reference.md). ## Find checkpoints A checkpoint is the model saved at one training step. You use one to deploy an agent or to resume training. ### Web app On the project’s **Experiments** tab, click **Deploy** on the experiment’s card. **Deploy** is off until the run has saved a checkpoint. The **Deploy Agent** sheet lists the checkpoints with **Steps**, **Training Score** and **Evaluation Score**, and charts both scores over training. A score shows **N/A** when the run has no metric for that step. Arena selects the checkpoint with the best evaluation score, or the last one if there are no scores. To delete a checkpoint, click its trash icon and confirm in **Delete checkpoint?**. From here, go on to [Deploy an agent](guides/deploy-an-agent.md). The same checkpoints appear in **Resume Experiment**; see [Monitor, halt and resume](guides/monitor-halt-resume.md#resume-from-a-checkpoint). ### CLI ```bash arena experiments checkpoints gsm8k-cispo ``` Each row’s `steps` value names the checkpoint for `arena agent deploy --checkpoint` and `arena experiments resume --checkpoint`. Scores are often empty. ## Choose what a checkpoint saves By default a language model run saves LoRA adapter weights only, at the end of the run. To also write the full model with the adapter merged in, set `training.checkpoint_export` in the manifest: ```yaml training: checkpoint_export: format: merged trigger: best ``` | Field | Values | Default | |-----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------| | `format` | `adapter` saves the LoRA weights only. `merged` also writes a merged Hugging Face model. | `adapter` | | `trigger` | When to write the merged model: `final` (the run’s last save), `best` (the best checkpoint, or the last if none is marked best), `every` (every save) or `on_demand` (not during training). | `final` | `trigger` only matters with `format: merged`. The full field list is in the [manifest schema](cli/manifest-schema.md). # guides/train-a-model.md # Train a model Set up an experiment on a dataset or environment, pick an algorithm and a base model, and start a training run. ## Prerequisites - A [project](guides/create-a-project.md). - A [dataset](guides/upload-a-dataset.md) or an [environment](guides/upload-an-environment.md) to train on. - For reasoning datasets, a prompt template and a reward function. See [Write prompts and reward functions](guides/prompts-and-rewards.md). What you train on decides which algorithms Arena offers, and whether you need extra setup such as a reward function. See [Algorithms by training data](reference/algorithms.md#by-training-data). The rest of the setup is the same for every algorithm. ## Steps ### Web app 1. Open **Experiments** in the sidebar, pick your project, and click **New experiment**. Enter a **Name**, and a **Description** if you like, then click **Create Experiment**. The wizard opens on the new draft. It has four steps: **Environment**, **Agent**, **Training** and **Summary**. 2. On **Environment**, pick a dataset or an environment from the grid. For an environment, use **Select version** to choose which version to train on. A reasoning dataset adds two tasks you finish on this step, **Prompts** and **Reward Function**; **Next** stays off until the reward passes [validation](guides/prompts-and-rewards.md#validate-the-reward-function). 3. On **Agent**, choose an algorithm and a base model. **Maximum context length** can’t go above the model’s own limit. Arena fills in the LoRA modules for the model, so you only set rank, alpha and dropout if you want to change them. 4. On **Training**, set the training parameters. On a dataset, leaving **Maximum Number of Training Steps** empty trains one pass over the data. For a first trial run, enter a small number such as 10 so it finishes fast and costs little. The **Training resources** bar picks GPUs that fit the run and shows **Est. time** and **Est. training cost**. To change them, see [Choose compute](guides/choose-compute.md). 5. On **Summary**, check the settings and click **Train**. Arena takes you back to the project’s **Experiments** tab. The status goes to **Pending**, then **Running**; training usually starts within about ten minutes. **Next** is off until the current step is complete, and a message says what is missing. **Save** on **Summary** keeps the draft without training it. A draft also saves itself after five idle minutes. You can start a saved draft later with **Train** on its card in the **Experiments** tab. To rename an experiment later, open its card’s **⋮** menu and choose **Edit name**. ### CLI Print a manifest with Arena’s defaults, edit it, check it, then submit: ```bash arena manifest template CISPO --model Qwen/Qwen3.5-4B --dataset gsm8k > run.yaml arena manifest validate run.yaml arena experiments submit run.yaml --project my-project --experiment-name gsm8k-cispo --reward-file reward.py ``` Use `--env` instead of `--dataset` to train on an environment, and drop `--reward-file` for anything other than a reasoning dataset. In the manifest, `environment.dataset` names the dataset Arena trains on. Without it, Arena trains on whatever `environment.name` names, a dataset or an environment. With `dataset` set, `name` is only a label, unless it is the name of a different registered dataset: then submit stops with `environment.dataset is '…' but environment.name is '…', a different dataset`. Set `name` to the same dataset, or remove it. `arena models list` lists the models `--model` takes. `arena manifest template` needs you to be signed in. For a reasoning dataset, check these fields under `environment` before you submit: - `prompt_template`: the chat messages, with `{question}` where the row’s question goes. - `max_reward`: the most your reward function can return. - `chat_template_kwargs`: for example `enable_thinking: false` on Qwen3.5. - `rubric_file_path`: `arena manifest template` sets it to `reward.py`. It must name the file you pass to `--reward-file`; if you remove it, `--reward-file` fills it in. What each one does is in [Write prompts and reward functions](guides/prompts-and-rewards.md). The Quickstart’s [`gsm8k_cispo.yaml`](/_downloads/b3de7108d540c16690dda685ef21f374/gsm8k_cispo.yaml) is a complete example. On a dataset, a manifest without `training.max_steps` trains one pass over the data. For a first trial run, set it to a small number such as `10`. `arena experiments submit` prints the GPUs, hourly rate and estimated total, then asks before it starts billing. Add `--dry-run` to see the price without submitting, or `--yes` to skip the question in a script. Arena picks the cheapest GPUs that fit; to choose them yourself, see [Choose compute](guides/choose-compute.md). Flags are in the [command reference](cli/command-reference.md). Every manifest field is in the [manifest schema](cli/manifest-schema.md). ## Next - Watch the run: [Monitor, halt and resume](guides/monitor-halt-resume.md). - Compare runs and pick a checkpoint: [Results and checkpoints](guides/results-and-checkpoints.md). # guides/train-on-traces.md # Train on traces Upload recorded conversations, tool calls included, and train a model on them with SFT or On-Policy Distillation (OPD). A traces dataset holds whole conversations in the OpenAI chat format, for example logs from a deployed assistant or agent, or answers from a stronger model you want a smaller one to learn from. It needs no column mapping, prompt template or reward function. ## File format Each row is one conversation: - `messages` (required): the conversation in order, as `system`, `developer`, `user`, `assistant` and `tool` messages. Every row needs at least one `assistant` message. - `tools` (optional): the tools the model could call. ```json {"messages": [{"role": "user", "content": "I can't sign in, MFA keeps failing."}, {"role": "assistant", "content": null, "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "lookup_user", "arguments": "{\"email\": \"a@b.com\"}"}}]}, {"role": "tool", "tool_call_id": "c1", "content": "{\"locked\": true}"}, {"role": "assistant", "content": "Your account was locked. I've sent an unlock link."}], "tools": [{"type": "function", "function": {"name": "lookup_user", "parameters": {"type": "object", "properties": {"email": {"type": "string"}}}}}]} ``` The rules that matter most: - Answer every tool call with a `tool` message carrying the same `tool_call_id` before the next `assistant` message. Only the last assistant message’s calls may go unanswered. - Every `assistant` message trains unless it has `"weight": 0`, which makes it context only. Two trained assistant messages can’t sit next to each other. - `assistant` messages may carry the model’s reasoning in `reasoning_content`. Other columns stay with the row and training ignores them. ### Files Arena accepts Upload one JSONL or Parquet file, upload a folder of Parquet files laid out like a Hugging Face dataset, or import a Hugging Face dataset. In Parquet, store `messages` and `tools` as JSON text. Arena reads each file in one of three layouts and converts it to `messages`: | The file has | Arena reads it as | |--------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------| | `prompt` and `completion` columns | Pairs. Each becomes a conversation, and only the completion trains. | | A `messages` column | Conversations, as they are | | A `conversations` column of ShareGPT turns (`from`, `value`) | ShareGPT. Turns become messages, and Hermes-style ``, `` and `` blocks become tool calls, tool messages and reasoning. | A `` or `` block converts when it is closed and its body is a JSON object, so prose that mentions the tags is left alone. In a tool turn made only of `` blocks, a block whose body isn’t JSON, such as a Python dict or cut-off JSON, becomes that tool result’s text with the tags removed. Tool use written as text in any other way, such as `` tags or tool results in a `user` turn, stays in the message text and trains as answer text, not as a tool call. Arena flags it: a note under the configuration on Hugging Face import, a **Tool calls are written as text** notice on the dataset’s **Data** tab, and a **Tool calls in text** badge on each such conversation. A row whose `label` is false (`false`, the text `"false"` in any case, or `0`) is skipped, so only completions labelled true train. Any other `label` value stays as a column. Per-call logs often repeat a conversation once per model call, each a longer prefix of the next. Arena keeps only the longest, so every turn trains once. When this happens, **Conversations** on the dataset’s **Data** tab shows how many pairs they came from, for example `Converted from 38 pairs`. ## Upload a traces dataset ### Web app 1. Open **Datasets** in the sidebar, click **New dataset** and pick **Type** **Traces**. 2. Enter a **Dataset name**. 3. Under **Select dataset**, do one of these: - Click **Upload a JSONL or Parquet** and pick your file. - Click **Upload a folder** and pick a folder of Parquet files named by split, such as `default/train-00000-of-00001.parquet`, one folder per configuration. Pick the configuration in **Select configuration** when it holds more than one. Every split of the configuration is imported into the dataset, and a folder with more than one split needs a `train` split. - Search Hugging Face and pick a configuration in **Select configuration**. Only configurations Arena can import as traces are listed; **Has labels** marks one with a `label` column. When it has more than one split, **Split** picks the one to import, `train` by default, and leaves the others out for evaluation. **All splits** imports every split instead, and runs train on `train`. 4. Click **Save**. Arena opens the dataset on **Data**. A summary card counts the **Conversations**, the **Assistant turns** that train and those that are context only, the **Tools** (**Browse tools** lists them), and, when rows were skipped, how many are **Skipped**, with **Review** for each reason and how to fix it. A warning shows when 10% or more of the rows were skipped. Under it, **Conversations** previews the stored conversations, with a search over message text, reasoning and tool calls. Pick one to read its **Messages**, **Tools**, **Other fields** and **JSON**; assistant turns with `"weight": 0` show as context. ### CLI ```bash arena datasets create helpdesk-traces --category traces --file ./conversations.jsonl ``` `--category traces` takes no column mapping. Arena checks the file on your machine before it uploads. Flags are in the [command reference](cli/command-reference.md). A row that breaks the rules is skipped and the rest are stored. The dataset says how many rows were skipped and why, and you can download the skipped rows as JSONL with **Download Rejected Rows** under **Skipped rows**, fix them and upload again. The upload fails only when no row passes, or when a JSONL line isn’t a JSON object. ## Choose SFT or OPD | Method | What the model learns from | |---------------------------------|---------------------------------------------------------------------------------------------| | **SFT** | The recorded assistant turns. The model learns to write them. | | **OPD** with a separate teacher | A teacher model’s scores of the student’s own replies. The trace only supplies the prompts. | | **OPD** with self-distillation | The student itself, shown the recorded reply as a hint, scoring the student’s own replies. | OPD needs no reward function. Without one, the run learns from the teacher alone. From the CLI you can add one with `--reward-file`, and it is mixed in with the teacher’s signal. ## Worked example: Capybara This imports `trl-lib/Capybara` (about 16,000 multi-turn chats) as a traces dataset, then trains `Qwen/Qwen3.5-0.8B` on it with SFT and with OPD in self-distillation mode. Both runs stop at 20 steps. ### Web app 1. **New dataset** → **Type** **Traces**. Name it `capybara-traces`, search `trl-lib/Capybara`, pick configuration `default`, keep **Split** on `train` and click **Save**. The `test` split is left out. 2. In your project, click **New experiment**. On **Environment**, select `capybara-traces` and click **Next**. 3. On **Agent**, pick **SFT** and the model `Qwen/Qwen3.5-0.8B`. 4. On **Training**, set **Maximum Number of Training Steps** to `20`. On **Summary**, click **Train**. For the OPD run, start a second experiment and pick **OPD** on **Agent**. Under **Teacher**, leave **Teacher source** on **Same as student (self-distillation)**. To use another model as teacher, choose **Separate model** and pick a **Teacher model**. Arena only lists models that share the student’s vocabulary, and the teacher needs extra GPUs. ### CLI ```bash arena datasets create capybara-traces --category traces \ --hf-dataset trl-lib/Capybara --hf-config default --hf-split train ``` `--hf-split` is required. Unlike the web app, the CLI imports every split of the configuration, so this dataset holds the `train` and `test` conversations. Save the SFT manifest as `sft.yaml`: ```yaml algorithm: name: SFT environment: name: capybara-traces env_type: dataset objective: sft dataset: capybara-traces dataset_format: traces network: pretrained_model_name_or_path: Qwen/Qwen3.5-0.8B max_context_length: 2048 training: max_steps: 20 ``` Save the OPD manifest as `opd.yaml`. `teacher: {}` means self-distillation. For a separate teacher, set `teacher.model.pretrained_model_name_or_path`. The lower `gpu_memory_utilization` leaves room for the rollout engine on L4 GPUs. ```yaml algorithm: name: OPD batch_size: 4 group_size: 2 max_output_tokens: 256 teacher: {} vllm_config: gpu_memory_utilization: 0.8 environment: name: capybara-traces env_type: rollout dataset: capybara-traces dataset_format: traces network: pretrained_model_name_or_path: Qwen/Qwen3.5-0.8B max_context_length: 2048 training: max_steps: 20 ``` Check both, then submit: ```bash arena manifest validate sft.yaml arena manifest validate opd.yaml arena memory estimate opd.yaml --gpu "NVIDIA L4" --num-gpus 4 arena experiments submit sft.yaml --project my-project --experiment-name capybara-sft arena experiments submit opd.yaml --project my-project --experiment-name capybara-opd ``` Follow the runs in [Monitor, halt and resume](guides/monitor-halt-resume.md). # guides/upload-a-dataset.md # Upload a dataset Upload a file or import a Hugging Face dataset, and tell Arena which columns hold what, so you can pick it as training data in an experiment. Datasets belong to your organization, so every project can use them. Each dataset has one type: | Type | Each row holds | |----------------|---------------------------------------------------------| | **SFT** | A prompt and the target reply | | **Preference** | A prompt, a chosen reply and a rejected reply | | **Reasoning** | A question and an answer your reward function can check | | **Traces** | A recorded conversation | The type decides which algorithms can train on it. See [Algorithms by training data](reference/algorithms.md#by-training-data). ## Upload the data The web app takes a CSV or Parquet file, a folder in Hugging Face layout (Parquet files per config), or a dataset you search for on Hugging Face. The CLI also takes JSONL. ### Web app 1. Click **Datasets** in the sidebar, then **New dataset**. 2. Enter a **Dataset name** and an optional **Description**, and choose the **Type**. 3. Add the data. Search Hugging Face in **Select dataset**, or click **Upload a CSV or Parquet** or **Upload a folder**. When the dataset has more than one configuration, such as `main` and `socratic` for GSM8K, choose one in **Select configuration**. ![The New Dataset panel with name, description, type and data source fields](tutorials/_images/upload-reasoning-dataset/02-create-dataset-modal.png)The **New Dataset** panel. 4. Click **Create**. The dataset opens so you can map its columns. 5. Each type has its roles across the top of the table: click a role, then the column that holds it. Click a role again to clear it. When every role is set, click **Confirm Selection**. Confirm the columns before you use the dataset in an experiment. The wizard won’t move on from a dataset whose roles aren’t set. ### CLI Create the dataset and map its columns in one command. The keys of `--column-mapping` are Arena’s role names; the values are your file’s column names. ```bash arena datasets create math-word-problems \ --category reasoning \ --file ./reasoning.csv \ --column-mapping '{"question": "question", "answer": "answer"}' ``` To import from Hugging Face instead of a file, pass `--hf-dataset`, `--hf-split` and, when the dataset has more than one configuration, `--hf-config`. The commands for each type are below. Flags are in the [command reference](cli/command-reference.md). ```bash arena datasets list ``` ## SFT Each row is a prompt and the reply the model should learn to write. Map **Prompt** and **Target**. Example: [`sft.csv`](/_downloads/330c4a58b606472c4eb9c121570f8f19/sft.csv), with `instruction` and `response` columns. CLI: ```bash arena datasets create support-tickets-sft \ --category sft \ --file ./sft.csv \ --column-mapping '{"prompt": "instruction", "target": "response"}' ``` If your data is whole conversations, with several turns or tool calls, use [Traces](guides/train-on-traces.md) instead. ## Preference Each row is a prompt with a better and a worse reply. In the web app, map **Question** (the prompt), **Chosen** and **Rejected**. The CLI calls the **Question** role `prompt`. Example: [`prefs.csv`](/_downloads/a902a2232278bbefcf587bed38a729de/prefs.csv). CLI: ```bash arena datasets create assistant-prefs \ --category preference \ --file ./prefs.csv \ --column-mapping '{"prompt": "prompt", "chosen": "chosen", "rejected": "rejected"}' ``` ## Reasoning Each row is a question and an answer. During training the model writes its own answer and your reward function scores it against the row’s answer, so the answer must be something code can check, such as a number. Map **Question** and **Answer**. Example: [`reasoning.csv`](/_downloads/4b53606af46a504e94f898a04acfe97f/reasoning.csv). CLI: ```bash arena datasets create gsm8k \ --category reasoning \ --hf-dataset openai/gsm8k \ --hf-config main \ --hf-split train \ --column-mapping '{"question": "question", "answer": "answer"}' ``` A reasoning experiment also needs a prompt template and a reward function: see [Write prompts and reward functions](guides/prompts-and-rewards.md). ## Traces Traces are conversations recorded from a model or agent, in the OpenAI chat format. They have no columns to map. See [Train on traces](guides/train-on-traces.md). # guides/upload-an-environment.md # Upload an environment Give Arena an environment so a model can learn by acting in it over one or more turns, for example playing a game or working through a support ticket. Arena drives environments through `reset` and `step` with the [OpenEnv API](https://huggingface.co/docs/openenv). A gym-style environment works too: Arena converts it. Multi-turn algorithms such as **LLMPPO** train against environments. If each training example is one question with an answer you can check in code, you don’t need an environment. Upload a reasoning dataset and write a reward function instead: see [Upload a dataset](guides/upload-a-dataset.md) and [Write prompts and reward functions](guides/prompts-and-rewards.md). ## Upload your own code Upload Python code as a file, a folder or an archive, in the web app or with `arena env validate`. To follow along, download the Guess The Number example: [`guess_the_number.tar.gz`](/_downloads/a4d94fdd3189e37ba9937ebf82794985/guess_the_number.tar.gz). ### Web app 1. Click **Environments** in the sidebar, then **New environment**. The **New Environment** panel has three steps: **Setup**, **Configuration** and **Finalization**. 2. On **Setup**, enter a **Name** and an optional **Description**. Under **Upload environment files**, click **Browse files** for single files or **Choose folder** for a folder. Click **Next**. ![The Setup step with name, description and one uploaded Python file](tutorials/_images/upload-llm-environment/03-upload-code-step.png)**Setup**, with the environment file uploaded. 3. On **Configuration**, list extra Python packages under **Requirements**, one per line in `requirements.txt` format. Arena fills this in from a `requirements.txt` in your upload. Under **Configuration**, add YAML arguments for your environment class’s constructor, such as `difficulty: hard`. Both are optional. Click **Next**. 4. On **Finalization**, check the **Version Name** (`v1` by default) and pick the **Entrypoint**: the module and class Arena builds, such as `guess_the_number:GuessTheNumberEnv`. Arena scans your files and lists the classes it finds; click **Refresh** to scan again. Click **Finish**. ![The Finalization step with version name v1 and an entrypoint selected](tutorials/_images/upload-llm-environment/04-entrypoint-step.png)**Finalization**. Arena opens the environment’s page and starts validating the first version. Environment names must be unique in your organization. ### CLI Upload and validate the code in one step, then list the entrypoints Arena found: ```bash arena env validate guess-the-number --version v1 --source ./guess_the_number.tar.gz arena env entrypoints guess-the-number --version v1 ``` `--source` takes a folder or a `.tar.gz` archive. A `requirements.txt` and an `env_config.yaml` at the top level are picked up. Entrypoints are module paths from the top of the upload, so archive the files rather than their folder: ```bash tar -czf guess_the_number.tar.gz -C guess_the_number . ``` A folder inside the archive becomes part of the module path (`guess_the_number.guess_the_number:GuessTheNumberEnv`). Then print a manifest that trains on it: ```bash arena manifest template LLMPPO --model Qwen/Qwen3.5-4B --env guess-the-number --env-version v1 > llmppo.yaml ``` Flags are in the [command reference](cli/command-reference.md). A version must pass validation before you can train on it. See [Validate and profile an environment](guides/validate-an-environment.md). # guides/validate-an-environment.md # Validate and profile an environment Check that an environment version runs, and measure what it needs, so you can train on it. **Validation** builds your entrypoint class in an isolated sandbox and runs a list of tests against it: that the class loads, that its spaces are consistent, and that `reset` and `step` behave. By default it also plays a few random episodes and records their scores. **Profiling** runs after a successful validation and measures the CPU and RAM each copy of the environment uses, so Arena can size the training job. You can launch an experiment on a version once it is validated and profiled. ## Prerequisites - An environment you uploaded from your own code. See [Upload an environment](guides/upload-an-environment.md). ## Check a version ### Web app Open **Environments** in the sidebar and click the environment. Pick a version from the version dropdown at the top left. Beside it, the page shows when the version was **Created** and **Validated**, and its **State**. | State | Meaning | |------------------------|------------------------------------------------------------------| | **Pending validation** | Validation hasn’t finished yet. | | **Validated** | All tests passed. | | **Failed validation** | A test failed. The **Validation failed** banner shows the error. | | **Edited** | You changed the code since it was validated. Validate again. | The results appear as cards: - **Resource Usage**: CPU and memory over time, with steps per second, from profiling. - **Random episode score distribution**: scores from the random episodes. - **Environment summary**: the observation and action spaces Arena found. The **Tests** list on the left shows each check and whether it passed. When the version is ready, the rocket button at the top right is enabled. Click it to start an experiment on this version. While it is disabled, its tooltip says what is missing: validation, profiling still running, or no resource estimate yet. ### CLI ```bash arena env list --name guess-the-number ``` lists the environment’s versions and whether each one is validated. To validate a registered version again, this time with random episodes: ```bash arena env validate guess-the-number --version v1 --do-rollouts ``` Flags are in the [command reference](cli/command-reference.md). ## Fix or change the code ### Web app 1. Click the code button beside the rocket (**Switch to editor**). The editor opens with your files, the **Entrypoint**, **Requirements** and **Configuration** on the left. 2. Edit the files. The state changes to **Edited**. 3. Click **Validate**. To skip the random episodes, which is faster but tells you less, open the arrow beside **Validate** and clear **Run with random episodes**. 4. When validation passes, click **Save**. In **Save version**, keep the version’s name to overwrite it, or enter a new name to save the changes as a new version. Click **Undo** instead to throw the changes away. Arena profiles the saved version. The rocket button stays disabled until profiling finishes. To start a new version from scratch, click **New Version**. To copy, rename or delete the selected version, use the **⋮** menu at the top right: **Duplicate version**, **Rename version** and **Delete version**. ### CLI Upload the changed code as a new version and validate it: ```bash arena env validate guess-the-number --version v2 --source ./guess_the_number.tar.gz ``` The new version is the changed copy; the versions you already have stay as they are. To copy a version without changing it, for example to keep a backup under another name: ```bash arena env duplicate guess-the-number v1-backup --version v1 ``` ## When validation fails - **A test fails.** The banner and the **Tests** list name the check. Fix the code or the entrypoint, then validate again. - **Requirements fail to install.** **Validate** stays disabled and its tooltip shows the install error. Fix the package list under **Requirements**. - **Profiling fails.** The version stays without a resource estimate. Fix the environment and validate again to rerun profiling. # partners.md # How the partner API works Offer fine-tuning inside your own product, under your own brand, with Arena doing the training and serving. Your backend calls the Arena HTTP API. Your customers use your product and never see Arena or log in to it. Arena for partners is part of the **Enterprise** offer. To get access, contact AgileRL. ## How it works AgileRL gives you two things: an API host and an organisation key. Your backend sends the key on every request, together with the ID your own product uses for the person making the request. Arena creates a matching user the first time it sees an ID, so every dataset, run and deployment belongs to one of your users. From there your backend does what a person does in the Arena web app: upload a dataset, create a project, submit a training run, follow its metrics, download the trained model or deploy it behind an HTTPS endpoint. Training covers supervised fine-tuning (SFT), preference tuning (DPO), reinforcement learning (CISPO, GRPO, GSPO, LLM PPO, LLM REINFORCE) and on-policy distillation (OPD) for language and vision-language models, with LoRA or full weights. ## Hosted or self-hosted The API is the same either way. Code written for one works on the other once you change the host and the key. | | Hosted | Self-hosted | |---------------------|---------------------------------|------------------------------------------------------------------| | Who runs Arena | AgileRL | You, in your own environment | | Where training runs | Arena’s GPUs | Each customer’s reserved GPUs | | What you call | AgileRL’s API host | The API of one Arena install per customer, called a **tenant** | | Data | Stored by Arena | Stays in the tenant; nothing connects to AgileRL or the internet | | Who sets it up | AgileRL issues the host and key | Your platform team installs each tenant from a release bundle | Self-hosted tenants run on NVIDIA GPUs from Ampere onwards, from A10G and L4 to GB300; see [Supported hardware](partners/self-hosted/reference.md#supported-hardware). The operator pages below cover the install, base models and day-to-day running. ## Pages in this section For developers building on the API: - [Your first model](partners/first-model.md): one model from dataset to deployed endpoint. - [Partner API reference](partners/api-reference.md): every call, field, reply and error. For operators running self-hosted tenants: - [Install a tenant](partners/self-hosted/install.md) - [Base models](partners/self-hosted/models.md) - [Operations](partners/self-hosted/operations.md) - [Self-hosted reference](partners/self-hosted/reference.md) # partners/api-reference.md # Partner API reference Every call your backend makes to train, download and deploy models on Arena, with the fields each one takes and what it returns. The API is the same on hosted Arena and on a self-hosted tenant. For a walk through one model end to end, start with [Your first model](partners/first-model.md). The `arena` CLI and the Python client call this same API. If your backend is in Python, the client in [Python](#python) saves you writing the HTTP yourself. ## Authentication AgileRL issues an API host and one organisation key. On a self-hosted tenant, your operator gives you the tenant’s host and key. | Item | Example | |------------------|----------------------------------------------------| | API host | `https://arena.agilerl.com`, or your tenant’s host | | Organisation key | `arena_org__` | Every request carries two headers. `Authorization` is the organisation key with the `Bearer` prefix. `X-External-User-Id` is the ID your product already uses for the person making the request. Send the same value for that person on every call; the first time Arena sees a new one, it creates a matching user. ```text Authorization: Bearer arena_org_11111111-2222-3333-4444-555555555555_k7mN9pQ2rS4tU6vW X-External-User-Id: user-42 ``` ```bash export ARENA_BASE="https://arena.agilerl.com" export ARENA_ORG_KEY="arena_org_11111111-2222-3333-4444-555555555555_k7mN9pQ2rS4tU6vW" export ARENA_USER="user-42" ``` Training calls are under `/api/cli/v1/…`. Model download is under `/api/internal/partners/…`. Both take the same headers. Most `/api/cli/v1` replies look like `{ "ok": true, "data": … }`. The default training spec, the model list, model info and every `/api/internal/partners` route return the JSON object itself, without that wrapper. Submit and environment upload stream one JSON object per line. Read the stream until `"status"` is `completed` or `failed`. A `429` with `Retry-After` (seconds) means slow down. A job that belongs to another organisation returns `404`. Keep the key on your backend. Never send it to a browser. ## Order of calls 1. `GET /api/cli/v1/resources`: confirms the key and lists GPU types. 2. `POST /api/cli/v1/datasets/create`. 3. Only to train against an environment instead of a dataset: `POST /api/cli/v1/environments/create-and-validate`. 4. `POST /api/cli/v1/projects/create`. 5. `GET /api/cli/v1/models` or `POST /api/cli/v1/models/info`. 6. `GET /api/cli/v1/experiments/run-spec/default`. 7. Set `algorithm.batch_size`, `algorithm.lr`, `network.max_context_length` and `training.checkpoint_export` on that body, and optionally `training.max_steps`. 8. `POST /api/cli/v1/experiments/jobs/submit`. The `experiment_name` you send is the handle for later calls. 9. `GET /api/cli/v1/experiments/jobs/checkpoints`, repeated until `data[]` has a row. 10. `POST /api/internal/partners/checkpoint-exports` with `{ "experimentName", "steps" }`, then fetch each `urls[]` entry and check `files[].bytes` and `files[].sha256`. 11. Optional, to serve the model: `POST /api/cli/v1/inference/deploy`, then `GET /api/cli/v1/inference/deployments/one?name=…` until `status` is `Deployed`. ## GPU type A resource is a machine: GPU count, memory and, on hosted Arena, an hourly cost. Listing them is a good first call because it also confirms the key. ```bash curl -sS "${ARENA_BASE}/api/cli/v1/resources" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" ``` ```json { "ok": true, "data": { "gpuTypes": [ { "gpuType": "h100-80", "gpusPerNode": [1, 8], "numGpus": [1, 8] } ] } } ``` Each entry is a GPU type that submit accepts as `gpu_type`, with the GPUs one node has and the totals you can ask for as `num_gpus`. The list is for language model training; add `?algorithm=` for another algorithm. `GET /api/cli/v1/resources/list` returns the same payload. Submit does not take a resource or a node count. Arena estimates the run’s GPU memory and picks the cheapest machines and node count that fit. To steer the pick, send `num_gpus` (GPUs in total), `gpu_type`, or both; Arena still picks only among layouts that fit. See [Submit](#submit). On a self-hosted tenant the list holds only the tenant’s reserved GPUs, and Arena charges nothing for them. ## Data Training data is a table. The `category` decides what each row means: | `category` | Each row | Mapping keys | |--------------|-----------------------------------|--------------------------------| | `reasoning` | Question and reference answer | `question`, `answer` | | `sft` | Prompt and the reply to copy | `prompt`, `target` | | `preference` | Prompt, better reply, worse reply | `prompt`, `chosen`, `rejected` | [Upload a dataset](guides/upload-a-dataset.md) describes each format in more detail. `column_mapping` uses Arena’s names as keys and your column names as values. If your file has `instruction` and `response`, send `{"prompt":"instruction","target":"response"}`. Send the file and the fields in one `multipart/form-data` request. On hosted Arena the upload can be up to 1 GB. On a self-hosted tenant the stored file can be at most 64 MiB, and Hugging Face datasets and dataset search return `400 huggingface_offline`, since the tenant has no internet access. ### Parquet folders Hugging Face datasets often ship several `.parquet` files in folders. Arena names the **config** from the folder left after shared prefixes: - `main/train-00000-of-00001.parquet` becomes config `main`. Train or test comes from the file name. - `train-00000-of-00001.parquet` at the top of the upload becomes config `default`. - A wrapping folder is dropped: `gsm8k/main/train-00000-of-00001.parquet` is treated as `main/…`. Folders named `train/` and `test/` become two configs, not two splits. Put the split in the file name instead, for example `train-00000-of-00001.parquet`. If the upload has more than one config, send form field `config` (for example `main`). Send each parquet file as its own `file` part, with the part filename set to its relative path. When the chosen config has several splits, Arena trains on `train`, or on the only split when there is one. Several splits with none named `train` fail the upload. A single CSV also works. A part counts as parquet if its name ends in `.parquet`, its type is `application/vnd.apache.parquet` or `application/parquet`, or its bytes start with `PAR1`. ### SFT ```bash curl -sS "${ARENA_BASE}/api/cli/v1/datasets/create" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -F "name=support-tickets-sft" \ -F "category=sft" \ -F "description=Support replies for supervised fine-tune" \ -F 'column_mapping={"prompt":"instruction","target":"response"}' \ -F "config=main" \ -F "file=@./main/train-00000-of-00001.parquet;filename=main/train-00000-of-00001.parquet;type=application/vnd.apache.parquet" ``` ```json { "ok": true, "data": { "name": "support-tickets-sft", "category": "sft", "uploaded": true, "is_ready": true, "hf_dataset_id": null } } ``` Submit once `is_ready` is `true`. If the reply has `missing_columns`, fix `column_mapping` and upload again. A `400` from parsing or column mapping leaves no dataset behind. On a self-hosted tenant, an upload while the GPU cluster is offline returns `409 gpu_cluster_unavailable` and creates no dataset. Upload again once the cluster is back. ### Reasoning ```bash curl -sS "${ARENA_BASE}/api/cli/v1/datasets/create" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -F "name=math-word-problems" \ -F "category=reasoning" \ -F 'column_mapping={"question":"question","answer":"answer"}' \ -F "file=@./train-00000-of-00001.parquet;filename=train-00000-of-00001.parquet;type=application/vnd.apache.parquet" ``` ### Preference ```bash curl -sS "${ARENA_BASE}/api/cli/v1/datasets/create" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -F "name=assistant-prefs" \ -F "category=preference" \ -F 'column_mapping={"prompt":"prompt","chosen":"chosen","rejected":"rejected"}' \ -F "file=@./main/train-00000-of-00001.parquet;filename=main/train-00000-of-00001.parquet;type=application/vnd.apache.parquet" ``` ### Check, list and delete datasets ```bash curl -sS "${ARENA_BASE}/api/cli/v1/datasets/exists?name=support-tickets-sft" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" ``` ```json { "ok": true, "data": { "exists": true, "datasetType": "sft" } } ``` ```bash curl -sS "${ARENA_BASE}/api/cli/v1/datasets" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" ``` ```json { "ok": true, "data": [ { "name": "support-tickets-sft", "hf_dataset_id": null, "category": "sft", "training_row_count": 1200 } ] } ``` `training_row_count` is `null` until Arena has counted the rows. On hosted Arena, `?search=gsm8k` searches the Hugging Face Hub. ```bash curl -sS -X DELETE "${ARENA_BASE}/api/cli/v1/datasets/delete" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -H "Content-Type: application/json" \ -d '{"name":"support-tickets-sft"}' ``` ## Environments An environment is Python code that plays out a task with the model, instead of a table of examples. Skip this section when you train on a dataset. [Upload an environment](guides/upload-an-environment.md) explains how to write one. Upload a gzip of the package with its `requirements.txt`. The reply is a status stream while Arena installs the packages and checks the code. ```bash curl -sS "${ARENA_BASE}/api/cli/v1/environments/create-and-validate" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -F "name=ticket-sim" \ -F "version=v1" \ -F "multi_agent=false" \ -F "language_based=true" \ -F "do_rollouts=true" \ -F "description=Turn-based support sim" \ -F "file=@./ticket_sim.tar.gz;type=application/gzip" \ -F "env_config=@./env_config.yaml;type=application/x-yaml" \ -F "requirements=@./requirements.txt;type=text/plain" ``` Send `env_config` and `requirements` every time; empty files are fine. If the tarball has one environment class, you can leave out `entrypoint` and Arena stores the name it finds. List environments and the entrypoints Arena found: ```bash curl -sS "${ARENA_BASE}/api/cli/v1/environments" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" curl -sS "${ARENA_BASE}/api/cli/v1/environments/entrypoints?name=ticket-sim&version=v1" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" ``` `data` is an array of strings such as `["env:TicketEnv"]`. Only those strings are valid entrypoints for that upload; any other name is `INVALID_ENTRYPOINT`. Send one as `gymEnvEntrypoint` on the default spec query, and as `entrypoint` when you validate the version again. To validate a stored version again, send JSON: ```bash curl -sS -X POST "${ARENA_BASE}/api/cli/v1/environments/validate" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -H "Content-Type: application/json" \ -d '{"name":"ticket-sim","version":"v1","entrypoint":"env:TicketEnv","do_rollouts":false}' ``` `name` is required; `version`, `entrypoint` and `do_rollouts` are optional. Multipart on this route returns `415`. Point a training spec at the environment once `validated` is `true`. `?include_arena=true` on the list adds Arena’s built-in environments. ## Projects A project groups training runs. ```bash curl -sS "${ARENA_BASE}/api/cli/v1/projects/create" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -H "Content-Type: application/json" \ -d '{ "name": "post-train", "description": "Partner post-training" }' ``` Projects created here are always for language-model runs: `llm_based` is ignored. ```bash curl -sS "${ARENA_BASE}/api/cli/v1/projects" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" ``` A duplicate name returns `400` `The project 'post-train' already exists.` List your projects and reuse them. ## Base models Runs start from a base model in Arena’s catalogue. On a self-hosted tenant the catalogue is the models your operator registered ([Base models](partners/self-hosted/models.md)). ```bash curl -sS "${ARENA_BASE}/api/cli/v1/models" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" ``` The reply is a JSON array, one entry per model. Here it is with `lora_info` trimmed to four of the model’s layers: ```json [ { "model_name": "Qwen/Qwen3.5-4B", "architecture": "hybrid", "num_params": 4539265536, "lora_info": { "q_proj": [ { "count": 8, "in_features": 2560, "kind": "module", "out_features": 8192, "scope": "model.language_model.layers.self_attn", "type": "Linear" } ], "k_proj": [ { "count": 8, "in_features": 2560, "kind": "module", "out_features": 1024, "scope": "model.language_model.layers.self_attn", "type": "Linear" } ], "v_proj": [ { "count": 8, "in_features": 2560, "kind": "module", "out_features": 1024, "scope": "model.language_model.layers.self_attn", "type": "Linear" } ], "o_proj": [ { "count": 8, "in_features": 4096, "kind": "module", "out_features": 2560, "scope": "model.language_model.layers.self_attn", "type": "Linear" } ] }, "max_context_length": 262144, "lora_ranks": [1, 8, 16, 32], "status": "live", "modalities": ["text", "vision"] } ] ``` `lora_info` lists the layers LoRA can adapt. LoRA trains a small extra set of weights on top of the base model. Its sizes (`lora_r`, `lora_alpha`, `lora_dropout`) are set later, in `network.lora_config` on the spec. ```bash curl -sS "${ARENA_BASE}/api/cli/v1/models/info" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -H "Content-Type: application/json" \ -d '{"model_name":"Qwen/Qwen3.5-4B"}' ``` The reply, with `lora_info` trimmed the same way: ```json { "modules": ["down_proj", "gate_proj", "in_proj_a", "in_proj_b", "in_proj_qkv", "in_proj_z", "k_proj", "linear_fc1", "linear_fc2", "o_proj", "out_proj", "q_proj", "qkv", "up_proj", "v_proj"], "parameters": [], "lora_info": { "q_proj": [ { "count": 8, "in_features": 2560, "kind": "module", "out_features": 8192, "scope": "model.language_model.layers.self_attn", "type": "Linear" } ], "k_proj": [ { "count": 8, "in_features": 2560, "kind": "module", "out_features": 1024, "scope": "model.language_model.layers.self_attn", "type": "Linear" } ], "v_proj": [ { "count": 8, "in_features": 2560, "kind": "module", "out_features": 1024, "scope": "model.language_model.layers.self_attn", "type": "Linear" } ], "o_proj": [ { "count": 8, "in_features": 4096, "kind": "module", "out_features": 2560, "scope": "model.language_model.layers.self_attn", "type": "Linear" } ] }, "num_params": 4539265536, "max_context_length": 262144, "lora_ranks": [1, 8, 16, 32] } ``` Pass `model_name` into the spec query exactly as listed. An unknown name returns `404`. Empty `modules` and `parameters` means the catalogue entry is incomplete; contact AgileRL. ## Default training spec Arena builds the training JSON from an algorithm, a dataset and a base model. The reply is the starting point for `manifest` on submit. The field names are in the [run spec schema](cli/manifest-schema.md), and the algorithms are described in [Algorithms](reference/algorithms.md). | `algorithm` | Data | Submit body | |----------------|----------------------------------------------------------------------------------|-------------------------------------------------------------------------------| | `SFT` | `sft` dataset | JSON | | `DPO` | `preference` dataset | JSON | | `CISPO` | `reasoning` dataset, or an environment | Multipart with `reward_file` on a reasoning dataset; JSON with an environment | | `GRPO` | Same as CISPO | Same as CISPO | | `GSPO` | Same as CISPO | Same as CISPO | | `LLMPPO` | `reasoning` dataset (`advantage_granularity` `token`) or an environment (`turn`) | `reward_file` on a reasoning dataset | | `LLMREINFORCE` | Same as LLMPPO | Same as LLMPPO | Query parameters: `algorithm` (required), `datasetName`, `pretrainedModelNameOrPath`. For an environment, send `gymEnv`, `gymEnvVersion` and `gymEnvEntrypoint` instead of `datasetName`. `gymEnvEntrypoint` is a name from the entrypoints list, and when you send it, `gymEnv` and `gymEnvVersion` (`v1` and `1` both work) are required too. Optional `field` returns one section (`algorithm`, `environment`, `network`, `training`, …). ```bash curl -sS -G "${ARENA_BASE}/api/cli/v1/experiments/run-spec/default" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ --data-urlencode "algorithm=CISPO" \ --data-urlencode "datasetName=math-word-problems" \ --data-urlencode "pretrainedModelNameOrPath=Qwen/Qwen3.5-4B" ``` For SFT, send `algorithm=SFT` with an `sft` dataset; for DPO, `algorithm=DPO` with a `preference` dataset. The reply: ```json { "algorithm": { "adv_filter_eps": 0.0, "adv_norm": "mean_only", "advantage_granularity": "auto", "answer_continuation": false, "beta": 0.001, "calc_position_embeddings": true, "clip_coef": 0.2, "filter_zero_adv": false, "group_size": 8, "kl_clamp": 10.0, "loss_norm": "accumulation_window", "loss_type": "cispo", "lr": 5e-07, "max_grad_norm": 0.1, "min_p": 0.0, "name": "CISPO", "off_policy_sequence_mask_threshold": 0.03, "off_policy_token_mask_bounds": [ 0.5, 5.0 ], "repetition_penalty": 1.0, "seed": 42, "temperature": 0.9, "top_k": 50, "top_p": 1.0, "turn_advantage_trajectory_fallback": true, "update_epochs": 1, "use_bias_correction_kl": true, "use_kl_advantage_shaping": false, "use_separate_reference_adapter": true, "vllm_config": { "frequency_penalty": 0.0, "presence_penalty": 0.0 }, "vllm_engine_args": {}, "vllm_importance_sampling_cap": 2.0, "vllm_max_clip_fraction": 0.02, "vllm_max_logprob_gap": 0.1, "whiten_advantages": false }, "apiVersion": "agilerl.com/v1", "environment": { "action_error_field": "", "adaptive_task_sampling": true, "apply_chat_template": true, "chat_template_kwargs": {}, "columns": { "answer": "answer", "question": "question" }, "dataset": "math-word-problems", "env_services": [], "env_session_ports": {}, "env_type": "rollout", "env_vars": {}, "max_reward": 1.0, "max_turns": 1, "name": "math-word-problems", "num_envs": 1, "prompt_template": { "system_prompt": "A conversation between User and Assistant. The user asks a question, and the Assistant solves it. The assistant first thinks about the reasoning process in the mind and then provides the user with the answer. The reasoning process and answer are enclosed within and tags, respectively, i.e., reasoning process here answer here ", "user_prompt": "Answer the following question as accurately, clearly, and concisely as possible.\n\nQuestion: {question}\n" }, "repeat_system_prompt": false, "restart_keep_turns": 0, "restart_older_images": true, "restart_older_obs_field": "", "rubric_file_path": "reward.py", "strict_chat_template_boundary": true, "task_family_prior_strength": 1.0, "train_test_split": 0.9 }, "network": { "lora_config": { "lora_alpha": 32, "lora_dropout": 0.0, "lora_r": 16, "task_type": "CAUSAL_LM" }, "max_context_length": 262144, "pretrained_model_name_or_path": "Qwen/Qwen3.5-4B" }, "replay_buffer": { "drop_uninformative_groups": true, "group_replay_max_age": 20, "kind": "llm", "max_rollout_version_lag": 2, "max_size": 10000 }, "training": { "checkpoint_optimizer": true, "eval_greedy": true, "eval_loop": 1, "eval_samples_per_task": 0, "evaluation_interval": 10, "evo_steps": 20, "overwrite_checkpoints": false, "pop_size": 1, "reporting_interval": 1, "rollout_version_stamp": "oldest_turn" } } ``` Language model replies include `network.lora_config`: `lora_r` 16, `lora_alpha` 32, `lora_dropout` 0.0 and `task_type` `CAUSAL_LM`. Keep it as Arena filled it. Arena trains LoRA on the catalogue’s modules for the model and drops any `target_modules` you send. For `network.lora_config.target_parameters`, an explicit `[]` means no LoRA on mixture-of-experts expert weights; leave the key out or send `null` to fill it from the catalogue. Before submitting, change only these fields and keep the rest of the reply: | Field | Example | |---------------------------------|-----------------------------------------------------------------------------------------------| | `algorithm.batch_size` | `8` | | `algorithm.lr` | `0.0001` | | `network.max_context_length` | `2048` | | `training.checkpoint_export` | `{ "format": "merged", "trigger": "final" }` or `{ "format": "adapter", "trigger": "final" }` | | `training.max_steps` (optional) | `500` | Arena checks them on validate and on submit: - `network.max_context_length` is a power of 2 from 1024 up to the model’s `max_context_length` from [Base models](#base-models), or that maximum itself when it isn’t a power of 2. Otherwise `400`, for example `network.max_context_length must be a power of 2 between 1024 and 262144. Allowed: 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144`. - `algorithm.batch_size` is a power of 2. The `400` lists the allowed values. - `training.max_steps` must be at least `training.evo_steps` (20 for the language model algorithms). Language model runs are sized in steps; `training.num_epochs` returns `400`. Leave `max_steps` unset on a dataset run to train one pass over the dataset: the row count divided by `algorithm.batch_size`, rounded up. - `training.checkpoint_export.format` `merged` gives the Hugging Face model in [Download the trained model](#download-the-trained-model); `adapter` gives a LoRA adapter. Without it, Arena uses `merged` with `trigger` `final`. ### Check a run fits `POST /api/cli/v1/experiments/validate-run-spec` checks context length, batch size and whether the run fits a resource: ```bash curl -sS "${ARENA_BASE}/api/cli/v1/experiments/validate-run-spec" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -H "Content-Type: application/json" -d @run-spec.json ``` A run that doesn’t fit returns `400 run_does_not_fit`. When a larger node count of the same class holds it, `required.gpus` is the fewest GPUs that do and `required.num_nodes` is that layout’s node count: ```json { "ok": false, "error": "run_does_not_fit", "message": "Resource class 'b300-8x1' does not fit this run at 1 node(s).", "required": { "gpus": 16, "num_nodes": 2, "gpu_memory_gb": 210.0 }, "available": { "resource": "b300-8x1", "gpus": 8, "num_nodes": 1, "gpu_memory_gb": 260.0 } } ``` When no node count of that class holds it, `required.gpus` and `required.num_nodes` are present and `null`, and `required.gpu_memory_gb` is what the run needs per GPU at the count it asked for. Branch on `null`. When the spec names no class and the miss is GPU memory, `message` is `No resource class has enough GPU memory for this run at N node(s).` and `available` is the closest class. Show the result to your user with a suggestion: a smaller model, a shorter context, or a smaller batch. A classic RL manifest (DQN, PPO, CQN, …) gets `410 classic_rl_gone`, as on quote and submit. ## Submit `POST /api/cli/v1/experiments/jobs/submit` | Field | Required | Example | |-------------------|------------|---------------------------------------------------------------| | `manifest` | yes | The spec from [Default training spec](#default-training-spec) | | `project` | yes | `"post-train"` (`projectName` also works) | | `experiment_name` | no | `"cispo-qwen-4b-dev"` | | `num_gpus` | no | `4` (`numGpus` also works) | | `gpu_type` | no | `"h100-80"` (`gpuType` also works) | | `idempotency_key` | no | See [Retries](#retries) | Without `num_gpus` or `gpu_type`, Arena picks the cheapest GPU type and count that the run’s memory estimate fits. With `num_gpus`, it picks the cheapest type at that count; with `gpu_type`, the smallest count of that type that fits. A request that doesn’t fit fails, and with `num_gpus` the message names the smallest count that fits. An unknown `gpu_type` fails and lists the valid names. `resource_id` and `num_nodes` return `400`. Arena trains on the dataset that `manifest.environment.dataset` names. Without `dataset`, it trains on what `environment.name` names, a registered dataset or an environment; the SFT example below sends only `name`. The default spec sets both to the dataset’s name. With `dataset` set, `name` is only a label, unless it names a different registered dataset: that returns `400` `environment.dataset is '' but environment.name is '', a different dataset. Set both to the dataset to train on, or remove environment.name.` A manifest with neither returns `400` `manifest.environment needs a name: set environment.dataset to a registered dataset, or environment.name`. ### SFT ```bash curl -sS -N "${ARENA_BASE}/api/cli/v1/experiments/jobs/submit" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: user-42:sft-qwen-4b-dev:1" \ -d '{ "experiment_name": "sft-qwen-4b-dev", "project": "post-train", "manifest": { "algorithm": { "name": "SFT", "lr": 0.0001, "batch_size": 8 }, "environment": { "name": "support-tickets-sft", "num_envs": 16 }, "network": { "pretrained_model_name_or_path": "Qwen/Qwen3.5-4B", "max_context_length": 2048, "lora_config": { "lora_r": 16, "lora_alpha": 32, "lora_dropout": 0.0 } }, "training": { "max_steps": 500, "eval_loop": 1 } } }' ``` The `manifest` here is shortened. Send the whole object from the default spec. ### Reasoning, with a reward file CISPO, GRPO and GSPO on a reasoning dataset also need a Python module that scores answers. Send it as `reward_file`, with the spec as the `manifest` part: ```bash curl -sS -N "${ARENA_BASE}/api/cli/v1/experiments/jobs/submit" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -H "Idempotency-Key: user-42:cispo-qwen-4b-dev:1" \ -F "experiment_name=cispo-qwen-4b-dev" \ -F "project=post-train" \ -F "manifest=@./cispo-run-spec.json;type=application/json" \ -F "reward_file=@./reward.py;type=text/x-python" ``` `reward.py` defines `def reward_fn(question, answer, completion)` and returns a float. [Prompts and rewards](guides/prompts-and-rewards.md) has examples. If the reward check fails, the stream’s `detail` includes `results` and `function_output`. ### Stream ```text {"kind":"status","stage":"validation","status":"running","message":"Validating manifest for math-word-problems:latest with CISPO","timestamp":"2026-09-07T09:15:01Z"} {"kind":"status","stage":"submission","status":"running","message":"Creating experiment","timestamp":"2026-09-07T09:15:02Z"} {"kind":"status","stage":"submission","status":"running","message":"Submitting to scheduler","timestamp":"2026-09-07T09:15:04Z"} {"kind":"status","stage":"submission","status":"completed","message":"Training job for 'cispo-qwen-4b-dev' submitted successfully","timestamp":"2026-09-07T09:15:05Z"} ``` A job that never reached GPUs ends like this: ```text {"kind":"status","stage":"submission","status":"failed","message":"Job rejected","detail":{"error_code":"JOB_REJECTED"}} ``` That usually means an incomplete catalogue entry or a dataset that isn’t ready. Fix the cause, then submit again with a new `Idempotency-Key` or none. On submit, `run_does_not_fit` and, on a self-hosted tenant, `gpu_cluster_unavailable` arrive as `detail.error_code` on the final `failed` line rather than as an HTTP status: ```json {"stage":"submission","status":"failed","message":"Experiment submission failed: …","detail":{"error_code":"gpu_cluster_unavailable","cluster":"tenant-a-gpus"}} ``` ### Retries Send `Idempotency-Key` as a header, or `idempotency_key` in the JSON body. The value must be unique across the organisation, so prefix it with your user ID, for example `user-42:cispo-qwen-4b-dev:1`. | Request | Arena response | |--------------------------------------------------------|------------------------------------| | Same key and body, last time succeeded | Same experiment, no second GPU job | | Same key and body, last time failed and can be retried | New experiment | | Same key, different body | `409 idempotency_conflict` | | Same key, first call still running | `409 idempotency_in_progress` | | No key | Always a new job | ## Status, stop and resume ```bash curl -sS "${ARENA_BASE}/api/cli/v1/experiments/list?project=post-train" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" ``` ```json { "ok": true, "data": [ { "experiment_name": "cispo-qwen-4b-dev", "environment": "math-word-problems", "algorithm": "CISPO", "last_modified": "2026-09-07T10:02:11+00:00", "status": "Running", "status_label": "Running" } ] } ``` `status` is one of the [experiment statuses](reference/experiment-statuses.md): `Queued`, `Pending`, `Running`, `Stopping`, `Stopped`, `Succeeded` or `Failed`. A `Queued` job starts on its own when GPUs free up, in submit order; don’t retry it. `status_label` is the text Arena shows for the run: “Waiting for capacity” while it waits for GPUs, “Waiting for cluster upgrade” while its cluster’s agent upgrades, “Starting GPUs (~N min)” while new machines start, then the cluster’s stage (`Scheduled`, `Deployed`, `Running`) while the job starts, otherwise `status`. A `Failed` row also has `failure_reason`, one or two sentences on why the run stopped, such as `"Training stopped because your code raised an error: reward.py, line 8"`. Show it to the run’s owner. ```bash curl -sS -X POST "${ARENA_BASE}/api/cli/v1/experiments/jobs/stop" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -H "Content-Type: application/json" \ -d '{"experiment_name":"cispo-qwen-4b-dev"}' ``` A stop takes effect within seconds. Resume starts a new run from a checkpoint of an old one. `checkpoint` is `best`, `final` or a step number: ```bash curl -sS "${ARENA_BASE}/api/cli/v1/experiments/jobs/resume" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -H "Content-Type: application/json" \ -d '{ "experiment_name": "cispo-qwen-4b-dev", "checkpoint": "final", "new_name": "cispo-qwen-4b-dev-resume", "max_steps": 2000 }' ``` `max_steps` is optional. It is the total step count from the start of the original run, so it must be greater than the checkpoint’s step. The reply is JSON, not a stream like submit: `{"ok": true, "data": [{"submissionId": null}]}`. `submissionId` is `null` on this response. Read the new run’s status from `experiments/list`. ## Metrics Metrics are the numbers the job logs, such as score and learning rate. `experiment_name` is required; `project` is optional. ```bash curl -sS -G "${ARENA_BASE}/api/cli/v1/experiments/metrics" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ --data-urlencode "experiment_name=cispo-qwen-4b-dev" \ --data-urlencode "project=post-train" ``` ```json { "ok": true, "data": [ { "display_name": "Score", "category": "training" }, { "display_name": "Learning Rate", "category": "hyperparam" } ] } ``` `display_name` is the chart label. `category` is `training`, `hyperparam`, `network`, `resource` or `null`. With `details=true` the list comes back as `data.metrics`. Add `preview_rows` (up to 50,000) to get the values as CSV instead. Send `metric=Score` for one column, repeat `metric` for several, or leave it out for all of them: ```bash curl -sS -G "${ARENA_BASE}/api/cli/v1/experiments/metrics" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ --data-urlencode "experiment_name=cispo-qwen-4b-dev" \ --data-urlencode "preview_rows=500" \ --data-urlencode "metric=Score" ``` ```text Score 0.12 0.18 0.21 ``` An empty list means nothing has been logged yet. Ask again after a short wait. ## Checkpoints A checkpoint is a snapshot of the model at a training step. List them until a row appears; empty `data` means there is no snapshot yet. ```bash curl -sS -G "${ARENA_BASE}/api/cli/v1/experiments/jobs/checkpoints" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ --data-urlencode "experiment_name=cispo-qwen-4b-dev" ``` ```json { "ok": true, "data": [ { "steps": 500, "training_score": null, "evaluation_score": null, "size_mb": 14200.5 } ] } ``` `steps` is how far training had got, and is what you pass to download and deploy. If two snapshots share a step count, Arena keeps the newest. Scores are often `null` until metrics catch up. Rows sort by evaluation score when there is one, otherwise by `steps`, largest first. [Results and checkpoints](guides/results-and-checkpoints.md) shows the same list in the web app. ## Download the trained model 1. Keep the `experiment_name` you sent on submit. 2. List checkpoints until `data[]` has a `steps` value. 3. POST an export with `{ "experimentName", "steps" }`, then fetch each `urls[]` entry. Download replies have no `{ ok, data }` wrapper and use camelCase field names. `experiment_name` is also accepted in the request body. Add `projectName` when the same experiment name exists in more than one project. ```bash curl -sS -X POST \ "${ARENA_BASE}/api/internal/partners/checkpoint-exports" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -H "Content-Type: application/json" \ -d '{"experimentName":"cispo-qwen-4b-dev","steps":500}' ``` Arena copies the files and returns HTTPS links that last about 15 minutes. If the checkpoint is 32 MiB or less, the POST reply already has `files` and `urls`. For a larger one, `state` is `queued` or `running` and `files` is empty; poll with GET until it completes. GET only reads the state; the POST starts the copy. There is one copy per organisation and checkpoint at a time: a second POST while it runs returns the same copy, and a POST after it completes reuses it and refreshes expired links. ```json { "format": "hf_merged", "state": "running", "acceptRanges": "bytes", "files": [], "urls": [] } ``` ```bash curl -sS -G "${ARENA_BASE}/api/internal/partners/checkpoint-exports" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ --data-urlencode "experimentName=cispo-qwen-4b-dev" \ --data-urlencode "steps=500" ``` | `state` | Next | |-----------------------------|----------------------------------------------------------------| | `queued` or `running` | Wait a few seconds, GET again | | `complete` | Download `urls` | | `409 export_renew_required` | Renew, then download | | `failed` or `cancelled` | POST the export again (cancel first if it was stuck `running`) | Large models take minutes. Polling every few seconds is enough. When complete (trimmed; every `files[].key` has a matching `urls[]` entry): ```json { "format": "hf_merged", "state": "complete", "acceptRanges": "bytes", "files": [ { "key": "config.json", "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "bytes": 1240, "contentType": "application/json" }, { "key": "model.safetensors", "sha256": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "bytes": 988000000, "contentType": "application/octet-stream" } ], "urls": [ { "key": "config.json", "url": "https://storage.example/config.json?X-Amz-Expires=900&X-Amz-Signature=…", "expiresAt": "2026-09-07T10:20:00Z" }, { "key": "model.safetensors", "url": "https://storage.example/model.safetensors?X-Amz-Expires=900&X-Amz-Signature=…", "expiresAt": "2026-09-07T10:20:00Z" } ] } ``` A merged model has `config.json`, `generation_config.json`, `chat_template.jinja`, `tokenizer.json`, `tokenizer_config.json` and `model.safetensors` (or `model-0000N-of-0000M.safetensors` when it is sharded). On a self-hosted tenant the links point at the tenant’s object store. If the links have expired, GET returns `409 export_renew_required`. Renew them: ```bash curl -sS -X POST \ "${ARENA_BASE}/api/internal/partners/checkpoint-exports/renew" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -H "Content-Type: application/json" \ -d '{"experimentName":"cispo-qwen-4b-dev","steps":500}' ``` The reply is the same JSON with new `urls`. Links support ranges (`acceptRanges` is `bytes`), so a download can resume with `Range` or `curl -C -`: ```bash curl -sS -C - -o config.json \ "https://storage.example/config.json?X-Amz-Expires=900&X-Amz-Signature=…" curl -sS -H "Range: bytes=0-10485759" -o shard.part0 \ "https://storage.example/model.safetensors?X-Amz-Expires=900&X-Amz-Signature=…" ``` Check `files[].sha256` and `files[].bytes` for each file. If a link expires halfway through a file, renew and carry on from where you stopped. If a copy is stuck `running`, cancel it and POST the export again: ```bash curl -sS -X POST \ "${ARENA_BASE}/api/internal/partners/checkpoint-exports/cancel" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -H "Content-Type: application/json" \ -d '{"experimentName":"cispo-qwen-4b-dev","steps":500}' ``` Cancelling a queued or running copy deletes it, and its links stop working. Cancelling after `complete` returns the existing links, or `409 export_renew_required` if they have expired. ## Deploy the model A deployment serves one checkpoint of a finished run behind an HTTPS endpoint. Every reply has the `{ "ok": true, "data": … }` wrapper and snake_case field names. | Call | Route | |--------------------------------------------|----------------------------------------------| | Deploy, or redeploy another checkpoint | `POST /api/cli/v1/inference/deploy` | | List | `GET /api/cli/v1/inference/deployments/list` | | Read one | `GET /api/cli/v1/inference/deployments/one` | | Rename, describe, take offline, bring back | `PATCH /api/cli/v1/inference/deployments` | | Delete | `DELETE /api/cli/v1/inference/deployments` | The deployment `name` is its handle. Names are unique in the organisation among deployments that haven’t been deleted; a clash returns `400` `A deployment with this name already exists in this organization`. An experiment has at most one enabled deployment, so deploying the same experiment again updates that deployment. ### Deploy ```bash curl -sS "${ARENA_BASE}/api/cli/v1/inference/deploy" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -H "Content-Type: application/json" \ -d '{ "experimentName": "sft-qwen-4b-dev", "name": "support-bot", "description": "Support replies, SFT on Qwen3.5 4B" }' ``` | Field | Required | Notes | |----------------------|------------|---------------------------------------------------------------------------------------------------------------------------------| | `experimentName` | yes | `experiment_name` also works | | `projectName` | no | `project` also works. Needed when the experiment name exists in more than one project. | | `checkpoint` | no | Left out, `best` or `final`: the checkpoint with the most steps. A number: that `steps` value from [Checkpoints](#checkpoints). | | `name` | no | Defaults to the experiment name | | `description` | no | Free text | | `memoryScope` | no | `user` (default) or `organization`. See [Memory scope](#memory-scope). | | `numGpus`, `gpuType` | no | See [GPUs](#gpus) | ```json { "ok": true, "data": { "created": true, "redeployed": false, "unchanged": false, "deployment": { "name": "support-bot", "status": "Pending", "enabled": true, "experiment_name": "sft-qwen-4b-dev", "project_name": "post-train", "algorithm": "SFT", "url": "https://6604b462e6fb4523b68cb6f28117d9b8.deploy.example", "description": "Support replies, SFT on Qwen3.5 4B", "memory_scope": "user", "spec": { "url": "https://6604b462e6fb4523b68cb6f28117d9b8.deploy.example", "is_llm": true, "model": { "algorithm_name": "SFT" } } } } } ``` A new deployment of a run trained on a dataset also returns `savedModel` (`name`, `description`, `source_checkpoint_steps`, `algorithm_name`). Exactly one of `created`, `redeployed` and `unchanged` is `true`: | Flag | Meaning | |--------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `created` | New deployment | | `redeployed` | The experiment already had an enabled deployment, or a stopped (not archived) one with the requested name, and this request changed it, for example to another `checkpoint`. A stopped deployment is enabled again. It keeps its name unless you send a different `name`. | | `unchanged` | Same request as last time. Nothing restarts. | A redeploy without `description` keeps the stored one. | Request | Response | |----------------------------------------------------|------------------------------------------------------------------| | Empty `experimentName` | `400` `experiment_name is required` | | Unknown experiment, or one in another organisation | `404` | | No checkpoint yet | `400` `No checkpoints found for experiment` | | `checkpoint` is a step with no checkpoint | `400` `No checkpoint registered at step 999 for this experiment` | | `checkpoint` is any other word, such as `latest` | `400` `checkpoint must be "best", "final", a step number, …` | | `memoryScope` not `user` or `organization` | `422`, plain-text body | | Pay-as-you-go organisation without enough balance | `403 spend_denied` | ### Status Poll `GET /deployments/one` until `status` is `Deployed`. That usually takes a minute and a half or more, depending on the checkpoint size. ```bash curl -sS -G "${ARENA_BASE}/api/cli/v1/inference/deployments/one" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ --data-urlencode "name=support-bot" ``` The reply is the `deployment` object from deploy. Add `experimentName` and `projectName` to narrow the lookup. An unknown name, or a deployment in another organisation, returns `404`. | `status` | Meaning | |--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `Pending` | Arena is copying the checkpoint and starting the server. A `Deployed` deployment drops back to `Pending` while its server stops answering health checks, and returns to `Deployed` when it recovers. | | `Deployed` | The server at `url` answers its health check | | `Undeployed` | Not serving. With `enabled: false` it was taken offline (by `PATCH`, or because a pay-as-you-go balance ran out) and stays off until enabled again. With `enabled: true` it is an Enterprise deployment waiting for an operator to start it. | | `Failed` | The rollout failed | ### List ```bash curl -sS "${ARENA_BASE}/api/cli/v1/inference/deployments/list" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" ``` ```json { "ok": true, "data": [ { "name": "support-bot", "status": "Deployed", "enabled": true, "experiment_name": "sft-qwen-4b-dev", "project_name": "post-train", "algorithm": "SFT", "url": "https://6604b462e6fb4523b68cb6f28117d9b8.deploy.example", "memory_scope": "user" } ] } ``` Optional query parameters are `name`, `experimentName` and `projectName`. Deleted deployments are left out unless you send `archived=true`. Rows have no `description` or `spec`; read one deployment for those. ### Rename, take offline, bring back ```bash curl -sS -X PATCH "${ARENA_BASE}/api/cli/v1/inference/deployments" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ -H "Content-Type: application/json" \ -d '{"name":"support-bot","newName":"support-bot-v1","description":"First SFT run","enabled":false}' ``` `name` finds the deployment (`experimentName` and `projectName` can narrow it). `newName` (or `new_name`), `description` and `enabled` are each optional. `enabled: false` takes the deployment offline and keeps it; `enabled: true` brings it back. The reply is the updated `deployment` object. To change the checkpoint, GPUs or memory scope, call deploy again. ### Delete ```bash curl -sS -X DELETE -G "${ARENA_BASE}/api/cli/v1/inference/deployments" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" \ -H "X-External-User-Id: ${ARENA_USER}" \ --data-urlencode "name=support-bot-v1" ``` ```json { "ok": true, "data": { "success": true } } ``` The deployment stops and is archived. Its name is free to use again, and it shows in the list only with `archived=true`. Deleting the same name again returns `404`. ### Memory scope Language model deployments keep chat sessions. `user` keeps each caller’s sessions separate. `organization` shares them across the organisation, and only an organisation admin can set it. Users created through `X-External-User-Id` are members, so for them `memoryScope: "organization"` returns `403` `Only organization admins can set memory_scope to organization`. A redeploy without `memoryScope` keeps the stored scope. ### GPUs Without `numGpus` or `gpuType`, a redeploy, including one that enables a stopped deployment again, keeps the deployment’s current machine. A new deployment of a run trained on the organisation’s own cluster, which includes every self-hosted tenant, runs on that cluster’s resource class. Any other new deployment gets the cheapest machine that Arena’s memory estimate says can serve the model. When Arena can’t size the model, the deploy returns `400` with the reason and the valid `gpuType` values and counts, for example `Arena can't size this run: . Choose a class with --gpu-type and --num-gpus to deploy it without sizing: h100-80 (1, 2, 8), l4 (1).` Send `numGpus` and `gpuType` to pick one. `numGpus` is the GPU count on the one inference machine. `gpuType` is a short name from that list (`l4`, `h100-80`) or the serving catalogue name (`nvidia-l4`, `nvidia-h100-80gb`). Serving GPU types are a different list from the training ones in [GPU type](#gpu-type). With a matching `gpuType`, Arena picks the cheapest matching machine that holds 8 sequences at full context, or else the cheapest matching one that fits. Failures return `400`: | Case | Message | |--------------------------------------|-------------------------------------------------------------------------------------------------------------| | Not a language model run | `Only LLM deployments take numGpus and gpuType.` | | Unknown GPU type | `Unknown gpu_type 'b200'. Valid GPU types: h100-80, l4.` | | No machine has that count | `No resource class offers 3 l4 GPU(s). l4 GPU counts offered: 1, 2, 4.` | | None of that count has enough memory | `No resource class has enough GPU memory for this run on 1 a100-80 GPU(s). a100-80 GPU counts that fit: 2.` | ### Calling the deployed model The server at `url` takes `POST /generate` and `POST /generate_stream`; the request and reply bodies are in the [inference contract](reference/inference-contract.md). It checks each request’s credentials with Arena before answering. On a self-hosted tenant, `url` is on the API host: `https:///api/deployments//inference`. Call it with the same two headers as every other call. Arena checks that the key’s organisation owns the deployment, then passes the request to the inference server with a one-minute credential for that deployment and that user in place of your key. A deployment that keeps memory per user keeps it per `X-External-User-Id`. ```bash curl -sS "${DEPLOYMENT_URL}/generate" \ -H "Authorization: Bearer ${ARENA_ORG_KEY}" -H "X-External-User-Id: ${ARENA_USER}" \ -H "Content-Type: application/json" \ -d '{"session_id":"ticket-4411","prompts":["My order has not arrived."],"params":{"max_new_tokens":256}}' ``` | Status | Cause | |------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------| | `401` `{"success": false, "error": "User is not authorized (OAuth2)"}` | The inference server could not check the call with the API. Check the API logs for `check-access denied` | | `403` | The key’s scope doesn’t cover inference | | `404` | No deployment with that id in the key’s organisation, or it isn’t running | On hosted Arena the inference server doesn’t yet accept an organisation key. Contact AgileRL if your product needs to call deployments there. On a self-hosted tenant a running deployment holds its GPUs, so new training runs may wait as `Queued` until you take it offline. ## Errors Coded errors have the body `{"ok": false, "error": "", "message": "…"}`. On submit, coded errors arrive as `detail.error_code` on the stream’s final `failed` line. | HTTP | Meaning | What to do | |---------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `400` | Bad field, file or mapping; `resource_id` or `num_nodes` on submit; export without `experimentName` and `steps`, or a shared experiment name without `projectName` | Fix the field named in `message`. `resource_id` comes from the `agilerl-arena` 1.x client; move to `agilerl`: `uv remove agilerl-arena && uv add agilerl`, or `pip uninstall -y agilerl-arena && pip install -U --force-reinstall agilerl` | | `400 run_does_not_fit` | The run can never fit the resource | Change the run ([Check a run fits](#check-a-run-fits)) | | `400 huggingface_offline` | Self-hosted: the request needed the Hugging Face Hub | Upload the dataset file; use a model from `/models` | | `401` | Key missing, wrong or revoked, or from another tenant | Check `Authorization: Bearer arena_org_…` | | `403` | `organization member limit reached` | Contact AgileRL | | `403 spend_denied` | Deploy on a pay-as-you-go organisation without enough balance | Contact AgileRL | | `403` | Deploy with `memoryScope: "organization"` | Leave `memoryScope` out; partner users aren’t organisation admins | | `404` | Unknown name or `steps`, another organisation’s job, or GET export before POST | Check the experiment name, the checkpoint `steps` or the deployment `name`. Another organisation’s data is always `404`, never `403`. | | `409 gpu_cluster_unavailable` | Self-hosted: the tenant’s GPU cluster is offline | Tell your user; ask your operator | | `409 idempotency_conflict` | Same retry key, different body | New key, or the original body | | `409 idempotency_in_progress` | First submit with that key still running | Wait, then retry with the same key and body | | `409 export_incomplete` | The merge isn’t finished | Wait, then POST the export again | | `409 export_renew_required` | Links expired | POST renew, then GET the files | | `409 export_replay_unavailable` | Body had `"replay": true` | POST the export with `experimentName` and `steps` | | `413` | Upload over the size limit | Use a smaller file | | `415` | Multipart on `POST /environments/validate` | Send JSON | | `422` | JSON that doesn’t match the route, such as an unknown `memoryScope` | Fix the field named in the plain-text body | | `429` | Rate limit | Wait `Retry-After` seconds | | `503 storage_unavailable` | Self-hosted: the tenant’s object store can’t be reached | Retry later; ask your operator | `JOB_REJECTED` on the submit stream means the job never reached GPUs. Check the model’s catalogue entry and that the dataset’s `is_ready` is `true`. ## Python ```bash uv add agilerl ``` Without uv, `pip install agilerl` works too. The package supports Python 3.10 to 3.13. `ArenaClient` sends the same two headers as the HTTP above: ```python from agilerl import ArenaClient ArenaClient.configure(base_url="https://arena.agilerl.com") client = ArenaClient( org_key="arena_org_11111111-2222-3333-4444-555555555555_k7mN9pQ2rS4tU6vW", external_user_id="user-42", ) client.create_project("post-train", "Partner post-training") client.create_dataset( name="support-tickets-sft", category="sft", file="./main", column_mapping={"prompt": "instruction", "target": "response"}, config="main", ) spec = client.get_default_run_spec( algorithm="SFT", dataset_name="support-tickets-sft", pretrained_model_name_or_path="Qwen/Qwen3.5-4B", ) spec["algorithm"]["batch_size"] = 8 spec["algorithm"]["lr"] = 0.0001 spec["network"]["max_context_length"] = 2048 spec["training"]["checkpoint_export"] = {"format": "merged", "trigger": "final"} spec["training"]["max_steps"] = 500 client.submit_experiment( manifest=spec, project="post-train", experiment_name="sft-qwen-4b-dev", ) print(client.list_experiments(project="post-train")) print(client.list_experiment_metric_names("sft-qwen-4b-dev")) print(client.list_checkpoints("sft-qwen-4b-dev")) ``` ### Host and credentials The key and user ID can come from `ARENA_ORG_KEY` and `ARENA_EXTERNAL_USER_ID` instead of the constructor. Setting only one of the two raises `ArenaAuthError` when the client is built. The host defaults to `https://arena.agilerl.com`. `ArenaClient.configure(base_url=…)` changes it for clients built afterwards and wins over `ARENA_BASE_URL`, which wins over the default. To point the same code at a self-hosted tenant, change only the host and the key. ### Replies and errors Methods return the `data` part of `{ "ok": true, "data": … }` replies, and the JSON as it is for routes without the wrapper. Submit reads the whole stream and returns its final result; a `failed` line raises instead. A `401` raises `ArenaAuthError`. Any other error status raises `ArenaAPIError`, which has `status_code` and `detail` (the server’s message). Dataset upload raises its subclass `ArenaValidationError`, and submit raises `ArenaTrainingError`. On `429` the client waits the `Retry-After` seconds (between 1 and 60) and tries again, up to five times, before raising. ```python from agilerl.exceptions import ArenaAPIError try: client.deploy_agent("sft-qwen-4b-dev", checkpoint="999") except ArenaAPIError as err: print(err.status_code, err.detail) ``` ### Deploy ```python result = client.deploy_agent("sft-qwen-4b-dev", checkpoint="500") print(result["created"], result["deployment"]["status"]) print(client.list_inference_deployments(experiment_name="sft-qwen-4b-dev")) client.update_inference_deployment("sft-qwen-4b-dev", new_name="support-bot") client.update_inference_deployment("support-bot", enabled=False) client.delete_inference_deployment("support-bot") ``` `deploy_agent` sends `experiment_name`, `checkpoint`, and when given, `memory_scope`, `num_gpus` and `gpu_type`. `checkpoint` is a string: `"best"`, `"final"` or a step such as `"500"`; `None` deploys the checkpoint with the most steps. It takes no name or description, so a new deployment is named after the experiment; rename it with `update_inference_deployment(…, new_name=…)`. `open_inference_agent(name)` returns an agent bound to the deployment’s `url`. It sends the client’s organisation key and external user ID, so on a self-hosted tenant `agent.generate(…)` works as in [Calling the deployed model](#calling-the-deployed-model). On hosted Arena its requests are refused. ### Methods and routes | Method | Route | |-----------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------| | `list_resources(algorithm=…)` | `GET /resources/list` | | `create_dataset(name=…, category=…, file=…, column_mapping=…, config=…)` | `POST /datasets/create` | | `dataset_exists(name)`, `list_datasets()` | `GET /datasets/exists`, `GET /datasets` | | `delete_dataset(name, confirm=True)` | `DELETE /datasets/delete` (without `confirm=True` it asks on standard input) | | `create_project(name, description)`, `list_projects()`, `delete_project(name)` | `POST /projects/create`, `GET /projects`, `DELETE /projects/delete` | | `list_models()`, `get_model_info(model_name)` | `GET /models`, `POST /models/info` | | `get_default_run_spec(algorithm, dataset_name=…, pretrained_model_name_or_path=…)` | `GET /experiments/run-spec/default` | | `submit_experiment(manifest, project=…, experiment_name=…, num_gpus=…, gpu_type=…, reward_file=…, idempotency_key=…)` | `POST /experiments/jobs/submit` | | `list_experiments(project=…)` | `GET /experiments/list` | | `stop_experiment(experiment_name)` | `POST /experiments/jobs/stop` | | `resume_experiment(experiment_name, max_steps=…, checkpoint=…, new_name=…)` | `POST /experiments/jobs/resume` | | `list_experiment_metric_names(experiment_name, details=…)` | `GET /experiments/metrics` | | `preview_experiment_metrics_csv(experiment_name, preview_rows=…, metrics=[…])` | `GET /experiments/metrics` with `preview_rows` | | `list_checkpoints(experiment_name)` | `GET /experiments/jobs/checkpoints` | | `deploy_agent(experiment_name, checkpoint=…, memory_scope=…, num_gpus=…, gpu_type=…)` | `POST /inference/deploy` | | `list_inference_deployments(name=…, experiment_name=…, project_name=…)` | `GET /inference/deployments/list` | | `update_inference_deployment(name, new_name=…, description=…, enabled=…)` | `PATCH /inference/deployments` | | `delete_inference_deployment(name)` | `DELETE /inference/deployments` | Routes are under `/api/cli/v1`. Download the trained model with the HTTP calls in [Download the trained model](#download-the-trained-model). The full client is documented in the [Python client reference](cli/python-client.md). # partners/first-model.md # Your first model Train one model from your backend, from uploading a dataset to a deployed endpoint. The calls are the same on hosted Arena and on a self-hosted tenant; only the host and key change. The [Partner API reference](partners/api-reference.md) has every field of every call. ## Before you start You need an API host and an organisation key. On hosted Arena, AgileRL issues both. On a self-hosted tenant, your operator gives you the tenant’s host and key. | Value | Hosted | Self-hosted | |---------|-----------------------------|-----------------------------------| | Host | `https://arena.agilerl.com` | `https://arena.tenant-a.internal` | | Key | `arena_org_8c1f…_Qx7…` | `arena_org_8c1f…_Qx7…` | Every request sends the key and the ID your product uses for the person making the request: ```text Authorization: Bearer arena_org_8c1f…_Qx7… X-External-User-Id: customer-user-17 ``` ```bash export ARENA_BASE="https://arena.agilerl.com" # or your tenant's host export ARENA_ORG_KEY="arena_org_8c1f…_Qx7…" export ARENA_USER="customer-user-17" ``` Use the same `X-External-User-Id` for the same person on every call. Arena creates a matching user the first time it sees an ID. Keep the key on your backend. Never send it to a browser. ## 1. See what you can train on ```bash curl -sS "$ARENA_BASE/api/cli/v1/resources" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" ``` ```json { "ok": true, "data": { "gpuTypes": [ { "gpuType": "b300", "gpusPerNode": [8], "numGpus": [8] } ] } } ``` This also confirms the key works. Submit takes a `gpuType` from the list as `gpu_type`, and one of its `numGpus` as `num_gpus`; both are optional. On a self-hosted tenant the list holds only the tenant’s own GPUs, and Arena charges nothing for the GPUs themselves, so price them in your own product. The tenant’s platform fee (`byocFee` in the [self-hosted reference](partners/self-hosted/reference.md#values), $2 per run-hour by default) still applies, and submit shows it as `Estimated cost`. ## 2. Upload a dataset ```bash curl -sS "$ARENA_BASE/api/cli/v1/datasets/create" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" \ -F "name=support-tickets-sft" -F "category=sft" \ -F 'column_mapping={"prompt":"instruction","target":"response"}' \ -F "file=@./train.parquet;type=application/vnd.apache.parquet" ``` Training can start once the reply has `"is_ready": true`. `column_mapping` maps Arena’s column names to yours; the categories and their columns are in [Data](partners/api-reference.md#data). On a self-hosted tenant the stored file can be at most 64 MiB, and datasets from Hugging Face return `400 huggingface_offline` because the tenant can’t reach the internet. Upload the file instead. ## 3. Create a project and pick a base model ```bash curl -sS "$ARENA_BASE/api/cli/v1/projects/create" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" \ -H "Content-Type: application/json" -d '{"name":"support-bot"}' curl -sS "$ARENA_BASE/api/cli/v1/models" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" ``` `/models` lists the base models you can train. On a self-hosted tenant those are the ones your operator registered ([Base models](partners/self-hosted/models.md)). Use a `model_name` from the list exactly as written: ```bash export ARENA_MODEL="qwen3.5-9b" ``` ## 4. Get training settings and check them ```bash curl -sS -G "$ARENA_BASE/api/cli/v1/experiments/run-spec/default" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" \ --data-urlencode "algorithm=SFT" \ --data-urlencode "datasetName=support-tickets-sft" \ --data-urlencode "pretrainedModelNameOrPath=$ARENA_MODEL" > run-spec.json ``` Change what your product exposes, for example `algorithm.lr`, `network.max_context_length` or `training.max_steps`. `network.max_context_length` is a power of 2 from 1024 up to the model’s maximum. Leave `training.max_steps` unset to train one pass over the dataset. Then ask Arena whether the run fits: ```bash curl -sS "$ARENA_BASE/api/cli/v1/experiments/validate-run-spec" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" \ -H "Content-Type: application/json" -d @run-spec.json ``` If it doesn’t fit, the reply is `400 run_does_not_fit`, with what the run needs and what is available ([Check a run fits](partners/api-reference.md#check-a-run-fits)). Show it to your user with a suggestion: a smaller model, a shorter context, or a smaller batch. ## 5. Start training ```bash curl -sS -N "$ARENA_BASE/api/cli/v1/experiments/jobs/submit" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" \ -H "Content-Type: application/json" \ -d '{"project":"support-bot","experiment_name":"support-bot-v1","manifest":'"$(cat run-spec.json)"'}' ``` Arena picks the GPUs from the run’s memory estimate. The reply streams one JSON object per line and ends with `"status":"completed"` (accepted) or `"status":"failed"` (with a reason). `experiment_name` is the handle for every later call. ## 6. Track status ```bash curl -sS "$ARENA_BASE/api/cli/v1/experiments/list?project=support-bot" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" ``` | `status` | Meaning | What your product shows | |-------------|------------------------------------------------------------------|-----------------------------| | `Queued` | Accepted; the GPUs are busy. Starts on its own, in submit order. | Waiting for GPUs | | `Pending` | GPUs assigned, workers starting | Starting | | `Running` | Training | Progress from metrics | | `Stopping` | A stop call is taking effect | Stopping | | `Stopped` | Stopped by a stop call | Stopped | | `Succeeded` | Finished | Ready to download or deploy | | `Failed` | Stopped with an error | The row’s `failure_reason` | Each row also has `status_label`, the text Arena shows for the run while it waits or starts. You never need to retry a queued job. ## 7. Show metrics, stop and resume ```bash curl -sS -G "$ARENA_BASE/api/cli/v1/experiments/metrics" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" \ --data-urlencode "experiment_name=support-bot-v1" curl -sS -X POST "$ARENA_BASE/api/cli/v1/experiments/jobs/stop" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" \ -H "Content-Type: application/json" -d '{"experiment_name":"support-bot-v1"}' curl -sS "$ARENA_BASE/api/cli/v1/experiments/jobs/resume" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" \ -H "Content-Type: application/json" \ -d '{"experiment_name":"support-bot-v1","checkpoint":"final","new_name":"support-bot-v1-more","max_steps":2000}' ``` Metrics update while the job runs. A stop takes effect within seconds. A resume’s `max_steps` counts from the start of the original run, so it must be greater than the checkpoint’s step. ## 8. Download the trained model List checkpoints, then ask for download links for one of them: ```bash curl -sS -G "$ARENA_BASE/api/cli/v1/experiments/jobs/checkpoints" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" \ --data-urlencode "experiment_name=support-bot-v1" curl -sS -X POST "$ARENA_BASE/api/internal/partners/checkpoint-exports" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" \ -H "Content-Type: application/json" \ -d '{"experimentName":"support-bot-v1","steps":500}' ``` `500` is a `steps` value from the checkpoint list. A model over 32 MiB comes back with `state` `queued` or `running` and no links yet. Poll the same route with GET until `state` is `complete`: ```bash curl -sS -G "$ARENA_BASE/api/internal/partners/checkpoint-exports" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" \ --data-urlencode "experimentName=support-bot-v1" \ --data-urlencode "steps=500" ``` Each `urls[]` entry is `{key, url, expiresAt}` and lasts about 15 minutes. Check each file against `files[].sha256` and `files[].bytes` for the same `key`. The files are a Hugging Face model (`config.json`, tokenizer, `.safetensors`). Renewing expired links and resuming a download are in [Download the trained model](partners/api-reference.md#download-the-trained-model). ## 9. Deploy the model ```bash curl -sS "$ARENA_BASE/api/cli/v1/inference/deploy" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" \ -H "Content-Type: application/json" -d '{"experimentName":"support-bot-v1","name":"support-bot"}' curl -sS -G "$ARENA_BASE/api/cli/v1/inference/deployments/one" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" \ --data-urlencode "name=support-bot" ``` The deployment is ready when its `status` is `Deployed`. Its `url` takes `POST /generate`, or `POST /generate_stream` to stream the reply, as described in the [inference contract](reference/inference-contract.md). A `session_id` keeps one conversation’s history together: ```bash DEPLOYMENT_URL="https://…" # url from deployments/one curl -sS "$DEPLOYMENT_URL/generate" \ -H "Authorization: Bearer $ARENA_ORG_KEY" -H "X-External-User-Id: $ARENA_USER" \ -H "Content-Type: application/json" \ -d '{"session_id":"ticket-4411","prompts":["My order has not arrived."],"params":{"max_new_tokens":256}}' ``` On a self-hosted tenant `url` is `https:///api/deployments//inference`, and this call works with the organisation key ([Calling the deployed model](partners/api-reference.md#calling-the-deployed-model)). On hosted Arena the inference server doesn’t yet accept an organisation key, so this last call is refused there. Contact AgileRL if your product needs to call deployments on hosted Arena. On a self-hosted tenant the deployment runs on the tenant’s GPUs, under the tenant’s domain. While it runs, those GPUs aren’t available for training, so new runs may wait as `Queued`. Take a deployment offline with `PATCH /api/cli/v1/inference/deployments` and `"enabled": false`, or remove it with `DELETE` ([Deploy the model](partners/api-reference.md#deploy-the-model)). ## Python The same steps from Python, after `uv add agilerl` (or `pip install agilerl`): ```python from agilerl import ArenaClient ArenaClient.configure(base_url="https://arena.tenant-a.internal") client = ArenaClient(org_key=key, external_user_id="customer-user-17") client.create_dataset( name="support-tickets-sft", category="sft", file="./train.parquet", column_mapping={"prompt": "instruction", "target": "response"}, ) ``` The [Python section](partners/api-reference.md#python) of the reference lists every method. # partners/self-hosted/install.md # Install a tenant Go from a release bundle to a finished training job for one tenant. With the prerequisites ready, this takes under an hour. Repeat steps 3 to 8 for each new tenant; steps 1 and 2 are once per release. The examples install tenant `tenant-a` from release `1.4.0`. The control plane goes into namespace `arena-tenant-a` and the agent into namespace `arena-agent` on the GPU cluster. ## Step 1: Get the release bundle ### What you do AgileRL sends you a links file for release `1.4.0`, `arena-self-hosted-1.4.0.links`. To ask for it, email [arena@agilerl.com](mailto:arena@agilerl.com) with your organisation’s name and the release you want. Each line names a file and gives a private download link for it. The release comes as numbered parts of one tar file (`arena-self-hosted-1.4.0.tar.000`, `.001` and so on, each at most 4 GiB) and a checksum file, `arena-self-hosted-1.4.0.tar.sha256`, about 50 GiB in all. Download the files on a machine with internet access and a fast connection. About 50 GiB takes around 3 hours at 5 MB/s, so an office line may not do; a staging host in a data centre or cloud region is quicker. You then carry the files into your environment, so plan for that copy too. The machine where you unpack them needs about 100 GiB free: the parts plus the unpacked bundle. On macOS, install `wget` first; it doesn’t ship with macOS. ```bash while read -r name url; do wget -c --tries=5 -O "$name" "$url"; done < arena-self-hosted-1.4.0.links ``` If the download stops, run the same command again. `wget -c` carries on each file from where it stopped. The links work for 7 days. If they expire before you finish, ask for new ones the same way. Anyone with the links file can download the release until then, so keep it to the people doing the install. Carry the files into your environment. Check the parts, join and unpack them, then check the bundle. On macOS, use `shasum -a 256 -c` in place of `sha256sum -c`: ```bash sha256sum -c arena-self-hosted-1.4.0.tar.sha256 cat arena-self-hosted-1.4.0.tar.[0-9]* | tar -x cd arena-self-hosted-1.4.0 sha256sum -c SHA256SUMS ``` ### What happens The bundle is everything a tenant needs: the charts `charts/arena-self-hosted-1.4.0.tgz` and `charts/arena-byoc-agent-1.4.0.tgz`, every container image for both amd64 and arm64 (under `images/`), and `images.lock`, which lists each image with its digest and platforms. It also holds `mirror-images.sh` with the Linux `crane` binaries it uses (under `tools/`; on macOS, install [crane](https://github.com/google/go-containerregistry) yourself), an example tenant values file `values-example-tenant.yaml`, and `RELEASE-NOTES.md`, which names the platform release and ML bundle and lists every image in the bundle with its digest. Nothing is downloaded later. ## Step 2: Mirror the images ### What you do Log in to your registry, then push every image from the bundle: ```bash docker login registry.internal ./mirror-images.sh . registry.internal/arena ``` A registry with no login needs no `docker login`. For a registry served over plain HTTP, add `--insecure` after the registry, for example `./mirror-images.sh . 10.0.0.5:5000/arena --insecure`, and make sure the container runtime on every node is set up to pull from it over HTTP. ### What happens The script pushes each image in `images.lock` to `registry.internal/arena`, keeping its repository path, tags and digests. For example `761296822462.dkr.ecr.us-east-1.amazonaws.com/containers/arena-train:59.7.2-cu130` becomes `registry.internal/arena/containers/arena-train:59.7.2-cu130`, and `public.ecr.aws/zinclabs/openobserve:v0.80.1` becomes `registry.internal/arena/zinclabs/openobserve:v0.80.1`. The tenant pulls only from your registry, so it needs no login to Arena’s. It talks only to your registry and stops if a pushed digest differs from `images.lock`. Running it again is safe. Every tenant on this release uses these images, so this is once per release, not once per tenant. ## Step 3: Prepare the tenant’s resources ### What you do Create, for the tenant: - A bucket (here `arena-tenant-a`) and an access key for it. When people use the tenant from a browser, browsers upload and download datasets and models straight to the store, so its endpoint must be reachable from your users’ network, and its CORS rules must allow the tenant’s UI origin (here `https://arena.tenant-a.internal`) to `GET`, `PUT`, `POST` and `HEAD` with the `Content-Type`, `Content-MD5` and `Content-Encoding` request headers, and expose `ETag`, which multipart uploads read. Put the key in a Secret in the control plane namespace: ```bash kubectl create namespace arena-tenant-a kubectl -n arena-tenant-a create secret generic tenant-a-s3 \ --from-literal=accessKeyId=… --from-literal=secretAccessKey=… ``` - A DNS name for the API (here `arena.tenant-a.internal`) pointing at your ingress, and a TLS certificate that covers that name and `*.arena.tenant-a.internal`. Deployments are served on the wildcard. Create the Secret only after the certificate includes both names: ```bash kubectl -n arena-tenant-a create secret tls arena-tenant-a-tls --cert=tls.crt --key=tls.key ``` - On the GPU cluster, a namespace for the agent (here `arena-agent`) with two Secrets. The store Secret has the **same name** as the one above, with the keys training and inference pods read. The TLS Secret serves the deployment hostnames. Any namespace name works, because the agent reads the store Secret from its own namespace: ```bash kubectl create namespace arena-agent kubectl -n arena-agent create secret generic tenant-a-s3 \ --from-literal=AWS_ACCESS_KEY_ID=… --from-literal=AWS_SECRET_ACCESS_KEY=… \ --from-literal=endpoint=https://s3.internal \ --from-literal=AWS_ENDPOINT_URL=https://s3.internal \ --from-literal=APP_AWS_CLIENT_ENDPOINT=https://s3.internal kubectl -n arena-agent create secret tls arena-tenant-a-tls --cert=tls.crt --key=tls.key ``` - A node label that picks the tenant’s reserved GPU nodes, for example `nvidia.com/gpu.product: NVIDIA-B300`. The NVIDIA GPU Operator (through GPU Feature Discovery) sets `nvidia.com/gpu.product` for you. With the device plugin alone, nodes don’t get it, so label them yourself, for example `kubectl label node nvidia.com/gpu.product=NVIDIA-B300`. Any label works, as long as `gpuCluster.nodeSelector` in step 4 matches it. - On the GPU cluster, a node with at least 20 GiB of memory, no GPUs and no `NoSchedule` or `NoExecute` taint. A training job’s Ray head holds the job’s own message broker and needs a node like this. An untainted control-plane node counts, as on a single-server k3s install; a separate CPU worker node is recommended, so the head doesn’t take the control plane’s CPU and memory. Without any such node, the job connects to the bundled broker, which nothing reads: Arena stops it by stopping its Ray job instead of halting it gracefully, and its metric names are not recorded. The head requests 16 GiB and has no node selector, so Kubernetes may also place it on a GPU node with room (a `PreferNoSchedule` taint doesn’t stop it), for example when a second job starts while the CPU node already holds one head. ### What happens Arena stores datasets, models, checkpoints and exported metrics under the bucket. The API is served only at the DNS name you give it, and the GPU cluster reaches the control plane through that name. The agent copies the store Secret into each job’s namespace, so training and inference pods reach the bucket with the tenant’s own key. ## Step 4: Write the tenant’s values file ### What you do Start from `values-example-tenant.yaml` in the bundle. Tenant settings go under `arena-platform:`; the bundled dependencies have their own top-level sections: ```yaml # tenant-a.yaml arena-platform: tenant: tenant-a domain: arena.tenant-a.internal image: registryOverride: registry.internal/arena storage: endpoint: https://s3.internal bucket: arena-tenant-a existingSecret: tenant-a-s3 ingress: className: nginx tls: existingSecret: arena-tenant-a-tls onPrem: images: trainImage: … # copy from values-example-tenant.yaml inferenceTag: … # copy from values-example-tenant.yaml gpuCluster: name: tenant-a-gpus nodeSelector: nvidia.com/gpu.product: NVIDIA-B300 gpuType: nvidia-b300 classes: - name: b300-8x1 gpusPerNode: 8 numNodes: 1 cpu: 192 memoryGib: 1536 openobserve: image: oss: repository: registry.internal/arena/zinclabs/openobserve ``` If your certificate comes from a private CA, add its PEM as `arena-platform.tls.caBundle`. The control plane, the agent and its validators, and training and inference pods trust it, as well as their images’ own roots, for calls to the API and to S3, so if your S3 store’s certificate also comes from a private CA, put that CA in the same bundle. The CA certificate must carry the key usage extension with `keyCertSign`. Training and inference pods run Python 3.13, which checks certificates strictly and rejects a CA without it (`CA cert does not include key usage extension`). A run still trains, but its metric names never reach the API and a stop can’t reach the job. `openssl x509 -in ca.crt -noout -ext keyUsage` should print `Certificate Sign`. For the same reason the certificate for `domain` needs an authority key identifier (`Missing Authority Key Identifier` otherwise): `openssl x509 -in tls.crt -noout -ext authorityKeyIdentifier` should print one. OpenSSL 3.0 adds it when it signs a certificate with `-CA`; some other tools do not. ### What happens This file is the whole tenant configuration. It names only resources inside your environment. `onPrem.images.trainImage` and `onPrem.images.inferenceTag` name the release’s training and inference images; copy them from the `values-example-tenant.yaml` of the release you install, because without `trainImage` bootstrap creates no resource classes and the install fails. `image.registryOverride` replaces the registry of every image the tenant runs, including Postgres and Pulsar, and the images Arena hands to the GPU cluster. OpenObserve takes its full repository in `openobserve.image.oss.repository`. Deployment hostnames and the address the GPU cluster calls follow `domain`. Each entry under `gpuCluster.classes` becomes a resource the tenant can train and deploy on: `gpusPerNode` GPUs of `gpuType`, `cpu` CPUs and `memoryGib` GiB of memory on each of `numNodes` nodes. Set `cpu` and `memoryGib` to no more than one GPU node has. Training pods request them less what Kubernetes keeps on each node, and more is kept back on a bigger class: about 6 GiB of 28 GiB, 8 GiB of 46 GiB, 16 GiB of 184 GiB. `/resources` shows what a run actually gets as `ram_gb`. Without `classes`, the tenant gets one class, `gpu-1x1` (one GPU, 6 CPUs, 28 GiB), the smallest that trains a 0.8B model. Training and inference workers of every class, and the agent’s own pods, run only on nodes that match `gpuCluster.nodeSelector`; a job’s Ray head doesn’t (step 3). Each class is its own pool of `numNodes` nodes. Arena runs one job per class node at a time and queues the rest, but it doesn’t know when two classes share the same machines. With `l4-1x1`, `l4-2x1` and `l4-4x1` on one 4-GPU node, two `l4-1x1` runs never run together, while one run of each class can be admitted at once, asking for 7 GPUs on a 4-GPU node; the pods that don’t fit wait in `Pending` until GPUs free up. Classes have no node selector of their own, so on shared nodes either define one class per node size or accept that waiting. `gpuCluster.tolerations` reaches the agent’s pods only; training and inference pods don’t get it. The [values reference](partners/self-hosted/reference.md#values) lists every key, including an external Postgres and resource limits. ## Step 5: Install ### What you do Install with the release name `arena`. The bundled services have fixed names (`arena-postgres`, `arena-pulsar`, `arena-openobserve`) that the tenant settings point at. ```bash helm install arena charts/arena-self-hosted-1.4.0.tgz \ -n arena-tenant-a -f tenant-a.yaml --wait --timeout 20m ``` ### What happens Helm creates the control plane: API, workers, scheduler, Postgres, Pulsar and OpenObserve. A migration Job creates the database schema; the API and workers restart until it exists, then turn Ready. Once every pod is Ready, two Jobs run: - **Bootstrap** (`arena-bootstrap`). Creates the tenant’s organisation and API key, registers the GPU cluster and creates its resource classes. - **Self-check** (`arena-doctor`). Checks every dependency and confirms that every configured endpoint is inside your environment. A failed check fails the install. A GPU cluster whose agent has stopped reporting is only a warning here, so the control plane installs and upgrades while the GPU side is offline. `helm install` returns when all pods are Ready and both Jobs have succeeded. ## Step 6: Read the self-check and bootstrap output ### What you do ```bash kubectl -n arena-tenant-a logs job/arena-doctor kubectl -n arena-tenant-a logs job/arena-bootstrap ``` ### What happens The self-check prints one line per dependency: ```text postgres ok arena-postgres:5432 object store ok https://s3.internal (bucket arena-tenant-a) openobserve ok arena-openobserve:5080 gpu cluster waiting tenant-a-gpus (agent not installed yet) outbound endpoints ok all 9 configured endpoints are inside the tenant ``` With a private CA (`arena-platform.tls.caBundle`) a `ca bundle` line follows `openobserve`. It fails when a CA in the bundle lacks key usage `keyCertSign`, which training and inference pods require, and names that CA. The endpoint count depends on your values. The check allows the tenant’s `domain` and `*.domain`, the release’s own services, the store endpoint, the database host and the registry. If you use an external OpenObserve, add its host to `arena-platform.doctor.allowlist`. Bootstrap prints what it created: ```text organisation tenant-a (created) api key arena_org_8c1f…Qx7a (stored in secret arena-partner-key) gpu cluster tenant-a-gpus registered agent values stored in secret arena-agent-values resource class b300-8x1 created ``` On later upgrades the same Job prints `exists`, `unchanged` and `already registered`. A class changed in the values file shows as `updated`. So do the agent values after an upgrade to a new release, because bootstrap writes that release’s agent images into them ([Upgrade](partners/self-hosted/operations.md#upgrade)). The full API key is in the Secret `arena-partner-key`, under `key`; the log shows only its start and end. Give it to the developer building your service (see [Your first model](partners/first-model.md)): ```bash kubectl -n arena-tenant-a get secret arena-partner-key -o jsonpath='{.data.key}' | base64 -d ``` ## Step 7: Connect the GPU cluster ### What you do Copy the agent values and the agent’s cluster token from the control plane. On the GPU cluster, store the token and install the agent: ```bash kubectl -n arena-tenant-a get secret arena-agent-values \ -o jsonpath='{.data.values\.yaml}' | base64 -d > agent-values.yaml kubectl -n arena-tenant-a get secret arena-agent-values \ -o jsonpath='{.data.cluster-token}' | base64 -d > cluster-token kubectl -n arena-agent create secret generic cluster-token --from-file=cluster-token=./cluster-token helm install arena-agent charts/arena-byoc-agent-1.4.0.tgz \ -n arena-agent -f agent-values.yaml --set provisioner.enabled=false --wait ``` A tenant doesn’t use the agent chart’s machine provisioner. `agent-values.yaml` from bootstrap already turns it off, and `--set provisioner.enabled=false` keeps it off whatever the values file says. The bundle has neither `containers/arena-byoc-provisioner` nor `containers/arena-wg` for that reason. If you turn the provisioner on, mirror both to your registry through `image.registryOverride`. Mirror `provisioner.image` (`containers/arena-byoc-provisioner`) at `provisioner.image.tag` in `agent-values.yaml`: the provisioner pod pulls that and stays in `ImagePullBackOff` when it is missing. Mirror `containers/arena-wg` at the chart’s `provisioner.wireguardImage.tag`: job VMs pull that and fail their WireGuard wait when it is missing. `agent-values.yaml` and `cluster-token` are the agent’s credentials. Keep them with your other tenant secrets. Run the self-check again from the API pod, with the allowlist the chart generated: ```bash kubectl -n arena-tenant-a get configmap arena-doctor-allowlist \ -o jsonpath='{.data.outbound-allowlist\.txt}' \ | kubectl -n arena-tenant-a exec -i deploy/arena-api -- \ sh -c 'cat > /tmp/allowlist.txt && /usr/app/arena-cli task doctor_outbound allowlist:/tmp/allowlist.txt' ``` ### What happens The agent connects to `https://arena.tenant-a.internal` and reports the GPUs it finds on the selected nodes. Within a few minutes the self-check shows: ```text gpu cluster ok tenant-a-gpus (Connected, agent 3.7.4) ``` The agent has its own version number, not the release’s; `RELEASE-NOTES.md` lists it as the `containers/arena-byoc-agent` tag. The tenant can now train and deploy on the classes bootstrap created in step 5, here `b300-8x1`. These are the only resources it has. ## Step 8: Add a base model and run a first job ### What you do Copy a model into the tenant’s bucket and register it ([Base models](partners/self-hosted/models.md) has the detail): ```bash aws --endpoint-url https://s3.internal s3 sync ./Qwen3.5-0.8B \ s3://arena-tenant-a/models/qwen3.5-0.8b/ kubectl -n arena-tenant-a exec deploy/arena-api -- \ /usr/app/arena-cli task register_model name:qwen3.5-0.8b \ path:s3://arena-tenant-a/models/qwen3.5-0.8b/ ``` Then run the built-in smoke test. It uploads a 200-row dataset, fine-tunes the model with SFT and LoRA for 20 steps, and checks the checkpoint, metrics and export. Add `deploy:true` to deploy the checkpoint as well: ```bash kubectl -n arena-tenant-a exec deploy/arena-api -- /usr/app/arena-cli task smoke model:qwen3.5-0.8b ``` ### What happens The smoke test calls the same partner API your service will use. It mints its own key, which expires within 24 hours and is revoked when the test ends. It reads the tenant’s GPU types from the API and lets submit pick the GPUs, as your service would. `gpu_type:b300` asks for one of the listed types instead. After training it downloads the exported model and checks every file’s size and sha256. A download that fails gets a fresh link and is tried again, up to 3 times per file. Then it resumes the run and stops it. It prints one line per step, and a green run means the tenant is ready: ```text auth ok unknown key 401, admin route 404 resources ok submit picks among b300 dataset ok smoke-20261123101500-sft (200 rows) project ok smoke-20261123101500 model ok qwen3.5-0.8b run-spec ok SFT, max_steps 20 submit ok Training job for 'smoke-20261123101500-run' submitted successfully train ok 20 steps in 3m41s checkpoint ok step 20 metrics ok 14 names, 21 CSV lines export ok 9 files, 1795164160 bytes, sha256 verified resume ok smoke-20261123101500-resume queued stop ok smoke-20261123101500-resume Stopped cleanup ok ``` On a tenant the auth line ends in `admin route 404`. On a hosted API it ends in `admin route 403`. With `deploy:true`, a `deploy` line before `cleanup` shows the deployment’s URL. The test removes everything it created, pass or fail. If it can’t stop one of its runs, `cleanup` fails and leaves the project and dataset in place, so stop that run and remove them yourself. If a step fails, its line says why, the steps after it are skipped, and the command exits non-zero. Ctrl-C or SIGTERM to the process skips the remaining steps, prints a `cancelled` line and still cleans up. The test waits up to an hour each for training, the export, the stop and the deployment. For a large model, raise that with `timeout_secs:`, keeping the whole run inside the key’s 24 hours. ## Next - Hand the API key and `https://arena.tenant-a.internal` to your developers: [Your first model](partners/first-model.md) and the [Partner API reference](partners/api-reference.md). - Plan upgrades, backups and key rotation: [Operations](partners/self-hosted/operations.md). # partners/self-hosted/models.md # Base models A tenant can’t download models from the internet. You add base models to the tenant’s bucket and register them, and they show up in the tenant’s model list for your service to offer. ## Add a model ### What you do 1. Get the model files on a machine that can reach the tenant’s object store. A model directory holds `config.json`, the tokenizer files and the weights (`.safetensors`), as published on Hugging Face. 2. Copy the directory into the tenant bucket under `models/`: ```bash aws --endpoint-url https://s3.internal s3 sync ./Qwen3.5-9B \ s3://arena-tenant-a/models/qwen3.5-9b/ ``` 3. Register it: ```bash kubectl -n arena-tenant-a exec deploy/arena-api -- \ /usr/app/arena-cli task register_model name:qwen3.5-9b \ path:s3://arena-tenant-a/models/qwen3.5-9b/ ``` The name may use letters, digits, `.`, `-` and `_`. The path must be in the tenant’s own bucket. ### What happens Arena reads `config.json` and checks that the weights and tokenizer are there: `config.json`, at least one `.safetensors` file, every shard named in `model.safetensors.index.json`, and one of `tokenizer.json`, `tokenizer.model` or `vocab.json`. It matches the architecture to a [supported model](#supported-models), which it then uses to size runs, and reports whether the model fits the tenant’s GPUs for training and for inference: ```text model qwen3.5-9b (Qwen3_5ForConditionalGeneration, 9.4B parameters, 262144 context) base Qwen/Qwen3.5-9B files ok 4 safetensors shards, tokenizer training fit ok b300-8x1 (LoRA) inference fit ok b300-8x1 registered yes ``` Training fit sizes a LoRA SFT run at batch size 8, first at the model’s full context. If a class doesn’t fit there, Arena tries the shorter context lengths a run can set (powers of 2, down to 4096 tokens) and names the longest one that fits, for example `l4-1x1 (LoRA at 32768 context)`. Set `network.max_context_length` in your run spec to train at that length. Running the command again with the same files prints `registered yes (unchanged)`; with changed files, `yes (updated)`. When the files match more than one supported model of different sizes, the command stops and lists them. Pick one with `base:`: ```bash kubectl -n arena-tenant-a exec deploy/arena-api -- \ /usr/app/arena-cli task register_model name:support-tuned \ path:s3://arena-tenant-a/models/support-tuned/ base:Qwen/Qwen3.5-9B ``` The model is available to every user of the tenant straight away. Your service trains and deploys it by its registered name, here `qwen3.5-9b`. ## Prefetch onto the GPU nodes Workers on the GPU cluster can copy a base model’s weights before a job starts. They read a Hugging Face id `org/name` from `//org/name/`, where the bucket and prefix are the chart values `storage.modelStore.bucket` and `storage.modelStore.prefix` ([Values](partners/self-hosted/reference.md#values)). The bucket defaults to the tenant bucket and the prefix has no default. The workers read it with the GPU cluster’s store Secret, so that key needs read access to the bucket, which matters when you point it at a shared bucket. ## Share models across tenants Each tenant has its own bucket, so each tenant needs its own copy. To add the same model to many tenants, run the copy and register commands per tenant. A script over your tenant list works well, because both commands are safe to repeat. ## Remove a model ```bash kubectl -n arena-tenant-a exec deploy/arena-api -- /usr/app/arena-cli task unregister_model name:qwen3.5-9b ``` The model disappears from the model list. The files stay in the bucket; delete them afterwards if you want the space back. ## Supported models A model can be registered when its `config.json` matches a model in the release’s catalogue: the same model type, hidden size, number of layers, vocabulary size and context length. That covers the published checkpoints and fine-tunes of them that keep the architecture. The catalogue ships in each release’s API image. To print the one a tenant runs: ```bash kubectl -n arena-tenant-a exec deploy/arena-api -- python3 -m agilerl.cli models supported ``` On release 4.8 and earlier the module is `agilerl.arena.cli`: `python3 -m agilerl.arena.cli models supported`. Datasets don’t need registering: your service uploads them through the API. # partners/self-hosted/operations.md # Operations Day-to-day running of tenants: health, upgrades, backups, keys and removal. Every command runs inside your environment. The examples use the tenant from [Install a tenant](partners/self-hosted/install.md): release `arena` in namespace `arena-tenant-a`, agent release `arena-agent` in namespace `arena-agent`. ## Check health The self-check runs after every install and upgrade (`kubectl -n arena-tenant-a logs job/arena-doctor`). To run it at any time, feed it the allowlist the chart generated: ```bash kubectl -n arena-tenant-a get configmap arena-doctor-allowlist \ -o jsonpath='{.data.outbound-allowlist\.txt}' \ | kubectl -n arena-tenant-a exec -i deploy/arena-api -- \ sh -c 'cat > /tmp/allowlist.txt && /usr/app/arena-cli task doctor_outbound allowlist:/tmp/allowlist.txt' ``` The self-check covers Postgres, the object store, OpenObserve and the GPU cluster, and confirms that every configured endpoint is inside your environment. Add `list:true` to print every endpoint it checked. It exits non-zero if anything fails, so you can run it from your own monitoring. Each component also has standard Kubernetes liveness and readiness probes. The API serves these paths on the `arena-api` Service, port 3001, inside the cluster. The ingress at the tenant’s domain doesn’t route them, so point in-cluster monitoring at `http://arena-api.arena-tenant-a.svc:3001`, or check by hand with `kubectl -n arena-tenant-a port-forward svc/arena-api 3001`: | Path | Returns | |--------------------|-------------------------------------------------------------------------------------------------------------| | `/livez` | `200` when the API process is up | | `/readyz` | `200` when Postgres and the object store both answer; `503` when either doesn’t. Point your monitoring here | | `/readyz/database` | `200` when Postgres answers. The API pod’s readiness probe uses this path | The readiness probe checks only Postgres. During an object store outage the API pod stays Ready, so your service still reaches it and gets an error that names the problem, such as `503 storage_unavailable`, while `/readyz` returns `503`. The API logs `/readyz dependency check failed` with the dependency that failed. The GPU cluster’s state and the agent’s last contact time: ```bash kubectl -n arena-tenant-a exec deploy/arena-api -- /usr/app/arena-cli task clusters_status ``` ```text tenant-a-gpus Ready 8x nvidia-b300 agent 1.4.0 last contact 4s ago jobs running 1, queued 2 ``` The state is `Waiting` until the agent first connects, `Ready` while it keeps polling without errors, `Degraded` when it stops polling or reports an error, and `Disabled` for a disabled cluster. The GPU count is that of the largest resource class of each GPU type in `gpuCluster.classes`. `jobs running` counts jobs that are training and jobs that have GPUs and are starting (`Pending`); `queued` counts jobs waiting for GPUs. ## Logs All components log to standard output, so your log tooling picks them up. Training and inference logs are also kept in the tenant’s OpenObserve, and your service can read them through the API next to metrics. ## Upgrade ### What you do 1. Read `RELEASE-NOTES.md` in the new bundle for the platform release, ML bundle and image versions it brings. 2. Mirror the new images (once per release): ```bash ./arena-self-hosted-1.5.0/mirror-images.sh arena-self-hosted-1.5.0 registry.internal/arena ``` 3. Upgrade each tenant with its existing values file: ```bash helm upgrade arena arena-self-hosted-1.5.0/charts/arena-self-hosted-1.5.0.tgz \ -n arena-tenant-a -f tenant-a.yaml --wait --timeout 20m ``` 4. Copy the agent values again, then upgrade the agent with them: ```bash kubectl -n arena-tenant-a get secret arena-agent-values \ -o jsonpath='{.data.values\.yaml}' | base64 -d > agent-values.yaml helm upgrade arena-agent arena-self-hosted-1.5.0/charts/arena-byoc-agent-1.5.0.tgz \ -n arena-agent -f agent-values.yaml --set provisioner.enabled=false --wait ``` ### What happens Each upgrade runs a new migration Job; the new API and worker pods restart until the schema matches, while the old ones keep serving. History, API keys, models, checkpoints and deployments carry over. Bootstrap and the self-check run again at the end of the upgrade. The self-check reports a GPU cluster whose agent has stopped reporting as `warning`, so you can upgrade the control plane while the GPU cluster is down. Bootstrap keeps the key and the cluster registration while `arena-partner-key` and `arena-agent-values` still hold them. It brings the resource classes and node selector in line with the values file, and writes the new release’s agent and validator images into `arena-agent-values`; its log shows `agent values updated in secret arena-agent-values`. The cluster token doesn’t change, so the `cluster-token` Secret stays as it is. An agent upgraded with the previous release’s `agent-values.yaml` keeps running the previous release’s images, so always copy the values again first. Each job and deployment runs in its own namespace on the GPU cluster, named `arena-ent-train--` or `arena-inf--`. The key is eight characters that differ for each GPU cluster registration, so two tenants’ agents in one Kubernetes cluster never pick the same name. The agent labels each namespace it creates with `arena.agilerl.com/agent-namespace: `, and only removes a namespace that already has its own label. An unlabelled namespace is left in place. Jobs and deployments that were running before the release that added the key keep their old names (`arena-ent-train-`, `arena-inf-`). A deployment which was not installed yet (no phase, or still copying its checkpoint) is given the new name at upgrade. Upgrade both agents first. The upgraded agent adds its label to an unlabelled `arena-ent-train-` or `arena-inf-` when it next installs into it. Stop that job only after `kubectl get namespace --show-labels` shows this agent’s `arena.agilerl.com/agent-namespace` label. Do not stop a shared id on the agent from before this release: that agent deletes `arena-ent-train-` with no owner check. If two tenants share one unlabelled namespace, set the label to the agent namespace of the tenant that owns the workload before either upgraded agent stops the job. After the namespace is deleted, the next start of that deployment uses the keyed name. To roll back, `helm rollback` to the previous revision. That brings back the previous charts and images but doesn’t undo database migrations. If the new release changed the schema, restore a backup taken before the upgrade instead. ## Back up A tenant’s state is its Postgres database, its bucket, and the Secret `arena-secrets-key`. Back up all three together. A restore without that Secret can’t read organisation secrets. Save the Secrets `arena-partner-key` and `arena-agent-values` with them, so a restored tenant keeps its API key and GPU cluster registration. ```bash DAY=$(date +%F) kubectl -n arena-tenant-a exec statefulset/arena-postgres -- \ sh -c 'pg_dump -U "$POSTGRES_USER" -Fc "$POSTGRES_DB"' > tenant-a-$DAY.dump aws --endpoint-url https://s3.internal s3 sync s3://arena-tenant-a s3://backups/tenant-a/$DAY/ for s in arena-secrets-key arena-partner-key arena-agent-values; do kubectl -n arena-tenant-a get secret $s -o json \ | jq 'del(.metadata.resourceVersion, .metadata.uid, .metadata.creationTimestamp, .metadata.managedFields, .metadata.ownerReferences)' \ > tenant-a-$s.json done ``` The `jq` step drops the fields the cluster sets, so the Secrets can be applied to a fresh namespace. The files hold the tenant’s encryption key, its API key and the agent’s credentials: store them like any other secret. If you use an external Postgres, back it up with your usual tooling. ## Restore Recreate the namespace and the Secrets your values file names (step 3 of [Install a tenant](partners/self-hosted/install.md)), then install a fresh tenant with the same values file and `restore` on, which skips bootstrap. The install has already created the schema, so load the backup into an empty database: stop the Deployments and wait for their pods to exit, drop and create the database, restore, copy the bucket back, then start the Deployments again. ```bash kubectl create namespace arena-tenant-a kubectl -n arena-tenant-a create secret generic tenant-a-s3 \ --from-literal=accessKeyId=… --from-literal=secretAccessKey=… kubectl -n arena-tenant-a create secret tls arena-tenant-a-tls --cert=tls.crt --key=tls.key helm install arena charts/arena-self-hosted-1.4.0.tgz -n arena-tenant-a -f tenant-a.yaml \ --set arena-platform.restore=true --wait --timeout 20m for s in arena-secrets-key arena-partner-key arena-agent-values; do kubectl -n arena-tenant-a apply -f tenant-a-$s.json done kubectl -n arena-tenant-a get deploy \ -o jsonpath='{range .items[*]}{.metadata.name}={.spec.replicas}{"\n"}{end}' > tenant-a-replicas.txt kubectl -n arena-tenant-a scale deploy --all --replicas=0 # Deployment pods carry pod-template-hash; the StatefulSets' pods, Postgres among them, don't. until pods=$(kubectl -n arena-tenant-a get pods -l pod-template-hash -o name) && [ -z "$pods" ]; do sleep 5 done kubectl -n arena-tenant-a exec statefulset/arena-postgres -- \ sh -c 'dropdb -U "$POSTGRES_USER" --force "$POSTGRES_DB" && createdb -U "$POSTGRES_USER" "$POSTGRES_DB"' kubectl -n arena-tenant-a exec -i statefulset/arena-postgres -- \ sh -c 'pg_restore -U "$POSTGRES_USER" -d "$POSTGRES_DB"' < tenant-a-2026-11-18.dump aws --endpoint-url https://s3.internal s3 sync s3://backups/tenant-a/2026-11-18/ s3://arena-tenant-a while IFS='=' read -r d n; do kubectl -n arena-tenant-a scale deploy "$d" --replicas="$n" done < tenant-a-replicas.txt ``` Each step exits 0, so they can run in a script with `set -e`. Don’t restore with `pg_restore --clean` over the installed schema instead: it can’t drop the keys of the audit log’s monthly partitions and exits 1. A fresh install creates its own `arena-secrets-key`. Applying the backup replaces it, and the Deployments load that key when they start again. API keys, experiments, models, checkpoints, deployments and organisation secrets come back as they were at backup time. OpenObserve’s volume isn’t part of this backup, so live logs and metrics from before it aren’t restored. If the agent was removed too, install it again as in step 7 of [Install a tenant](partners/self-hosted/install.md). Leave `restore` out of later upgrades. Bootstrap then runs again, finds the key and cluster from the backup, and keeps them. ## Rotate the API key Turn on `bootstrap.rotateKey` for one upgrade, then turn it off again: ```bash helm upgrade arena charts/arena-self-hosted-1.4.0.tgz -n arena-tenant-a -f tenant-a.yaml \ --set arena-platform.bootstrap.rotateKey=true --wait --timeout 20m kubectl -n arena-tenant-a get secret arena-partner-key -o jsonpath='{.data.key}' | base64 -d helm upgrade arena charts/arena-self-hosted-1.4.0.tgz -n arena-tenant-a -f tenant-a.yaml \ --wait --timeout 20m ``` The bootstrap Job writes a new key to the Secret `arena-partner-key`, and its log shows when the old keys stop working (`old api keys 1 valid until …`). The old key keeps working for 24 hours, so your service can switch without downtime. To end it at once, also set `arena-platform.bootstrap.revokeOld=true` on the first upgrade; `revokeOld` without `rotateKey` fails the upgrade. Don’t leave `rotateKey` on: every upgrade would mint another key. ## Change the private CA Put the new CA’s PEM in `arena-platform.tls.caBundle` and run `helm upgrade`. Bootstrap writes it into the agent values in `arena-agent-values`. Copy the agent values again and upgrade the agent, as in step 7 of [Install a tenant](partners/self-hosted/install.md); the agent restarts with the new CA. Training and inference pods started after the upgrade trust it. While the old and new certificates overlap, put both CAs in the bundle. ## Change a tenant’s GPUs The tenant’s resources are the classes in `arena-platform.gpuCluster.classes`. To add one, for example `b300-8x2` after adding a second node, add it to the list and run `helm upgrade`. Bootstrap creates new classes and updates changed ones in place, matched by name. Taking a class out of the list doesn’t delete it. To point a tenant at different nodes, change `arena-platform.gpuCluster.nodeSelector` and run `helm upgrade`. Bootstrap applies the new selector to every class and to the agent values in `arena-agent-values`. Copy the agent values again and upgrade the agent, as in step 7 of [Install a tenant](partners/self-hosted/install.md), so the agent’s own pods move too. ## Remove a tenant ### What you do ```bash helm uninstall arena-agent -n arena-agent --timeout 10m # on the GPU cluster kubectl delete namespace arena-agent # on the GPU cluster helm uninstall arena -n arena-tenant-a kubectl delete namespace arena-tenant-a aws --endpoint-url https://s3.internal s3 rm --recursive s3://arena-tenant-a ``` ### What happens Uninstalling the agent stops every job and deployment on the GPU cluster. Before it removes itself, a hook Job (`arena-byoc-agent-namespace-cleanup`) first scales the agent to 0 and waits until its pod is deleted, then deletes every namespace labelled `arena.agilerl.com/agent-namespace: arena-agent`, the agent’s own namespace. That removes each job’s and deployment’s Helm release, pods, Roles, RoleBindings and the store Secret copied into it. The Job can run for 400 seconds, past Helm’s default 5 minute wait, so the command passes `--timeout 10m` and `helm uninstall` waits for the namespaces to go. If the hook fails, the agent stays scaled to 0; run the same `helm uninstall --timeout 10m` again. A retry that uses the default timeout deletes the Job while the namespace delete is still running. A namespace with no label is one from before the label existed and is not deleted: if `kubectl get namespace -l '!arena.agilerl.com/agent-namespace' | grep -E 'arena-(ent-train|inf)-[0-9]+$'` lists any, check they belong to this tenant and delete them. Uninstalling the control plane removes every Kubernetes object it created. The generated Secrets (`arena-secrets-key`, `arena-postgres` and the OpenObserve credentials) outlive `helm uninstall` and go with the namespace, as do the bundled Postgres, Pulsar and OpenObserve volumes. Deleting the bucket contents removes datasets, models and checkpoints. Nothing of the tenant remains anywhere else, since nothing was ever sent outside your environment. ## Troubleshooting API errors with a code have the body `{"ok": false, "error": "", "message": "…"}`. Training submit streams its answer, so it reports `run_does_not_fit` and `gpu_cluster_unavailable` as `detail.error_code` on the final `failed` line instead of as an HTTP status. The [Partner API reference](partners/api-reference.md#errors) lists every error your developers can see. | Symptom | Cause | Fix | |-------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Pods stuck in `ImagePullBackOff` | Images not in your registry, or `arena-platform.image.registryOverride` points somewhere else | Run `mirror-images.sh` for this release; check `arena-platform.image.registryOverride` and `openobserve.image.oss.repository` | | Install fails on the `arena-doctor` Job | A dependency is down, or a value points outside your environment | `kubectl -n arena-tenant-a logs job/arena-doctor` names the dependency, or the key and host. Fix the values file, or add an external OpenObserve host to `arena-platform.doctor.allowlist` | | `gpu cluster waiting` after the agent install | Agent can’t reach the API’s DNS name, doesn’t trust its certificate, or has no `cluster-token` Secret | From a GPU node, call the partner API’s resources endpoint at `https://arena.tenant-a.internal` over HTTPS without a key, trusting your CA: a `401` reply means the name resolves, the certificate is trusted and the API answers. `/livez` isn’t routed through the ingress, so it returns `404` there. For a private CA, check that `caBundle.pem` in the agent values matches `arena-platform.tls.caBundle`, then upgrade the agent. Check the `cluster-token` Secret in `arena-agent` | | No resources listed | `gpuCluster.classes` is empty, or bootstrap failed before creating the classes | `kubectl -n arena-tenant-a logs job/arena-bootstrap` should end with one `resource class` line per class | | Training or inference pods stay `Pending` | No nodes match `gpuCluster.nodeSelector`, or the GPU Operator isn’t running | `kubectl get nodes -l `; check `nvidia.com/gpu` capacity on the nodes | | Jobs stay `Queued` | GPUs are taken by running jobs or deployments | `/usr/app/arena-cli task clusters_status`; take deployments you don’t need offline | | Pods can’t read the bucket | The store Secret in `arena-agent` is missing or has the wrong keys | It needs the same name as `arena-platform.storage.existingSecret` and the keys from step 3 of [Install a tenant](partners/self-hosted/install.md) | | `503 storage_unavailable` | Object store unreachable or key wrong | Check the endpoint and the key in the `arena-platform.storage.existingSecret` Secret | | `/readyz` returns `503` while the API pod is Ready | The object store doesn’t answer | The API log line `/readyz dependency check failed` names the dependency | | Dataset upload fails | `409 gpu_cluster_unavailable`: the agent is down. Otherwise the stored file is over 64 MiB | Upload again once `clusters_status` shows the cluster `Ready`. Keep the file at or under 64 MiB | | Environment create fails, or an environment never validates | `409 gpu_cluster_unavailable`: the agent is down. An environment created while the GPU cluster was offline, before the release that pins environments to the cluster’s store, has no cluster: its files are in the tenant bucket outside the cluster’s `clusters//` prefix, and its validation goes to a control-plane validator that a tenant does not run | Wait until `clusters_status` shows the cluster `Ready`. For an environment made while the cluster was offline before that release, delete it first, then create it again: creating the same name without deleting it reuses the old environment | | `409 gpu_cluster_unavailable` | The GPU cluster is disabled, never connected, or its agent has been silent for more than 3 minutes. The body has `cluster` on a dataset upload or an environment create | `clusters_status`; check the agent’s pods in `arena-agent` | | `400 run_does_not_fit` | The run can never fit the resource it names, or any resource when it names none. The body has `required` (`gpus`, `num_nodes`, `gpu_memory_gb`) and `available` (`resource`, `gpus`, `num_nodes`, `gpu_memory_gb`) | Change the run, or add a larger class to `gpuCluster.classes` | | `400 huggingface_offline` | The request needed the Hugging Face Hub: dataset search, or a dataset from Hugging Face | Upload the dataset file. Add base models as in [Base models](partners/self-hosted/models.md) | | `401` | Key wrong, revoked, or from another tenant | Read the current key from the Secret `arena-partner-key` | | `404` | Not found in this tenant | Check the name | | `429` | Rate limited | Wait `Retry-After` seconds | # partners/self-hosted/reference.md # Self-hosted reference ## How a tenant is laid out ```text Your environment, one tenant ├── Arena control plane CPU nodes: API, workers, Postgres, Pulsar, OpenObserve ├── GPU cluster the tenant's reserved GPUs, with the BYOC agent ├── Object store any S3-compatible bucket └── Registry images mirrored from the release bundle Your backend ──HTTPS──▶ tenant API ``` The control plane and the GPU cluster can be in the same Kubernetes cluster or in two clusters on the same network. Tenants share nothing with each other. ## Requirements | Item | Requirement | |-----------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Control plane cluster | Kubernetes 1.28+, an ingress controller, a default StorageClass | | Control plane capacity per tenant | 1.96 vCPU and 4.14 GiB memory requested ([Sizing](#sizing)), and 40 GiB of persistent volumes: Postgres 20 GiB, Pulsar 10 GiB and OpenObserve 10 GiB | | GPU cluster | Kubernetes 1.28+, NVIDIA GPU Operator or device plugin, nodes labelled for each tenant, and a node with at least 20 GiB of memory, no GPUs and no `NoSchedule` or `NoExecute` taint for training jobs’ Ray heads (a separate CPU worker node is recommended; an untainted control-plane node also counts) | | GPUs | Any NVIDIA GPU in the [supported list](#supported-hardware); at least 2 per run for reinforcement learning that generates rollouts | | Object store | S3-compatible API with path-style or virtual-host addressing, one bucket per tenant | | Registry | OCI registry reachable from both clusters | | DNS and TLS | One name per tenant for the API, and a wildcard under it for deployments (`*.arena.tenant-a.internal`) | | Operator machine | `kubectl`, Helm 3, `docker` (for `docker login`), `wget` and `sha256sum` (on macOS `shasum`), [crane](https://github.com/google/go-containerregistry) on macOS (the bundle carries the Linux build), the AWS CLI for copying models and backups, and `jq` for backups | ## Supported hardware Training and serving run on NVIDIA GPUs, so every tenant needs real NVIDIA GPUs. The control plane needs none: it runs on ordinary CPU nodes and requests 1.96 vCPU and 4.14 GiB of memory per tenant, plus 0.25 vCPU and 512 MiB while the install and upgrade Jobs run ([Sizing](#sizing)). Arena supports the NVIDIA GPUs in its GPU catalogue that have compute capability 8.0 or newer (Ampere and later), on amd64 or arm64 hosts. Training needs that capability for bf16 and FlashAttention 2, and Arena sizes every run from the catalogue’s figures for the GPU. The bundle contains amd64 and arm64 images, and Kubernetes picks the right one. | Architecture | GPUs | |----------------|----------------------------------------------------------------------------------------------------------------| | Blackwell | GB300 (arm64 Grace host), B300, B200, RTX PRO 6000 Blackwell Server Edition, RTX 6000 Blackwell Server Edition | | Hopper | H200, H100 80GB | | Ada Lovelace | L40S, L4, RTX 6000 Ada Generation | | Ampere | A100 80GB, A100 40GB, A10G | Reinforcement learning that generates its own rollouts (GRPO, CISPO, GSPO, LLM PPO and LLM REINFORCE on a language environment) needs at least 2 GPUs per run: one trains and one runs vLLM to generate. Submit refuses fewer, and `/resources` lists no smaller count for these algorithms. SFT and DPO train on one GPU. Rollout RL also needs the two GPUs to read each other’s memory directly, over NVLink or PCIe peer-to-peer. On release 4.8 (ML bundle 60.0), a run on GPUs without it fails a few minutes after it starts, with `LoRA sync needs NVLink or PCIe P2P` in its driver log. AWS L4 (g6), L40S (g6e) and A10G (g5) instances don’t offer peer-to-peer, so on those, run SFT and DPO only until a release with the fallback weight sync. Submit doesn’t check this yet. Tested with the self-hosted install so far (November 2026): SFT on NVIDIA L4 on AWS, on a 4-GPU g6.12xlarge node. GRPO on the same node failed for lack of peer-to-peer, as above. The other GPUs are sized from the catalogue but haven’t yet run a tenant job. The examples in these pages use B300 nodes. ## Values Install the chart as release `arena`. Tenant keys go under `arena-platform:` in the values file; the bundled dependencies take the top-level keys in the second table. Defaults are in `values.yaml` inside the chart, and `values-example-tenant.yaml` in the bundle is a starting point. The example also carries release pins that this table doesn’t list: `appVersion`, `image.repository`, `images.*` with their digests, `onPrem.image.tag`, `onPrem.provisioner.image.tag` and the validator tags under `onPrem.images`. Keep them as the release sets them. Some name AgileRL’s registry (for example `onPrem.images.trainImage`); `image.registryOverride` rewrites that host to your mirror, so nothing pulls from AgileRL. Under `arena-platform:`: | Key | Required | Description | |-------------------------------------------------------------------|----------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `tenant` | yes | Tenant name. Used for the organisation. | | `domain` | yes | DNS name of the tenant API. Deployments get names under it, and the GPU cluster calls the API at `https://`. | | `image.registryOverride` | yes | Registry the bundle was mirrored to. Replaces the registry of every image the tenant runs, including the bundled Postgres and Pulsar and the images Arena starts on the GPU cluster. | | `image.pullSecrets` | no | Image pull Secrets for the registry. | | `storage.endpoint` | yes | Object store URL. | | `storage.bucket` | yes | Tenant bucket. | | `storage.prefix` | no | Path inside the bucket for the control plane’s objects. Default `platform`. The GPU cluster keeps its datasets, models, checkpoints and logs under `clusters//` in the same bucket, whatever this is set to. | | `storage.region` | no | Region name the store expects. Default `us-east-1`. | | `storage.pathStyle` | no | Path-style addressing. Default `true`. | | `storage.existingSecret` | yes | Secret with `accessKeyId` and `secretAccessKey`. A Secret with the same name must exist in the agent namespace on the GPU cluster ([step 3](partners/self-hosted/install.md#step-3-prepare-the-tenant-s-resources)). | | `storage.modelStore.bucket` | no | Bucket GPU workers prefetch base model weights from before a job starts. A Hugging Face id `org/name` is read from `//org/name/`. Default: `storage.bucket`. The GPU cluster’s store Secret must be able to read this bucket. Used only with `storage.existingSecret`. | | `storage.modelStore.prefix` | no | Path inside `storage.modelStore.bucket` that holds the `org/name/` directories. No default: the directories sit at the top of the bucket. | | `postgres.bundled` | no | Run Postgres in the namespace. Default `true`. | | `postgres.external.host`, `.port`, `.database`, `.existingSecret` | if not bundled | External Postgres. The Secret holds `username` and `password`. | | `ingress.className` | yes | Ingress class for the API and deployments. | | `tls.existingSecret` | yes | TLS Secret for `domain` and `*.domain`. A TLS Secret with the same name serves deployments from the agent namespace. | | `tls.caBundle` | no | PEM CA bundle, for private CAs. The control plane, the agent and its validators, and training and inference pods trust it for the API and S3. Each CA needs key usage `keyCertSign`, and each certificate it signs needs an authority key identifier. | | `gpuCluster.name` | yes | Name for the tenant’s GPU cluster. | | `gpuCluster.nodeSelector` | yes | Labels selecting the tenant’s GPU nodes. Every resource class and the agent’s pods use it. | | `gpuCluster.tolerations` | no | Tolerations for the agent’s pods. Training and inference pods don’t get them. | | `gpuCluster.gpuType` | yes, for GPU classes | GPU type of the tenant’s nodes, for example `nvidia-b300`. Used by every class that doesn’t set its own `gpuType`. | | `gpuCluster.classes` | no | Resources the tenant trains and deploys on. Each entry has `name`, `gpusPerNode`, `numNodes`, `cpu`, `memoryGib` and optionally `gpuType`; the figures are per node. Default: one class `gpu-1x1` (1 GPU, 1 node, 6 CPUs, 28 GiB). | | `onPrem.images.trainImage`, `onPrem.images.inferenceTag` | yes, from `values-example-tenant.yaml` | The training image and the inference image tag of the release’s ML bundle. Both images are in the bundle; `image.registryOverride` points the GPU cluster at your mirror. Copy them from the example of the release you install, and again on every upgrade. Without `trainImage`, bootstrap creates no resource classes and the install fails. | | `resources.` | no | Override requests and limits per component, for example `resources.api`, `resources.bootstrap`. | | `doctor.allowlist` | no | Extra hosts the self-check accepts, for an external Pulsar or OpenObserve. | | `bootstrap.rotateKey` | no | Mint a new API key on this upgrade. Default `false`. Set it back afterwards. | | `bootstrap.revokeOld` | no | With `rotateKey`, end the old key at once. Default `false`. | | `byocFee.trainingUsdPerRunHour` | no | Platform fee in USD for each hour a training run runs on the tenant’s GPU cluster, whatever its node count. It is debited from the organisation’s wallet with the run’s other costs. Default `"2.0"`; `"0"` charges nothing. Quote the value. A run keeps the rate it started with, so a change applies to runs started afterwards. | | `byocFee.inferenceUsdPerDeploymentHour` | no | Platform fee in USD for each hour a deployment is up on the tenant’s GPU cluster, whatever its node count. Default `"1.0"`; `"0"` charges nothing. Quote the value. A deployment keeps the rate it had when it last started. | | `restore` | no | Skip bootstrap, for restores. Default `false`. | With `postgres.bundled: false`, the `postgres.external.*` values replace the bundled database for the API, the workers and the migration Job. `postgres.external.database` defaults to `arena`, and `postgres.external.port` to `5432`. Give an external Postgres a `max_connections` of at least 300, as the bundled one has: during an upgrade the old and new pods run together and can open up to 242 connections. Top level: | Key | Default | Description | |-----------------------------------------------------------|---------------------------------------|-----------------------------------------------------------------------------------------------------------| | `openobserve.image.oss.repository` | `public.ecr.aws/zinclabs/openobserve` | Set to the mirrored repository, for example `registry.internal/arena/zinclabs/openobserve`. | | `pulsar.service.type`, `openobserve.service.type` | `ClusterIP` | `LoadBalancer` or `NodePort` when the GPU cluster is a separate Kubernetes cluster ([Network](#network)). | | `pulsar.advertisedAddress` | empty | For a separate GPU cluster: a name both clusters resolve to the Pulsar Service. | | `postgres.persistence.size`, `.storageClass` | `20Gi`, cluster default | Bundled Postgres volume. | | `postgres.maxConnections` | `300` | Bundled Postgres connection limit. | | `pulsar.persistence.size`, `openobserve.persistence.size` | `10Gi` | Bundled Pulsar and OpenObserve volumes. | ## Commands Operator commands run in the API pod: `kubectl -n exec deploy/arena-api -- /usr/app/arena-cli …`. | Command | Does | |------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `task doctor_outbound [allowlist:] [list:true] [gpu_cluster_down:warn]` | Checks every dependency; fails if any configured endpoint is outside the tenant, or if a GPU cluster’s agent reports an error or has stopped reporting. With `gpu_cluster_down:warn` an agent that has stopped reporting is a `warning` instead. Default allowlist `config/outbound-allowlist.txt`; the chart’s is in ConfigMap `arena-doctor-allowlist` | | `task clusters_status` | GPU cluster state, GPUs, agent version, time since the agent’s last contact, running and queued jobs | | `task smoke model: [gpu_type:] [steps:] [deploy:true] [timeout_secs:]` | End-to-end test through the partner API with its own key, which expires within 24 hours: dataset, SFT with LoRA (20 steps by default), checkpoint, metrics, export with sha256 checks, resume and stop, plus a deployment with `deploy:true`. `gpu_type` is one of the tenant’s GPU types, as the API lists them (for example `b300`); without it, submit picks. `timeout_secs` is the longest wait for training, the export, the stop or the deployment (default 3600). Removes what it created, also after Ctrl-C or SIGTERM, and exits non-zero if a step fails | | `task register_model name: path: [base:]` | Adds a base model from the tenant bucket | | `task unregister_model name:` | Removes a base model from the list | The chart runs two Jobs after every install and upgrade: | Job | Runs | Notes | |-------------------|-------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `arena-bootstrap` | `task install_bootstrap` | Creates the organisation, API key, cluster registration and resource classes. The cluster can serve the models it trains. Safe to repeat. Every run writes the release’s agent and validator images into `arena-agent-values`. Key rotation is the `bootstrap.rotateKey` value. Skipped with `restore: true`. | | `arena-doctor` | `task doctor_outbound` with the chart’s allowlist and `gpu_cluster_down:warn` | A failure fails the install or upgrade. A GPU cluster whose agent has stopped reporting is a warning. | ## Secrets Created by the install in the tenant namespace: | Secret | Holds | |--------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `arena-partner-key` | The tenant’s API key (`key`) | | `arena-agent-values` | Agent chart values (`values.yaml`) and the agent’s cluster token (`cluster-token`). The values include the token of the OpenObserve user `arena-otlp-ingest@arena.local`, which the agent adds to training metrics and logs. That token is an admin credential on OpenObserve gRPC port 5081, and that port should not be exposed beyond the agent. | | `arena-secrets-key` | Encryption key for organisation secrets. Back it up; without it, stored secrets can’t be read after a restore. | | `arena-postgres` | Bundled Postgres `username` and `password` | | `arena-openobserve-root` | OpenObserve root user | | `arena-o2-runtime` | The API’s credentials for OpenObserve | `arena-secrets-key`, `arena-postgres`, `arena-openobserve-root` and `arena-o2-runtime` are generated on first install, read back on every upgrade and kept on uninstall. If you manage tenants with Argo CD or `helm template`, create these four before the first sync: generation reads the cluster, which a template render can’t, and the chart leaves alone a Secret with one of these names that it didn’t create. Created by you: | Secret | Namespace | Holds | |-----------------------------------------|--------------------------------------------------|---------------------------------------------------------------------------------------------------------| | Store Secret (`storage.existingSecret`) | tenant | `accessKeyId`, `secretAccessKey` | | Store Secret, same name | agent, on the GPU cluster | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `endpoint`, `AWS_ENDPOINT_URL`, `APP_AWS_CLIENT_ENDPOINT` | | TLS Secret (`tls.existingSecret`) | tenant, and the same name in the agent namespace | Certificate for `domain` and `*.domain` | | `cluster-token` | agent | `cluster-token` from `arena-agent-values` | ## Network All traffic stays inside your environment. These are the connections a tenant makes: | From | To | Port | Purpose | |----------------------------------------|--------------------------|--------|-----------------------------------------------------------------------------------------------------------------------------| | Your backend | API (`domain`) | 443 | Partner API | | Your backend | Deployments (`*.domain`) | 443 | Inference | | Agent | API (`domain`) | 443 | Desired state, status | | API | OpenObserve | 5080 | Metric and log queries | | Training pods on their own broker | Their job’s Ray head | 6650 | That job’s message broker | | Training pods on their own broker | Agent (API relay) | 443 | Job commands and metric names | | Training pods without their own broker | Pulsar | 6650 | The bundled broker the job still connects to. Nothing reads it: a stop is a Ray job stop, and metric names are not recorded | | Training pods | Agent (`arena-egress`) | 443 | Metrics and logs (OTLP gRPC) | | Agent | OpenObserve | 5081 | Training metrics and logs, sent with the ingest user’s token | | Training and inference pods, API | Object store | 443 | Datasets, models, checkpoints | | Both clusters | Registry | 443 | Images | Pulsar’s admin port (8080) stays inside the control plane namespace. The token in the agent values is an admin credential on OpenObserve gRPC port 5081, and that port should not be exposed beyond the agent. When the GPU cluster is a separate Kubernetes cluster, expose Pulsar and OpenObserve to it with `pulsar.service.type` and `openobserve.service.type` (`LoadBalancer` or `NodePort`), and set `pulsar.advertisedAddress` to a name both clusters resolve: Pulsar clients connect to the address the broker returns, not the one they first dialled. In a single cluster, no extra exposure is needed. ## Sizing Requests per tenant control plane, with the bundled databases: | Component | CPU | Memory | |------------------------------------------------------------|----------|--------------| | API | 0.2 | 768 MiB | | Worker | 0.1 | 128 MiB | | Cron scheduler | 0.1 | 256 MiB | | Storage service | 0.05 | 64 MiB | | Model memory planner | 0.2 | 384 MiB | | Pulsar standalone (heap 512 MiB) and its bootstrap sidecar | 0.51 | 1040 MiB | | OpenObserve | 0.25 | 512 MiB | | Postgres | 0.5 | 1 GiB | | **Total** | **1.91** | **4.08 GiB** | These are the chart’s default requests. An idle tenant uses about 0.2 vCPU and 2 GiB. The install and upgrade Jobs add 0.25 vCPU and 512 MiB while they run. Every pod sets requests and limits; the defaults are in the chart’s `values.yaml`. Change them per component with `arena-platform.resources.`, and for Postgres, Pulsar and OpenObserve with `postgres.resources`, `pulsar.resources` and `openobserve.resources`. The GPU cluster runs the BYOC agent and its environment and reward function validators, which request about 0.4 vCPU and 1.6 GiB together, plus the pods of running jobs and deployments. Every validation of the tenant’s environments, reward functions, datasets and models runs in those validators, next to the tenant’s data. ## Supported models The catalogue of models a tenant can register, and how to print it, is in [Base models](partners/self-hosted/models.md#supported-models). ## Errors The API’s error codes and what to do about each are in [Troubleshooting](partners/self-hosted/operations.md#troubleshooting). ## Data kept by a tenant | Data | Where | |-------------------------------------------------------------------------|--------------------| | Organisations, users, experiments, deployments, keys, registered models | Tenant Postgres | | Datasets, base models, checkpoints, exported metrics | Tenant bucket | | Live metrics and logs | Tenant OpenObserve | | Job commands | Tenant Postgres | Nothing is stored or sent anywhere else. # reference/algorithms.md # Algorithms The training algorithms Arena offers, and what each one trains on. The **Agent** step of the experiment wizard lists only the algorithms that fit the dataset or environment you picked. | Algorithm | Trains on | Reward | What it does | |--------------------------------|-----------------------------------|--------------------------------------------|-----------------------------------------------------------------------------------------------------------| | **GRPO** | Reasoning dataset, environment | Your reward function, or the environment’s | Group-relative policy optimisation: scores several answers per prompt against each other. No value model. | | **GSPO** | Reasoning dataset, environment | Your reward function, or the environment’s | GRPO with sequence-level importance ratios, for steadier updates. | | **CISPO** | Reasoning dataset, environment | Your reward function, or the environment’s | GRPO with clipped importance-sampling weights, for more conservative updates. | | **PPO** (`LLMPPO`) | Reasoning dataset, environment | Your reward function, or the environment’s | Actor-critic PPO with a learned value head. Credits advantage per token or per turn. | | **REINFORCE** (`LLMREINFORCE`) | Reasoning dataset, environment | Your reward function, or the environment’s | Monte Carlo policy gradient. No value model. Credits advantage per token or per turn. | | **OPD** | Reasoning or traces dataset | Optional | On-policy distillation: the model learns from its own answers while a teacher model scores every token. | | **DPO** | Preference dataset | None | Direct preference optimisation from chosen and rejected answers. | | **SFT** | SFT, preference or traces dataset | None | Supervised fine-tuning on prompt and target pairs. | The wizard shows **PPO** and **REINFORCE**. The CLI, manifests and the Python client use the names in brackets. ## By training data | You picked | Algorithms offered | Extra setup | |--------------------|----------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------| | Reasoning dataset | GRPO, GSPO, CISPO, OPD, PPO, REINFORCE | A prompt template and a reward function, on the **Environment** step. See [Write prompts and reward functions](guides/prompts-and-rewards.md). | | Environment | GRPO, GSPO, CISPO, PPO, REINFORCE | None. For a multi-turn run, pick PPO and set advantage granularity to `turn`. | | Preference dataset | DPO, SFT | None | | SFT dataset | SFT | None | | Traces dataset | SFT, OPD | See [Train on traces](guides/train-on-traces.md). | PPO and REINFORCE have an advantage granularity setting, `token` or `turn`. On reasoning datasets the default is `token`. OPD’s teacher is either the model itself, shown a reference answer it does not see while writing, or a separate model from the catalog that shares its vocabulary. A separate teacher needs extra GPUs. With no reward function, OPD learns from the teacher alone. Setting it up is on [Train a model](guides/train-a-model.md) and [Train on traces](guides/train-on-traces.md). Every algorithm here deploys the same way and answers through **generate**. See [Inference contract](reference/inference-contract.md). ## Related - [Upload a dataset](guides/upload-a-dataset.md) - [Write prompts and reward functions](guides/prompts-and-rewards.md) - [Run spec and manifest schema](cli/manifest-schema.md) # reference/experiment-statuses.md # Experiment statuses Every experiment has a status. You see it in the project’s experiment list, in the wizard header, and in `arena experiments list`. | Status | Meaning | What you can do | |---------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------| | **Draft** | You are still setting it up. Wizard steps can be changed. | **Train** once the setup is complete | | **Pending** | Submitted and waiting to start. While it waits, the status shows how far its cluster has got (see below). | **Stop training** | | **Queued** | Submitted, but waiting for GPUs: the resource class’s machines are busy, or older runs are ahead of it. It goes back to **Pending** once GPUs are reserved. Lists usually show it as **Waiting for capacity**. | **Stop training** | | **Running** | Training. | **Stop training**, watch metrics and logs | | **Stopping** | You stopped it and the job is shutting down. | Wait for **Stopped** | | **Stopped** | Stopped before it finished. | **Resume**, view results | | **Succeeded** | Training finished. | View results, deploy, **Resume** | | **Failed** | Training failed or never started. The failure reason says why. | Read the logs, **Duplicate**, **Resume** | Once an experiment leaves **Draft**, its wizard steps are locked. To change settings, duplicate it from the row menu. **Resume** appears on a **Stopped**, **Succeeded** or **Failed** experiment that saved at least one checkpoint. How to stop and resume a run is on [Monitor, halt and resume](guides/monitor-halt-resume.md). ## While a run starts A **Pending** or **Queued** run shows one of these in the experiment list and in `arena experiments list`. Apart from the first three, they are stages of the run’s training cluster. They are not experiment statuses, and the cluster’s **Deployed** has nothing to do with a deployed agent. | Shown | Meaning | |---------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **Waiting for capacity** | The run is **Queued**, or no GPUs are free for its resource class yet. It starts on its own when they are. | | **Waiting for cluster upgrade** | On a BYOC class: Arena is upgrading the cluster’s agent. The run starts on its own when the upgrade finishes, or after 70 minutes if it does not. | | **Queued** | On a BYOC class: the cluster’s agent upgrade just finished. Arena’s next queue check starts the run when the class has room, and otherwise shows **Waiting for capacity** again. | | **Scheduled** | GPUs are reserved and the machines are being created. | | **Starting** *gpu* **GPUs** | On your own cloud cluster, the run’s machines are being created and are starting up. Once the machines exist and enough runs have been measured, it adds \*\*(~\*\**N* **min)**: how long recent runs on that class took from there to start. | | **Deployed** | The cluster is up and the training job is starting. | | **Running** | The cluster is running the job. The experiment’s own status turns **Running** shortly. | ## Why a run fails before it starts A run that never started is not charged. These end in **Failed** with the reason shown: - **The machines cannot be created**, for example a cloud quota is exceeded or the resource class has no enabled region. The run fails at once. - **No capacity for 24 hours.** A run still waiting for GPUs 24 hours after you submitted it fails. - **No progress for 60 minutes** on your own cloud cluster. The reason names the last step it reached, and its machines are deleted. - **The container image cannot be pulled for 10 minutes** on Arena cloud, for example `The run's head node could not pull its container image (ImagePullBackOff)`. Its machines are released. ## Related - [Monitor, halt and resume](guides/monitor-halt-resume.md) - [Choose compute](guides/choose-compute.md) - [Troubleshooting](reference/troubleshooting.md) # reference/glossary.md # Glossary Words Arena uses across training, billing and deployments. | Term | Meaning | |--------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **Organization (org)** | Your workspace: projects, data, agents, secrets, members and a balance. You can belong to several and switch between them from the profile menu. See [Profile and organizations](account/account.md). | | **Admin** and **Member** | The two roles in an organization. **Admins** handle billing, members and bring your own compute. | | **Project** | Holds experiments and pipelines. | | **Experiment** | A training setup (data or environment, base model, algorithm, settings and GPUs) together with the one training run it starts. Resuming creates a new experiment. It has a [status](reference/experiment-statuses.md). | | **Run** | The training an experiment does once you click **Train** or run `arena experiments submit`. Charged while its machines exist. | | **Manifest** | A YAML file that describes an experiment for `arena experiments submit`. See [Run spec and manifest schema](cli/manifest-schema.md). | | **Environment** | Code that the model interacts with during training, for multi-turn and tool-use tasks. Arena environments implement **OpenEnv**. | | **OpenEnv** | The interface Arena environments implement: training drives the environment through reset and step calls. Uploaded environment code must serve it. | | **Dataset** | Training data in one of four types: reasoning, preference, SFT or traces. See [Upload a dataset](guides/upload-a-dataset.md). | | **Reward function** | Python that scores the model’s answers during reinforcement learning. See [Write prompts and reward functions](guides/prompts-and-rewards.md). | | **Checkpoint** | Saved model weights from a run. Used to resume training or deploy an agent. | | **Agent** | A trained model deployed from a checkpoint so you can call it. Listed under **Agents** in the sidebar. The CLI’s `arena agent` commands also call it a deployment. | | **Agent** step | The wizard step where you pick the algorithm and the base model. It doesn’t create an agent. | | **Agent (BYOC)** | The service you install into a BYOC cluster, with its own agent token. It runs training jobs on the cluster for Arena. See [Install a BYOC cluster](compute/install-byoc-cluster.md). | | **Coding agent** | A tool such as Claude Code, Cursor or Codex that runs `arena` commands for you. See [Using Arena from a coding agent](cli/coding-agents.md). | | **Deployment status** | Where an agent is in starting up: **Not deployed**, **Copying**, **Deploying**, **Deployed**, **Stopped** or **Deployment failed**. See [Inference contract](reference/inference-contract.md). | | **Resource class** | A kind of machine a run can use: GPU type, region, and Arena cloud or your own compute. In the wizard you pick a GPU type and count in the **Training resources** bar and Arena picks the class. See [Choose compute](guides/choose-compute.md). | | **Bring your own compute (BYOC)** | An **Enterprise** feature: train on Kubernetes you run yourself or in your cloud. See [How BYOC works](compute/byoc.md). | | **Snowflake training** | Training and serving a model inside your own Snowflake account with the Arena Native App. Data and weights stay in the account. See [Snowflake Native App](compute/snowflake-native-app.md). | | **Balance** | Credits the organization spends on training, deployments and storage. Shown as **Credits** in the profile menu. See [Billing and credits](account/billing.md). | | **Pay as you go** and **Enterprise** | The two ways to pay. Pay as you go spends a prepaid balance. Enterprise is a contract. | | **Organization secret** | An API key or token stored for the organization, which training jobs read as an environment variable. See [Organization secrets](account/account.md#organization-secrets). | | **`ARENA_API_KEY`** | Your personal CLI key (it starts with `arena_pat_`). Created under **Settings** → **Profile management**. See [CLI API key](account/account.md#cli-api-key). | # reference/inference-contract.md # Inference contract What a deployed agent’s statuses mean, when it is billed, and what its endpoint accepts. How to deploy is on [Deploy an agent](guides/deploy-an-agent.md). How to call it is on [Invoke an agent](guides/invoke-an-agent.md). ## Deployment statuses The agent card on **Agents** and the header of the agent’s page show the same status, with two differences: a failed deploy reads **Deployment failed** on the card and **Failed** in the header, and on your own cluster the card reads **Copying** while the header reads **Deploying**. | Status | What it means | What to do | |------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------| | **Not deployed** | Inference is off. It has not been started. | **Connect** on the card, or **Deploy** on the agent’s page | | **Copying** | On your own cluster, the checkpoint is being copied. | Wait. **Disconnect** on the card or **Cancel** on the agent’s page stops it. | | **Deploying** | Inference is starting. On Arena cloud this includes copying the checkpoint. | Wait. **Disconnect** or **Cancel** stops it. | | **Deployed** | Inference is up. The agent’s page shows the endpoint and code snippets. | Call it. **Disconnect** or **Stop agent** turns it off. | | **Stopped** | Turned off while starting or running: you disconnected it, an Arena admin stopped it, or the organization’s balance could not cover the next hour. | **Connect** or **Deploy** starts it again | | **Deployment failed** / **Failed** | The deploy, or a later health check, failed. The agent’s page shows the reason. | Fix the cause, then **Connect** or **Deploy** to try again | Going from **Deploying** to **Deployed** usually takes a minute and a half or more, longer for large checkpoints. A **Deployed** agent goes back to **Deploying** if Arena finds its endpoint unreachable. That usually clears by itself. On Arena cloud, while no GPU machine is free for the deployment, the card shows **Waiting for capacity**. Arena keeps trying for up to 24 hours, and that time isn’t charged. Once a machine runs the deployment, it has 90 minutes to become healthy, counted from when the machine arrives. If it isn’t healthy by then, it is stopped, marked failed, and you get a notification. If it was **Deployed** for less than 30 minutes before it fell back to **Deploying**, it keeps counting from when it first started waiting. Thirty minutes or more of **Deployed** starts the count over. On your own cluster there is no time limit. ## Billing An agent is billed by the hour only while it is **Deployed**. **Copying** and **Deploying** are free. See [Billing and credits](account/billing.md). ## Calling the endpoint Every agent Arena trains is a language model, and it answers on one path: **generate**, appended to the **Endpoint** shown on the agent’s page. The chat playground uses the same path. Once the agent is **Deployed**, its page has a **Chat Playground** and three snippet tabs: | Tab | Use it for | |------------------|------------------------------------------------| | **Arena client** | Python, with `ArenaClient` from `agilerl` | | **Arena CLI** | The shell: `arena agent generate` | | **Manual HTTP** | Any HTTP client. The snippet has the full URL. | All three sign in with `arena login` or `ARENA_API_KEY`. A manual request sends the key as a `Bearer` token in the authorization header. A generate request takes: - `session_id`: a name for the conversation. Requests with the same `session_id` share its history. A request without one is refused with a 422 error. - `prompts`: one prompt or a list of prompts. - `params`, optional: `max_new_tokens`, `temperature`, `top_p` and `do_sample`. The reply has one result per prompt, each with its `prompt` and `completion`. Copy the snippet from the agent’s page rather than building the URL yourself. While an agent is not **Deployed**, its page shows no endpoint. # reference/troubleshooting.md # Troubleshooting Find what you see below, then follow the fix. ## Training will not start **Train is turned off, or a submit is refused for balance.** On Pay as you go you cannot start a run once the balance is `$10.00` or less. Check the balance under **Credits** in the profile menu, or run `arena user credits`. An **Admin** adds balance under **Settings** → **Billing**. See [Billing and credits](account/billing.md). **Next or Save is blocked in the wizard.** The current step has a problem: no GPUs picked, no dataset or environment, an invalid algorithm field, or a reward function that has not passed its check. The message on screen names it. See [Train a model](guides/train-a-model.md). **Train is missing on the summary.** The experiment is not complete yet. Go back through the steps until each one saves. **The algorithm you want is not offered.** The list depends on the dataset or environment you picked. See [Algorithms](reference/algorithms.md). **A run fails at once with a quota or region message.** Its machines could not be created. The failure reason says why, and you are not charged. See [Experiment statuses](reference/experiment-statuses.md#why-a-run-fails-before-it-starts). ## A run is waiting **Waiting for capacity.** No GPUs are free for the run’s resource class. It starts by itself when they are. You can stop it and pick another GPU type in [Choose compute](guides/choose-compute.md). A run that is still waiting after 24 hours fails and is not charged. **Scheduled, or Starting GPUs.** The machines are being created. Wait; the run moves on by itself. On your own cloud cluster the status shows how long it usually takes once enough runs have been measured. **Waiting for cluster upgrade.** Arena is upgrading the agent on your BYOC cluster. The run starts by itself when the upgrade finishes, or after 70 minutes if it does not. **Waiting longer than you expect on your own cluster.** Check that a node matches the class’s placement labels: the cluster’s **Health** names any class under **Classes with no matching nodes**. Run `arena cluster smoke` to test that the cluster can start a job. See [BYOC troubleshooting](compute/install-byoc-cluster.md#troubleshooting). **Your BYOC cluster shows Degraded, or a health check shows Failing.** See [BYOC troubleshooting](compute/install-byoc-cluster.md#troubleshooting). **An Update badge on a BYOC resource class.** The image stored on the class is behind the current training image. Jobs still run the current image, and **Reinstall** leaves the badge in place. See [Resource classes](compute/resource-classes.md#change-or-remove-a-class). To cancel a waiting run, use **Stop training** from the row menu, or `arena experiments stop`. All statuses are on [Experiment statuses](reference/experiment-statuses.md). ## A run failed or stopped **Find out why.** Open the row menu and click **View logs**, or run `arena experiments status` and `arena experiments logs`. The failure reason says whether it was your code, data or settings, or an error on Arena’s side. Runs that fail on Arena’s side are refunded. **A running job stopped on its own.** On Pay as you go, running jobs stop when the balance falls below `$5.00`. Add balance and resume. **Resume is missing.** **Resume** needs a saved checkpoint and a **Stopped**, **Succeeded** or **Failed** run. See [Monitor, halt and resume](guides/monitor-halt-resume.md). **No metrics on the results page.** Charts fill in once the run is **Running**. See [Results and checkpoints](guides/results-and-checkpoints.md). ## Environments and datasets **An environment version fails validation.** The error shows on the version. Fix the code or dependencies and validate again. See [Validate and profile an environment](guides/validate-an-environment.md). **You cannot train on an environment yet.** It needs a validated version and a finished profile. Profiling takes about fifteen minutes. **A dataset upload is rejected.** Each dataset type has its own columns. Check the format for your type on [Upload a dataset](guides/upload-a-dataset.md). ## Agents **Stuck on Deploying.** Starting inference usually takes a minute or two, longer for large checkpoints. On Arena cloud, a deployment first waits for a free GPU machine (**Waiting for capacity**, up to 24 hours, not charged), then has 90 minutes from the machine’s arrival to become healthy. If it doesn’t, it fails and you get a notification. **Deployed, then back to Deploying.** Arena found the endpoint unreachable and is bringing it back. If the card turns **Deployment failed**, read the reason on the agent’s page, then **Connect** or **Deploy** again. **Stopped without you stopping it.** The balance could not cover the next hour, or an Arena admin stopped it. Add balance, then deploy again. **Calls fail or return nothing.** Check the agent is **Deployed**, and copy the snippet from the agent’s page. See [Invoke an agent](guides/invoke-an-agent.md) and [Inference contract](reference/inference-contract.md). ## CLI **A command fails with a sign-in error.** Run `arena login` again. If `ARENA_API_KEY` is set, the CLI uses it instead, so check it has not been rotated or revoked. See [Install and sign in](cli/install.md). **A judge or job cannot find an API key.** The job reads organization secrets by name. Check the name in your manifest matches one in `arena secrets list`. See [Organization secrets](account/account.md#organization-secrets). ## Account and organization **You cannot invite members or add balance.** Only an organization **Admin** can. Ask an **Admin** to do it, or to make you one. See [Profile and organizations](account/account.md#roles). **You see someone else’s projects, or not your own.** Data belongs to one organization at a time. Use **Switch organisation** in the profile menu. **Bring your own compute classes are missing in the wizard.** Your organization needs to be on **Enterprise**, and an **Admin** needs to connect a cluster and switch its resource classes **On**. The cluster must be **Connected** and not disabled, and each class needs at least one GPU per worker. See [Resource classes](compute/resource-classes.md). If none of this matches, contact AgileRL support with your organization, the experiment or agent name, and the status you see.