gpu-rich 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gpu_rich/__init__.py +3 -0
- gpu_rich/_skills/.keep +0 -0
- gpu_rich/_skills/gpu-rich/SKILL.md +152 -0
- gpu_rich/_skills/gpu-rich/references/backends.md +85 -0
- gpu_rich/_skills/gpu-rich/references/job-format.md +107 -0
- gpu_rich/_skills/gpu-rich/references/json-contract.md +193 -0
- gpu_rich/_skills/gpu-rich/references/recipes.md +77 -0
- gpu_rich/_skills/gpu-rich/references/troubleshooting.md +136 -0
- gpu_rich/backends/__init__.py +44 -0
- gpu_rich/backends/base.py +115 -0
- gpu_rich/backends/brev.py +307 -0
- gpu_rich/backends/colab.py +648 -0
- gpu_rich/backends/hf_jobs.py +577 -0
- gpu_rich/backends/kaggle.py +823 -0
- gpu_rich/backends/local.py +177 -0
- gpu_rich/backends/modal.py +491 -0
- gpu_rich/backends/ssh.py +523 -0
- gpu_rich/bootstrap/__init__.py +1 -0
- gpu_rich/bootstrap/runner.py +391 -0
- gpu_rich/bundle.py +226 -0
- gpu_rich/catalog/__init__.py +9 -0
- gpu_rich/catalog/api.py +134 -0
- gpu_rich/catalog/commands.py +223 -0
- gpu_rich/catalog/data/catalog.sqlite +0 -0
- gpu_rich/catalog/index.py +481 -0
- gpu_rich/catalog/report.py +52 -0
- gpu_rich/cli.py +527 -0
- gpu_rich/config.py +38 -0
- gpu_rich/errors.py +88 -0
- gpu_rich/jobspec.py +110 -0
- gpu_rich/models.py +134 -0
- gpu_rich/output.py +55 -0
- gpu_rich/router.py +118 -0
- gpu_rich/skills_cmd.py +202 -0
- gpu_rich/store.py +69 -0
- gpu_rich-0.0.1.dist-info/METADATA +168 -0
- gpu_rich-0.0.1.dist-info/RECORD +40 -0
- gpu_rich-0.0.1.dist-info/WHEEL +4 -0
- gpu_rich-0.0.1.dist-info/entry_points.txt +2 -0
- gpu_rich-0.0.1.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# Troubleshooting
|
|
2
|
+
|
|
3
|
+
## Two kinds of failure
|
|
4
|
+
|
|
5
|
+
In both kinds, read `error.error_class` and `error.hint`. These two fields are always there.
|
|
6
|
+
|
|
7
|
+
1. The command failed. stdout holds `{"error": {"error_class", "hint", "kind", "message", "fix"}}` and the exit code is 2, 3, 4 or 5. No run started, or the command could not reach the run. `error_class` equals `kind`. `message` and `fix` are extra detail.
|
|
8
|
+
2. The run failed. The command worked, stdout holds a run, `state` is `failed`, `timed_out` or `cancelled`, and `wait` exits with 1. The run's `error` has only `error_class` and `hint`.
|
|
9
|
+
|
|
10
|
+
| Exit | `error.error_class` (= `kind`) | Meaning | What to do |
|
|
11
|
+
|---|---|---|---|
|
|
12
|
+
| 2 | `usage` | Wrong flag, missing file, bad header, unknown run id, secret not exported, Kaggle refused secrets. | Read `message`. Fix the command or the file. |
|
|
13
|
+
| 3 | `auth` | Not signed in, or the token expired. `doctor` also exits 3 when no remote backend is ready. | Show `fix` to the user. The user signs in. |
|
|
14
|
+
| 4 | `quota` | No backend can run the job now: quota used up, job too long, paid backend not allowed. | Read `candidates[].reason` from `plan`. Shorten `max_hours`, try later, or ask the user about another backend. |
|
|
15
|
+
| 5 | `platform` | The platform answered with an error. | Run the same command once more. Then try another backend. |
|
|
16
|
+
|
|
17
|
+
## Error classes of a failed run
|
|
18
|
+
|
|
19
|
+
The class comes from the last log lines and the exit code.
|
|
20
|
+
|
|
21
|
+
### out_of_memory
|
|
22
|
+
|
|
23
|
+
The GPU ran out of memory (`CUDA out of memory`, `OutOfMemoryError`). Apply the first change that fits, then run again:
|
|
24
|
+
|
|
25
|
+
1. Halve `per_device_train_batch_size` and double `gradient_accumulation_steps`. The effective batch stays the same.
|
|
26
|
+
2. Turn on gradient checkpointing: `gradient_checkpointing=True` in `TrainingArguments`, or `model.gradient_checkpointing_enable()`.
|
|
27
|
+
3. Shorten the maximum sequence length (`max_seq_length`, `max_length`, `max_source_length`). 512 instead of 2048 saves a lot.
|
|
28
|
+
4. Use half precision: `fp16=True` on a T4. A T4 has no bf16 support.
|
|
29
|
+
5. Load the model in 4-bit and train a LoRA adapter (QLoRA), see below.
|
|
30
|
+
6. Use a smaller model.
|
|
31
|
+
|
|
32
|
+
Make one or two changes at a time, and write them down in your reply, so the user sees what changed.
|
|
33
|
+
|
|
34
|
+
### missing_dependency
|
|
35
|
+
|
|
36
|
+
`ModuleNotFoundError`, a failed install (exit code 97), or packages that do not fit together. Add the package to `dependencies`. The pip name can differ from the import name (`import cv2` needs `opencv-python-headless`, `import sklearn` needs `scikit-learn`). When the install fails, read the log for the package that failed and pin versions that work together. Do not pin `torch`: the platform image already has a CUDA build.
|
|
37
|
+
|
|
38
|
+
### missing_secret
|
|
39
|
+
|
|
40
|
+
`401 Client Error`, `GatedRepoError`, or a login prompt. Choose in this order:
|
|
41
|
+
|
|
42
|
+
1. Use a public model or data set that does the same job (for example an ungated copy).
|
|
43
|
+
2. Declare `secrets = ["HF_TOKEN"]`, read `os.environ["HF_TOKEN"]` in the job, ask the user to export the variable in their shell, and run on a backend that accepts secrets (not Kaggle, for now).
|
|
44
|
+
|
|
45
|
+
Remove `notebook_login()` and `huggingface-cli login` from the job in both cases.
|
|
46
|
+
|
|
47
|
+
### timeout
|
|
48
|
+
|
|
49
|
+
The job reached `max_hours` (exit code 124). Lower `max_steps` or `num_train_epochs`, train on a subset, or raise `max_hours` when the quota allows it. Resume from the last checkpoint under `outputs/` when there is one.
|
|
50
|
+
|
|
51
|
+
### queue_timeout
|
|
52
|
+
|
|
53
|
+
The run stayed `queued` too long and was cancelled. The platform had no free machine at that moment.
|
|
54
|
+
|
|
55
|
+
1. Run the same command again first. Free queues stall, and a fresh submission often starts in seconds.
|
|
56
|
+
2. When it stalls again, run with another backend (`--backend colab`), or try the same backend later. Do not retry in a tight loop.
|
|
57
|
+
|
|
58
|
+
- Detached runs: `gpu-rich --json wait RUN_ID --timeout 300 --queue-timeout 300` cancels a run still queued at the end of the call.
|
|
59
|
+
- Attached runs (`run` without `--detach`, with `--queue-timeout`): `run --requeue N` (default 2) submits again to the same backend N times when its queue stalls, before it tries the next backend.
|
|
60
|
+
|
|
61
|
+
### disk_full
|
|
62
|
+
|
|
63
|
+
`No space left on device`. Set `save_total_limit=1`, save only the LoRA adapter instead of the full model, stream the data set (`streaming=True`), and delete caches you do not need during the run.
|
|
64
|
+
|
|
65
|
+
### missing_file
|
|
66
|
+
|
|
67
|
+
`FileNotFoundError`. Add the file or folder to `include`, check that the path is relative to the script folder, or download the data inside the job.
|
|
68
|
+
|
|
69
|
+
### platform
|
|
70
|
+
|
|
71
|
+
The platform or the runner failed before the job finished (exit code 98 or unknown), or the platform lost the run. Read the full log with `gpu-rich --json logs RUN_ID`. Run once more. When it fails again, try another backend and tell the user.
|
|
72
|
+
|
|
73
|
+
### job_failed
|
|
74
|
+
|
|
75
|
+
The job exited with a non-zero code for another reason. Read the traceback in `last_lines`, or the full log. Fix the code. Run a short smoke test (fewer steps) before the full run again.
|
|
76
|
+
|
|
77
|
+
### cancelled
|
|
78
|
+
|
|
79
|
+
Someone ran `cancel`. Nothing to fix.
|
|
80
|
+
|
|
81
|
+
## Reading logs
|
|
82
|
+
|
|
83
|
+
- `last_lines` in the run JSON holds the newest 20 non-empty lines.
|
|
84
|
+
- `gpu-rich --json logs RUN_ID --tail 200` gives more as `lines`.
|
|
85
|
+
- After the run, `gpu-rich-runs/<run_id>/_gpr/` holds the runner files: `log.txt` (the full log, when the platform still had it), `result.json` (`error`, `phase`, `exit_code`), `exit_code` (the job's exit code as plain text), `executed.ipynb` for a notebook, and on Kaggle `kaggle_raw_log.json` (the platform's raw log, useful when `log.txt` is short).
|
|
86
|
+
- Lines that start with `[gpr]` come from the runner: `phase=deps` (installing), `phase=run` (your job runs), `phase=collect` (copying outputs), `exit_code=N`, `done`. A run that fails in `phase=deps` is a dependency problem, not a code problem.
|
|
87
|
+
|
|
88
|
+
Runner exit codes: 0 success, 1 or other job errors, 97 dependency install failed, 98 runner error, 124 time limit, 130 and 143 stopped by a signal.
|
|
89
|
+
|
|
90
|
+
## Sizing a model for a 16 GB T4
|
|
91
|
+
|
|
92
|
+
A T4 has about 15 GB of usable memory, no bf16, and is slow. Kaggle gives two T4s. A plain PyTorch loop uses one. A script with multi-GPU helpers (`Trainer`, `accelerate`, `DataParallel`) uses both, so the effective batch size doubles and the step count halves. When you want one GPU, pass `--env CUDA_VISIBLE_DEVICES=0` to `run`.
|
|
93
|
+
|
|
94
|
+
### Library mismatch on a third-party notebook
|
|
95
|
+
|
|
96
|
+
A catalog recipe can fail on the first run even at portability 1.00: the platform image has other library versions than the author had. In a usability test, such a recipe failed on Kaggle because of a version mismatch. Expect one or two fix rounds: read the traceback, pin the packages it names in `dependencies`, run a short test again.
|
|
97
|
+
|
|
98
|
+
These are ROUGH rules of thumb. Real use depends on sequence length, batch size, optimizer and framework. Always test with a few steps first.
|
|
99
|
+
|
|
100
|
+
| Setup | Rough GPU memory |
|
|
101
|
+
|---|---|
|
|
102
|
+
| Inference in fp16 | about 2 GB per billion parameters, plus activations |
|
|
103
|
+
| Full fine-tuning with AdamW in mixed precision | about 16 GB per billion parameters |
|
|
104
|
+
| LoRA on an fp16 base model | about 2 GB per billion parameters, plus activations |
|
|
105
|
+
| QLoRA (4-bit base model plus LoRA) | about 0.7 GB per billion parameters, plus activations |
|
|
106
|
+
|
|
107
|
+
So on one T4, roughly:
|
|
108
|
+
|
|
109
|
+
- Full fine-tuning: models up to about 0.5 billion parameters (BERT, T5-base, Whisper small, small vision models).
|
|
110
|
+
- LoRA in fp16: models up to about 3 billion parameters with short sequences.
|
|
111
|
+
- QLoRA: models up to about 8 billion parameters with a sequence length of 1024 or less and batch size 1 or 2.
|
|
112
|
+
|
|
113
|
+
### 4-bit loading (QLoRA)
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
import torch
|
|
117
|
+
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
|
|
118
|
+
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
|
|
119
|
+
|
|
120
|
+
bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
|
|
121
|
+
bnb_4bit_compute_dtype=torch.float16, bnb_4bit_use_double_quant=True)
|
|
122
|
+
model = AutoModelForCausalLM.from_pretrained(MODEL_ID, quantization_config=bnb, device_map="auto")
|
|
123
|
+
model = prepare_model_for_kbit_training(model)
|
|
124
|
+
model = get_peft_model(model, LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, task_type="CAUSAL_LM",
|
|
125
|
+
target_modules="all-linear"))
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Add `bitsandbytes`, `peft` and `accelerate` to `dependencies`. Use `compute_dtype=torch.float16` on a T4, not bfloat16.
|
|
129
|
+
|
|
130
|
+
### Batch size and gradient accumulation
|
|
131
|
+
|
|
132
|
+
Start with `per_device_train_batch_size=1` or `2` and `gradient_accumulation_steps=8` or `16`. Raise the batch size only after one run succeeds and the log shows memory to spare. The effective batch size is the batch size times the accumulation steps.
|
|
133
|
+
|
|
134
|
+
### Sequence length
|
|
135
|
+
|
|
136
|
+
Memory for activations grows with the sequence length (and faster than linear for attention without flash attention, which a T4 does not support well). Check the length of your data first, and cut to the length most examples need.
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Backend registry. Adapters are imported lazily so a missing SDK breaks only its own backend.
|
|
2
|
+
|
|
3
|
+
Names: kaggle, colab, modal, hf, brev, local, and ssh:<host> for a host from the config file.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from .base import Backend, BackendError
|
|
8
|
+
|
|
9
|
+
# Default preference order for the router: free and reliable first.
|
|
10
|
+
_NAMES = ("kaggle", "colab", "modal", "hf", "brev", "local")
|
|
11
|
+
|
|
12
|
+
_CLASSES = {
|
|
13
|
+
"kaggle": ("kaggle", "KaggleBackend"),
|
|
14
|
+
"colab": ("colab", "ColabBackend"),
|
|
15
|
+
"modal": ("modal", "ModalBackend"),
|
|
16
|
+
"hf": ("hf_jobs", "HFJobsBackend"),
|
|
17
|
+
"brev": ("brev", "BrevBackend"),
|
|
18
|
+
"local": ("local", "LocalBackend"),
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def names() -> tuple[str, ...]:
|
|
23
|
+
"""Built-in backends plus one `ssh:<host>` per configured SSH host."""
|
|
24
|
+
from .. import config
|
|
25
|
+
|
|
26
|
+
return _NAMES + tuple(f"ssh:{h}" for h in config.ssh_hosts())
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def get(name: str) -> Backend:
|
|
30
|
+
import importlib
|
|
31
|
+
|
|
32
|
+
if name.startswith("ssh:"):
|
|
33
|
+
from .ssh import SSHBackend
|
|
34
|
+
|
|
35
|
+
return SSHBackend(name.split(":", 1)[1])
|
|
36
|
+
if name not in _CLASSES:
|
|
37
|
+
raise BackendError(f"Unknown backend '{name}'. Known backends: {', '.join(names())}.", kind="usage")
|
|
38
|
+
module, cls = _CLASSES[name]
|
|
39
|
+
try:
|
|
40
|
+
return getattr(importlib.import_module(f"{__name__}.{module}"), cls)()
|
|
41
|
+
except ModuleNotFoundError as e:
|
|
42
|
+
if e.name and e.name.startswith(__name__):
|
|
43
|
+
raise BackendError(f"The '{name}' backend is not available in this version.", kind="usage") from e
|
|
44
|
+
raise
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""The adapter interface. One class per platform implements it.
|
|
2
|
+
|
|
3
|
+
Rules for every adapter:
|
|
4
|
+
* `submit` returns fast and never waits for the job. The job must keep running
|
|
5
|
+
after the local process exits.
|
|
6
|
+
* Every other method must work from a NEW process, given only the RemoteRef.
|
|
7
|
+
* `logs` yields the job's own output lines, without trailing newlines and
|
|
8
|
+
without platform noise. With follow=True it ends when the run ends.
|
|
9
|
+
* `pull` puts the run's files under `dest`:
|
|
10
|
+
dest/_gpr/result.json written by the bootstrap runner
|
|
11
|
+
dest/_gpr/exit_code
|
|
12
|
+
dest/<declared outputs> e.g. dest/outputs/...
|
|
13
|
+
dest/_gpr/executed.ipynb for notebook jobs
|
|
14
|
+
dest/_gpr/log.txt the full log, when the platform still has it
|
|
15
|
+
After a successful pull of a FINISHED run, the adapter releases every remote
|
|
16
|
+
resource that still costs money or quota (session, VM, app). Pull stays
|
|
17
|
+
repeatable from the local copy the CLI keeps; adapters need not serve a
|
|
18
|
+
second pull after release.
|
|
19
|
+
* `status` reports the JOB result: a platform that says "complete" while the
|
|
20
|
+
job's exit code is 1 is `failed`. The exit code comes from the runner's
|
|
21
|
+
`[gpr] exit_code=N` log line or from `_gpr/result.json` / `_gpr/exit_code`.
|
|
22
|
+
A run the platform no longer knows is `unknown`.
|
|
23
|
+
* `cancel` stops billing and quota use. It is safe to call twice.
|
|
24
|
+
* Adapters raise BackendError with a clear message and an optional fix.
|
|
25
|
+
* Adapters never print. They never log, store or return secret values.
|
|
26
|
+
* Third-party SDKs are imported inside methods, never at module import time,
|
|
27
|
+
so a missing SDK breaks only its own backend. A missing SDK or CLI is a
|
|
28
|
+
BackendError(kind="auth") from `doctor()` with a `fix` that installs it.
|
|
29
|
+
|
|
30
|
+
The bundle (see models.Bundle and bundle.py) is one .tar.gz:
|
|
31
|
+
manifest.json {"schema":1,"run_id","kind","entry","args","dependencies",
|
|
32
|
+
"requires_python","outputs","env","secret_names","max_seconds","created_at"}
|
|
33
|
+
runner.py the bootstrap; stdlib only; Python 3.8+
|
|
34
|
+
job/ the user's source
|
|
35
|
+
|
|
36
|
+
Every adapter gets the bundle onto the remote machine, extracts it to some folder
|
|
37
|
+
DIR, and starts:
|
|
38
|
+
|
|
39
|
+
python -u DIR/runner.py --bundle-dir DIR --out-dir OUT [--secrets-file FILE]
|
|
40
|
+
|
|
41
|
+
The runner installs the dependencies, runs the job with live output, copies the
|
|
42
|
+
declared outputs into OUT, writes OUT/_gpr/result.json and OUT/_gpr/exit_code,
|
|
43
|
+
prints the markers below, and exits with the job's exit code
|
|
44
|
+
(97 = dependency install failed, 98 = runner error, 124 = time limit, 143/130 = signal).
|
|
45
|
+
`--secrets-file` is a JSON object {NAME: value}; the runner loads it into the job's
|
|
46
|
+
environment and deletes the file before the job starts.
|
|
47
|
+
"""
|
|
48
|
+
from __future__ import annotations
|
|
49
|
+
|
|
50
|
+
from pathlib import Path
|
|
51
|
+
from typing import Iterator, Mapping, Protocol, runtime_checkable
|
|
52
|
+
|
|
53
|
+
from ..models import AuthState, Bundle, JobSpec, Offer, Quota, RemoteRef, RunStatus
|
|
54
|
+
|
|
55
|
+
# Lines the bootstrap runner prints. Adapters and the CLI parse these.
|
|
56
|
+
MARK = "[gpr]"
|
|
57
|
+
MARK_START = "[gpr] start"
|
|
58
|
+
MARK_PHASE = "[gpr] phase=" # deps | run | collect
|
|
59
|
+
MARK_EXIT = "[gpr] exit_code="
|
|
60
|
+
MARK_DONE = "[gpr] done"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class BackendError(Exception):
|
|
64
|
+
"""A platform problem the user can act on."""
|
|
65
|
+
|
|
66
|
+
def __init__(self, message: str, *, kind: str = "platform", fix: str | None = None):
|
|
67
|
+
super().__init__(message)
|
|
68
|
+
self.kind = kind # auth | quota | platform | usage
|
|
69
|
+
self.fix = fix
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@runtime_checkable
|
|
73
|
+
class Backend(Protocol):
|
|
74
|
+
name: str
|
|
75
|
+
|
|
76
|
+
def doctor(self) -> AuthState: ...
|
|
77
|
+
|
|
78
|
+
def offers(self) -> list[Offer]: ...
|
|
79
|
+
|
|
80
|
+
def quota(self) -> Quota | None: ...
|
|
81
|
+
|
|
82
|
+
def submit(
|
|
83
|
+
self, bundle: Bundle, spec: JobSpec, run_id: str, secrets: Mapping[str, str] | None = None
|
|
84
|
+
) -> RemoteRef: ...
|
|
85
|
+
|
|
86
|
+
def status(self, ref: RemoteRef) -> RunStatus: ...
|
|
87
|
+
|
|
88
|
+
def logs(self, ref: RemoteRef, follow: bool = False) -> Iterator[str]: ...
|
|
89
|
+
|
|
90
|
+
def pull(self, ref: RemoteRef, dest: Path) -> list[Path]: ...
|
|
91
|
+
|
|
92
|
+
def cancel(self, ref: RemoteRef) -> None: ...
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def parse_exit_code(line: str) -> int | None:
|
|
96
|
+
"""Return N from a `[gpr] exit_code=N` line, else None."""
|
|
97
|
+
if MARK_EXIT in line:
|
|
98
|
+
try:
|
|
99
|
+
return int(line.split(MARK_EXIT, 1)[1].strip().split()[0])
|
|
100
|
+
except (ValueError, IndexError):
|
|
101
|
+
return None
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def state_from_exit_code(code: int | None):
|
|
106
|
+
"""Map the runner's exit code to a RunState. Shared by all adapters."""
|
|
107
|
+
from ..models import RunState
|
|
108
|
+
|
|
109
|
+
if code is None:
|
|
110
|
+
return RunState.unknown
|
|
111
|
+
if code == 0:
|
|
112
|
+
return RunState.succeeded
|
|
113
|
+
if code == 124:
|
|
114
|
+
return RunState.timed_out
|
|
115
|
+
return RunState.failed
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"""The `brev` backend: one NVIDIA Brev GPU VM per run, driven by the `brev` CLI, used over SSH.
|
|
2
|
+
|
|
3
|
+
STATUS: NOT YET VERIFIED ON THE REAL PLATFORM. Every command below comes from the Brev
|
|
4
|
+
docs and the brev-cli source; the tests run the same code against a fake `brev` and a
|
|
5
|
+
local SSH transport. The first real run must follow the checklist in the project notes.
|
|
6
|
+
|
|
7
|
+
Flow of one run:
|
|
8
|
+
1. `brev create gpr-<run_id> --gpu-name <GPU> --detached` (default GPU T4).
|
|
9
|
+
2. Poll `brev ls --json` (bounded) until the instance is RUNNING and its shell is READY.
|
|
10
|
+
3. `brev refresh` so ~/.brev/ssh_config has the alias, then poll `ssh <name> echo ok` (bounded).
|
|
11
|
+
4. Upload and start the job with the SSH adapter (gpu_rich.backends.ssh), pointed at the
|
|
12
|
+
instance name as the SSH host. A watchdog starts in the same remote command.
|
|
13
|
+
If anything fails after step 1 starts (also Ctrl-C), the adapter runs `brev delete` before it raises.
|
|
14
|
+
|
|
15
|
+
COST SAFETY. A forgotten instance bills until someone deletes it. The guarantees:
|
|
16
|
+
* `pull()` of a finished run and `cancel()` both run `brev delete <name>`. A failed delete
|
|
17
|
+
raises a BackendError whose fix is the exact `brev delete` command.
|
|
18
|
+
* A remote watchdog (a small sh script, detached in its own session) shuts the VM down with
|
|
19
|
+
`sudo -n shutdown -h now` when
|
|
20
|
+
- the job ended and nobody pulled within `idle_minutes` (default 20), or
|
|
21
|
+
- `max_hours` + 20 minutes passed since start, whatever the job does (hard limit).
|
|
22
|
+
A pull writes the `pulled` marker, which stops only the idle rule; the hard limit stays.
|
|
23
|
+
The limits, stated honestly:
|
|
24
|
+
* Shutdown is not delete. Brev docs: a stopped instance has "No compute charges while
|
|
25
|
+
stopped (minimal storage costs apply)" (docs.nvidia.com/brev/latest/concepts/gpu-instances).
|
|
26
|
+
So the watchdog stops the GPU bill, but the disk still bills until `brev delete`.
|
|
27
|
+
* Brev says some resources are "non-stoppable". On such a provider, an OS shutdown may not
|
|
28
|
+
stop billing at all. Not verified which GPU types this hits.
|
|
29
|
+
* The watchdog needs passwordless `sudo` (true on standard Brev VMs, not verified) and runs
|
|
30
|
+
inside the VM or container that the SSH alias reaches. If that is a container, `shutdown`
|
|
31
|
+
may not halt the VM. Verify in the first real run.
|
|
32
|
+
* If the VM dies, loses its disk, or the watchdog process is killed, nothing local watches it.
|
|
33
|
+
`gpr status`/`gpr pull`/`gpr cancel` are the only other cleanup paths.
|
|
34
|
+
|
|
35
|
+
Brev CLI facts this adapter relies on (looked up 2026-11-29):
|
|
36
|
+
* `brev create [name] --gpu-name/-g <partial name> --min-vram/-v <GB> --detached/-d
|
|
37
|
+
[--timeout <s>]`; without --detached it waits up to 300 s. Prints the instance name.
|
|
38
|
+
https://docs.nvidia.com/brev/latest/cli/instance-creation
|
|
39
|
+
* `brev ls --json` (alias `brev list`): JSON with name, id, status, build_status,
|
|
40
|
+
shell_status, health_status, instance_type, gpu. shell_status is READY only when status
|
|
41
|
+
is RUNNING and the build is COMPLETED.
|
|
42
|
+
https://github.com/brevdev/brev-cli/blob/main/pkg/cmd/ls/ls.go
|
|
43
|
+
* `brev stop <name...>`, `brev delete <name...>` (irreversible), `brev refresh` (rewrites
|
|
44
|
+
~/.brev/ssh_config, which ~/.ssh/config includes, so `ssh <name>` works).
|
|
45
|
+
https://docs.nvidia.com/brev/latest/cli/instance-management
|
|
46
|
+
https://docs.nvidia.com/brev/latest/cli/connectivity
|
|
47
|
+
* `brev exec <name> "<cmd>"` and `brev copy` exist; this adapter uses plain ssh/scp on the
|
|
48
|
+
alias instead, so the SSH adapter's code path is shared.
|
|
49
|
+
* `brev login` is a browser flow; when not logged in, `brev ls` fails (we treat a non-zero
|
|
50
|
+
exit as "not logged in"). https://docs.nvidia.com/brev/latest/cli/cli-overview
|
|
51
|
+
* Pricing: `brev search --gpu-name X --json` shows $/HR. Billing is from organisation credits.
|
|
52
|
+
https://docs.nvidia.com/brev/latest/cli/search-discovery
|
|
53
|
+
"""
|
|
54
|
+
from __future__ import annotations
|
|
55
|
+
|
|
56
|
+
import json
|
|
57
|
+
import re
|
|
58
|
+
import shlex
|
|
59
|
+
import shutil
|
|
60
|
+
import subprocess
|
|
61
|
+
import time
|
|
62
|
+
from pathlib import Path
|
|
63
|
+
from typing import Any, Iterator, Mapping
|
|
64
|
+
|
|
65
|
+
from ..models import AuthState, Bundle, JobSpec, Offer, Quota, RemoteRef, RunState, RunStatus
|
|
66
|
+
from .base import BackendError
|
|
67
|
+
from .ssh import SSHBackend, detach_sh
|
|
68
|
+
|
|
69
|
+
INSTALL_FIX = "Install the Brev CLI (see https://docs.nvidia.com/brev/latest/cli/getting-started), then run `brev login`"
|
|
70
|
+
LOGIN_FIX = "Run `brev login`"
|
|
71
|
+
PRICES_AS_OF = "2026-11"
|
|
72
|
+
|
|
73
|
+
# Dated ESTIMATES, not quotes. Check with `brev search --gpu-name <GPU> --sort price`.
|
|
74
|
+
_OFFERS = (
|
|
75
|
+
("T4", 16.0, 0.40),
|
|
76
|
+
("L4", 24.0, 0.17),
|
|
77
|
+
("A10G", 24.0, 1.00), # g5.xlarge example from the Brev search docs
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
WATCHDOG_SH = r"""#!/bin/sh
|
|
81
|
+
# gpr watchdog: shuts this VM down when nobody comes back for it.
|
|
82
|
+
# args: RUN_DIR IDLE_SECONDS HARD_SECONDS POLL_SECONDS SHUTDOWN_COMMAND
|
|
83
|
+
d=$1; idle=$2; hard=$3; poll=$4; off=$5
|
|
84
|
+
start=$(date +%s)
|
|
85
|
+
ended=""
|
|
86
|
+
while :; do
|
|
87
|
+
now=$(date +%s)
|
|
88
|
+
if [ $((now - start)) -ge "$hard" ]; then
|
|
89
|
+
echo "gpr-watchdog: hard limit reached; shutting down"
|
|
90
|
+
sh -c "$off"; exit 0
|
|
91
|
+
fi
|
|
92
|
+
if [ ! -f "$d/pulled" ]; then
|
|
93
|
+
done_=0
|
|
94
|
+
if [ ! -d "$d" ] || [ -f "$d/out/_gpr/exit_code" ]; then done_=1
|
|
95
|
+
else
|
|
96
|
+
pid=$(cat "$d/pid" 2>/dev/null)
|
|
97
|
+
if [ -z "$pid" ] || ! kill -0 "$pid" 2>/dev/null; then done_=1; fi
|
|
98
|
+
fi
|
|
99
|
+
if [ "$done_" = 1 ]; then
|
|
100
|
+
[ -n "$ended" ] || ended=$now
|
|
101
|
+
if [ $((now - ended)) -ge "$idle" ]; then
|
|
102
|
+
echo "gpr-watchdog: job ended and nobody pulled; shutting down"
|
|
103
|
+
sh -c "$off"; exit 0
|
|
104
|
+
fi
|
|
105
|
+
fi
|
|
106
|
+
fi
|
|
107
|
+
sleep "$poll"
|
|
108
|
+
done
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def instance_name(run_id: str) -> str:
|
|
113
|
+
name = "gpr-" + re.sub(r"[^a-z0-9-]+", "-", run_id.lower()).strip("-")
|
|
114
|
+
return name[:60].rstrip("-")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class BrevBackend:
|
|
118
|
+
name = "brev"
|
|
119
|
+
|
|
120
|
+
# Bounded waits and watchdog timings; tests make them tiny.
|
|
121
|
+
ready_timeout = 900.0 # seconds for the instance to be RUNNING with a READY shell
|
|
122
|
+
ssh_timeout = 300.0 # seconds for `ssh <name>` to work after that
|
|
123
|
+
poll_s = 10.0
|
|
124
|
+
idle_minutes = 20.0
|
|
125
|
+
hard_extra_minutes = 20.0
|
|
126
|
+
watchdog_poll_s = 30
|
|
127
|
+
shutdown_command = "sudo -n shutdown -h now"
|
|
128
|
+
remote_python = "python3"
|
|
129
|
+
remote_workdir = "~/.gpu-rich"
|
|
130
|
+
|
|
131
|
+
# ------------------------------------------------------------------ CLI
|
|
132
|
+
def _brev(self, args: list[str], timeout: float = 120) -> tuple[int, str, str]:
|
|
133
|
+
"""Run the brev CLI. Every Brev call goes through here."""
|
|
134
|
+
exe = shutil.which("brev")
|
|
135
|
+
if not exe:
|
|
136
|
+
raise BackendError("The Brev CLI (`brev`) is not installed.", kind="auth", fix=INSTALL_FIX)
|
|
137
|
+
try:
|
|
138
|
+
p = subprocess.run([exe, *args], capture_output=True, text=True, timeout=timeout,
|
|
139
|
+
stdin=subprocess.DEVNULL)
|
|
140
|
+
except subprocess.TimeoutExpired as exc:
|
|
141
|
+
raise BackendError(f"`brev {args[0]}` timed out after {timeout:.0f} s.", kind="platform") from exc
|
|
142
|
+
except OSError as exc:
|
|
143
|
+
raise BackendError(f"Cannot run the Brev CLI: {exc}", kind="auth", fix=INSTALL_FIX) from exc
|
|
144
|
+
return p.returncode, p.stdout, p.stderr
|
|
145
|
+
|
|
146
|
+
def _instances(self) -> list[dict[str, Any]]:
|
|
147
|
+
rc, out, err = self._brev(["ls", "--json"], timeout=60)
|
|
148
|
+
if rc != 0:
|
|
149
|
+
msg = (err or out).strip()[-300:]
|
|
150
|
+
if re.search(r"log ?in|auth|token|credential", msg, re.I):
|
|
151
|
+
raise BackendError(f"Not logged in to Brev: {msg}", kind="auth", fix=LOGIN_FIX)
|
|
152
|
+
raise BackendError(f"`brev ls` failed: {msg}", kind="platform")
|
|
153
|
+
try:
|
|
154
|
+
data = json.loads(out or "[]")
|
|
155
|
+
except ValueError as exc:
|
|
156
|
+
raise BackendError("`brev ls --json` did not print JSON.", kind="platform") from exc
|
|
157
|
+
if isinstance(data, dict):
|
|
158
|
+
data = data.get("workspaces") or data.get("instances") or []
|
|
159
|
+
return [d for d in data if isinstance(d, dict)]
|
|
160
|
+
|
|
161
|
+
def _instance(self, name: str) -> dict[str, Any] | None:
|
|
162
|
+
for inst in self._instances():
|
|
163
|
+
if inst.get("name") == name:
|
|
164
|
+
return inst
|
|
165
|
+
return None
|
|
166
|
+
|
|
167
|
+
def _delete(self, name: str) -> None:
|
|
168
|
+
"""`brev delete`; an instance that is already gone counts as success."""
|
|
169
|
+
rc, out, err = self._brev(["delete", name], timeout=180)
|
|
170
|
+
if rc == 0:
|
|
171
|
+
return
|
|
172
|
+
if self._instance(name) is None:
|
|
173
|
+
return
|
|
174
|
+
raise BackendError(f"Could not delete Brev instance {name}: {(err or out).strip()[-300:]}. It still bills.",
|
|
175
|
+
kind="platform", fix=f"brev delete {name}")
|
|
176
|
+
|
|
177
|
+
def _ssh_for(self, name: str) -> SSHBackend:
|
|
178
|
+
"""The SSH adapter pointed at the instance alias that `brev refresh` writes."""
|
|
179
|
+
return SSHBackend(name, settings={"host": name, "python": self.remote_python, "workdir": self.remote_workdir})
|
|
180
|
+
|
|
181
|
+
# --------------------------------------------------------------- doctor
|
|
182
|
+
def doctor(self) -> AuthState:
|
|
183
|
+
try: # a missing CLI raises from _brev with INSTALL_FIX
|
|
184
|
+
n = len(self._instances())
|
|
185
|
+
except BackendError as exc:
|
|
186
|
+
return AuthState(ok=False, detail=str(exc), fix=exc.fix or LOGIN_FIX)
|
|
187
|
+
return AuthState(ok=True, detail=f"Brev CLI logged in; {n} instance(s); not yet verified by a real run.")
|
|
188
|
+
|
|
189
|
+
def offers(self) -> list[Offer]:
|
|
190
|
+
return [Offer(backend=self.name, gpu=g, vram_gb=v, usd_per_hour=p, free=False, accelerator_id=g,
|
|
191
|
+
note=f"billed to your Brev credits; estimate as of {PRICES_AS_OF}, check `brev search --gpu-name {g}`")
|
|
192
|
+
for g, v, p in _OFFERS]
|
|
193
|
+
|
|
194
|
+
def quota(self) -> Quota | None:
|
|
195
|
+
return None # credits balance is not exposed by a documented CLI command
|
|
196
|
+
|
|
197
|
+
# --------------------------------------------------------------- submit
|
|
198
|
+
def watchdog_sh(self, spec: JobSpec) -> str:
|
|
199
|
+
"""Shell lines (run with $d and $py set) that write and start the watchdog."""
|
|
200
|
+
idle = int(self.idle_minutes * 60)
|
|
201
|
+
hard = int(spec.max_hours * 3600 + self.hard_extra_minutes * 60)
|
|
202
|
+
words = ["sh", '"$d/watchdog.sh"', '"$d"', str(idle), str(hard), str(int(self.watchdog_poll_s)),
|
|
203
|
+
shlex.quote(self.shutdown_command)]
|
|
204
|
+
return ("cat > \"$d/watchdog.sh\" <<'GPR_WATCHDOG_EOF'\n" + WATCHDOG_SH + "GPR_WATCHDOG_EOF\n"
|
|
205
|
+
+ detach_sh(words, '"$d/watchdog.log"')
|
|
206
|
+
+ 'echo "$!" > "$d/watchdog.pid"\n')
|
|
207
|
+
|
|
208
|
+
def _wait_ready(self, name: str) -> None:
|
|
209
|
+
deadline = time.monotonic() + self.ready_timeout
|
|
210
|
+
last = "not listed yet"
|
|
211
|
+
while True:
|
|
212
|
+
inst = self._instance(name)
|
|
213
|
+
if inst is not None:
|
|
214
|
+
status = str(inst.get("status") or "").upper()
|
|
215
|
+
shell = str(inst.get("shell_status") or "").upper().replace(" ", "_")
|
|
216
|
+
last = f"status {status or '?'}, shell {shell or '?'}"
|
|
217
|
+
if "FAIL" in status or "FAIL" in str(inst.get("build_status") or "").upper():
|
|
218
|
+
raise BackendError(f"Brev could not start instance {name} ({last}).", kind="platform")
|
|
219
|
+
if status == "RUNNING" and shell in ("READY", ""):
|
|
220
|
+
return
|
|
221
|
+
if time.monotonic() >= deadline:
|
|
222
|
+
raise BackendError(f"Brev instance {name} was not ready after {self.ready_timeout:.0f} s ({last}).",
|
|
223
|
+
kind="platform")
|
|
224
|
+
time.sleep(self.poll_s)
|
|
225
|
+
|
|
226
|
+
def _wait_ssh(self, ssh: SSHBackend) -> None:
|
|
227
|
+
deadline = time.monotonic() + self.ssh_timeout
|
|
228
|
+
err = ""
|
|
229
|
+
while True:
|
|
230
|
+
rc, out, err = ssh._exec("echo ok", 30)
|
|
231
|
+
if rc == 0 and out.strip().endswith("ok"):
|
|
232
|
+
return
|
|
233
|
+
if time.monotonic() >= deadline:
|
|
234
|
+
raise BackendError(f"SSH to Brev instance {ssh.host_name} did not work after {self.ssh_timeout:.0f} s: "
|
|
235
|
+
f"{err.strip()[-200:]}", kind="platform")
|
|
236
|
+
time.sleep(self.poll_s)
|
|
237
|
+
|
|
238
|
+
def submit(self, bundle: Bundle, spec: JobSpec, run_id: str, secrets: Mapping[str, str] | None = None) -> RemoteRef:
|
|
239
|
+
name = instance_name(run_id)
|
|
240
|
+
gpu = spec.gpu or "T4"
|
|
241
|
+
args = ["create", name, "--gpu-name", gpu, "--detached"]
|
|
242
|
+
if spec.min_vram_gb:
|
|
243
|
+
args += ["--min-vram", str(int(spec.min_vram_gb + 0.999))]
|
|
244
|
+
try:
|
|
245
|
+
rc, out, err = self._brev(args, timeout=300)
|
|
246
|
+
if rc != 0:
|
|
247
|
+
raise BackendError(f"`brev create` failed: {(err or out).strip()[-300:]}", kind="platform")
|
|
248
|
+
self._wait_ready(name)
|
|
249
|
+
self._brev(["refresh"], timeout=120)
|
|
250
|
+
ssh = self._ssh_for(name)
|
|
251
|
+
self._wait_ssh(ssh)
|
|
252
|
+
inner = ssh._submit(bundle, spec, run_id, secrets, extra_sh=self.watchdog_sh(spec),
|
|
253
|
+
extra={"instance": name, "gpu": gpu})
|
|
254
|
+
except BaseException as exc: # Ctrl-C too: a half-made instance must not keep billing
|
|
255
|
+
try:
|
|
256
|
+
self._delete(name)
|
|
257
|
+
note = f" Instance {name} was deleted."
|
|
258
|
+
except Exception:
|
|
259
|
+
note = f" Instance {name} may still exist and bill: run `brev delete {name}`."
|
|
260
|
+
if isinstance(exc, BackendError):
|
|
261
|
+
raise BackendError(str(exc) + note, kind=exc.kind, fix=exc.fix or None) from exc
|
|
262
|
+
raise
|
|
263
|
+
return RemoteRef(backend=self.name, id=name, url=None, extra=dict(inner.extra))
|
|
264
|
+
|
|
265
|
+
# ------------------------------------------------------- status / logs
|
|
266
|
+
def _name(self, ref: RemoteRef) -> str:
|
|
267
|
+
return str(ref.extra.get("instance") or ref.id)
|
|
268
|
+
|
|
269
|
+
def status(self, ref: RemoteRef) -> RunStatus:
|
|
270
|
+
name = self._name(ref)
|
|
271
|
+
inst = self._instance(name)
|
|
272
|
+
if inst is None:
|
|
273
|
+
return RunStatus(state=RunState.unknown, message=f"Brev instance {name} no longer exists")
|
|
274
|
+
st = str(inst.get("status") or "").upper()
|
|
275
|
+
if st != "RUNNING":
|
|
276
|
+
return RunStatus(state=RunState.unknown,
|
|
277
|
+
message=f"Brev instance {name} is {st or 'in an unknown state'} (the watchdog may have stopped it)")
|
|
278
|
+
return self._ssh_for(name).status(ref)
|
|
279
|
+
|
|
280
|
+
def logs(self, ref: RemoteRef, follow: bool = False) -> Iterator[str]:
|
|
281
|
+
name = self._name(ref)
|
|
282
|
+
try:
|
|
283
|
+
yield from self._ssh_for(name).logs(ref, follow=follow)
|
|
284
|
+
except BackendError:
|
|
285
|
+
if self._instance(name) is None:
|
|
286
|
+
return
|
|
287
|
+
raise
|
|
288
|
+
|
|
289
|
+
# --------------------------------------------------------- pull / cancel
|
|
290
|
+
def pull(self, ref: RemoteRef, dest: Path) -> list[Path]:
|
|
291
|
+
name = self._name(ref)
|
|
292
|
+
if self._instance(name) is None:
|
|
293
|
+
raise BackendError(f"Brev instance {name} no longer exists; its files are gone.", kind="platform")
|
|
294
|
+
files, finished = self._ssh_for(name)._pull(ref, Path(dest), cleanup=False)
|
|
295
|
+
if finished:
|
|
296
|
+
self._delete(name)
|
|
297
|
+
return files
|
|
298
|
+
|
|
299
|
+
def cancel(self, ref: RemoteRef) -> None:
|
|
300
|
+
name = self._name(ref)
|
|
301
|
+
if self._instance(name) is None:
|
|
302
|
+
return
|
|
303
|
+
try: # let the runner write its result; the delete below is what stops billing
|
|
304
|
+
self._ssh_for(name).cancel(ref)
|
|
305
|
+
except BackendError:
|
|
306
|
+
pass
|
|
307
|
+
self._delete(name)
|