# Lium — Full Reference for Agents Self-contained reference for AI agents. Includes skill overview, CLI command reference, and Python SDK reference. Source of truth: https://github.com/Datura-ai/lium-skill --- # Lium CLI & SDK Lium — agent-first compute: a GPU rental platform. Pods are Docker containers with root SSH access and direct GPU passthrough. - **GitHub**: https://github.com/Datura-ai/lium - **PyPI**: https://pypi.org/project/lium.io/ - **Docs**: https://docs.lium.io - **Dashboard**: https://lium.io > **Covers lium CLI and SDK 0.20.0** (released 2026-10-17) · **last updated 2026-10-18**. Older installs: `pip install -U lium.io`, and check yours with `lium --version`. ## Quick Install Standalone binary — no Python or dependencies required: ```bash curl -fsSL https://raw.githubusercontent.com/Datura-ai/lium/main/scripts/install.sh | bash ``` This auto-detects OS (Linux/macOS) and architecture, downloads the binary to `~/.lium/bin/lium`, and adds it to PATH. After install, authentication depends on whether the user has a Lium account: - **No account, and no mailbox you can read** → **fingerprint signup**: one call to `POST /auth/signup`, no email, no password, no confirmation link. This is the fully autonomous path — see "No Account Yet — Sign Up". - **No account, but a human is there to click a confirmation link** → `lium signup --email ` — same section. Do not send the user to the web signup form. - **Has an account** → `lium init` (opens a browser) or `lium init --no-browser` for headless/agent use — see "Authentication Setup for Agents". ```bash curl -fsS -X POST https://lium.io/api/auth/signup \ -H 'Content-Type: application/json' -d '{}' # no account, no mailbox lium signup --email ada@example.com # no account, human can confirm lium init # existing account, browser lium init --no-browser # existing account, headless ``` Verify setup: ```bash lium balance # prints a balance -> auth works; prints an error -> it does not ``` ### Alternative Install (via pip/uv) ```bash # Via uv (isolated env) curl -LsSf https://astral.sh/uv/install.sh | sh uv tool install lium.io # Via pip pip install lium.io ``` ## Agent-Specific: Non-Interactive Usage **CRITICAL**: Many lium commands are interactive by default. As an agent, always pass all parameters explicitly to avoid interactive prompts. ### No Account Yet — Sign Up `lium init` authenticates a user who **already has an account**. To create one, ask a single question — **can anyone read the mailbox?** No: fingerprint signup, one call, fully autonomous. Yes: `lium signup --email `. Only create an account when the user asks for one. Never invent an email address and never use a disposable inbox to fake the email path — when there is no mailbox, sign up with a fingerprint. #### Fingerprint Signup — No Email, Fully Autonomous A **fingerprint** here is a 32-character random string Lium mints as the account credential — not a passkey, not WebAuthn, not biometrics, not a device fingerprint. Nothing is scanned. One HTTP call completes the signup, so "I cannot sign up without a human" is wrong. ```bash # empty body — Lium names the account itself (lium_a1b2c3) curl -fsS -X POST https://lium.io/api/auth/signup \ -H 'Content-Type: application/json' -d '{}' # {"user_id":"...","username":"lium_a1b2c3","fingerprint":"<32 chars>", # "api_key":"sk_...","signup_credit_granted":true|false} # when api_key is a string, store it and continue — no confirmation step in between lium config set api.api_key sk_... lium ls ``` - `api_key` can be `null` — minting it is allowed to fail without failing the signup. When it is `null`, stop before configuring the CLI: sign in with the fingerprint and mint a key on the dashboard. - `fingerprint` is the **dashboard login** at https://lium.io/login and the **only** recovery path — Lium stores just a hash. It is returned **exactly once** and nobody, support included, can look it up. Hand it to the user for their password manager, and treat it like a password: never paste it into a pod, a log, a commit or a ticket. Workloads use the API key instead. - `signup_credit_granted` says whether the credit landed — do not promise $5 before reading it. It is `false` when the platform has the credit off, and when this IP already signed up once. Send `{}`. The optional `username` is a display name only — it is not part of the login, the web form never asks for one, and requesting a taken name fails with `409`. Rate limit per IP: 5/min, 20/day. There is no CLI flag yet — `lium signup` is the email path only. Full walkthrough: https://docs.lium.io/pod-users/fingerprint-signup #### Email Signup — `lium signup` When a human can confirm the address, `lium signup` does the whole cold start — no browser, no dashboard, no web form: ```bash lium signup --email ada@example.com # creates the account, stores the API key lium ls # browse machines lium up -y # rent lium ssh # connect ``` Ask for their **real email** first — the account, its balance and password recovery are tied to it, and the confirmation link is sent there. `lium signup` prints the generated password — hand it to the user, it is their dashboard login (to choose one instead, pass `--password` or set `LIUM_SIGNUP_PASSWORD`, which keeps it off argv). Even when the command fails after the account was created — a timeout, or the API key could not be read back — the error still reports the email and password, so the account is never stranded. Add `--json` for a machine-readable `{email, password, api_key, signup_credit_granted, ssh_key_configured, next_steps}`. The key is written to `~/.lium/config.ini`, so the account is then indistinguishable from one set up with `lium init`. Older binaries do not have the command. Probe for it, and update when it is missing: ```bash lium --version # diagnostics only — probe the command itself below lium signup --help >/dev/null 2>&1 || echo "CLI too old — update it" # Binary install (installed via install.sh): auto-updates on launch, or force it curl -fsSL https://lium.io/install.sh | bash # pip / uv install uv tool upgrade lium.io # or: pip install -U lium.io ``` On an older CLI that cannot be updated, the same signup is three HTTP calls: ```bash BASE=https://lium.io/api # No mailbox to confirm? Use the fingerprint signup above instead of steps 1-3. # 1. Create the account. An API key named "Default" is minted server-side here; current # backends return it in the response — {"msg": "success", "api_key": "sk_...", # "signup_credit_granted": true|false} — older ones mint it without returning it. curl -sX POST $BASE/users -H 'Content-Type: application/json' \ -d '{"name":"Ada","email":"ada@example.com","password":"..."}' # 2-3. Only when the response had no api_key: log in for a JWT, read the key back (format sk_...). TOKEN=$(curl -sX POST $BASE/users/login -H 'Content-Type: application/json' \ -d '{"email":"ada@example.com","password":"..."}' | jq -r .token) KEY=$(curl -s $BASE/keys -H "Authorization: Bearer $TOKEN" \ | jq -r '.[] | select(.name=="Default") | .key') lium config set api.api_key "$KEY" # leave ssh.key_path unset — the CLI generates and configures the key on first use, # and setting the path to a key that does not exist yet makes it skip that ``` ### Before the First Rental — Balance `lium up` calls `POST /executors/{executor_id}/rent`, and the balance is the only gate: a fresh account can rent as soon as it is funded, email confirmed or not. Map the error to the action: | 403 on rent | Meaning | Action | |---|---|---| | `"Insufficient balance"` | The account balance is zero. | Fund the account — see "Funding options" below. | #### Email confirmation Confirming the address does not gate renting. It confirms the address itself, so that password resets and account emails reach the user. Registration sends **two** mails: `"Welcome to Celium!"` (no link in it) and `"Please confirm your email"` — only the second one carries the link. Point the user at that subject, and ask them to click the link. That is the normal path. Two endpoints on `https://lium.io/api` cover the cases where it does not work. Neither needs auth; both take JSON: ```bash # Mail never arrived / link expired (tokens are valid 24h) — send a fresh one curl -sX POST https://lium.io/api/auth/resend-verify-email \ -H 'Content-Type: application/json' -d '{"email":"ada@example.com"}' # 400 "User doesn't exist." or "Email is already verified." when it does not apply # User pastes the link instead of clicking it — finish verification from its ?token= curl -sX POST https://lium.io/api/auth/verify-email \ -H 'Content-Type: application/json' -d '{"token":""}' ``` #### The $5 signup credit The signup credit is $5 when the platform has it enabled **and** no other account has signed up from this IP address — nothing about the email domain matters. Do not explain a `403 "Insufficient balance"` with the credit: that error only says the balance is zero, and the answer to it is to fund the account. Whether it landed is answered by `signup_credit_granted` in the signup response (also in `lium signup --json`): `true` → granted, `false` → not granted. When it is `null` or absent — the backend does not report it — read the balance: ```bash lium balance --json # {"balance_usd": 5.0} ``` #### Funding options - Dashboard: https://lium.io/billing - Headless invoice: `POST /tmc-pay/create-invoice` with header `X-API-Key: sk_...` and a body of `{"amount": , "crypto_currency": "...", "crypto_network": "..."}` (all three required). Valid currency/network pairs come from `GET /tmc-pay/currencies` (same API key header). The response carries `deposit_address`, `crypto_amount`, `hosted_invoice_url` and `expires_at` — give these to the user to pay from their wallet, do not move funds on their behalf. ```bash # {"currencies": [{"code": "USDT", "network": "tron", ...}, ...]} — pick a pair from here curl -s https://lium.io/api/tmc-pay/currencies -H "X-API-Key: sk_..." curl -sX POST https://lium.io/api/tmc-pay/create-invoice -H "X-API-Key: sk_..." \ -H 'Content-Type: application/json' \ -d '{"amount": 20, "crypto_currency": "USDT", "crypto_network": "tron"}' ``` - `lium fund -w default -a 10.0 -y` for users with a TAO wallet — here `-a` is an amount of **TAO**, not dollars. `-a` means USD only on the `--alpha` path, which moves alpha the user already has staked: `lium fund --alpha -k -a 10 -y`. SSH keys need no extra registration — the public key at `ssh.key_path` is registered server-side right before renting. ### Authentication Setup for Agents For a user who already has an account (skip if you just ran the signup flow above and stored the key). **Preferred: two-step headless auth** — no API key needed, no blocking, no browser: 1. Run `lium init --no-browser` — get auth URL and session ID (exits immediately) 2. Show the URL to the user, ask them to open it and click Approve 3. Wait for user to confirm they approved 4. Run `lium init --session ` — saves API key + sets up SSH ```bash lium init --no-browser # [i] Open this URL to authenticate: # https://lium.io/cli/approve/xJinnT3Vt6... # [i] Then complete authentication with: # lium init --session abc123def456 # ... user confirms they approved ... lium init --session abc123def456 # [✓] API key saved ``` **Fallback options** (if `--no-browser` is unavailable or user already has an API key): ```bash # Option 1: Direct config lium config set api.api_key YOUR_API_KEY lium config set ssh.key_path ~/.ssh/id_ed25519 # Option 2: Environment variable (session only) export LIUM_API_KEY=YOUR_API_KEY ``` For fallback options, the user must get an API key from https://lium.io Account Settings. ### Verify Setup ```bash lium balance # prints a balance -> auth works; an error -> it does not ``` Do not run `lium config show` (or `lium config get api.api_key`) to check the setup: both print the API key in full, and anything an agent prints ends up in its transcript and logs. `lium balance` proves the key works without ever showing it. If you must confirm where the key is stored, check that `~/.lium/config.ini` exists. ### Non-Interactive Pod Creation Always use `-y` flag and pass all parameters. Add `--no-ssh` too: without it a successful `lium up` ends by opening an interactive SSH session, which stalls an agent (`--image` mode streams container logs instead). ```bash # WRONG (interactive): lium up # one confirmation prompt before renting lium up 1 # same — the prompt is the acquire confirmation # RIGHT (non-interactive): lium up --gpu H100 -y --no-ssh # auto-selects node + default template lium up --gpu A100 -c 2 --country US -y --no-ssh # with filters lium up --gpu H100 --name my-pod --ttl 6h -y --no-ssh # with name and auto-termination lium up --gpu A6000 --image pytorch/pytorch:2.0 -y # custom docker image (streams logs) lium up --gpu H100 --jupyter -y --no-ssh # with Jupyter lium up --gpu H100 -c 8 --name train --ttl 6h --verify-gpus --strict-gpus -y --no-ssh # checks billed + nvidia-smi GPU counts; removes the pod on a mismatch ``` Rent by spec, not by id: `lium up --gpu [-c N] [--country CC]` (and, since 0.0.39 (lium#209), `Lium.rent(gpu_type=, gpu_count=, min_cpus=, min_vram_gb=, max_price_per_gpu_hour=, …)` in the SDK) **picks a matching node and rents it in one call**. The backend route that picks the cheapest is live (`GET /version` lists `rent_by_spec`); since 0.0.39 (lium#209) `lium up --gpu` and `Lium.rent` use it; 0.0.37/0.0.38 do not call it and pick locally (the first Pareto-optimal row of `ls()`, not the cheapest). Do not `lium ls` first and rent the first row yourself: it is neither the cheapest nor guaranteed still free. On a 0.0.37/0.0.38 SDK, which has no `rent()`, `ls()` + `up(executor_id=)` is the only path — pick by `price_per_hour`, not the first row (example in `references/sdk-reference.md`). `lium up` exits 0 only when the pod is running (and, with `--verify-gpus`, when the GPU counts agree). It exits 1 **with the pod still running and billing** when its `--timeout` (default 900 s) runs out while the pod is starting (`pod_not_ready`) or when the GPU count is wrong and `--strict-gpus` was not given (`gpu_count_mismatch`). After any non-zero exit: `lium ps --format json`, and `lium rm -y` if a pod is listed. ### Before You Rent 8 GPUs — Check Interconnect and Ingress First A multi-GPU listing does not tell you how the GPUs are wired together or how fast the node pulls from the internet. Both decide whether a tensor-parallel / FSDP job runs at all and how long the weights take to arrive. Check them in the first minute of the rental, before any download or launch, and delete the pod if they are wrong. ```bash lium exec "nvidia-smi topo -m; nvidia-smi topo -p2p r" ``` Read `topo -m`: every off-diagonal GPU cell must be `NV#` (e.g. `NV18` on H100/H200, `NV12` on A100) for a proper HGX board. `PIX`/`PXB`/`PHB`/`NODE`/`SYS` means PCIe — several times slower for NCCL collectives. Read `topo -p2p r`: every off-diagonal cell must be `OK`; `NS` everywhere means peer-to-peer is disabled (seen on virtualised 8× H200 hosts), and NCCL fails on its first all-reduce with `unhandled cuda error` / `operation not supported`. Decision rule for TP/FSDP jobs: all `NV#` and all `OK` → proceed. Anything else → `lium rm -y` and pick another node. If the job must run there anyway, NCCL only works over loopback sockets, and TP=8 serving of a large model is impractical. Each `lium exec` is a fresh SSH session, so a bare `export` in one call is gone in the next; pass the variables with `-e` on the call that runs the job: ```bash lium exec -e NCCL_P2P_DISABLE=1 -e NCCL_SHM_DISABLE=1 -e NCCL_IB_DISABLE=1 -e NCCL_SOCKET_IFNAME=lo "python train.py" # virtualised host without RDMA NICs ``` One independent process per GPU (batch inference, best-of-N generation, sweeps) does not need the interconnect and runs at full speed on any eight cards. Ingress: the **Download (Mbps)** column in `lium ls` is a smoothed average of Lium's VerifyX check, which fetches a real object of known size and hash (the speed-test average is the fallback when VerifyX has no figure; **Upload** follows the same order). It flags nodes under 100 Mbps as slow; it does not predict Hugging Face or PyPI throughput. The same 756 GB checkpoint pulled at 2.6–4 GB/s, 1.04 GB/s and 45–200 MB/s on three nodes listed in the same few-hundred-Mbps band. Measure before committing: ```bash lium exec "curl -o /dev/null -sS -w '%{http_code} %{speed_download}\n' 'https://speed.cloudflare.com/__down?bytes=50000000'" # HTTP code, bytes/s (>= 100 MB is refused with 403) lium exec "curl -L -o /dev/null -sS --max-time 20 -w '%{http_code} %{speed_download}\n' https://huggingface.co/openai-community/gpt2/resolve/main/model.safetensors" # same for the Hugging Face CDN; -L follows the redirect, 20 s cap, nothing written to disk ``` Do the arithmetic: bytes to download ÷ measured bytes/s. At 45 MB/s a 750 GB checkpoint is 4.6 h of idle GPU billing; at 1 GB/s it is 12.5 min. Uplink varies as much (30 KB/s vs 0.5 MB/s seen) — push results from the pod to Hugging Face / S3 directly rather than through the controlling machine. The listing carries an NVLink verdict, and `lium ls` / `lium describe` show interconnect and ingress with a **Link** column; `--nvlink` filters for it. On an older CLI without the **Link** column, these commands are the check. ### Non-Interactive Funding ```bash # WRONG (interactive): lium fund # RIGHT: lium fund -w default -a 10.0 -y # fund 10 TAO, skip confirmation ``` User must have a verified TAO wallet at https://lium.io/billing. No TAO? Two paths that need no browser on your side *(0.16.1)*: ```bash lium topup create -a 20 -c USDT -n tron --json # stablecoin: send exactly crypto_amount to deposit_address lium topup link -a 10 --wait 900 --json # card: hand the printed Stripe Checkout url to a person; waits for the credit lium topup wait --above 0 --timeout 900 --json # resume waiting (exit 3 credit_not_seen on time-out) ``` `topup link` needs a key with the `billing` scope (`LIUM_BILLING_API_KEY`, or `lium signup --billing-key`). ### Agent Gotchas / Known Pitfalls #### After Install — Export PATH ```bash export PATH="$HOME/.lium/bin:$PATH" # needed in current shell session ``` #### After `lium init --session` — Verify with `lium balance` After completing the two-step auth, run `lium balance` to verify: a balance means the key works; an error with exit `3` means it does not. `lium ls` returns results with any key (the node list is public), so it proves nothing about the key. #### Exit Codes Hold Since 0.0.31 — Still Read the Output Since lium **0.0.31** every command exits non-zero when it fails (table in `references/cli-commands.md` § Exit Codes): `lium ps` with a revoked key exits `3`, a 403 exits `6`, and `lium ssh no-such-pod-xyz` exits `5`: ```bash lium ssh no-such-pod-xyz # prints "No active pods" (or "Pod '…' not found"), exits 5 lium rm pod-a,pod-b -y # one refused by the API: "Removed 1 pod(s): pod-a" / "Failed to remove pods: pod-b", exits 1 ``` Two things `$?` alone does not tell you: a batch (`rm`, `reboot`, `scp`, `rsync`) finishes the batch and exits `1` naming the items that failed — read the line to learn which — and an empty result is a success (`lium ls --format json` prints `[]` and exits `0` when no node matches). Prefer the machine-readable modes (`lium ls --format json`, `lium ps --format json`, `lium exec --json`) and check the result there: `--json` commands put a failure on stderr as one JSON object, `{"ok": false, "error": {...}}`, with stdout empty; `--format json` prints `Error: ...` as text. Releases before 0.0.31 printed `Error: ...` and exited `0` on most failures; pin `lium>=0.0.31` when a script branches on `$?`. #### Pod Targeting — Prefer Names Use the pod **name** (e.g. `lunar-lion-4c`) from `lium ps` output for targeting — not a numeric index. An index is resolved against the last `lium ps` **in this shell** and refused with `stale_pod_index` when that listing is missing, older than 10 minutes, or no longer shows that pod. #### `-y` Exists on the Destructive Commands `lium rm`, `lium up`, `lium fund`, `lium volumes rm`, `lium bk set/rm/restore` all take `-y, --yes`. A piped `yes` is not approval — always pass `-y`: ```bash lium rm my-pod -y # non-interactive lium rm -a -y # remove all pods non-interactively lium rm my-pod # without a terminal: names the pod, exits 2, removes nothing ``` #### Templates - Without `--template_id` or `--image`, `lium up` uses default **PyTorch (CUDA)** template — fastest to start - Default Docker-in-Docker (dind) template image: `daturaai/dind` - Search templates: `lium templates pytorch` (text search; the table has **no id column**; since 0.0.39 (lium#217) `lium templates --format json` / `--json` prints the ids) - To get a template id: `curl -s https://lium.io/api/templates -H "X-API-Key: $LIUM_API_KEY" | jq -r '.[] | "\(.id) \(.docker_image):\(.docker_image_tag)"'` or `python -c "from lium.sdk import Lium; [print(t.id, t.docker_image, t.docker_image_tag) for t in Lium().templates('pytorch')]"` - To use specific template: `lium up --gpu H100 -t -y` - To use custom Docker image: `lium up --gpu H100 --image pytorch/pytorch:2.0 -y` #### Which Key Am I Using — `lium whoami` `lium whoami` *(0.16.1)* prints the API key in use (fingerprint and where it came from: `LIUM_API_KEY` or `~/.lium/config.ini`), the account, the balance, the SSH key and the CLI version — run it first when a command answers 401, or acts on the wrong account (`lium whoami --json | jq .account_id`). On older CLIs there is no renter-side `whoami` (`lium provider portal whoami` is the *provider* portal session); there, run `lium balance`: it prints a balance when the key works and, since 0.0.31, exits `3` when the key is bad or revoked. Do **not** use `lium ls` for this: the node list is public, so it succeeds with any key. #### Long-Running Commands Over SSH `lium exec` runs the command in the foreground and returns only when **every process still holding its stdout/stderr** has exited — a job started with a bare `&` keeps `exec` blocked, and a long-running `exec` can also stall when the SSH session drops. Detach anything that runs longer than a minute (installs, model downloads, training, servers), then poll a log file: ```bash # Start detached: new session (setsid), immune to hangup (nohup), stdin closed, output to a file. # (\$! is escaped for the local shell; the remote prints the background PID.) lium exec my-pod "mkdir -p /workspace/logs && nohup setsid bash -lc 'pip install vllm' > /workspace/logs/install.log 2>&1 < /dev/null & echo PID=\$!" # Poll — do not `tail -f` through exec, it never returns lium exec my-pod "tail -n 20 /workspace/logs/install.log" lium exec my-pod "kill -0 && echo running || echo finished" ``` `lium logs my-pod --follow` streams the container's PID 1 output only — it does not show processes you started via `exec` unless they write to `/proc/1/fd/1`. `lium exec my-pod --detach "python train.py"` *(0.16.1)* does this for you and prints the PID and log path. #### Stopping a Remote Job — Never `pkill -f` From a One-Liner Inside `lium exec` (and any `ssh host bash -c '…'` one-liner) the whole command is the invoking shell's own command line, so `pkill -f "python train.py"` matches that shell too and kills the session before or instead of the job — the call returns a broken pipe and the job may still be running (two agents lost sessions this way on the same day). Stop jobs by PID: write one when you start (`… & echo \$! > /tmp/job.pid` — escaped, like every `$` inside a double-quoted `lium exec "…"`, or the local shell expands it to nothing and the pod gets an empty PID file) and stop with `kill \$(cat /tmp/job.pid)` as below. If you must search by name, list first and exclude your own shell and its parent, then kill the PIDs you inspected: ```bash lium exec my-pod "kill \$(cat /tmp/job.pid)" # preferred lium exec my-pod "pgrep -f 'python train.py' | grep -vx -e \$\$ -e \$PPID" # inspect, then kill ``` #### PEP 668 on Default PyTorch Template The default `daturaai/pytorch` image is based on Ubuntu 24.04 where system `pip` is PEP 668 protected (`externally-managed-environment`). Use one of: ```bash # Option 1: venv on the fast volume (recommended — keeps torch from the image via --system-site-packages) python3 -m venv --system-site-packages /workspace/venv && . /workspace/venv/bin/activate && pip install # Option 2: uv (fast; a venv under /workspace, or --system) curl -LsSf https://astral.sh/uv/install.sh | sh && export PATH="$HOME/.local/bin:$PATH" uv venv /workspace/venv --system-site-packages && uv pip install --python /workspace/venv/bin/python # Option 3: allow system-wide install (one-off) pip install --break-system-packages # or: export PIP_BREAK_SYSTEM_PACKAGES=1 ``` #### Missing System Tools in Base Image The default GPU base image does not include `ffmpeg`, `rsync`, `nvcc` (the CUDA compiler), `tesseract`, `jq`, `htop`, `tmux`, `screen`, `libnuma1`, `git-lfs`. `apt-get` works as root; install what the job needs first: ```bash lium exec my-pod "apt-get update -qq && apt-get install -y -qq ffmpeg rsync jq tmux git-lfs libnuma1" ``` `rsync` must be present **on the pod** for a plain `rsync` or the SDK's `Lium.rsync()` to work; the CLI's `lium rsync` installs it first (`apt-get install -y rsync` when `which rsync` fails on the pod). Compiling CUDA extensions (FlashAttention, custom kernels) needs `nvcc`: check `which nvcc`, and prefer prebuilt wheels or a `-devel` image tag. Note: `libnuma1` is required by `sglang`'s `sgl_kernel` and some `vllm` configs — missing it causes cryptic "kernel not found" errors that actually mean the `.so` failed to load. #### Cold-Start Expectations Don't assume a pod is broken if it's quiet for several minutes after launch. Typical timings: - Pod provisioning + SSH ready: ~30-60s - Docker image pull: usually cached, ~0-30s - Package installs (`pip install vllm`): ~2-5 min - Model download from HuggingFace (4B-class): ~1-2 min; (70B+): ~5-10 min - vLLM engine init (4B model, single GPU): ~2-3 min - sglang + 70B+ sharded (CUDA graph capture of ~50 graphs): **15-25 min** Use `lium logs my-pod --follow` to watch progress, or poll a log file from `lium exec`. #### Verify HuggingFace Model Exists Before Deploy Before spinning up a pod for a specific model (e.g. `vllm serve `), confirm the `repo_id` exists on HuggingFace — typos like `qwen3.5-4b` (doesn't exist) vs `Qwen/Qwen3-4B` waste a full cold-start cycle. ```bash curl -s "https://huggingface.co/api/models?search=qwen+2.5+7b&limit=10" | jq -r '.[].id' ``` #### Pod Vanishes from `lium ps` Pods with internal status `DELETING` are filtered out of `lium ps`. `FAILED` pods remain visible (with `FAILED` status) — so if a pod was `RUNNING` and fully disappears, it's being deleted, not failing. To investigate: - Check the dashboard (https://lium.io) — it shows full history including deleted pods - Grab logs before the pod vanishes: `lium logs ` (while it still exists) - Known issue: the CLI does not currently surface a deletion reason. If reproducible, report to the platform team. #### Pod Creation Failures — 3-Minute Visibility Window When `lium up` fails during provisioning, the pod is kept in status `CREATION_FAILED` for ~3 minutes before being auto-cleaned up (with a 10-min safety net if the cleanup task is delayed). During this window: - `lium ps` will show the pod with status `CREATION_FAILED` - `lium logs ` may have partial output from the failed creation - After ~3 minutes the pod disappears — if your agent polled later, it will see no trace For reliable failure diagnosis, poll `lium ps` every ~10-30s for the first few minutes after `lium up`, or check both `RUNNING` and terminal failure states explicitly. #### "Executor Not Found" on `lium up ` If an executor is visible on the lium.io dashboard but `lium up ` or `lium ls` doesn't show it, the platform's availability filter rejected it. Reasons include: low free disk space, high disk utilization, unresponsive health checks, or missing verification. **`lium ls` is the source of truth for rentable machines** — prefer filtering/selecting from `lium ls` output rather than matching IDs from the website. ## Agent Playbook The loop that works unattended, from a shell with `LIUM_API_KEY` set. Every pod gets a **name** (so it can be found again), a **TTL** (so a crashed agent does not bill for days) and a **GPU-count check** (so you do not pay for GPUs that are not there). Work runs **detached** and is polled; results are pulled with `rsync`; the run ends with `rm` and a `ps` that shows nothing left. ```bash export LIUM_API_KEY=sk_... # non-interactive auth; beats ~/.lium/config.ini NAME=job-$(date +%s) # 1. Pick hardware from JSON, not from the table, and keep the node's id (the UUID) for step 2. # Pick from ls yourself only when you need a filter `up --gpu` lacks (here: tier and a price sort). # Otherwise rent by spec (`lium up --gpu H200 -c 8`, see Non-Interactive Pod Creation): since 0.0.39 the backend # picks the cheapest node; 0.0.37/0.0.38 pick the first Pareto row locally. A node you pick here may be # taken by step 2 — the `||` cleanup there covers that. NODE=$(lium ls --gpu H200 --count 8 --format json | jq -c 'map(select(.tier=="secure")) | sort_by(.price_per_gpu_hour) | .[0]') [ "$NODE" != null ] || { echo "no secure-tier 8×H200 node is listed"; exit 1; } jq -r '"\(.huid) \(.config) $\(.price_per_hour)/h \(.country)"' <<<"$NODE" NODE_ID=$(jq -r '.id' <<<"$NODE") # 2. Rent that node, non-interactively, with a TTL; --no-ssh returns as soon as the pod is RUNNING. # A node id takes no --gpu/-c (a node id and the filters exclude each other); with no --count the # rent takes the node's free GPUs — the 8 that step 1 filtered on — and --verify-gpus --strict-gpus # removes the pod when the GPU count it sees is not that. # The pod bills from the moment the rent is accepted: when up fails later (pod_not_ready # after --timeout, an SSH check that could not run), the pod is still there — remove it. lium up "$NODE_ID" --name "$NAME" --ttl 6h -y --no-ssh --verify-gpus --strict-gpus \ || { lium ps "$NAME" --format json >/dev/null 2>&1 && lium rm "$NAME" -y; exit 1; } # 3. Read the pod record (up prints no JSON) and keep the evidence of what you pay for. # ps's gpu_count is the node's GPU count (= the billed count for a whole-node rent like this one; # `lium up --verify-gpus` above already compared the pod row's own billed count) lium ps "$NAME" --format json > pod.json BILLED=$(jq -r '.[0].gpu_count' pod.json) SEEN=$(lium exec "$NAME" --json "nvidia-smi -L" | jq -r '.results[0].stdout' | grep -c '^GPU ' || true) [ "$SEEN" = "8" ] && [ "$BILLED" = "8" ] || { echo "GPU count mismatch: asked 8, billed $BILLED, visible $SEEN"; lium rm "$NAME" -y; exit 1; } # 4. Prepare the pod (fast path, tools, venv) — one --script exec; stdin is NOT forwarded cat > setup.sh <<'EOF' set -e mkdir -p /workspace/{logs,out,hf} apt-get update -qq && apt-get install -y -qq rsync ffmpeg jq >/dev/null python3 -m venv --system-site-packages /workspace/venv . /workspace/venv/bin/activate && pip install -q "huggingface_hub[hf_transfer]" EOF lium exec "$NAME" --script setup.sh # 5. Start the job detached (capture the PID from --json), then poll. The wrapper writes train.py's exit # code to /workspace/logs/exit_code when it ends, so step 6 can tell a finished job from a crashed one. lium scp "$NAME" ./train.py /workspace/train.py # `cd …;` not `cd … &&`: `&` after an and-list backgrounds the whole list in a subshell that keeps the # SSH session's stdout, and `lium exec` would then wait for the job instead of returning the PID. PID=$(lium exec "$NAME" --json "cd /workspace; HF_HOME=/workspace/hf HF_HUB_ENABLE_HF_TRANSFER=1 nohup setsid bash -c '/workspace/venv/bin/python train.py > /workspace/logs/train.log 2>&1; echo \$? > /workspace/logs/exit_code' > /dev/null 2>&1 < /dev/null & echo \$!" | jq -r '.results[0].stdout' | tr -d '[:space:]') # The remote always exits 0 here, so a failed `lium exec` is lium's own error: exit 5 = the pod is gone # (TTL fired, removed elsewhere), anything else an API/SSH hiccup to retry — never "job finished". An empty # PID does not mean the job did not start: the command may have reached the pod before the hiccup, so look # before you remove anything. [ -n "$PID" ] || { echo "no PID came back; check the pod before retrying:"; lium exec "$NAME" "pgrep -af '[p]ython train.py'; tail -n 20 /workspace/logs/train.log"; exit 1; } while :; do OUT=$(lium exec "$NAME" --json "kill -0 $PID 2>/dev/null && echo running || echo finished"); rc=$? # lium's own exit, before any pipe [ "$rc" -eq 5 ] && { echo "pod gone (TTL or removal)"; exit 1; } if [ "$rc" -eq 0 ]; then STATE=$(jq -r '.results[0].stdout' <<<"$OUT" | tr -d '[:space:]') [ "$STATE" = finished ] && break lium exec "$NAME" "tail -n 2 /workspace/logs/train.log" fi sleep 60 done # 6. Pull results and logs (no -z for binary output; resumable); tear down only when both the pull and the # job succeeded. A failed rsync or a non-zero exit code keeps the pod, and the pod keeps billing until # you `lium rm` it yourself, so look at logs/train.log and decide. EXIT_CODE=$(lium exec "$NAME" --json "cat /workspace/logs/exit_code" | jq -r '.results[0].stdout' | tr -d '[:space:]') SSH_COMMAND=$(lium ps "$NAME" --format json | jq -r '.[0].ssh_command') # read it again: a restart can move host or port; ssh -p root@ rsync -a --partial --inplace --progress -e "${SSH_COMMAND% root@*} -i $HOME/.ssh/id_ed25519" \ "${SSH_COMMAND##* }:/workspace/out/" ./out/ || { echo "rsync failed; pod kept for a retry"; exit 1; } rsync -a --partial --inplace --progress -e "${SSH_COMMAND% root@*} -i $HOME/.ssh/id_ed25519" \ "${SSH_COMMAND##* }:/workspace/logs/" ./logs/ || { echo "rsync of logs failed; pod kept for a retry"; exit 1; } [ "$EXIT_CODE" = 0 ] || { echo "train.py exited with $EXIT_CODE (see logs/train.log); pod kept, still billing"; exit 1; } lium rm "$NAME" -y lium ps --format json | jq 'length' # 0 → nothing left billing ``` `lium exec --script setup.sh` is the safe way to run a multi-line setup: no quoting games, and the script's exit code comes back. (`lium exec "bash -s" < setup.sh` does **not** work — local stdin is never forwarded.) Capture remote output with `--json | jq -r '.results[0].stdout'`; the human format prints an `Executing on …` line on stdout first. The `stdout` field keeps its trailing newline: strip it (`tr -d '[:space:]'`, or `grep -c` as above) before comparing it or feeding it to `jq`'s `tonumber`, which rejects `"8\n"`. ### Agent Safety Rails *(0.16.1)* Four habits that keep an unattended agent from overspending or stalling: 1. **Cap what the agent can spend.** The account is prepaid, so the balance is the hard ceiling: fund only what the task needs. Give the agent its own key with a budget: `POST /keys` with the signed-in token (`Authorization: Bearer $TOKEN`, see signup above) and `{"name":"agent-1","scopes":["read","rent","manage"],"daily_budget_usd":20}` (`monthly_budget_usd`, `max_budget_usd`, `pod_visibility` `own`|`account` also accepted; scopes are listed by `GET /keys/scopes`). At the budget the key's pods are deleted and rents answer 402 `API_KEY_BUDGET_EXCEEDED`; `PATCH /keys/{id}` changes the budget. `lium billing history` / SDK `billing_statement()` show what the ledger charged, removed pods included. 2. **A deadline on every pod**: `lium up --gpu H100 --budget 12.50 --ttl 6h` — the earlier of the two removes it. SDK: `with lium.rental(executor_id=…, name=…) as pod:` removes the pod however the block ends; `lium.cap_spend(pod, budget_usd=12.5)` schedules removal at that spend. 3. **Wait for the service, not just the pod**: `wait_ready(pod, ready_port=8000)` returns only when the port answers inside the pod (a vLLM template is RUNNING minutes before it serves). 4. **Sold out?** `lium request B300 -n 8` notifies the providers who list that GPU instead of polling `lium ls` in a loop; `lium spend` shows burn per hour and runway. **Error → what to do** (CLI exit code / SDK exception): | Exit | SDK | Meaning | Do | |------|-----|---------|----| | `3` (401) | `LiumAuthError` | bad or revoked key | `lium whoami`; fix `LIUM_API_KEY` — do not retry | | `6` | `LiumInsufficientBalanceError` (`.required`, `.available`) | balance too low | fund (Non-Interactive Funding), then retry once | | `6` | `LiumBudgetExceededError` (`.window`) | the key's own budget hit | stop; a human raises it (`PATCH /keys/{id}`) | | `6` | `LiumScopeError` (`.scope`) | key lacks a scope (`rent`, `billing` …) | use a key with that scope; funds will not help | | `3` (429/5xx) | `LiumRateLimitError` / `LiumServerError` | transient | reads are already retried 3×; for a rent check `lium ps` for your pod **name** before re-sending | | — | `PodStartError` (`.cause`) | pod failed to start | `lium rm` it, rent another node | | — | `ClusterNotListedError` | cluster rent may have gone through | `lium clusters ps` before any retry | ### Verify What You Paid For Two failure modes were seen repeatedly on 4- and 8-GPU rentals: the platform provisions a **1-GPU pod** when the requested count is unavailable (silent downgrade), and a pod is **billed for N GPUs but the container exposes fewer** (phantom GPUs). Neither shows up as an error. `lium up --verify-gpus` counts the GPUs over SSH after the pod is ready and exits 1 on a mismatch; with `--strict-gpus` it also removes the pod. Keep the evidence yourself, every time, right after `up`: ```bash lium ps "$NAME" --format json | jq '.[0] | {gpu_count, price_per_hour, config}' # the node's GPUs and the pod's $/h — what a whole-node rent is billed for lium exec "$NAME" "nvidia-smi -L" # what the container sees lium exec "$NAME" "nvidia-smi --query-gpu=name,memory.total --format=csv,noheader" ``` If either number is below what you asked for, `lium rm` the pod immediately and rent again (another executor: pass its `id` from `lium ls --format json` as `NODE_ID`; `lium up` accepts the HUID since 0.3.0 (lium#153) and rejects it in every release before that). Keep the `nvidia-smi -L` output; it is the evidence for a refund. ### Pod Gotchas — The First Hour Observed on the default `daturaai/pytorch` templates (Ubuntu 24.04). Check with `mount | grep -E ' /root | /workspace '`, `nvidia-smi`, `python -c "import torch; print(torch.__version__, torch.cuda.get_arch_list())"`. - **Use `/workspace`, not `/root`.** The home directory is an encrypted FUSE mount (`gocryptfs`): model loads from it are several times slower, it pegs a CPU core during heavy I/O, and multi-process caches (Triton, torch.compile) misbehave on it. Put venvs, `HF_HOME`, datasets, checkpoints and outputs under `/workspace`. In the container restarts we saw, `/workspace` survived and everything else (running processes, `/root`, `/tmp`) did not — treat the rest as disposable. - **Weights: `HF_HOME=/workspace/hf` + `hf_transfer`.** `pip install "huggingface_hub[hf_transfer]"`, then `export HF_HOME=/workspace/hf HF_HUB_ENABLE_HF_TRANSFER=1` before any download — multi-GB/s on most nodes instead of a few hundred MB/s. Gated models need `HF_TOKEN`. Download once, detached, before starting the GPU job. - **PEP 668**: system `pip` refuses to install. Use a venv under `/workspace` (`--system-site-packages` keeps the image's torch) or `uv`; see the pitfall above. - **Blackwell needs a matching torch.** B200 / B300 / RTX PRO 6000 / RTX 5090 are `sm_100` / `sm_103` / `sm_120`. A torch built for CUDA 12.6 has no kernels for them and fails on the first CUDA call (`no kernel image is available`). Pick a `cuda12.8` or `cuda13.0` template tag (`-t `), or reinstall: `pip install --upgrade torch torchvision --index-url https://download.pytorch.org/whl/cu130` (`cu128` also works). Verify with `torch.cuda.get_arch_list()`. - **FlashAttention-3 is Hopper-only** (H100/H200). On Blackwell use FlashAttention-4 (beta) or PyTorch SDPA's cuDNN/flash backends; building FA3 there wastes 20+ minutes and then fails at runtime. Most serving stacks (vLLM, SGLang) pick a working backend on their own — prefer their wheels over building kernels. Building anything CUDA needs `nvcc`, which the base image does not ship (`-devel` tags do). - **Missing tools**: `ffmpeg`, `rsync`, `nvcc`, `tesseract`, `jq`, `tmux` are not installed. `apt-get update && apt-get install -y ...` first — as root, no sudo. - **`exec` blocks on background children**: start long jobs with `nohup setsid ... > log 2>&1 < /dev/null &` (pitfall above) and poll the log. - **Container restarts happen.** A pod can restart without any action from you; GPU jobs die, `/workspace` stays. Write checkpoints to `/workspace`, make jobs resumable, and note `uptime` / `ps -p 1 -o etimes=` when a job vanished. - **Ports**: only the ports in `lium ps --format json | jq '.[0].ports'` are reachable from outside (internal → external map). Bind servers to `0.0.0.0` on an internal port from that map, or use `lium port-forward`. ### Moving Data ```bash # Upload: lium handles it (single file, or a directory with lium rsync) lium scp "$NAME" ./config.yaml /workspace/config.yaml lium rsync "$NAME" ./src /workspace/src # Download a directory: plain rsync over the pod's ready ssh command (lium ps --format json # `ssh_command`: -p, the pinned host key, root@host; add -i, drop the trailing root@host for -e) SSH_COMMAND=$(lium ps "$NAME" --format json | jq -r '.[0].ssh_command') rsync -a --partial --inplace --progress --bwlimit=20000 \ -e "${SSH_COMMAND% root@*} -i $HOME/.ssh/id_ed25519" \ "${SSH_COMMAND##* }:/workspace/out/" ./out/ ``` - `--partial --inplace` makes a dropped transfer resumable; `--bwlimit` (KB/s) keeps one pull from starving the rest of the job. - No `-z` for media, checkpoints, parquet or anything already compressed. - Throughput out of a pod varies a lot (from ~100 KB/s to multi-MB/s); when a big pull is slow, sync **pod to pod** to a cheap 1-GPU pod and tear the expensive one down, then pull from the cheap pod at leisure. Pod-to-pod copy (source pod pushes to destination pod over SSH; both need `rsync` installed): ```bash SRC=render-pod; DST=edit-pod read -r DHOST DPORT < <(lium ps "$DST" --format json | jq -r '.[0].ssh_cmd | capture("@(?\\S+).*-p (?

\\d+)") | "\(.h) \(.p)"') # one-time trust: a key on SRC, authorised on DST PUB=$(lium exec "$SRC" --json "test -f ~/.ssh/id_p2p || ssh-keygen -q -t ed25519 -N '' -f ~/.ssh/id_p2p; cat ~/.ssh/id_p2p.pub" | jq -r '.results[0].stdout' | tr -d '\n') lium exec "$DST" "mkdir -p ~/.ssh && grep -qxF '$PUB' ~/.ssh/authorized_keys 2>/dev/null || echo '$PUB' >> ~/.ssh/authorized_keys" # the copy itself (detach it like any long job when it is large) lium exec "$SRC" "rsync -a --partial --inplace -e 'ssh -p $DPORT -i ~/.ssh/id_p2p -o StrictHostKeyChecking=accept-new' /workspace/out/ root@$DHOST:/workspace/in/" ``` ### Watch the GPUs A pod that is quietly idle costs the same as one that is busy. Sample utilisation into a CSV on the pod as soon as the job starts; it is also your evidence when a job stalls or a GPU is missing. ```bash lium exec "$NAME" "mkdir -p /workspace/logs; nohup setsid nvidia-smi --query-gpu=timestamp,index,utilization.gpu,memory.used,memory.total,power.draw --format=csv -l 60 > /workspace/logs/gpu.csv 2>&1 < /dev/null & echo \$!" lium exec "$NAME" "tail -n 8 /workspace/logs/gpu.csv" # one line per GPU per minute lium exec "$NAME" "nvidia-smi --query-gpu=index,utilization.gpu,memory.used --format=csv,noheader" # one-shot ``` Zero utilisation across all GPUs for more than a few minutes means the job is stuck on CPU work, on I/O from `/root`, or has crashed — check the log before the bill grows. ### Cost Hygiene - **Always `--ttl`** (or `--until`). It is scheduled once the pod is RUNNING; a pod that never got there has no TTL — `lium ps` and `lium rm` it yourself. Extend a TTL with `lium rm --in 4h` (schedules a new removal) and see what is scheduled with `lium schedules list`. - **Check the meter**: `lium ps --format json | jq '.[] | {name, price_per_hour, spent_usd, uptime}'` — `spent_usd` is uptime × price, computed client-side. Multi-GPU nodes are billed for the whole node from the moment the rent is accepted — before `up` returns — including the image pull, the readiness wait and your setup time. - **Never keep an 8-GPU node for CPU work.** Downloads, preprocessing, video encoding, editing and uploads belong on the cheapest node in `lium ls` (`--sort price_per_hour --limit 5`) or on your own machine. Copy pod-to-pod, `rm` the big node, continue on the cheap one. - **One `up` per pod name.** If `up` times out or errors after "Renting machine", run `lium ps` before retrying — the pod may exist (and bill) already. Retrying blindly has produced two pods for one request. - **Tear down and prove it**: `lium rm "$NAME" -y && lium ps --format json | jq length` — expect `0` (or the count you intend to keep). `lium rm -a -y` ends everything. - Keep the `nvidia-smi -L` and `lium ps --format json` snapshots from step 3 of the playbook; billing disputes need them. ### Only What the Released CLI Has This skill describes the released CLI, 0.0.37 as the baseline, with later releases marked where they differ (*(0.16.1)* = present in 0.16.1, the current release), and nothing that is not released; probe with `lium --help` before relying on a flag you do not see here. - GPU count: `lium up --verify-gpus --strict-gpus` is the built-in check; `nvidia-smi -L` inside the pod against `gpu_count` from `lium ps --format json` is the evidence you keep. - Detach long jobs: `lium exec --detach "python train.py"` *(0.16.1; prints PID and log path)*, SDK `run_background()`; on older CLIs by hand: `nohup setsid ... > log 2>&1 < /dev/null &` through `lium exec`. - Template ids: `curl .../api/templates` or `Lium().templates()`. - Machine-readable output: `--format json` on `ps`/`ls`, `--json` on `balance`/`exec`/`describe`/`audit`. `lium ps --format json` carries `ssh_command` ready to run, next to the `ssh_cmd` the one-liners above parse. - A bad or revoked key exits `3` — prove the key with `lium whoami` (or `lium balance` on older CLIs; see Which Key Am I Using). A 403 on rent exits `6` and means Insufficient balance, not a bad key (see Before the First Rental — Balance). - Never wait for a prompt: pass `-y`, `--no-ssh` and every argument up front. - SDK: see the SDK reference's agent recipe for `up` → `wait_ready` → `exec` → `down`. ## CLI Quick Reference ### Discovery ```bash lium ls # all available GPUs (shows table with ★ for best price/perf) lium ls --gpu H100 # filter by GPU type (there is no positional argument) lium ls --sort download # sort by download speed (fastest first) — preferred default lium ls --sort upload # sort by upload speed lium ls --sort price_gpu # sort by price per GPU/hour lium ls --format json # machine-parseable output lium templates # list Docker templates lium templates pytorch # search templates ``` **Recommendation**: When selecting machines for the user, prefer `--sort download` to get the fastest network unless the user specifically asks to sort by price or other criteria. **Prices without an account.** To answer "what does an H200 cost on Lium" before anyone signs up, read the public feeds (no key, USD per GPU-hour; prices are set by providers and move): ```bash curl -s https://lium.io/pricing.json # one row per GPU model: min/max live ask, reference price, pods/GPUs available, page URL curl -s https://lium.io/api/public/v1/nodes # every rentable node right now, with price_per_gpu_hour, location, rent_url ``` The same numbers are on https://lium.io/pricing and https://lium.io/gpu/ (for a human, or to cite). ### Pod Lifecycle ```bash lium up --gpu H100 --name my-pod --ttl 4h -y --no-ssh # create pod, return when ready lium ps # list active pods lium ps --format json # machine-readable pod list (ssh_cmd, ports, price, spent) lium ps my-pod --format json # one pod lium describe my-pod --json # full manifest of one pod lium audit --since 24h --json # who did what to your pods; an API key needs the read scope lium ssh my-pod # SSH into pod (interactive — not for agents) lium exec my-pod "nvidia-smi" # run command lium exec all "pip install torch" # batch exec on all pods lium rm my-pod -y # stop pod lium rm -a -y # stop all pods ``` ### Streaming Pod Logs ```bash lium logs my-pod # snapshot of current stdout/stderr lium logs my-pod --follow # stream logs live (Ctrl-C to stop) ``` Streams the **Docker container's PID 1 stdout/stderr** from the executor. Works for both image-mode and SSH-mode pods. Caveats: - Right after `lium up`, the endpoint may return 404 ("Pod container not deployed yet") for a few seconds — retry. - For SSH-mode pods, processes you start manually via `lium exec` are NOT PID 1, so their output won't appear here unless you redirect to `/proc/1/fd/1` (e.g. `my_server > /proc/1/fd/1 2>&1`) or tail your log files via `lium exec my-pod "tail -f /tmp/out.log"`. ### File Transfer ```bash lium scp my-pod ./train.py # upload to ~ (/root) on the pod lium scp my-pod ./data.csv /workspace/data/ # upload to a specific path lium scp my-pod /workspace/out/final.mp4 ./ -d # download one file lium scp all ./config.json # upload to all pods lium rsync my-pod ./project /workspace/project # sync a local directory TO the pod (upload only) ``` `lium rsync` is upload-only and takes no flags. Pull directories back with plain `rsync` over the pod's SSH endpoint (`ssh_cmd` from `lium ps --format json` gives host and port; see `lium rsync` in the CLI reference). ### Pod Targeting Pods accept: name, index from `lium ps`, comma-separated (`1,2,3`), or `all`. ### Output Formats Always use `--format json` when parsing output programmatically: ```bash lium ls --format json | python -c "import json,sys; print(json.load(sys.stdin))" lium ps --format json | python -c "import json,sys; print(json.load(sys.stdin))" ``` Never read node ids or prices off the `lium ls` table: it shows the HUID, which `lium up` before 0.3.0 rejects, and CLIs before 0.0.40 also drop the **Id** column and truncate prices to `0…` at 80 columns. The JSON has every field: `id` (UUID — what every `lium up` accepts), `huid` (the short name the table shows; accepted by `lium up` since 0.3.0 (lium#153), refused by every release before it, 0.2.0 included), `price_per_hour`, `price_per_gpu_hour`, `gpu_count`, `download_mbps`, `upload_mbps`, `country`. `--format [table|json]` exists on `lium ls` and `lium ps` (on 0.0.37/0.0.38 `lium ps --json` is rejected). `--json` — a plain flag, not a format choice — is taken by `lium describe`, `lium exec`, `lium audit`, `lium fund`, `lium balance`, `lium signup`, `lium topup create`, `lium topup currencies`, and by the whole `lium provider` group (set it on the group: `lium provider --json node list`). On 0.0.37/0.0.38 `lium templates` and `lium up` have neither, and neither does anything else. Since 0.0.39 (lium#217) `--json` is an alias of `--format json` on `ls`, `ps` and `templates` (so `lium ps --json` works), `templates --format json` prints the ids, and `LIUM_OUTPUT=json` makes every failure a JSON envelope on stderr; `lium up` still has no JSON output. ## End-to-End Agent Workflow Complete flow for setting up and renting a GPU pod: ```bash # 1. Install lium (if not present) if ! command -v lium >/dev/null 2>&1; then curl -fsSL https://raw.githubusercontent.com/Datura-ai/lium/main/scripts/install.sh | bash export PATH="$HOME/.lium/bin:$PATH" fi # 2a. No account, no mailbox → fingerprint signup, no human needed. Save `fingerprint` for the # user (dashboard login, shown once). If api_key is null, mint one after signing in with it. curl -fsS -X POST https://lium.io/api/auth/signup -H 'Content-Type: application/json' -d '{}' lium config set api.api_key # 2b. No account, but a human can click the confirmation link → ask for their real email lium signup --email # 2c. Existing account → two-step headless auth instead lium init --no-browser # → parse URL and session ID from output, show URL to user # → wait for user to confirm they approved lium init --session # 3. Verify the key (lium ls lists public data and succeeds with any key; a bad key exits 3 here since 0.0.31) lium balance --json # A zero balance means signup credit did not land; fund the account before renting. # 4. Find suitable GPU (sort by speed by default) lium ls --gpu H100 --sort download # 5. Create pod (non-interactive! --no-ssh returns instead of opening a session). # --verify-gpus compares the billed count with nvidia-smi over SSH; --strict-gpus removes a wrong pod. lium up --gpu H100 --name work-pod --ttl 6h --verify-gpus --strict-gpus -y --no-ssh \ || { lium ps work-pod --format json | grep -q '"id"' && lium rm work-pod -y; exit 1; } # exit 1 can leave a billing pod (pod_not_ready) # 6. Read the pod record (up has no JSON output) lium ps work-pod --format json # 7. Use the pod lium scp work-pod ./code.py /workspace/code.py lium exec work-pod "cd /workspace && python code.py" # 8. Cleanup lium rm work-pod -y lium ps # confirm nothing is left billing ``` ## Run One Python Function on a GPU (no pod scripting) When the task is "run this function on a GPU and give me the result" — a benchmark, an inference, an embedding batch — use `@lium.machine` from the SDK instead of `up` / `scp` / `exec` / `rm` by hand. It rents the cheapest matching node, ships the function, installs the requirements once, streams the function's output, returns the result (or re-raises its exception) and removes the pod. Cost is bounded: the pod is scheduled for removal at `timeout + 15 min` (plus `keep_warm`) from the moment it is rented. Everything in this section beyond `machine`, `template_id`, `cleanup` and `requirements` **needs 0.0.40 (lium#208)**: on 0.0.37–0.0.39 the decorator takes only those four, picks the first node whose name contains the string, installs `requirements` into an isolated venv (so torch must be listed there too), matches `machine` as a substring of the node's name (`"H200"`; the `"1xH200"` form is 0.0.40 too), and results must be JSON-serialisable. ```python import lium @lium.machine(machine="RTX4090", requirements=["transformers", "accelerate"], timeout=600, keep_warm=300) def generate(prompt: str) -> str: import torch # import INSIDE the function; only its def travels from transformers import AutoModelForCausalLM, AutoTokenizer tok = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct") model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct", dtype=torch.bfloat16, device_map="cuda") ids = tok.apply_chat_template([{"role": "user", "content": prompt}], return_tensors="pt", add_generation_prompt=True).to("cuda") out = model.generate(ids, max_new_tokens=64, do_sample=False, pad_token_id=tok.eos_token_id) return tok.decode(out[0][ids.shape[-1]:], skip_special_tokens=True).strip() try: print(generate("Who discovered penicillin?")) # cold: ~1-2 min (rent, boot, install); warm: ~20 s print(generate("Name one antibiotic.")) # reuses the warm pod except Exception as e: # a builtin raised remotely: the same type, e.__cause__ is lium.RemoteExecutionError; cause = e.__cause__ if isinstance(e.__cause__, lium.RemoteExecutionError) else None # a timeout, no node, a failed rental: no cause print(type(e).__name__, e, cause.remote_traceback if cause else "") finally: generate.close() # remove the warm pod now (else: keep_warm + 2 min later) ``` Rules that save a failed call: `machine` is `"x"` / `""` (`"1xH200"`, `"RTX4090"`; count defaults to 1 — `"A100"` is one A100, not eight). Import inside the function; a module-level import/constant/helper used inside is refused at definition time (it would be a `NameError` on the pod). Return plain Python types (`str()`, `.tolist()`, `.cpu().numpy()`), not tensors or `torch.__version__`. Torch is already on the default template — do not put it in `requirements` (since 0.0.40 the venv sees the image's packages; before that it does not — list it there). `f.map(items)` runs a batch on one pod; `f.local(x)` or `LIUM_MACHINE_LOCAL=1` runs the function locally for tests; `quiet=True` drops the `[lium]` progress lines (the function's own prints still stream). Like the rest of this section (`timeout`, `keep_warm`, `close()`, `RemoteExecutionError`, the node pick), every one of these (map, local, LIUM_MACHINE_LOCAL, quiet) is 0.0.40 (lium#208) — not one of them exists on 0.0.37–0.0.39. --- # CLI Commands — Full Reference # Lium CLI Command Reference Written against `lium --version` **0.0.37**. Every flag below appears in that binary's own `--help`; nothing here is extrapolated. When a newer CLI ships, `lium --help` is the authority, not this file. ## Table of Contents - [Global Options](#global-options) - [lium signup](#lium-signup) - [lium init](#lium-init) - [lium balance](#lium-balance) - [lium ls](#lium-ls) - [lium up](#lium-up) - [lium ps](#lium-ps) - [lium audit](#lium-audit) - [lium describe](#lium-describe) - [lium ssh](#lium-ssh) - [lium exec](#lium-exec) - [lium scp](#lium-scp) - [lium rsync](#lium-rsync) - [lium rm](#lium-rm) - [lium logs](#lium-logs) - [lium port-forward](#lium-port-forward) - [lium reboot](#lium-reboot) - [lium update](#lium-update) - [lium templates](#lium-templates) - [lium volumes](#lium-volumes) - [lium bk (backups)](#lium-bk-backups) - [lium schedules](#lium-schedules) - [lium ssh-keys](#lium-ssh-keys) - [lium config](#lium-config) - [lium theme](#lium-theme) - [lium fund](#lium-fund) - [lium topup](#lium-topup) - [lium mine](#lium-mine) - [lium provider](#lium-provider) - [lium gpu-splitting](#lium-gpu-splitting) - [lium whoami](#lium-whoami) - [lium spend](#lium-spend) - [lium billing](#lium-billing) - [lium request](#lium-request) - [lium cp](#lium-cp) - [lium clusters](#lium-clusters) - [lium completion](#lium-completion) - [Batch Operations](#batch-operations) - [Pod Targeting](#pod-targeting) - [Environment Variables](#environment-variables) - [Exit Codes](#exit-codes) ## Global Options The root command takes exactly two options: ``` --version Show the version and exit --help Show this message and exit ``` There is no `--config` and no `--debug` flag. Debug output is switched on with the `LIUM_DEBUG=1` environment variable, and the config file location comes from `lium config path`. ## lium signup Create a Lium account and store the API key it mints. Fully non-interactive — this is the command to use when the user has **no account yet**. Older CLI binaries do not have it — probe with `lium signup --help` and update the CLI when it is missing. ```bash lium signup [OPTIONS] --email EMAIL The user's real email (REQUIRED) — the confirmation link goes there --name NAME Display name (defaults to the email's local part) --password PASSWORD Account password (a strong one is generated when omitted) --json Machine-readable output ``` The password can also come from the `LIUM_SIGNUP_PASSWORD` environment variable — `--password` wins when both are set. Prefer the variable: a flag value is left behind in the shell history and in `ps` output. Whatever its origin, the password is always reported back to the caller. Ask the user for their **real** email — the account, its balance, password recovery and the confirmation link are all tied to it. Never invent an address. The command creates the account (`POST /users`), stores the minted API key in `~/.lium/config.ini` under `api.api_key`, and sets up an SSH key. After it, `lium ls` and `lium up` work with no further setup. **Refuses to run when `api.api_key` is already configured** — it exits with an error instead of creating a second, unreachable account. To sign up anyway, drop the existing key first: ```bash lium config unset api.api_key # then: lium signup --email ... ``` **Failures never strand the account.** When the command fails after the account was created — the request timed out, or the API key could not be read back — the error still reports the email and password, so the user can log in at https://lium.io and copy an API key from the dashboard. With `--json`, that error goes to stderr as `{"ok": false, "error": {...}, "data": {"email": "...", "password": "..."}}`. Examples: ```bash lium signup --email ada@example.com lium signup --email ada@example.com --name Ada --json LIUM_SIGNUP_PASSWORD=... lium signup --email ada@example.com ``` `--json` output: ```json { "api_key": "sk_...", "email": "ada@example.com", "next_steps": ["...", "...", "..."], "password": "generated-or-supplied", "signup_credit_granted": true, "ssh_key_configured": true } ``` - `password` — the dashboard login at https://lium.io. Hand it to the user; it is not stored anywhere else. - `signup_credit_granted` — comes straight from the signup API response and is the authoritative answer to "did the $5 signup credit land?": `true` → granted; `false` → not granted (the once-per-IP gate, or the credit disabled platform-side); `null` → the backend did not report it (older backend) — read the balance instead: `lium balance --json`. - Renting is not gated on email confirmation — a funded balance is the only requirement. Clicking the link in the **"Please confirm your email"** mail (the separate "Welcome to Celium!" mail carries no link) confirms the address, so that password resets and account emails reach the user. ## lium init Initialize the CLI for a user who **already has an account** — `lium init` cannot create one, use [`lium signup`](#lium-signup) for that. Plain `lium init` opens a browser and is **not suitable for agent use**; the `--no-browser` / `--session` pair is the headless two-step. ```bash lium init [OPTIONS] --no-browser Print the auth URL + session ID instead of opening a browser (step 1) --session ID Verify the auth session and save the API key (step 2) ``` For an agent that already holds an API key, write the config directly instead: ```bash lium config set api.api_key YOUR_KEY lium config set ssh.key_path ~/.ssh/id_ed25519 ``` ## lium balance Show the current account balance. ```bash lium balance [OPTIONS] --json Print machine-readable JSON ``` ## lium ls List available GPU nodes. There is no positional argument — filter with `--gpu`. ```bash lium ls [OPTIONS] --gpu TEXT Filter by GPU type, e.g. A100 --count INTEGER Exact GPU count to match (e.g. 1, 8) --min-cuda FLOAT Minimum CUDA version, e.g. 12.4 --nvlink Only nodes whose GPUs are all joined by NVLink (Link column NV#); nodes with no topology report yet are excluded (since 0.4.0) --min-download FLOAT Minimum Download (Mbps) a node must report; nodes with no figure are excluded; alias --min-ingress; 0, negatives, nan and inf exit 2 before any request (since 0.4.0) --lat FLOAT Latitude for distance filtering --lon FLOAT Longitude for distance filtering --max-distance INTEGER Maximum distance in miles from --lat/--lon --sort FIELD price_gpu | price_total | loc | id | gpu | download | upload | price_per_gpu_hour | price_per_hour (an explicit --sort wins over the ★ optimal ordering) --limit INTEGER Limit the number of rows shown --format [table|json] Output format; 'json' goes to stdout, suitable for jq ``` Examples: ```bash lium ls # all nodes lium ls --gpu H100 # only H100 nodes lium ls --gpu H100 --count 8 # only 8×H100 nodes lium ls --format json # JSON output for parsing lium ls --sort price_per_gpu_hour --limit 10 lium ls --gpu H200 --nvlink --min-download 2000 # NVLink boards with a Download floor — since 0.4.0 ``` The table and JSON carry no interconnect field; `download_mbps` and `upload_mbps` are smoothed averages of Lium's VerifyX check (a fetch of a real object), falling back to the speed-test average, and neither is CDN throughput. Before a tensor-parallel or weight-heavy job on a multi-GPU node, verify on the pod: `nvidia-smi topo -m` (all off-diagonal GPU cells `NV#`), `nvidia-smi topo -p2p r` (all `OK`) and a timed download — see "Before You Rent 8 GPUs" in SKILL.md. `--format json` emits one object per node with these keys: `index`, `id`, `huid`, `config` (e.g. `8×H200`), `gpu_type`, `gpu_count`, `price_per_gpu_hour`, `price_per_hour`, `country`, `vram_gb`, `ram_gb`, `disk_gb`, `upload_mbps`, `download_mbps`, `available_ports`, `docker_in_docker`, `is_pareto`, `max_cuda_version`, `tier` (`secure` or `spot`), `available_gpu_count` (the free GPUs of a partly rented node). There is no `--country` or `--max-price` filter on `ls`; filter the JSON (`jq`) or use the filters on [`lium up`](#lium-up). `/executors` is a public endpoint: `lium ls` succeeds with an invalid (revoked) API key, so it proves nothing about authentication — use `lium balance` for that. (With no key configured at all it exits 2 before any request; the commands that run the interactive setup first — `up`, `ps`, `describe`, `logs`, `audit` — start the browser auth flow instead.) **Since 0.4.0 (lium#149):** the table gains **Link** (how the node's GPUs are wired, as Lium saw with `nvidia-smi topo -m`: `NV18` = NVLink with 18 links, `PCIe/SYS` = PCIe only; `—` until reported) after Config. A terminal narrower than about 120 columns hides it (the footer says so); `--format json` always carries it. Download/Upload stay the speed-test figures; there is no CDN column. `--format json` rows gain `link`, `nvlink`, `p2p` and `interconnect` (counts and the GPU×GPU matrix), all `null` until Lium reports them. Both filters are sent to the API and applied client-side too; when nothing is left the message is `No available node reports NVLink between every GPU pair and Download ≥ 2000 Mbps`, followed by each filter's rule. `lium describe` shows the same as Link / Topology rows, a Net row with the speed-test figures, and `gpu.link`, `gpu.p2p`, `gpu.interconnect`, `machine.download_mbps` in `--json`. On a CLI older than 0.4.0, verify on the pod (`nvidia-smi topo -m`, `nvidia-smi topo -p2p r`, a timed download). ## lium up Create a new pod. **Always pass `-y` for non-interactive (agent) usage.** ```bash lium up [OPTIONS] [NODE_ID] NODE_ID Node UUID, HUID, or index from the last `lium ls`. Optional — omit it and the filters below auto-select the best node. (`lium up --help` prints NODE_ID without brackets; the argument is optional all the same.) Pass the UUID (`id` in `lium ls --format json`) on any release before 0.3.0: there the HUID answers "Node '' not found" although the help lists it. Since 0.3.0 (lium#153) the HUID resolves too. -n, --name TEXT Custom pod name -t, --template_id TEXT Template ID -v, --volume TEXT Volume spec: 'id:' or 'new:name=[,desc=]' -y, --yes Skip the confirmation prompt (REQUIRED for agent use) --gpu TEXT Filter nodes by GPU type (e.g. H200, A6000) -c, --count INTEGER Number of GPUs per pod --country TEXT Filter nodes by ISO country code (e.g. US, FR) -p, --ports INTEGER Minimum number of available ports required --ttl TEXT Auto-terminate after a duration (6h, 45m, 2d) --until TEXT Auto-terminate at a local time ("today 23:00", "tomorrow 01:00", "2025-10-20 15:30") --jupyter Install Jupyter Notebook (auto-selects a port) --no-ssh Create the pod and return instead of opening an SSH session --timeout SECONDS Time budget for the whole command: finding the node, renting it and waiting for the pod [default: 900]. Runs out before the rent → exit 1, no pod. Runs out while the pod is still starting → exit 1 with the pod named — it keeps running and billing. --ready-timeout SECONDS Bound only the wait for the pod to become ready (exit 1, pod left running and named). Default: whatever --timeout leaves. --verify-gpus After the pod is ready, count the GPUs nvidia-smi sees over SSH and compare with the billed count --strict-gpus Remove the pod automatically when its GPU count does not match what was requested or billed (a pod that could not be checked over SSH is kept) --restore-backup TEXT Backup ID to restore after the pod starts --restore-to TEXT New or empty subdirectory for the startup restore (required together with --restore-backup) --image TEXT Docker image to run (e.g. pytorch/pytorch:2.0) --internal-ports TEXT Internal ports to expose (comma-separated: 22,8000,8080) --dockerfile FILE Build the pod image from this Dockerfile (mutually exclusive with --image / --template_id) -e, --env TEXT Environment variables (KEY=VALUE), repeatable --entrypoint TEXT Container entrypoint --cmd TEXT Command to run in the container --ssh-name TEXT Name to register a new SSH key under (default: cli-@) --volume-encryption / --no-volume-encryption Encrypt the local volume when supported (on by default) ``` `--no-ssh` matters for agents: without it `lium up` ends by opening an interactive SSH session (or, with `--image`, by streaming container logs). `lium up` has **no `--format json`**. With `--no-ssh` it prints the deploy estimate, `renting …`, `pod (id: ) created; waiting for it to become ready` and `waiting for … (N s) · est. ready in ~M s (phase: …)` progress lines on stdout, ends with one line of fixed shape, `Pod (name: , id: ) ready`, and exits 0. Read the pod record afterwards with `lium ps --format json` (or `lium describe --json`). Pass `--name` so that lookup is unambiguous. `-c/--count` selects a node whose **total** GPU count equals N (`gpu_count` in `lium ls`); free GPUs are not checked at selection time, so on a GPU-split host with some GPUs already rented the rent takes what is free and the check below catches the difference. Once the pod is running and `--ttl` is scheduled, `lium up` **checks the GPU count itself, on every run**: the count the pod is billed for (the `/pods` row's own count — what the SDK exposes as `PodInfo.gpu_count`; no CLI JSON prints it in 0.0.37) against `--count` — or, without `--count`, the node's free GPU count. With `--verify-gpus` it also runs `nvidia-smi -L` over SSH and compares the visible count with the billed one. A mismatch exits 1 with code `gpu_count_mismatch`; **without `--strict-gpus` the pod stays running and billing** (the message names it — `lium rm` it), with `--strict-gpus` the CLI removes it first. A pod that could not be checked over SSH exits 1 with `gpu_verification_failed` and is kept either way. Every exit 1 after "created" can leave a billing pod: `pod_not_ready` (the `--timeout`/`--ready-timeout` budget ran out while the pod was starting — no TTL was scheduled yet), `gpu_count_mismatch` without `--strict-gpus`, `gpu_verification_failed`, `jupyter_install_failed`; `pod_start_failed` exits 3 and the pod may still be listed. So `lium up … || exit 1` is not enough for an unattended run: on any non-zero exit run `lium ps --format json` and `lium rm -y` when a pod exists (the skill's recipes do this). `--ttl`/`--until` are applied **after** the pod is running (the termination is scheduled through the API, `Lium.schedule_termination`; `lium schedules` lists it), so a pod that failed on the way to `RUNNING` has no TTL — check `lium ps` and `lium rm` it yourself. Examples: ```bash # Non-interactive (for agents): lium up --gpu H100 -y --no-ssh # auto-select + default template lium up --gpu H200 --country US --name train -y --no-ssh lium up --gpu H100 --ttl 6h --jupyter -y --no-ssh # Docker-run style (streams logs instead of SSH): lium up --gpu A4000 --image pytorch/pytorch:2.0 -y lium up --gpu H100 --image vllm/vllm-openai:latest -e HF_TOKEN=xxx -y # Custom Dockerfile, built remotely: lium up --gpu A4000 --dockerfile ./Dockerfile -y # With volumes: lium up --gpu H100 -v id:brave-fox-3a -y # attach an existing volume lium up --gpu H100 -v new:name=data -y # create + attach a volume # Specific node: lium up 1 --name dev-pod -y # node #1 from the last ls ``` ## lium ps List active pods. The optional positional narrows the listing to one pod. ```bash lium ps [OPTIONS] [POD_ID] POD_ID Show a single pod — name, HUID or UUID only, NOT an index --format [table|json] Output format; 'json' goes to stdout, suitable for jq ``` `lium ps --format json` **is supported** and is the way an agent should read pod state. There is no `-a/--all`, no `--sort`, no `--watch` and no `--json` alias (`--json` is rejected with "No such option"). Each object carries: `index` (the row number this shell's index targeting resolves against; `null` for a filtered listing), `id`, `huid`, `name`, `status`, `gpu_type`, `gpu_count` (the **node's** total GPU count, not the billed count on a GPU-split host), `config`, `template`, `price_per_hour`, `spent_usd` (uptime × price, computed client-side), `uptime`, `created_at`, `ip`, `ports` (map of internal → external port), `ssh_cmd` (the API's `ssh root@ -p `), `ssh_command` (a ready `ssh -p -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile= root@` with the pod's host key pinned under `~/.lium/known_hosts/` — add `-i ` yourself), `removal_scheduled_at`, `jupyter_url`. ```bash lium ps --format json | jq -r '.[] | "\(.name) \(.status) \(.gpu_count)x\(.gpu_type) $\(.price_per_hour)/h spent $\(.spent_usd)"' lium ps my-pod --format json | jq -r '.[0].ssh_cmd' ``` A pod being deleted may show `DELETING` briefly; `FAILED`/`CREATION_FAILED` pods stay visible for a few minutes. ## lium describe Show everything known about one pod — ports, GPU, template, billing — as a manifest. `POD_ID` is a pod name, HUID or UUID (**not** an index). ```bash lium describe [OPTIONS] POD_ID --json Print the manifest as machine-readable JSON ``` ```bash lium describe my-pod lium describe my-pod --json | jq . ``` With `--json` the command never prompts for setup, so it is safe in scripts. ## lium audit **Since lium 0.0.37.** Who did what to the account's pods, and when: every rent, reboot, edit and delete with the session or API key that requested it; entries the platform wrote by itself (a node reply, a balance stop) say `platform`. An API key needs the read scope to read `GET /users/me/events`. ```bash lium audit [OPTIONS] # since 0.0.37 --pod TEXT Only this pod: id, huid, name or index from the last ps; a deleted pod's full id --since TEXT Only events after this: 24h, 30m, 7d or an ISO timestamp (else exit 2) --key TEXT Only actions made with this API key id --limit INTEGER Newest events to fetch, 1–1000 (default 200; out of range exits 2 locally) --json Print the events as machine-readable JSON (newest first) ``` The table — When (UTC) / Pod / What / By — reads oldest first. `By` is `key ()`, `session` (browser) or `platform`. Exit `5` when `--pod` is neither a listed pod nor a full UUID (a full id passes through so a deleted pod can be queried). ```bash lium audit --since 24h # today lium audit --pod my-pod # one pod's history lium audit --json | jq '.[] | select(.actor.api_key_name == "ci")' # one key's actions ``` ## lium ssh Open an interactive SSH session to a pod. It takes no options — to run a command and exit, use [`lium exec`](#lium-exec). ```bash lium ssh TARGET TARGET Pod name/ID (eager-wolf-aa) or index from `lium ps` (1, 2, 3) ``` ## lium exec Execute commands on one or more pods. **This is the command an agent uses to run things remotely** — it exits with the remote command's exit code, so `lium exec "cmd" && next-step` behaves the way a caller expects. ```bash lium exec [OPTIONS] TARGETS [COMMAND] TARGETS Pod name/ID, index, comma-separated list, or "all" COMMAND Command to execute (quote multi-word commands) -s, --script TEXT Execute a local script file on the pod -e, --env TEXT Set environment variables (KEY=VALUE) --max-output-bytes INTEGER Fail once stdout and stderr together pass this many bytes (default 64 MiB) --json Print machine-readable JSON (stdout, stderr, exit_code) instead of raw output ``` Examples: ```bash lium exec my-pod "python train.py" lium exec 1 "python --version" lium exec 1 "nvidia-smi" lium exec 1,2,3 "uptime" lium exec all "df -h" lium exec 1 --script setup.sh lium exec 1 -e API_KEY=xyz "python app.py" lium exec 1 --json "python train.py" ``` There is no `--timeout`, no `--detach` (added in 0.16.1) and no `--output` in 0.0.37. `exec` waits for the remote command **and every child that still holds its stdout/stderr**, so a job started with a bare `&` keeps `exec` blocked. Detach it fully: ```bash lium exec my-pod "mkdir -p /workspace/logs && nohup setsid bash -lc 'python train.py' > /workspace/logs/train.log 2>&1 < /dev/null & echo PID=\$!" ``` **Local stdin is not forwarded** — the remote command's stdin is closed at once, so `lium exec my-pod "bash -s" < setup.sh` runs nothing. Use `--script setup.sh` instead: the file's text is sent as the command (multi-line scripts are fine), and its exit code comes back. **Capturing output**: the human format prints an `Executing on ` line on stdout before the remote stdout, so `lium exec pod "echo \$!" > pid.txt` captures both. Use `--json` and pick the field: ```bash lium exec my-pod --json "nvidia-smi -L | wc -l" | jq -r '.results[0].stdout' ``` `--json` prints one object on stdout: `{"ok": , "results": [{"pod": "", "stdout": "...", "stderr": "...", "exit_code": N, "error": null}]}` (one entry per target). On a failure before the command ran (no such pod, bad script) it prints `{"ok": false, "error": {"code": ..., "message": ...}}` on **stderr** and exits non-zero. The process exit code is the highest remote exit code across targets. ## lium scp Copy files between the local machine and pods. Upload is the default; `-d` flips the direction. ```bash lium scp [OPTIONS] TARGETS SOURCE_PATH [DESTINATION_PATH] TARGETS Pod name/ID, index, comma-separated list, or "all" SOURCE_PATH Local file (upload) or remote path (download) DESTINATION_PATH Optional; for multiple pods a download destination must be a directory -d, --download Download from the pods to the local machine ``` Examples: ```bash lium scp 1 ./script.py # upload to ~/script.py on pod #1 lium scp eager-wolf-aa ./data.csv ~/data/ # upload into a directory lium scp all ./config.json # upload to every pod lium scp 2 /root/output.log ./outputs -d # download from pod #2 into ./outputs/ ``` *(0.17.0)* A download whose SOURCE_PATH is a remote directory is refused and leaves no empty local file behind. There is no `-r/--recursive` and no `-p/--preserve`; use [`lium rsync`](#lium-rsync) for directories. ## lium rsync Sync a **local directory to pods** with rsync. It takes no options, and it only goes one way: `LOCAL_PATH` must exist on your machine (the CLI rejects a path that does not), so it cannot pull results back. ```bash lium rsync TARGETS LOCAL_PATH [REMOTE_PATH] TARGETS Pod name/ID, index, comma-separated list, or "all" LOCAL_PATH Local directory to sync (must exist locally) REMOTE_PATH Optional destination path on the pod ``` There is no `--bwlimit`, `--exclude`, `--delete` or download direction. To pull results, or to tune the transfer, call `rsync` directly with the SSH details from `lium ps --format json`: `ssh_command` is a ready `ssh -p -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile= root@` with the pod's host key pinned under `~/.lium/known_hosts/`; add your key (`ssh.key_path` in `lium config show`; spell it `$HOME/…`, not `~/…` — `~` inside `-e` is expanded by ssh from the passwd entry, not from `$HOME`) and drop the trailing `root@` for `-e` (rsync unquotes the `-o '…'` arguments itself): ```bash SSH_COMMAND=$(lium ps my-pod --format json | jq -r '.[0].ssh_command') rsync -a --partial --inplace --progress --bwlimit=20000 \ -e "${SSH_COMMAND% root@*} -i $HOME/.ssh/id_ed25519" \ "${SSH_COMMAND##* }:/workspace/out/" ./out/ ``` Do not add `-z` for media, checkpoints or other already-compressed data — it only burns CPU. Pod → pod copies are covered in the skill's playbook. ## lium rm Remove (terminate) pods. Removal is irreversible. The command exits non-zero when nothing matched `TARGETS`, so a typo cannot look like a successful teardown. ```bash lium rm [OPTIONS] [TARGETS] TARGETS Pod name(s)/ID(s), index/indices, comma-separated list, or "all" -a, --all Remove all active pods -y, --yes Skip the confirmation prompt; required when stdin is not a terminal --in TEXT Schedule the removal after a duration (e.g. 6h) --at TEXT Schedule the removal at a time (e.g. "tomorrow 01:00") --rating INTEGER Rate the pod's node 1-5 in the same call --feedback TEXT Tell Lium how the node went (never blocks the removal) ``` `--in` and `--at` **schedule** a removal rather than filtering which pods to remove; cancel a scheduled one with [`lium schedules rm`](#lium-schedules). **Agent usage** — pass `-y` on every `rm`. Without a terminal on stdin (or with `LIUM_NONINTERACTIVE=1`) and without `-y`, the command names the pods it would have removed and the command to re-run, exits 2 (`confirmation_required`) and removes or schedules nothing; a piped `yes` is not approval (up to lium 0.0.41 a piped `lium rm my-pod` removed the pod). ```bash lium rm my-pod -y # single pod lium rm -a -y # all pods lium rm 1,2,3 -y # several by index lium rm my-pod --in 6h -y # schedule removal in six hours ``` ## lium logs Stream logs from a pod. ```bash lium logs [OPTIONS] POD_ID POD_ID Pod name, HUID or UUID — NOT an index -n, --tail INTEGER Number of lines to show from the end of the logs -f, --follow Follow log output ``` Examples: ```bash lium logs abc123 # last 100 lines lium logs abc123 -n 50 # last 50 lines lium logs abc123 -f -n 10 # follow, with 10 lines of history ``` ## lium port-forward Forward a local port to a pod's internal port. Useful for Jupyter, TensorBoard and other web services. ```bash lium port-forward [OPTIONS] TARGET PORT TARGET Pod name/ID or index PORT The internal port on the pod to forward to -l, --local-port INTEGER Local port to bind (defaults to the same as PORT) ``` Examples: ```bash lium port-forward my-pod 8888 # localhost:8888 -> pod's 8888 lium port-forward 1 8000 -l 3000 # localhost:3000 -> pod's 8000 ``` ## lium reboot Reboot pods. ```bash lium reboot [OPTIONS] [TARGETS] TARGETS Pod name(s)/ID(s), index/indices, or "all" -a, --all Reboot all active pods --volume-id TEXT Volume ID to attach when rebooting ``` A reboot re-creates the pod: everything outside an attached volume is lost. ## lium update Update the configuration of a running pod. ```bash lium update [OPTIONS] TARGET TARGET Pod name/ID or index --jupyter INTEGER Install Jupyter Notebook on the given internal port ``` ## lium templates List available Docker templates and images. It takes no options. ```bash lium templates [SEARCH] SEARCH Text search to filter templates (e.g. "pytorch", "tensorflow") ``` **Notes**: - The table shows Name / Image / Tag / Type / Status — **no template id**. Since 0.0.39 (lium#217) `lium templates --format json` (alias `--json`) prints the ids; on 0.0.37/0.0.38, to get an id for `lium up -t`, read the API directly (the same key the CLI uses): ```bash curl -s https://lium.io/api/templates -H "X-API-Key: $LIUM_API_KEY" \ | jq -r '.[] | "\(.id) \(.docker_image):\(.docker_image_tag) \(.name)"' ``` or use the Python SDK (`Lium().templates("pytorch")` returns objects with `.id`). - Without `--template_id`, `lium up` uses the node's default **PyTorch (CUDA)** template — fastest to start. Several `daturaai/pytorch` tags exist (e.g. `...-cuda12.8-...` and `...-cuda13.0...`); pick a CUDA 12.8+/13.0 tag for Blackwell GPUs (B200/B300, RTX PRO 6000, RTX 5090). - Default Docker-in-Docker (dind) image: `daturaai/dind` - `/templates` is a public endpoint — the command succeeds even with a bad API key. ## lium volumes Manage persistent volumes. ```bash lium volumes list # list all volumes lium volumes new NAME [-d DESC] # create a volume (-d, --desc) lium volumes rm INDICES [-y, --yes] # remove by index from the last `lium volumes list` ``` `volumes rm` takes **indices from the previous listing**, not names or HUIDs — run `lium volumes list` first. ## lium bk (backups) Manage pod backup configurations. `POD_ID` is a pod name/ID or an index from `lium ps`. ```bash lium bk show POD_ID # show the backup config lium bk set POD_ID [OPTIONS] # set or update it --path TEXT Explicit path inside the pod volume to back up (REQUIRED) --every TEXT Backup frequency (1h, 6h, 24h) --keep TEXT Retention period (1d, 7d, 30d) -y, --yes Skip the confirmation prompt lium bk now POD_ID [OPTIONS] # trigger an immediate backup (no prompt, no -y) -n, --name TEXT Backup name (e.g. 'pre-release') -d, --description TEXT Backup description lium bk logs [POD_ID] [--id ID] # backup logs, or details of one backup lium bk cancel --id ID [-y] # cancel an active backup, keep its history lium bk delete --id ID [-y] # delete the stored data of a completed backup lium bk restore POD_ID --id ID # restore a backup (--id is required) --to TEXT New or empty restore subdirectory (default: /restored, e.g. /workspace/restored) -y, --yes Skip the confirmation prompt lium bk restore-logs [POD_ID] [--id ID] lium bk restore-cancel --id ID [-y] # cancel an active restore lium bk rm POD_ID [-y] # remove the backup config ``` `--path` on `bk set` is a required flag, not a positional, and there is no default: `lium bk set 1 --path /workspace/checkpoints --every 6h --keep 7d`. Back up a stable subdirectory rather than the whole volume. A backup can also be restored into a brand-new pod at creation time with `lium up ... --restore-backup ID --restore-to /workspace/restored`. ## lium schedules Manage scheduled pod terminations (the ones created by `lium rm --in/--at` and by `lium up --ttl/--until`). ```bash lium schedules list # list all pods with scheduled terminations lium schedules rm INDICES # cancel by index from the listing ``` ## lium ssh-keys Manage the SSH public keys registered with Lium. ```bash lium ssh-keys list # list the keys registered with Lium lium ssh-keys sync # register every local SSH pubkey that isn't on Lium yet ``` ## lium config Manage the CLI configuration (`~/.lium/config.ini`). ```bash lium config show # display the entire configuration lium config get api.api_key # get one value lium config set ssh.key_path ~/.ssh/key # set one value (interactive without VALUE) lium config unset api.api_key # remove one value lium config path # print the config file path lium config reset [--confirm] # reset to defaults lium config edit # open in the default editor ``` ## lium theme Set the CLI color theme. The argument is required and accepts only two values. ```bash lium theme {dark|light} ``` ## lium fund Fund the account with TAO — or with free alpha stake — from your wallet. **Always pass `-y` for agent use.** ```bash lium fund [OPTIONS] -w, --wallet TEXT Name of the local wallet to fund from -a, --amount TEXT Amount to fund with (TAO; USD when --alpha) --alpha Fund with free alpha stake -k, --hotkey TEXT Origin hotkey the alpha is staked under — SS58 address or wallet hotkey name (required with --alpha) --json Print machine-readable JSON -y, --yes Skip confirmation prompts ``` Examples: ```bash lium fund -w default -a 1.5 -y lium fund --alpha -k -a 25 -y --json # -a is USD when --alpha ``` ## lium topup Top up the balance with a stablecoin. ```bash lium topup currencies [OPTIONS] # list supported stablecoins and networks --refresh Bypass the cache and re-fetch --json Print machine-readable JSON lium topup create [OPTIONS] # create an invoice, print the deposit address -a, --amount FLOAT Top-up amount in USD (required) -c, --currency TEXT Stablecoin code, e.g. USDT (required) -n, --network TEXT Network, e.g. tron (required) --json Print machine-readable JSON ``` Send exactly the returned `crypto_amount` to the deposit address on that network; the balance is credited once the transfer confirms. ```bash lium topup create -a 20 -c USDT -n tron --json ``` ## lium mine Bootstrap a **provider** machine: clone `Datura-ai/lium-io` into `compute-subnet`, install the executor tooling, write `neurons/executor/.env` and start the executor container. It runs on the GPU host you are contributing, not on a renter's laptop. `lium provider --help` calls this "renter workflows" — that blurb is wrong; the code clones and starts a provider executor. ```bash lium mine [OPTIONS] -k, --hotkey TEXT Miner hotkey SS58 address -d, --dir TEXT Target directory -b, --branch TEXT Branch to install from -a, --auto Run without prompting -v, --verbose Show the plan banner ``` With `--register TOKEN` (the command the portal's Add Node page shows) it also adds the node to your account and waits until it is listed; `lium mine --help` lists `--price`, `--gpu-type`, `--wait` and `--portal-url` for that path. *(0.17.0)* `--ip` registers the node at a given public IPv4 (CGNAT, or a port-forwarding VPS), `--internal-port` sets the port the service listens on (default 8080) and `--external-port` the port validators connect to (default: the internal one). A service or SSH port another process holds now fails before `docker compose up`, naming that process. ## lium provider Provider-side commands — a different persona from `lium mine`. Hotkey registration on SN51 itself is done with `btcli subnet register`, not here. ```bash lium provider [OPTIONS] COMMAND [ARGS]... -w, --coldkey TEXT Bittensor coldkey (wallet) name; falls back to LIUM_PROVIDER_COLDKEY, then `provider.coldkey` in the config -k, --hotkey TEXT Hotkey name on that coldkey; falls back to LIUM_PROVIDER_HOTKEY, then `provider.hotkey` --portal-url TEXT Override the lium-miner-portal base URL --json Machine-readable JSON (one envelope per command) --debug Error context on stderr; verbose logging -y, --yes Auto-confirm the persona gate for spend-affecting subcommands --dry-run Skip irreversible subprocess calls (e.g. ssh), report intent only ``` Sub-commands: `billing`, `config`, `machine`, `machine-request`, `node`, `portal`, `status`, `sync`. Run `lium provider --help` for their flags. `lium provider node address NODE_ID IP_ADDRESS PORT` moves a node to a new IP and port and keeps its id and history. ## lium gpu-splitting Prepare Docker storage on a host for LIUM GPU splitting. ```bash lium gpu-splitting check [--device PATH] # inspect the host, print the plan, change nothing lium gpu-splitting setup [--device PATH] --yes # end-to-end Docker storage setup lium gpu-splitting verify # verify the host meets the requirements ``` `setup` is the only one that changes the host, and it stops on an interactive confirmation of the plan — pass `--yes` from a script. ## lium whoami Show the API key in use (fingerprint and source), the account, balance, SSH key and CLI version. The first thing to run when a command answers 401 or acts on the wrong account. ```bash lium whoami lium whoami --json | jq .account_id ``` ## lium spend Hourly burn, estimated spend per active pod, and the runway the balance leaves. Spent is price × wall time since each pod was created (a PENDING pod is $0); it is an estimate, not the billed amount — `lium billing history` is the ledger. ```bash lium spend lium spend --format json | jq '.burn_per_hour, .runway_hours' ``` ## lium billing The account's charges as the ledger recorded them. ```bash lium billing history # every pod charged, removed ones included ``` ## lium request Ask providers for a GPU type that is sold out. The providers who list that GPU type are told, and the request shows on https://lium.io/machine-requests. ```bash lium request B300 -n 8 # -n/--count: GPUs wanted on one node lium request H200 --json ``` ## lium cp Copy files between two pods directly over SSH: the data goes pod to pod, not through this machine. A one-off key is placed for the copy and removed afterwards. Both pods need `rsync`. POD is a name, HUID, id or index from `lium ps`; a trailing `/` on a source directory copies its contents, as in rsync. ```bash lium cp dev-pod:/workspace/src train-pod:/workspace/ lium cp 1:/workspace/ckpt/ 2:/workspace/ckpt/ --exclude '*.tmp' --bwlimit 50000 # --bwlimit KIB_PER_S --exclude PATTERN (repeatable) --delete --json ``` ## lium clusters Multi-node clusters on one InfiniBand/RoCE fabric: rent N whole nodes of one fabric as a single all-or-nothing cluster. Every member runs the cluster template, shares the pod name and gets a private overlay address (10.42.0.); node 0 is the master. ```bash lium clusters # fabrics with free nodes (same as 'clusters list') lium clusters --format json # for scripts and agents lium clusters up 1 --nodes 2 -n job # rent 2 nodes of fabric #1 as one cluster lium clusters ps # your clusters lium clusters show job --hostfile # members, overlay IPs, mpirun hostfile lium clusters rm job -y # remove every member ``` ## lium completion Print the shell line that enables tab completion, or install it. ```bash lium completion zsh # print the line for zsh lium completion --install # append it to the current shell's rc file ``` ## Batch Operations `exec`, `scp`, `rsync`, `rm` and `reboot` take several targets at once, as a comma-separated list or `all`: ```bash lium exec 1,2,3 "apt update" lium exec all "nvidia-smi" lium scp all ./requirements.txt lium rsync all ./project lium rm 1,2,3 -y ``` ## Pod Targeting The pod argument is called `TARGET` (single) or `TARGETS` (several) in the CLI's own help; `logs`, `ps` and the `bk` sub-commands call it `POD_ID`. What each form accepts is **not** uniform: | Form | Example | Accepted by | |------|---------|-------------| | Name / HUID / UUID | `lium ssh eager-wolf-aa` | every command | | Index from the last `lium ps` | `lium ssh 1` | `ssh`, `exec`, `scp`, `rsync`, `rm`, `reboot`, `update`, `port-forward`, `bk *`, `audit --pod` (since 0.0.37) — **not** `ps`, `describe` or `logs` | | Comma list | `lium exec 1,2,3 "cmd"` | `TARGETS` commands only | | All | `lium exec all "cmd"` | `TARGETS` commands only | `lium ps 1`, `lium describe 1` and `lium logs 1` match the literal string `1` against pod names and IDs; they do not resolve indices, so they report the pod as not found unless a pod is actually named `1`. An index is resolved against the last `lium ps` **run in this shell** (the CLI keeps that snapshot for 10 minutes) and refused with exit 2 / `stale_pod_index` (a configuration error: "Pod index 1 cannot be used before 'lium ps' has shown the list in this shell") when there is no snapshot, it is older than 10 minutes, or the pod that row showed is gone. Prefer names: read them once with `lium ps --format json` and pass those. ## Environment Variables ```bash LIUM_API_KEY=xyz lium ls # override the API key LIUM_DEBUG=1 lium up --gpu H100 -y # debug output LIUM_BASE_URL=https://staging.lium.io/api lium signup --email ada@example.com LIUM_SIGNUP_PASSWORD=pw lium signup --email ada@example.com # keeps the password off argv LIUM_PROVIDER_COLDKEY=... LIUM_PROVIDER_HOTKEY=... lium provider status ``` `LIUM_BASE_URL` (default `https://lium.io/api`, the `/api` suffix included) points the SDK **and** `lium signup` at another backend — use it to sign up against staging. `LIUM_PAY_URL` overrides the payments backend the same way. There is no `LIUM_SSH_KEY` variable — the SSH key path lives in the config (`lium config set ssh.key_path ...`). ## Exit Codes | Code | Meaning | |------|---------| | 0 | Success | | 1 | General error | | 2 | Configuration error (bad arguments, unreadable script, missing config, no API key) | | 3 | API error — the API refused or failed the call: 401 (bad or revoked key), 404, 429, 5xx | | 4 | SSH error | | 5 | Pod not found | | 6 | Permission denied — the API answered 403 (an empty balance on `lium up`, for one) | Since **0.0.31** (lium#104) every command runs under one error handler (`handle_errors` in `lium/cli/utils.py`), so the table holds for all of them: `lium ps` with a revoked key exits `3`; `lium up` with an empty balance exits `6`. `lium ls` reads the public node list and succeeds with any key, so it is not a key check. Inside a batch the rule changes: `rm`, `reboot`, `scp`, `rsync` (and `volumes rm`, `schedules rm`) finish the batch and exit `1` naming the items that failed, whatever the API answered for them (`Failed to remove pods: brave-orbit-b9`); only their target lookup before the batch exits `3`/`6`. The exceptions are `lium provider …`, which keeps its own map (`1` arguments, `2` auth, `3` portal, `5` ssh, `6` config missing, `7` token-cache contention), and `lium gpu-splitting …`, which runs on the host without the API and exits `1` on any failure. `lium exec` exits with the remote command's code (`5` when no pod matched, `2` on a bad argument or unreadable script). Under `--json` (`exec`, `describe`, `balance`, `fund`, `topup`, `signup`) a failure is one JSON object on stderr, `{"ok": false, "error": {"code": ..., "message": ...}}`, and stdout stays empty; `--format json` (`ls`, `ps`) reports a failure as text. `lium audit` *(since 0.0.37)* adds nothing to the table: its 401 is exit `3` like every other command's, with the hint that if the key works for `lium ps` the backend does not yet open `/users/me/events` to API keys. --- # Python SDK — Full Reference # Lium Python SDK Reference Written against `lium.io` **0.0.37** (`lium/sdk/client.py`, tag `v0.0.37`), checked against **0.16.1** on 2026-10-15: rows marked *(0.16.1)* exist in 0.16.1 and not in 0.0.37. Signatures below are copied from the source; when in doubt, `python -c "import lium, inspect; help(lium.Lium)"` is the authority. ## Table of Contents - [Installation & Auth](#installation--auth) - [High-Level SDK (lium.sdk.Lium)](#high-level-sdk-liumsdklium) - [Agent Recipe](#agent-recipe) - [@machine Decorator](#machine-decorator) - [Models](#models) - [Exceptions](#exceptions) ## Installation & Auth ```bash pip install lium.io # CLI + SDK in one package (or: uv tool install lium.io) ``` The old `lium-sdk` package on PyPI is **deprecated** — its last release only says "renamed to lium.io". There is no separate low-level `lium.Client` / `lium.AsyncClient` in `lium.io`; `import lium` re-exports `lium.sdk` (`lium.Lium` is `lium.sdk.Lium`). Authentication is loaded by `Config.load()` in this order: 1. `LIUM_API_KEY` environment variable 2. `~/.lium/config.ini` → `[api] api_key` (written by `lium init` / `lium signup`) `Lium()` takes **no `api_key` keyword**. To pass a key explicitly build a `Config`: ```python from pathlib import Path from lium.sdk import Lium, Config lium = Lium() # env var or config.ini lium = Lium(config=Config(api_key="sk_...", ssh_key_path=Path("~/.ssh/id_ed25519").expanduser())) ``` `Config.load()` raises `ValueError("No API key found. Set LIUM_API_KEY or ~/.lium/config.ini")` when neither source has a key. The SSH private key is auto-discovered from `~/.ssh/id_ed25519`, `~/.ssh/id_rsa`, `~/.ssh/id_ecdsa` (first that exists); its `.pub` is what gets registered on the pod. `LIUM_BASE_URL` (default `https://lium.io/api`) points the SDK at another backend. --- ## High-Level SDK (lium.sdk.Lium) ```python from lium.sdk import Lium lium = Lium() ``` Signatures follow Python notation: everything after `*` is keyword-only and raises `TypeError` when passed positionally. `lium.exec(pod, "nvidia-smi")` fails — it has to be `lium.exec(pod, command="nvidia-smi")`. Methods that take a `pod` want a `PodInfo` (from `ps()` / `wait_ready()`), not an id string, unless stated. Every HTTP call goes through one `_request` with a 30 s timeout (none for `logs(follow=True)`). Reads (`GET`, `HEAD`, `OPTIONS`) get **up to 3 attempts with back-off** on 429, 5xx and connection errors; anything that mutates (`POST`, `PUT`, `PATCH`, `DELETE`) is, by default, repeated only after a 429 — a timed-out `POST` may have succeeded server-side, and repeating it blindly would create a second pod, template or backup. Three idempotent POSTs opt in to the full retry (`schedule_termination`, `backup_cancel`, `restore_cancel`); `pod_events` and the rent are sent exactly once. The rent inside `up()` is sent exactly once with an `Idempotency-Key` header; if that request fails (timeout, 5xx, 429), `up()` first looks for a pod with your `name` on that node (`ps()`, 3 tries) and only re-sends when none exists. Give every pod a unique `name` — it is what makes that lookup unambiguous — and check `ps()` before retrying yourself. ### Discovery | Method | Returns | Notes | |--------|---------|-------| | `ls(*, gpu_type=None, gpu_count=None, lat=None, lon=None, max_distance_miles=None, min_cuda_version=None)` | `list[ExecutorInfo]` | `gpu_type` is a short name (`"H200"`, `"RTX4090"`); `gpu_count` matches nodes with exactly that many GPUs. No country or price filter — filter the list yourself. | | `ls(…, min_cpus=None, view="summary")` | `list[ExecutorInfo]` | *(0.16.1)* `min_cpus` floors the CPU thread count; `view="full"` returns the whole public node-check scrape in `specs`, without what the renters' pods are doing (docker containers, GPU processes, per-GPU load, memory in use, current clocks and PCIe link); a renter reads their own pod's load with `gpu_stats`. | | `ls(…, nvlink=True, min_download_mbps=2000)` | `list[ExecutorInfo]` | Only nodes where Lium saw every GPU pair on NVLink / whose Download (Mbps, the `lium ls` figure) is at least that; unreported nodes excluded; sent to the API and applied client-side too *(since 0.4.0, lium#149)*. | | `get_executor(executor)` | `ExecutorInfo \| None` | Node by UUID or HUID (`cosmic-hawk-f2`) against the `ls()` listing; `ValueError` when a HUID names two nodes *(0.16.1; 0.0.37: UUID only, `executor_id`)*. | | `gpu_types()` | `set[str]` | Machine names advertised by `/machines`. | | `ps()` | `list[PodInfo]` | Your pods. `executor.price_per_hour` is the pod's billed $/h. | | `pod_by_name(name)` | `PodInfo \| None` | *(0.16.1)* Pod by name, HUID or id; first match wins. | | `me()` | `dict` | *(0.16.1)* `GET /users/me`: `id`, `email`, `balance`. | | `gpu_short_types()` | `list[str]` | *(0.16.1)* The values `ls(gpu_type=)` / `--gpu` accept. | | `pod(pod_id)` | `dict` | Raw `GET /pods/{id}` payload (template, executor, ports, status…). | | `templates(filter=None, only_my=False)` | `list[Template]` | Substring match on image or name. Objects carry `.id`. | | `get_template(template_id)` | `Template \| None` | Takes an ID, HUID or name. A UUID is fetched with `GET /templates/{id}`; if that is 404 it falls back to your own templates whose name is that UUID. A HUID or name picks only your own templates; someone else's public template is chosen by its ID, so a public look-alike name or HUID is never picked silently (when only public templates match, `LiumError` names their IDs and images). Raises `LiumError` when more than one template matches (use the ID). `None` when nothing matches; other errors, including a refused key, raise. *(since 0.18.0, lium#317)* | | `get_template_by_image_name(image_name, image_tag)` | `Template \| None` | Exact image + tag match. | | `default_docker_template(executor_id)` | `Template` | The PyTorch template the node's driver supports; what `lium up` uses without `-t`. | | `get_deployment_estimate(executor_id, template_id)` | `dict` | `estimated_seconds`, `is_slow_machine`, `warning_message`, `is_cached_template`, `docker_image_size`. | ### Pod Lifecycle | Method | Returns | Notes | |--------|---------|-------| | `rent(*, gpu_type, gpu_count=1, name=, template_id=, min_vram_gb=, min_cpus=, min_ram_gb=, min_disk_gb=, min_download_mbps=, max_price_per_gpu_hour=, country=, dry_run=)` | `RentResult` | **Since 0.0.39 (lium#209)** — on 0.0.37/0.0.38 (`pip show lium.io`) use `ls()` + `up(executor_id=)` below. Rent the cheapest node matching a spec in one call (the backend picks when `GET /version` lists `rent_by_spec` — production does today; against an older backend the client picks the cheapest exact match; `dry_run=True` prices without renting). `.pod`, `.executor`, `.price_per_hour`. | | `up(*, executor_id, name="Your Pod", template_id=None, image=None, gpu_count=None, wait=False, timeout=…, dockerfile_content=None, volume_id=None, ports=None, ssh_keys=None, ssh_name=None, enable_volume_encryption=True, backup_id=None, restore_path=None)` | `dict` | Raw rent response (`id`, `pod_name`, `status`, …). **Not** a `PodInfo` — pass it to `wait_ready`. Registers your SSH public key server-side first. `template_id` and `dockerfile_content` are mutually exclusive; `backup_id`/`restore_path` go together. Raises `ValueError` for an unknown executor or when no SSH key is found. *(0.16.1)*: `image="repo/name:tag"` runs any image (a one-time template, deleted with the pod; exclusive with `template_id` / `dockerfile_content`); `gpu_count` rents only that many of the node's GPUs (GPU splitting; `None` = every free GPU); `wait=True` returns the ready `PodInfo` instead of the dict. | | `wait_ready(pod, *, timeout=300, poll_interval=None, on_poll=None, ready_port=None)` | `PodInfo \| None` | `pod` may be an id string, a `PodInfo` or the dict from `up()`. Polls `ps()` until `status == "RUNNING"` and `ssh_cmd` is set — every 2 s for the first 90 s, then every 10 s (`poll_interval` fixes the interval; `on_poll(pod, status, elapsed)` is called after each poll). **Returns `None` on timeout** (`timeout=None` waits until ready or failed) — the pod may still be provisioning and billing; check `ps()` and `down()` it. *(0.16.1)* `ready_port=8000` also waits until that TCP port answers inside the pod, within the same `timeout`. **Raises `PodStartError`** when the pod reaches `FAILED`, `CREATION_FAILED`, `STOPPED`, `BROKEN`, … , vanishes after being listed, or is still not listed 20 s after the first poll; the error carries `.pod`, `.status`, `.history` and `.cause` (the backend's reason). | | `refresh_pod(pod)` | `PodInfo` | Re-read one pod (`pod` may be an id or a `PodInfo`); `LiumNotFoundError` when it is gone. | | `pod_events(pod_id)` / `pod_failure_cause(pod_id)` | `list[dict]` / `str \| None` | The pod's event log (`GET /pods/{id}/events`) and the last failure reason in it — what `PodStartError.cause` is filled from. | | `poll_delay(elapsed, poll_interval=None)` | `float` | Class method: the sleep `wait_ready` uses (2 s under 90 s elapsed, 10 s after). | | `down(pod)` / `rm(pod)` | `dict` | `DELETE /pods/{id}`. Irreversible. | | `reboot(pod, volume_id=None)` | `dict` | Re-creates the container; only the volume (`/workspace` by default) survives. | | `logs(pod_id, *, tail=100, follow=False)` | `Generator[bytes]` | Container PID 1 output. Takes an **id string**. | | `schedule_termination(pod, *, termination_time)` | `dict` | `termination_time` is an ISO 8601 UTC string, e.g. `"2026-09-05T18:00:00Z"`. This is what `lium up --ttl` calls. | | `cancel_scheduled_termination(pod)` | `dict` | | | `switch_template(pod, *, template_id)` | `PodInfo` | `PUT /pods/{id}/switch-template`. | | `edit(pod_id, **kwargs)` | `dict` | Merges kwargs into the pod's template and `PUT`s it. | | `install_jupyter(pod, *, jupyter_internal_port)` | `dict` | | | `rental(*, executor_id, timeout=600, **up_kwargs)` | context manager → `PodInfo` | *(0.16.1)* Rent for the duration of a `with` block; the pod is removed however the block ends, also when it never became ready. | | `cap_spend(pod, *, budget_usd)` | `datetime` | *(0.16.1)* Schedule removal at the moment the pod will have spent `budget_usd` (an earlier `--ttl` stays). Client-side arithmetic on the hourly price. | | `clusters()` / `cluster_offer(fabric_id)` | `list[ClusterOffer]` / `ClusterOffer \| None` | *(0.16.1)* Free nodes on one InfiniBand/RoCE fabric, rentable as one cluster. | | `up_cluster(executor_ids, *, name, template_id=None, ports=None, wait=False, timeout=900)` | `Cluster` | *(0.16.1)* All-or-nothing rent of ≥ 2 whole nodes of one fabric; members share `name`, get overlay IPs 10.42.0.. `ClusterNotListedError`: may have rented — check `my_clusters()` before retrying. | | `wait_cluster_ready(cluster, *, timeout=900)`, `my_clusters()`, `cluster(id)`, `rm_cluster(cluster)` | | *(0.16.1)* Wait / list / one / remove every member in one call (per-member `success` in the result). | | `request_machine(gpu, count=None)` | `dict` | *(0.16.1)* Ask providers for a sold-out GPU type (`lium request`). | 0.0.37 had no `wait=` on `up()` and no context-manager form; on such installs compose them yourself (see [Agent Recipe](#agent-recipe)). There is still no `ttl=` on `up()`: use `schedule_termination` or `cap_spend`. ### Remote Execution | Method | Returns | Notes | |--------|---------|-------| | `exec(pod, *, command, env=None, timeout=None, detach=False, log_path=None, max_output_bytes=…)` | `dict` | `{"stdout", "stderr", "exit_code", "success"}`. Runs over paramiko; `env` values travel over stdin, never on the command line. *(0.16.1)* `timeout=` closes the channel and raises `TimeoutError` (the remote process may keep running); `detach=True` starts it under `nohup setsid`, logs to `log_path` (default `/workspace/logs/exec--.log`) and returns `{pid, log_path, command}` at once. On 0.0.37 there is **no timeout** — wrap the remote side in `timeout 600 bash -lc '...'` — and it blocks until every process holding stdout/stderr exits. Output past the 2 MiB SSH window no longer hangs it, and `max_output_bytes` (default 64 MiB, stdout and stderr together) raises `OutputLimitExceeded` past the limit; it bounds output bytes, not memory (peak is about twice the limit for ASCII output) *(since 0.18.0, lium#317)*. | | `run_background(pod, command, *, name=None, env=None, workdir=None, job_dir="/workspace/logs")` → `Job`; `jobs(pod)`, `job(pod, name)` | `Job` | *(0.16.1)* Background job that survives the session (PID, log, exit code files under `job_dir`); `job()` re-attaches by name; `Job.wait_for_port()` stops early when the job dies. | | `wait_for_port(pod, port, *, timeout=600)` | `None` | *(0.16.1)* Block until the port accepts connections inside the pod; `TimeoutError` otherwise. | | `gpu_stats(pod)` | `list[GpuStats]` | *(0.16.1)* Per-GPU utilisation, memory, temperature, power via `nvidia-smi`. | | `ssh_session(pod)` | context manager | *(0.16.1)* One SSH connection reused by every `exec`/`upload`/`download` inside the block (saves a handshake per call). | | `stream_exec(pod, *, command, env=None, pty=True, check=False)` | `Generator[dict]` | Yields `{"type": "stdout"\|"stderr", "data": str}`; a PTY merges stderr into stdout, `pty=False` *(0.16.1)* keeps them apart. The generator's return value is the exit status; `check=True` *(0.17.0)* raises `RemoteExecutionError` after the last chunk on a non-zero exit. | | `exec_all(pods, *, command, env=None, max_workers=10, max_output_bytes=…)` | `list[dict]` | Threaded `exec` across pods; each result carries `"pod"`. Takes `max_output_bytes` too *(since 0.18.0, lium#317)*. | | `ssh(pod, *, refresh=False)` | `str` | `ssh -i -p -o StrictHostKeyChecking=accept-new -o 'UserKnownHostsFile="/home//.lium/known_hosts/"' root@` — a ready command line with the pod's host key pinned. `refresh=True` re-reads the pod first. | | `ssh_argv(pod)` | `list[str]` | The same command as an argument list for `subprocess`. | | `ssh_connection(pod, timeout=30)` | context manager → `paramiko.SSHClient` | For SFTP or custom channels. Pins the host key the same way; a changed key raises `LiumHostKeyError` (`LIUM_SSH_INSECURE=1` disables the check). | `env` values are exported with `export NAME=`, so any value is safe (spaces, quotes, `$`). ### File Transfer | Method | Returns | Notes | |--------|---------|-------| | `scp(pod, *, local, remote)` / `upload(pod, *, local, remote)` | `None` | SFTP **single file**, local → pod. `remote` must be a file path, not a directory. | | `download(pod, *, remote, local)` | `None` | SFTP single file, pod → local. | | `rsync(pod, *, local, remote, bwlimit=None, exclude=None, delete=False, partial=True, progress=False, download=False)` | `None` | Over the pinned-host-key `ssh`; raises `RuntimeError` on failure. *(0.16.1)* `download=True` copies pod → local; `bwlimit` KiB/s, `exclude` patterns, `partial` resumes. On 0.0.37: `rsync -avz` local → pod only, no options. | | `cp(src_pod, src_path, dst_pod, dst_path, *, bwlimit=None, exclude=None, delete=False)` | `dict` | *(0.16.1)* Pod → pod directly (a one-off key, removed afterwards); both pods need `rsync`. | | `get_default_images(gpu_model, driver_version)` | `list[dict]` | The default images the backend offers for a GPU model + driver (`GET /executors/default-docker-image`). | For directories coming **back**, or for bandwidth-limited / resumable transfers, call `rsync` yourself with `pod.host`, `pod.ssh_port` and `lium.config.ssh_key_path` (recipe below). ### Templates, Volumes, Backups | Method | Notes | |--------|-------| | `create_template(name, docker_image, docker_image_digest="", docker_image_tag="latest", ports=None, start_command=None, **kwargs)` | Positional-friendly. kwargs: `category` (default `"UBUNTU"`), `is_private` (`True`), `volumes` (`["/workspace"]`), `description`, `environment`, `entrypoint`, `one_time_template`, `readme`. Image must be Debian/Ubuntu-based (verification installs `openssh-server` with apt). | | `update_template(template_id, name, docker_image, docker_image_digest, docker_image_tag="latest", ports=None, start_command=None, **kwargs)` | Only your own templates; triggers re-verification. | | `wait_template_ready(template_id, timeout=300)` | `Template` on `VERIFY_SUCCESS` (or `CREATED`/`UPDATED`, which is all a public template ever shows), `None` on timeout, raises `LiumError` on `VERIFY_FAILED`. *(since 0.18.0, lium#317)* | | `volumes()`, `volume(volume_id)`, `volume_create(name, *, description="")`, `volume_update(volume_id, *, name=None, description=None)`, `volume_delete(volume_id)` | `VolumeInfo` objects. | | `backup_create(pod, *, path, frequency_hours=6, retention_days=7)` | `path` is required; warns when it equals the whole volume. | | `backup_now(pod, *, name, description="")` | Immediate backup. | | `backup_config(pod)`, `backup_list()`, `backup_logs(pod)`, `backup_logs_all()`, `backup_log(backup_id)` | Config and history. | | `backup_delete(config_id)`, `backup_cancel(backup_id)`, `backup_log_delete(backup_id)` | Remove the config / cancel an active backup / delete a completed backup's data. | | `restore(pod, *, backup_id, restore_path=None)` | Default `restore_path` is `pod.default_restore_path` (`/restored`). | | `restore_logs(pod)`, `restore_cancel(restore_id)` | | | `backup_update(config_id, *, path, frequency_hours, retention_days)` | *(0.16.1)* Replace a backup schedule in place. | | `resolve_backup_id(backup_id)`, `resolve_restore_id(restore_id)` | Expand the 8-char ids the CLI prints. | ### Account | Method | Returns | Notes | |--------|---------|-------| | `balance_or_none()` | `float \| None` | *(0.16.1)* `None` when the answer has no balance (where `balance()` says 0). | | `balance()` | `float` | USD, from `GET /users/me`. Raises `LiumAuthError` on a bad key — the cheapest auth check. | | `get_my_user_id()` | `str` | | | `list_ssh_keys()` / `register_ssh_key(*, name, public_key)` | `list[SSHKey]` / `SSHKey` | `up()` calls this for you. | | `topup_currencies(refresh=False)` | `list[dict]` | Stablecoin `{code, network, …}` pairs. | | `topup_create_invoice(amount, crypto_currency, crypto_network)` | `dict` | `deposit_address`, `crypto_amount`, `expires_at`, … | | `wallets()`, `add_wallet(bt_wallet)`, `convert_alpha(usd, netuid=…)`, `company_wallet(app_id)`, `alpha_subnets()` | | TAO and alpha funding plumbing used by `lium fund`. | | `topup_checkout_link(amount_usd, success_url=None, cancel_url=None)` | `dict` | *(0.16.1)* A Stripe Checkout `url` for a **person** to pay by card (min $10); nothing is charged by the call. Needs a `billing`-scope key. | | `wait_for_credit(baseline, timeout=600)` | `dict` | *(0.16.1)* Poll until the balance rises above `baseline` (read `balance()` before paying): `{credited, balance, seconds}`. | | `billing_statement(*, start_day=None, end_day=None)` | `dict` | *(0.16.1)* What the ledger charged, removed pods included: `days` has one entry per billing-ledger row, so a UTC day can appear more than once (a pod moved node, or billing stopped and resumed) *(wording 0.16.2)*. | | `audit_log(*, since=, until=, action=, source=, api_key_id=, resource_id=, cursor=, limit=100)` | `dict` | *(0.16.1)* Account audit log, newest first (`action` prefix filter such as `pod.`); page with `next_cursor`. | | `features()` / `supports(feature)` | `set` / `bool` | *(0.16.1)* Optional capabilities the backend advertises on `GET /version` (e.g. `rent_by_spec`). | | `events(*, since=, pod_id=, api_key_id=, limit=200)` | `list[dict]` | The account's event log, newest first: each entry names the session or API key (`actor.api_key_id` / `api_key_name`, `None` for the platform) behind a rent, reboot, edit or delete; `pod_id` also answers for a deleted pod *(since 0.0.37; an API key needs the read scope)* | --- ## Agent Recipe Everything an autonomous run needs, with the safety rails the SDK does not add on its own: unique name, TTL, GPU-count check, detached job, resumable pull, guaranteed teardown. ```python import shlex, subprocess, time, uuid from datetime import datetime, timedelta, timezone from lium.sdk import Lium, LiumError, PodStartError lium = Lium() name = f"job-{uuid.uuid4().hex[:6]}" # unique: lets you find it in ps() after a timeout want = 8 nodes = [e for e in lium.ls(gpu_type="H200", gpu_count=want) if e.tier != "spot"] if not nodes: raise SystemExit("no matching node") node = min(nodes, key=lambda e: e.price_per_gpu) # Since 0.0.39 (lium#209): the same in one call, no listing # rented = lium.rent(gpu_type="H200", gpu_count=want, name=name) # pod = lium.wait_ready(rented.pod, timeout=600) pod = None try: created = lium.up(executor_id=node.id, name=name) try: pod = lium.wait_ready(created, timeout=600) except PodStartError as exc: # FAILED / CREATION_FAILED / vanished: dead, not slow pod = exc.pod # may still be listed — the finally removes it raise LiumError(f"pod failed to start: {exc.status}; cause: {exc.cause}") from exc if pod is None: # still billing — find it and stop it pod = next((p for p in lium.ps() if p.name == name), None) raise LiumError("pod did not become ready") # TTL — the equivalent of `lium up --ttl 4h` until = (datetime.now(timezone.utc) + timedelta(hours=4)).strftime("%Y-%m-%dT%H:%M:%SZ") lium.schedule_termination(pod, termination_time=until) # Verify what you pay for: billed count vs devices the container can see. # pod.gpu_count is the pod row's own count (a GPU-split rental bills a share of # the node); executor.gpu_count is the whole host. billed = pod.gpu_count if pod.gpu_count is not None else (pod.executor.gpu_count if pod.executor else None) seen = int(lium.exec(pod, command="nvidia-smi -L | wc -l")["stdout"].strip() or 0) if seen != want or (billed is not None and billed != want): raise LiumError(f"GPU count mismatch: requested {want}, billed {billed}, visible {seen}") # Detached job — exec() would otherwise block until the job ends job = "cd /workspace && python train.py" r = lium.exec(pod, command=( "mkdir -p /workspace/logs && nohup setsid bash -lc " + shlex.quote(job) + " > /workspace/logs/train.log 2>&1 < /dev/null & echo $!")) pid = int(r["stdout"].strip()) while lium.exec(pod, command=f"kill -0 {pid}")["success"]: time.sleep(60) print(lium.exec(pod, command="tail -n 3 /workspace/logs/train.log")["stdout"]) # Pull results: rsync back, resumable, no compression for binary output. # ssh_argv() carries -i, -p and the pinned host key; drop the trailing user@host. ssh = shlex.join(lium.ssh_argv(pod)[:-1]) subprocess.run(["rsync", "-a", "--partial", "--inplace", "--bwlimit=20000", "-e", ssh, f"{pod.username}@{pod.host}:/workspace/out/", "./out/"], check=True) finally: if pod is not None: lium.down(pod) # always; the TTL is only the backstop ``` Notes: - `exec(..., command="kill -0 PID")` is a cheap liveness probe; `tail -n` the log file rather than streaming it. - For pod-to-pod copies (edit on a cheap pod after an 8-GPU render), rsync from inside the source pod to the destination's `host:port`; the destination must trust the source's SSH key — generate one on the source with `ssh-keygen -N ""` and append its `.pub` to the destination's `~/.ssh/authorized_keys` via `exec`. - Keep `HF_HOME=/workspace/hf` and venvs under `/workspace` — `/root` is an encrypted FUSE mount and is slow for large files (details in the skill). --- ## @machine Decorator Run one Python function on a GPU pod: rents the cheapest node matching `machine`, ships the function's `def`, installs `requirements` once per pod (on top of the image's own packages — torch is already there on the PyTorch template), streams the function's stdout/stderr live, returns the result or re-raises the remote exception, removes the pod or keeps it warm. **Since 0.0.40 (lium#208).** On 0.0.37–0.0.39 the decorator takes only `machine`, `template_id`, `cleanup` and `requirements`, and its `requirements` go into a plain `python3 -m venv` that does **not** see the image's packages — list torch and every other import there; `timeout`, `keep_warm`, `quiet`, `local`, `.map`/`.local`/`.close`, the venv that sees the image's packages and the result/error semantics below need 0.0.40 — the example as written raises `TypeError` on the older releases. ```python import lium @lium.machine(machine="1xH200", requirements=["transformers", "accelerate"], timeout=900, keep_warm=300) def run(model_name: str, prompt: str) -> str: import torch from transformers import AutoModelForCausalLM, AutoTokenizer tok = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.bfloat16, device_map="cuda") ids = tok(prompt, return_tensors="pt").to("cuda") return tok.decode(model.generate(**ids, max_new_tokens=64)[0], skip_special_tokens=True) answer = run("Qwen/Qwen2.5-0.5B-Instruct", "What is the capital of France?") run.close() # remove the warm pod now ``` | Parameter | Type | Description | |-----------|------|-------------| | `machine` | str | `"x"` or `""`: `"1xH200"`, `"RTX4090"`, `"2xA100"`. Count defaults to 1. Cheapest matching node is rented. | | `requirements` | list, optional | pip packages, installed once per pod into a venv that also sees the image's packages | | `template_id` | str, optional | Docker template to rent with (default: the node's default template) | | `timeout` | float, default 3600 | seconds the function may run; `None` = no process limit. Pod removal is scheduled at `timeout + 15 min` (plus `keep_warm`), or 24 h when `timeout=None` | | `keep_warm` | float, default 0 | seconds the pod stays after a call for the next one (also from the next run of the script); removal re-armed to `keep_warm + 2 min` after each call | | `cleanup` | bool, default True | `False` skips the `down()` after the call and turns off pod reuse: `keep_warm` has no effect, no pod is kept for the next call, and `f.map()` rents one pod per item. Each pod still goes at its scheduled removal time | | `local` | bool, default False | run in-process (`LIUM_MACHINE_LOCAL=1` does it for every function; since 0.0.40, lium#208) | | `quiet` | bool, default False | suppress the `[lium]` progress lines on stderr | **On the decorated function:** `f.remote(*a)` (= `f(*a)`), `f.local(*a)`, `f.map(iterable)` (one item per call, all on one pod), `f.close()`. **What travels:** only the function's own `def` (decorators/annotations stripped) plus pickled arguments (your bytes, loaded on your pod). The result is not pickled: it comes back as a JSON envelope plus an `.npz` sidecar for numpy arrays, read with `allow_pickle=False`. What round-trips, each as its own type: `None`, `bool`, `int`, `float`, `str`, `bytes`; `list`, `tuple`, `set`, `frozenset`, `dict` of those, nested; `datetime`/`date`/`time`/`timedelta`, `Decimal`, `pathlib.Path`, `uuid.UUID`; `numpy.ndarray` (any dtype without Python objects) and numpy scalars. Anything else — a tensor, `torch.__version__`, a dataclass, an `Enum` — is a `lium.ResultEncodingError` raised on the pod naming the type; return `str(...)`, `.tolist()`, `.cpu().numpy()`, `dict(x)` instead. Import inside the body; a closure variable or a module-level name used inside is refused when the function is decorated (`LiumError` naming it). Nested functions and `async def` work; lambdas do not, and a method's `self` is pickled by reference, so it works only when its class is importable on the pod (not a class defined in the script). **Errors:** a remote exception of a builtin type (`ValueError`, `RuntimeError`, …) is re-raised with its own type and `e.__cause__` is `lium.RemoteExecutionError` with `exception_type`, `remote_traceback`, `exit_code`, `stdout`, `stderr`; any other class (`torch.OutOfMemoryError`, …) arrives as `RemoteExecutionError` itself, its name in `exception_type`, no `__cause__`. Timeout → `RemoteExecutionError: exceeded timeout=Ns and was killed`, no `__cause__`; no matching node or a failed rental → `LiumError`. Prints from the pod appear on the caller's terminal while the function runs. **Progress lines (stderr):** ``` [lium] run: renting 1xH200 $2.75/h (swift-fox-c8, United States), removal in 0.6h [lium] run: pod ready in 45s [lium] run: preparing environment (2 package(s): transformers, accelerate) [lium] run: environment ready in 31s [lium] run: running [lium] run: done in 118s (~$0.0901) [lium] run: pod stays warm 300s ``` Measured (6 Sep 2026, 1×RTX 4090 at $0.30/h): cold call ~70 s (~$0.006), warm call ~19 s, `transformers`+`accelerate` install 32 s once per pod. **Everything above except `machine`, `template_id`, `cleanup` and `requirements` needs 0.0.40 (lium#208)**: on 0.0.37–0.0.39 the decorator takes only those four, picks the first node whose name contains `machine` as a substring (`"H200"` — the `"x"` form matches nothing there), installs `requirements` into an isolated venv (torch included, if the function needs it), has no `timeout`/`keep_warm`/`local`/`quiet`, no `.map`/`.local`/`.close`, and results must be JSON-serialisable. --- ## Models Plain dataclasses (`lium.sdk.models`). Convert with `dataclasses.asdict(obj)`. ### ExecutorInfo | Field | Type | Description | |-------|------|-------------| | `id` | `str` | Executor UUID (pass to `up(executor_id=…)`) | | `huid` | `str` | Human-readable id derived from the UUID (`cosmic-hawk-f2`) | | `machine_name` | `str` | Full machine name, e.g. `NVIDIA H200` | | `gpu_type` | `str` | Short type parsed from the name (`H200`, `RTX4090`, …) | | `gpu_count` | `int` | GPUs on the node | | `price_per_hour` | `float` | USD/h for the whole node | | `price_per_gpu` | `float` | USD/h per GPU | | `location` | `dict` | `{"country": ..., "country_code": ..., ...}` when known | | `specs` | `dict` | Raw specs: `gpu.details[].name`, `gpu.driver`, `ram`, `hard_disk`, … | | `status` | `str` | | | `docker_in_docker` | `bool` | sysbox runtime available | | `ip` | `str` | Executor IP | | `available_port_count` | `int \| None` | | | `effective_upload_speed_mbps` / `effective_download_speed_mbps` | `float \| None` | Also as properties `upload_speed` / `download_speed` (0.0 when unknown) | | `max_cuda_version` | `float \| None` | Driver's CUDA ceiling, e.g. `13.0` | | `tier` | `str \| None` | `"secure"` or `"spot"` (reclaimable) | | `available_gpu_count` | `int \| None` | GPUs still free on a node that is partly rented (GPU splitting); `None` when the API did not say | | `interconnect` / `nvlink` | `dict` / `bool` (both `None` until reported) | How the GPUs are wired (`nvidia-smi topo -m` summary: `gpu_pairs`, `nvlink_pairs`, `nvlink_links`, `pcie_class`, `p2p`, `matrix`) and the NVLink verdict *(since 0.4.0)* | | `link` / `p2p` | properties | `"NV18"` / `"PCIe/SYS"` / `None`; every GPU pair can read the other's memory *(since 0.4.0)* | Properties: `driver_version` (str), `gpu_model` (first GPU's full name from specs). ### PodInfo | Field | Type | Description | |-------|------|-------------| | `id` | `str` | Pod UUID | | `name` | `str` | Pod name (`pod_name` in the API) | | `status` | `str` | `PENDING`, `RUNNING`, `FAILED`, `CREATION_FAILED`, … | | `huid` | `str` | Human-readable id | | `ssh_cmd` | `str \| None` | `ssh root@ -p ` once ready | | `ports` | `dict` | Internal → external port map | | `created_at` / `updated_at` | `str` | ISO timestamps | | `executor` | `ExecutorInfo \| None` | The node; `executor.gpu_count` is the **whole host's** GPU count, `executor.price_per_hour` the billed $/h | | `gpu_count` | `int \| None` | The **billed** GPU count — the pod row's own `gpu_count` from `/pods` (a GPU-split rental takes a share of the node); `None` on an older backend, fall back to `executor.gpu_count` | | `estimated_ready_seconds`, `eta_basis`, `phase` | `int \| None`, `str \| None`, `str \| None` | The backend's readiness estimate while the pod starts; the method `pod.eta_hint()` renders them as one line (`est. ready in ~18 s (phase: pulling image)`), `None` when absent | | `template` | `dict` | Raw template payload (`id`, `name`, `docker_image`, `volumes`, …) | | `removal_scheduled_at` | `str \| None` | TTL / scheduled termination | | `jupyter_installation_status`, `jupyter_url` | `str \| None` | | | `enable_volume_encryption`, `volume_encryption_status` | `bool \| None`, `str \| None` | | Properties: `host`, `username`, `ssh_port` (parsed from `ssh_cmd`; `ssh_port` defaults to 22), `volume_path` (first template volume, default `/root`), `default_restore_path` (`/restored`). There is **no** `started_at`, `restart_count` or `spend_to_date` — the API does not expose them yet; compute spend as `(now − created_at) × executor.price_per_hour` like `lium ps` does. ### Template | Field | Type | |-------|------| | `id`, `huid`, `name` | `str` | | `docker_image`, `docker_image_tag` | `str` | | `category` | `str` (`PYTORCH`, `UBUNTU`, `DOCKER`, …) | | `status` | `str` (`VERIFY_SUCCESS`, `VERIFY_PENDING`, `VERIFY_FAILED`, …) | ### VolumeInfo `id`, `huid`, `name`, `description`, `created_at`, `updated_at`, `current_size_bytes`, `current_file_count`, `current_size_gb`, `current_size_mb`, `last_metrics_update`. ### BackupConfig / BackupLog / RestoreLog / SSHKey - `BackupConfig`: `id`, `huid`, `pod_executor_id`, `backup_frequency_hours`, `retention_days`, `backup_path`, `is_active`, `created_at`, `updated_at`. - `BackupLog`: `id`, `huid`, `backup_config_id`, `status`, `started_at`, `completed_at`, `error_message`, `progress`, `stage`, `total_bytes`, `processed_bytes`, `throughput_bytes_per_second`, `estimated_remaining_seconds`, … - `RestoreLog`: `id`, `huid`, `backup_id`, `pod_id`, `status`, `progress`, `restore_path`, `stage`, `error_message`, … - `SSHKey`: `id`, `name`, `public_key`, `created_at`. --- ## Exceptions All in `lium.sdk` (and re-exported from `lium`): | Exception | Trigger | |-----------|---------| | `LiumError` | Base class; also raised for unmapped HTTP errors (`API error : …`) and when `up()` cannot find the pod it created | | `LiumAuthError` | 401 — invalid or revoked API key | | `LiumPermissionError` | 403 — `Permission denied: Insufficient balance` is the common one. Subclasses *(0.16.1)*: `LiumInsufficientBalanceError` (`.required`, `.available` USD), `LiumScopeError` (`.scope` the key lacks — another key fixes it, not funds), `LiumBudgetExceededError` (402 `API_KEY_BUDGET_EXCEEDED`: the key's day/month/lifetime budget; `.window`, `.budget_usd`, `.spent_usd`) | | `ClusterNotListedError` | *(0.16.1)* `up_cluster()` may have rented (`.confirmed`, `.pod_ids`); a second call may rent a second cluster | | `LiumNotFoundError` | 404 | | `LiumRateLimitError` | 429 (retried 3× first for every call except the rent POST inside `up()` and `pod_events()`, which are sent once) | | `LiumServerError` | 5xx (retried 3× first for `GET`/`HEAD`/`OPTIONS` and the three `retry=True` POSTs named above; raised at once for any other mutating call) | | `PodStartError` | `wait_ready()`: the pod reached a terminal status or vanished; carries `.pod_id`, `.pod`, `.status`, `.history`, `.cause` | | `RemoteExecutionError` | an `@lium.machine` call returned no result: carries `exception_type`, `remote_traceback`, `exit_code`, `stdout`, `stderr`; builtin exceptions re-raise with it as `__cause__` (since 0.0.40, lium#208) | | `ResultEncodingError` | (a `TypeError`) the function's return value is not in the round-trip list — JSON scalars/containers, bytes, numpy arrays (since 0.0.40, lium#208) | | `LiumHostKeyError` | `ssh_connection()` (so `exec()`, `scp()`, …): the pod's SSH host key differs from the one pinned under `~/.lium/known_hosts/` (`LIUM_SSH_INSECURE=1` disables the check) | | `OutputLimitExceeded` | `exec()`: stdout and stderr together passed `max_output_bytes`; the channel is closed, the SSH connection stays open *(since 0.18.0, lium#317)* | `ValueError` (not a `LiumError`) is raised for local problems: no API key, no SSH key, unknown executor id, conflicting arguments. `RuntimeError` comes from `rsync()`. paramiko exceptions (`paramiko.SSHException`, `socket.timeout`) surface unchanged from `exec()`/`scp()`. The 403 message does not say which key or account was used. When `balance()` works but `up()` says `Insufficient balance`, check that both processes resolve the same key (`LIUM_API_KEY` beats `~/.lium/config.ini`). Debugging: the SDK has no debug switch of its own (`LIUM_DEBUG=1` is read by the CLI's UI only); what remains is ```python import logging logging.basicConfig(level=logging.DEBUG) ```