DavidBShan commited on
Commit
1fe8e9a
·
verified ·
1 Parent(s): 9740f83

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. code/autoslm/__init__.py +11 -0
  2. code/autoslm/_logging.py +66 -0
  3. code/autoslm/catalog.py +219 -0
  4. code/autoslm/cli/__init__.py +1 -0
  5. code/autoslm/cli/main.py +920 -0
  6. code/autoslm/client/__init__.py +14 -0
  7. code/autoslm/client/config.py +60 -0
  8. code/autoslm/client/http.py +187 -0
  9. code/autoslm/client/specs.py +23 -0
  10. code/autoslm/engine/__init__.py +7 -0
  11. code/autoslm/engine/accounting.py +37 -0
  12. code/autoslm/engine/multiturn_rollout.py +266 -0
  13. code/autoslm/engine/recipe.py +91 -0
  14. code/autoslm/engine/rope.py +371 -0
  15. code/autoslm/engine/vram.py +323 -0
  16. code/autoslm/engine/worker.py +0 -0
  17. code/autoslm/envs/__init__.py +10 -0
  18. code/autoslm/envs/adapter.py +706 -0
  19. code/autoslm/envs/base.py +49 -0
  20. code/autoslm/envs/registry.py +95 -0
  21. code/autoslm/mcp/__init__.py +1 -0
  22. code/autoslm/mcp/server.py +83 -0
  23. code/autoslm/providers/__init__.py +60 -0
  24. code/autoslm/providers/_http.py +100 -0
  25. code/autoslm/providers/_poll.py +87 -0
  26. code/autoslm/providers/allocator.py +262 -0
  27. code/autoslm/providers/base.py +549 -0
  28. code/autoslm/providers/preflight.py +80 -0
  29. code/autoslm/providers/runpod/__init__.py +108 -0
  30. code/autoslm/providers/runpod/api.py +117 -0
  31. code/autoslm/providers/runpod/auth.py +25 -0
  32. code/autoslm/providers/runpod/gpus.py +46 -0
  33. code/autoslm/providers/runpod/jobs.py +461 -0
  34. code/autoslm/providers/runpod/preflight.py +30 -0
  35. code/autoslm/providers/runpod/pricing.py +110 -0
  36. code/autoslm/providers/runpod/train.py +820 -0
  37. code/autoslm/providers/vast/__init__.py +124 -0
  38. code/autoslm/providers/vast/_bootstrap.py +274 -0
  39. code/autoslm/providers/vast/api.py +218 -0
  40. code/autoslm/providers/vast/auth.py +25 -0
  41. code/autoslm/providers/vast/gpus.py +21 -0
  42. code/autoslm/providers/vast/jobs.py +737 -0
  43. code/autoslm/providers/vast/preflight.py +26 -0
  44. code/autoslm/providers/vast/pricing.py +51 -0
  45. code/autoslm/providers/vast/train.py +27 -0
  46. code/autoslm/py.typed +0 -0
  47. code/autoslm/runner.py +994 -0
  48. code/autoslm/schema.py +410 -0
  49. code/autoslm/serve/__init__.py +1 -0
  50. code/autoslm/serve/deploy.py +518 -0
code/autoslm/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AutoSLM — managed LoRA post-training: log in with your freesolo key, train.
2
+
3
+ A focused developer experience (TOML run specs, pluggable environments,
4
+ CLI/API/MCP entry points, adapter deployment). Users authenticate with their
5
+ freesolo API key (`slm login`); the control plane runs each job on a managed
6
+ GPU (RunPod or Vast.ai) behind the scenes.
7
+ """
8
+
9
+ __all__ = ["__version__"]
10
+
11
+ __version__ = "0.2.0"
code/autoslm/_logging.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Package logging helpers.
2
+
3
+ Library code logs through the ``autoslm`` logger and never configures handlers on import (it
4
+ attaches a :class:`logging.NullHandler`), so importing AutoSLM stays silent for downstream
5
+ applications. The CLI calls :func:`configure_logging` to attach a console handler whose
6
+ level is controlled by ``-v/--verbose`` or the ``AUTOSLM_LOG_LEVEL`` environment variable.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import os
13
+
14
+ _ROOT_NAME = "autoslm"
15
+
16
+ # Attach a NullHandler once so "No handlers could be found" warnings never appear and
17
+ # importing the library produces no output unless the app opts in.
18
+ _root = logging.getLogger(_ROOT_NAME)
19
+ if not any(isinstance(h, logging.NullHandler) for h in _root.handlers):
20
+ _root.addHandler(logging.NullHandler())
21
+
22
+
23
+ def get_logger(name: str | None = None) -> logging.Logger:
24
+ """Return a logger under the ``autoslm`` namespace (e.g. ``get_logger(__name__)``)."""
25
+ if not name or name == _ROOT_NAME:
26
+ return logging.getLogger(_ROOT_NAME)
27
+ if name.startswith(_ROOT_NAME + "."):
28
+ return logging.getLogger(name)
29
+ return logging.getLogger(f"{_ROOT_NAME}.{name}")
30
+
31
+
32
+ def _level_from_env(default: int = logging.WARNING) -> int:
33
+ raw = os.environ.get("AUTOSLM_LOG_LEVEL")
34
+ if not raw:
35
+ return default
36
+ raw = raw.strip()
37
+ if raw.isdigit():
38
+ return int(raw)
39
+ # Map names (INFO/DEBUG/...) to ints via the canonical name->level mapping rather
40
+ # than logging.getLevelName, whose name->int behaviour is deprecated and which
41
+ # returns "Level FOO" for unknown names instead of signalling failure.
42
+ return logging.getLevelNamesMapping().get(raw.upper(), default)
43
+
44
+
45
+ def configure_logging(verbosity: int = 0, level: int | None = None) -> None:
46
+ """Attach a console handler to the ``autoslm`` logger and set its level.
47
+
48
+ ``verbosity`` maps repeated ``-v`` flags to levels (0=WARNING, 1=INFO, >=2=DEBUG).
49
+ An explicit ``level`` (or the ``AUTOSLM_LOG_LEVEL`` env var) overrides the verbosity mapping.
50
+ """
51
+ if level is None:
52
+ if os.environ.get("AUTOSLM_LOG_LEVEL"):
53
+ level = _level_from_env()
54
+ else:
55
+ level = {0: logging.WARNING, 1: logging.INFO}.get(verbosity, logging.DEBUG)
56
+
57
+ logger = logging.getLogger(_ROOT_NAME)
58
+ logger.setLevel(level)
59
+ # Replace any prior console handler we installed so repeated calls don't stack handlers.
60
+ for h in [h for h in logger.handlers if getattr(h, "_autoslm_console", False)]:
61
+ logger.removeHandler(h)
62
+ handler = logging.StreamHandler() # stderr
63
+ handler.setLevel(level)
64
+ handler.setFormatter(logging.Formatter("%(levelname)s %(name)s: %(message)s"))
65
+ handler._autoslm_console = True # type: ignore[attr-defined]
66
+ logger.addHandler(handler)
code/autoslm/catalog.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Curated model catalog for one-consumer-GPU LoRA jobs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import asdict, dataclass
7
+ from typing import Any
8
+
9
+ ALGORITHMS = ("sft", "grpo")
10
+
11
+
12
+ def normalize_algorithm(value: str) -> str:
13
+ """Canonical (lowercased, validated) algorithm name."""
14
+ value = (value or "grpo").lower()
15
+ if value not in ALGORITHMS:
16
+ raise ValueError(f"unsupported algorithm: {value}; known: {', '.join(ALGORITHMS)}")
17
+ return value
18
+
19
+
20
+ # The default GPU class a run lands on when none is pinned (also the open-model-policy
21
+ # sizing reference and the spec/from_dict fallback). The validated GPU class set
22
+ # (SUPPORTED/is_validated) lives in providers.base; per-provider classes and pricing live
23
+ # under providers/{runpod,vast}. Defined above ModelInfo so it can back the
24
+ # recommended_gpu field default.
25
+ DEFAULT_GPU = "RTX 5090"
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class ModelInfo:
30
+ id: str
31
+ display_name: str
32
+ params: str
33
+ algos: tuple[str, ...]
34
+ min_vram_gb: int
35
+ quant: str = "bf16"
36
+ recommended_gpu: str = DEFAULT_GPU
37
+ # GRPO needs more VRAM than SFT (a colocated vLLM rollout engine holds a second copy of
38
+ # the weights + KV cache). 0 => GRPO uses ``min_vram_gb`` like SFT; set it when the GRPO
39
+ # tier needs a bigger card than SFT (the colocate 2nd weight copy + KV pool). Consumed by
40
+ # engine.vram.model_required_vram_gb.
41
+ grpo_min_vram_gb: int = 0
42
+ notes: str = ""
43
+ # Worker container disk this model needs (GB). 0 = the platform default (64 GB)
44
+ # suffices. The runner raises gpu.disk_gb to at least this, so big-checkpoint
45
+ # models whose weights alone exceed 64 GB work out of the box.
46
+ min_disk_gb: int = 0
47
+ # Thinking/reasoning capability of the checkpoint's chat template:
48
+ # "none" no <think> support (or a non-thinking variant) — `thinking = true` is
49
+ # rejected for these models
50
+ # "hybrid" template honors enable_thinking (Qwen3-style hybrid reasoning)
51
+ # "always" the model always emits reasoning; enable_thinking can't turn it off,
52
+ # so `thinking = true` is required
53
+ # "unknown" open-model-policy entries (capability not verified)
54
+ thinking: str = "none"
55
+
56
+ def to_dict(self) -> dict[str, Any]:
57
+ return asdict(self)
58
+
59
+
60
+ # The default model AutoSLM trains when a config omits one. A current-gen dense 4B
61
+ # (text-only fine-tune) on the modern worker stack — the safe out-of-the-box choice for
62
+ # the average developer. It is thinking-"hybrid"; the thinking flag now defaults ON.
63
+ DEFAULT_MODEL = "Qwen/Qwen3.5-4B"
64
+
65
+ MODELS: dict[str, ModelInfo] = {
66
+ "openbmb/MiniCPM5-1B": ModelInfo(
67
+ id="openbmb/MiniCPM5-1B",
68
+ display_name="MiniCPM5 1B",
69
+ params="1.2B dense (Llama arch)",
70
+ algos=("sft", "grpo"),
71
+ min_vram_gb=12,
72
+ recommended_gpu="RTX 4090",
73
+ thinking="hybrid",
74
+ notes="On-device class SLM (131k ctx); standard Llama architecture.",
75
+ ),
76
+ # ---- Qwen3.5 dense family: validated on the modern worker stack ----
77
+ # (trl 1.x / vllm 0.19 / transformers 5.x). Trained + served TEXT-ONLY: the
78
+ # checkpoints are natively multimodal, so LoRA excludes the vision tower and vLLM
79
+ # loads language_model_only (see autoslm.engine.worker). Each entry passed a real
80
+ # train+eval smoke on its recommended GPU (bench/results/phase1/).
81
+ "Qwen/Qwen3.5-0.8B": ModelInfo(
82
+ id="Qwen/Qwen3.5-0.8B",
83
+ display_name="Qwen3.5 0.8B",
84
+ params="0.9B (text-only fine-tune)",
85
+ algos=("sft", "grpo"),
86
+ min_vram_gb=12,
87
+ recommended_gpu="RTX 4090",
88
+ thinking="hybrid",
89
+ notes="Smallest Qwen3.5; cheap smoke/dev runs with the modern arch.",
90
+ ),
91
+ "Qwen/Qwen3.5-2B": ModelInfo(
92
+ id="Qwen/Qwen3.5-2B",
93
+ display_name="Qwen3.5 2B",
94
+ params="2.3B (text-only fine-tune)",
95
+ algos=("sft", "grpo"),
96
+ min_vram_gb=16,
97
+ recommended_gpu="RTX 4090",
98
+ thinking="hybrid",
99
+ ),
100
+ "Qwen/Qwen3.5-4B": ModelInfo(
101
+ id="Qwen/Qwen3.5-4B",
102
+ display_name="Qwen3.5 4B",
103
+ params="4.7B (text-only fine-tune)",
104
+ algos=("sft", "grpo"),
105
+ min_vram_gb=32,
106
+ recommended_gpu="RTX 5090",
107
+ thinking="hybrid",
108
+ notes="Current-gen 4B. GRPO uses the sleep-mode memory recipe (hybrid arch needs "
109
+ "extra engine state-cache); fused DeltaNet kernels ship in the default stack.",
110
+ ),
111
+ "Qwen/Qwen3.5-9B": ModelInfo(
112
+ id="Qwen/Qwen3.5-9B",
113
+ display_name="Qwen3.5 9B",
114
+ params="9.7B (text-only fine-tune)",
115
+ algos=("sft", "grpo"),
116
+ min_vram_gb=16,
117
+ # MEMORY-OPTIMIZED: 4-bit NF4 frozen base + bf16 LoRA adapter (QLoRA). The base
118
+ # drops from ~19 GB bf16 to ~5.3 GB, so colocated GRPO holds two 4-bit copies
119
+ # (trainer + bnb-quantized vLLM rollout) instead of two bf16 copies -> it fits a
120
+ # ~24-32 GB card instead of an 80 GB A100. NF4 is near-lossless for adapter training
121
+ # (QLoRA paper + follow-ups), a small quality trade for a ~3x cheaper GPU. No GRPO
122
+ # floor: the matrix sizes the (much smaller) 4-bit footprint directly.
123
+ grpo_min_vram_gb=0,
124
+ quant="4bit-qlora",
125
+ recommended_gpu="RTX 5090",
126
+ thinking="hybrid",
127
+ notes="QLoRA (4-bit NF4 base + bf16 LoRA). GRPO's colocated vLLM rollout loads the "
128
+ "base 4-bit via bitsandbytes too, so both copies are 4-bit -> fits ~24-32 GB "
129
+ "instead of 80 GB bf16. ~near-lossless vs bf16 LoRA.",
130
+ ),
131
+ }
132
+
133
+
134
+ def list_models() -> list[ModelInfo]:
135
+ return sorted(MODELS.values(), key=lambda m: (m.min_vram_gb, m.id))
136
+
137
+
138
+ def get_model(model_id: str) -> ModelInfo:
139
+ try:
140
+ return MODELS[model_id]
141
+ except KeyError as exc:
142
+ allowed = ", ".join(MODELS)
143
+ raise ValueError(
144
+ f"unsupported model {model_id!r}; choose one of: {allowed} — or set "
145
+ f'model_policy = "allow" in the config to run any HF model that fits the GPU '
146
+ f"(open-model policy)"
147
+ ) from exc
148
+
149
+
150
+ def resolve_model(
151
+ model_id: str,
152
+ algorithm: str,
153
+ policy: str = "catalog",
154
+ gpu: str | None = None,
155
+ ) -> ModelInfo:
156
+ """Resolve a model under the configured policy.
157
+
158
+ ``catalog`` (default): the model must be a curated catalog entry.
159
+ ``allow``: any HF model is accepted; a coarse VRAM-fit estimate (HF safetensors
160
+ metadata, no download) blocks only provably-impossible fits and warns on tight ones.
161
+ """
162
+ algo = normalize_algorithm(algorithm)
163
+ if model_id in MODELS:
164
+ return validate_model_for_algorithm(model_id, algo)
165
+ if policy != "allow":
166
+ # Reuse get_model's error (includes the open-model hint).
167
+ return get_model(model_id)
168
+ return _resolve_open_model(model_id, algo, gpu)
169
+
170
+
171
+ def _resolve_open_model(model_id: str, algo: str, gpu: str | None) -> ModelInfo:
172
+ """Synthesize a ModelInfo for the open-model "allow" policy from a coarse VRAM-fit
173
+ estimate (HF safetensors metadata, no download). Blocks provably-impossible fits and
174
+ warns on tight ones. Isolates the engine.vram dependency + disk-floor heuristic from
175
+ the curated-catalog path in resolve_model."""
176
+ from autoslm.engine.vram import check_fit
177
+
178
+ est = check_fit(model_id, algo, gpu or DEFAULT_GPU)
179
+ if est.verdict == "too_big":
180
+ raise ValueError(
181
+ f"{model_id} does not fit the requested GPU: {est.describe()}. "
182
+ f"Pick a smaller model or a larger supported GPU."
183
+ )
184
+ if est.verdict in ("tight", "unknown"):
185
+ print(f"warning: open-model policy: {est.describe()}")
186
+ params = f"{est.params_b:.1f}B" if est.params_b else "unknown size"
187
+ # Disk floor for the open model: a bf16 checkpoint is ~2 GB per billion params;
188
+ # add worker-stack headroom so a large model that passes the VRAM check can't
189
+ # provision a paid worker and then fail in prefetch_model when the checkpoint
190
+ # overflows the 64 GB container default. 0 (unknown size) leaves the default
191
+ # (the user can still raise it with gpu.disk_gb).
192
+ min_disk = int(est.params_b * 2) + 64 if est.params_b else 0
193
+ return ModelInfo(
194
+ id=model_id,
195
+ display_name=model_id,
196
+ params=params,
197
+ algos=ALGORITHMS,
198
+ min_vram_gb=math.ceil(est.est_gb) if est.est_gb else 24,
199
+ min_disk_gb=min_disk,
200
+ recommended_gpu=gpu or DEFAULT_GPU,
201
+ thinking="unknown",
202
+ notes="unlisted model accepted via the open-model policy (not curated/validated)",
203
+ )
204
+
205
+
206
+ def validate_model_for_algorithm(model_id: str, algorithm: str) -> ModelInfo:
207
+ info = get_model(model_id)
208
+ algo = normalize_algorithm(algorithm)
209
+ # Catalog entries advertise the capability classes "sft" and "grpo": grpo needs the
210
+ # colocated rollout engine, sft is trainer-only.
211
+ required = "grpo" if algo == "grpo" else "sft"
212
+ if required not in info.algos:
213
+ allowed = ", ".join(info.algos)
214
+ raise ValueError(f"{model_id} supports {allowed}, not {algo}")
215
+ return info
216
+
217
+
218
+ def public_model_rows() -> list[dict[str, Any]]:
219
+ return [m.to_dict() for m in list_models()]
code/autoslm/cli/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """CLI package."""
code/autoslm/cli/main.py ADDED
@@ -0,0 +1,920 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CLI for the managed AutoSLM service.
2
+
3
+ Every run-lifecycle command is a thin HTTP call to the AutoSLM control plane —
4
+ users authenticate with their freesolo API key (`slm login` verifies it against
5
+ the freesolo backend), never with provider credentials. Config parsing/validation
6
+ and `--dry-run` stay fully local.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import ast
13
+ import json
14
+ import os
15
+ import sys
16
+ import time
17
+ from pathlib import Path
18
+
19
+ from autoslm import __version__
20
+ from autoslm._logging import configure_logging, get_logger
21
+ from autoslm.catalog import public_model_rows
22
+ from autoslm.client import (
23
+ ApiClient,
24
+ ClientError,
25
+ client_from_config,
26
+ save_credentials,
27
+ verify_freesolo_key,
28
+ )
29
+ from autoslm.client.config import load_credentials
30
+ from autoslm.client.specs import spec_payload
31
+ from autoslm.runner import TERMINAL_STATES, new_run_id
32
+ from autoslm.schema import ConfigError, spec_from_file
33
+ from autoslm.spec import _coerce_bool
34
+
35
+ logger = get_logger(__name__)
36
+
37
+
38
+ # Exceptions that represent expected user/config errors: report them as a clean one-line
39
+ # message instead of a Python traceback (use --debug / AUTOSLM_DEBUG=1 to see the full trace).
40
+ _USER_ERRORS = (
41
+ ConfigError,
42
+ ClientError,
43
+ FileNotFoundError,
44
+ ValueError,
45
+ )
46
+
47
+ # Run states after which nothing more will happen (polling can stop).
48
+ _CLI_DONE_STATES = TERMINAL_STATES | {"deployed"}
49
+ _OK_STATES = {"done", "dry_run", "deployed"}
50
+
51
+
52
+ def main(argv: list[str] | None = None) -> int:
53
+ parser = argparse.ArgumentParser(prog="slm", description="Managed LoRA post-training")
54
+ parser.add_argument("-V", "--version", action="version", version=f"slm {__version__}")
55
+ parser.add_argument(
56
+ "--debug",
57
+ action="store_true",
58
+ help="show full tracebacks on error (or set AUTOSLM_DEBUG=1)",
59
+ )
60
+ parser.add_argument(
61
+ "-v",
62
+ "--verbose",
63
+ action="count",
64
+ default=0,
65
+ help="increase log verbosity (-v for info, -vv for debug; or set AUTOSLM_LOG_LEVEL)",
66
+ )
67
+ sub = parser.add_subparsers(dest="cmd", required=True)
68
+
69
+ version = sub.add_parser("version", help="print the AutoSLM version")
70
+ version.set_defaults(func=cmd_version)
71
+
72
+ login = sub.add_parser("login", help="log in with your freesolo API key (verified by freesolo)")
73
+ login.add_argument(
74
+ "--api-key",
75
+ help="your freesolo API key (default: FREESOLO_API_KEY); created in the dashboard",
76
+ )
77
+ login.add_argument(
78
+ "--freesolo-url",
79
+ dest="freesolo_url",
80
+ help="freesolo backend base URL (default: FREESOLO_BASE_URL or https://api.freesolo.co)",
81
+ )
82
+ login.add_argument(
83
+ "--api-url", help="autoslm control-plane URL for training calls (default: AUTOSLM_API_URL)"
84
+ )
85
+ login.set_defaults(func=cmd_login)
86
+
87
+ whoami = sub.add_parser("whoami", help="show the identity behind your stored key")
88
+ whoami.set_defaults(func=cmd_whoami)
89
+
90
+ lab = sub.add_parser("lab", help="local authoring scaffolds")
91
+ lab_sub = lab.add_subparsers(dest="lab_cmd", required=True)
92
+ setup = lab_sub.add_parser("setup", help="scaffold environments/ + configs/ in the cwd")
93
+ setup.set_defaults(func=cmd_lab_setup)
94
+
95
+ models = sub.add_parser("models", help="list supported base models")
96
+ models.set_defaults(func=cmd_models)
97
+
98
+ gpus = sub.add_parser("gpus", help="list managed GPU classes with live $/hr")
99
+ gpus.set_defaults(func=cmd_gpus)
100
+
101
+ env = sub.add_parser("env", help="manage verifiers environments")
102
+ env_sub = env.add_subparsers(dest="env_cmd", required=True)
103
+ init = env_sub.add_parser("init", help="scaffold a new local verifiers environment")
104
+ init.add_argument("name")
105
+ init.set_defaults(func=cmd_env_init)
106
+
107
+ env_list = env_sub.add_parser("list", help="list installed + local environments")
108
+ env_list.set_defaults(func=cmd_env_list)
109
+
110
+ env_install = env_sub.add_parser("install", help="install a published Prime Hub environment")
111
+ env_install.add_argument("env_id", help='the env id to install (a Hub slug, "owner/name")')
112
+ env_install.set_defaults(func=cmd_env_install)
113
+
114
+ env_push = env_sub.add_parser(
115
+ "push", help="publish a local verifiers env to the Prime Hub (private); prints its env id"
116
+ )
117
+ env_push.add_argument("path", nargs="?", default=".")
118
+ env_push.set_defaults(func=cmd_env_push)
119
+
120
+ train = sub.add_parser("train", help="submit a managed training run from a TOML config")
121
+ train.add_argument("config")
122
+ train.add_argument(
123
+ "--config",
124
+ dest="extra_configs",
125
+ action="append",
126
+ default=[],
127
+ help="additional TOML to deep-merge (config composition); repeatable",
128
+ )
129
+ train.add_argument(
130
+ "--set",
131
+ dest="overrides",
132
+ action="append",
133
+ default=[],
134
+ metavar="key=value",
135
+ help="override a config value; repeatable",
136
+ )
137
+ train.add_argument("--dry-run", action="store_true")
138
+ train.add_argument(
139
+ "--background",
140
+ action="store_true",
141
+ help="submit and return immediately instead of following logs",
142
+ )
143
+ train.set_defaults(func=cmd_train)
144
+
145
+ status = sub.add_parser("status", help="show a run's full status JSON")
146
+ status.add_argument("run_id")
147
+ status.set_defaults(func=cmd_status)
148
+
149
+ attach = sub.add_parser(
150
+ "attach", help="follow a running job's logs to completion (resumable any time)"
151
+ )
152
+ attach.add_argument("run_id")
153
+ attach.set_defaults(func=cmd_attach)
154
+
155
+ ps = sub.add_parser("ps", help="list runs and their state/cost")
156
+ ps.set_defaults(func=cmd_ps)
157
+
158
+ cost = sub.add_parser("cost", help="show a run's accrued cost (USD)")
159
+ cost.add_argument("run_id")
160
+ cost.set_defaults(func=cmd_cost)
161
+
162
+ cancel = sub.add_parser("cancel", help="cancel a run (best-effort)")
163
+ cancel.add_argument("run_id")
164
+ cancel.set_defaults(func=cmd_cancel)
165
+
166
+ logs = sub.add_parser("logs")
167
+ logs.add_argument("run_id")
168
+ logs.add_argument("-f", "--follow", action="store_true", help="stream new log lines")
169
+ logs.set_defaults(func=cmd_logs)
170
+
171
+ deploy = sub.add_parser("deploy")
172
+ deploy.add_argument("run_id")
173
+ deploy.add_argument(
174
+ "--mode",
175
+ choices=["dev", "always-on"],
176
+ default="dev",
177
+ help="dev: scale-to-zero, cold start after idle, $0 when unused (default). "
178
+ "always-on: one warm worker 24/7, no cold starts, continuous billing.",
179
+ )
180
+ deploy.add_argument(
181
+ "--idle-timeout",
182
+ type=int,
183
+ default=300,
184
+ help="dev mode: seconds of inactivity before the worker scales to zero (default 300)",
185
+ )
186
+ deploy.add_argument("--dry-run", action="store_true")
187
+ deploy.set_defaults(func=cmd_deploy)
188
+
189
+ undeploy = sub.add_parser("undeploy", help="tear down a run's serving endpoint")
190
+ undeploy.add_argument("run_id")
191
+ undeploy.set_defaults(func=cmd_undeploy)
192
+
193
+ deployments = sub.add_parser("deployments", help="list active serving deployments")
194
+ deployments.set_defaults(func=cmd_deployments)
195
+
196
+ chat = sub.add_parser("chat", help="chat with a deployed adapter")
197
+ chat.add_argument("run_id")
198
+ chat.add_argument("-m", "--message", required=True)
199
+ chat.add_argument("--max-tokens", type=int, default=512)
200
+ chat.add_argument("--temperature", type=float, default=0.0)
201
+ chat.set_defaults(func=cmd_chat)
202
+
203
+ # The control plane is operator-only and run as a separate one-off service via the
204
+ # `autoslm-server` console script (autoslm.server.__main__:main), not a `slm` subcommand.
205
+
206
+ args = parser.parse_args(argv)
207
+ configure_logging(verbosity=getattr(args, "verbose", 0))
208
+ debug = getattr(args, "debug", False) or _coerce_bool(os.environ.get("AUTOSLM_DEBUG", ""))
209
+ try:
210
+ return args.func(args)
211
+ except _USER_ERRORS as exc:
212
+ if debug:
213
+ raise
214
+ print(f"error: {exc}", file=sys.stderr)
215
+ return 1
216
+ except KeyboardInterrupt:
217
+ print("aborted", file=sys.stderr)
218
+ return 130
219
+
220
+
221
+ def cmd_version(args) -> int:
222
+ print(f"slm {__version__}")
223
+ return 0
224
+
225
+
226
+ def cmd_login(args) -> int:
227
+ # Login is handled by the freesolo backend (not the autoslm control plane): the user
228
+ # supplies the freesolo API key they created in the dashboard, and we verify it against
229
+ # freesolo before storing it. The same key authenticates autoslm's control plane.
230
+ api_key = args.api_key or os.environ.get("FREESOLO_API_KEY")
231
+ if not api_key:
232
+ raise ClientError(
233
+ "no API key provided: pass `--api-key <key>` or set FREESOLO_API_KEY. "
234
+ "Create a key in your freesolo dashboard."
235
+ )
236
+ verify_freesolo_key(api_key, base_url=getattr(args, "freesolo_url", None))
237
+ api_url = args.api_url or load_credentials()[0]
238
+ # save_credentials clears the stored url when it's the default, so logging into the
239
+ # default plane also drops a stale custom url from a previous custom-URL login.
240
+ path = save_credentials(api_key, api_url=api_url)
241
+ # Never echo the key itself; the stored file is the single source of truth.
242
+ print(f"logged in: freesolo verified your key (saved to {path})")
243
+ print("you're ready to train — try `slm train <config.toml>`")
244
+ return 0
245
+
246
+
247
+ def cmd_whoami(args) -> int:
248
+ print(json.dumps(client_from_config().me(), indent=2))
249
+ return 0
250
+
251
+
252
+ _STARTER_ENV_PY = '''\
253
+ """Starter local verifiers environment.
254
+
255
+ Replace the dataset and rubric with your task, then publish it to the Prime Hub with
256
+ `slm env push environments/starter_env.py`. A managed run references the published env by
257
+ its Hub slug: set [environment] id = "owner/name" in the config.
258
+ See https://github.com/PrimeIntellect-ai/verifiers for the full API.
259
+ """
260
+
261
+ import verifiers as vf
262
+ from datasets import Dataset
263
+
264
+
265
+ def load_environment(**kwargs) -> vf.Environment:
266
+ dataset = Dataset.from_list(
267
+ [
268
+ {"prompt": [{"role": "user", "content": "What is 2 + 2?"}], "answer": "4"},
269
+ {"prompt": [{"role": "user", "content": "What is 3 + 5?"}], "answer": "8"},
270
+ ]
271
+ )
272
+
273
+ def correct_answer(completion, answer, **_):
274
+ """Reward 1.0 when the gold answer appears in the model's final message."""
275
+ text = completion[-1]["content"] if isinstance(completion, list) else str(completion)
276
+ return 1.0 if str(answer) in text else 0.0
277
+
278
+ rubric = vf.Rubric(funcs=[correct_answer], weights=[1.0])
279
+ return vf.SingleTurnEnv(dataset=dataset, rubric=rubric, **kwargs)
280
+ '''
281
+
282
+
283
+ def cmd_lab_setup(args) -> int:
284
+ Path("environments").mkdir(exist_ok=True)
285
+ Path("configs").mkdir(exist_ok=True)
286
+ Path("configs/endpoints.toml").write_text(
287
+ "# OpenAI-compatible endpoints returned by `slm deploy` can be stored here.\n"
288
+ )
289
+ starter_env = Path("environments/starter_env.py")
290
+ if not starter_env.exists():
291
+ starter_env.write_text(_STARTER_ENV_PY)
292
+ sample = Path("configs/verifiers_grpo.toml")
293
+ if not sample.exists():
294
+ sample.write_text(
295
+ 'model = "Qwen/Qwen3.5-4B"\n'
296
+ 'algorithm = "grpo"\n\n'
297
+ "# Environment: a verifiers / Prime Hub env slug. Publish the scaffolded\n"
298
+ "# environments/starter_env.py with `slm env push environments/starter_env.py`\n"
299
+ "# (then `slm env install owner/name`) to get the slug, and set it below.\n"
300
+ "[environment]\n"
301
+ 'id = "owner/name" # a verifiers / Prime Hub env slug\n\n'
302
+ "[train]\n"
303
+ 'hf_repo = "your-org/your-runs" # HF dataset repo for adapters/checkpoints\n'
304
+ "steps = 150\n"
305
+ "lora_rank = 32\n"
306
+ "seeds = [0]\n\n"
307
+ "# Managed GPU (RTX 4090 or RTX 5090 only).\n"
308
+ "[gpu]\n"
309
+ 'type = "RTX 5090"\n'
310
+ )
311
+ print(
312
+ "created environments/, environments/starter_env.py, configs/, "
313
+ "configs/verifiers_grpo.toml, configs/endpoints.toml"
314
+ )
315
+ return 0
316
+
317
+
318
+ def cmd_models(args) -> int:
319
+ for row in public_model_rows():
320
+ print(
321
+ f"{row['id']}\t{row['params']}\talgos={','.join(row['algos'])}\t{row['quant']}"
322
+ f"\tthinking={row.get('thinking', 'none')}"
323
+ )
324
+ return 0
325
+
326
+
327
+ def cmd_gpus(args) -> int:
328
+ """List GPU classes, VRAM, per-provider $/hr and live validation."""
329
+ from autoslm.providers import available_providers
330
+ from autoslm.providers.base import GPU_INFO
331
+ from autoslm.providers.runpod.pricing import live_rates
332
+
333
+ rates = live_rates()
334
+ # Cheapest live verified-datacenter offer per class (vast key + network only).
335
+ vast_rates: dict[str, float] = {}
336
+ if "vast" in available_providers():
337
+ try:
338
+ from autoslm.providers.vast.jobs import usable_offers
339
+
340
+ for offer in usable_offers(0, 0):
341
+ vast_rates.setdefault(offer.gpu, offer.dph_total) # offers are price-sorted
342
+ except Exception as exc:
343
+ print(f"warning: vast offers unavailable ({exc})", file=sys.stderr)
344
+
345
+ def fmt_rate(v: float | None) -> str:
346
+ return f"{v:>10.2f}" if v else f"{'-':>10}"
347
+
348
+ print(f"{'gpu':<16}{'vram':>6}{'runpod$/hr':>11}{'vast$/hr':>10} validated_on")
349
+ for info in sorted(GPU_INFO.values(), key=lambda g: rates.get(g.name, g.hourly_usd)):
350
+ runpod_rate = rates.get(info.name, info.hourly_usd) if info.enum_member else None
351
+ validated = ",".join(info.validated_on) or "- (needs gpu.allow_unvalidated)"
352
+ print(
353
+ f"{info.name:<16}{info.vram_gb:>5}G{fmt_rate(runpod_rate):>11}"
354
+ f"{fmt_rate(vast_rates.get(info.name))} {validated}"
355
+ )
356
+ print(
357
+ '\nTip: omit gpu.type (or set "cheapest") to allocate the cheapest validated class\n'
358
+ "across providers that fits the model; gpu.provider pins runpod/vast."
359
+ )
360
+ return 0
361
+
362
+
363
+ def cmd_env_init(args) -> int:
364
+ mod = args.name.replace("-", "_")
365
+ root = Path("environments") / mod
366
+ root.mkdir(parents=True, exist_ok=True)
367
+ # Verifiers-only: scaffold a real verifiers env whose load_environment returns a
368
+ # vf.Environment (here a SingleTurnEnv + Rubric over a datasets.Dataset). This is what
369
+ # a Hub push expects, so a freshly scaffolded env actually loads.
370
+ (root / f"{mod}.py").write_text(
371
+ f'"""Custom verifiers environment ({args.name}).\n\n'
372
+ "Replace the dataset and rubric with your task, then publish it to the Prime Hub\n"
373
+ f"with `slm env push environments/{mod}/{mod}.py` and reference it by id\n"
374
+ '([environment] id = "owner/name") in your config.\n'
375
+ "See https://github.com/PrimeIntellect-ai/verifiers for the full API.\n"
376
+ '"""\n\n'
377
+ "import verifiers as vf\n"
378
+ "from datasets import Dataset\n\n\n"
379
+ "def load_environment(**kwargs) -> vf.Environment:\n"
380
+ " dataset = Dataset.from_list(\n"
381
+ " [\n"
382
+ ' {"prompt": [{"role": "user", "content": "What is 2 + 2?"}], "answer": "4"},\n'
383
+ ' {"prompt": [{"role": "user", "content": "What is 3 + 5?"}], "answer": "8"},\n'
384
+ " ]\n"
385
+ " )\n\n"
386
+ " def correct_answer(completion, answer, **_):\n"
387
+ ' """Reward 1.0 when the gold answer appears in the model\'s final message."""\n'
388
+ " text = (\n"
389
+ ' completion[-1]["content"] if isinstance(completion, list) else str(completion)\n'
390
+ " )\n"
391
+ " return 1.0 if str(answer) in text else 0.0\n\n"
392
+ " rubric = vf.Rubric(funcs=[correct_answer], weights=[1.0])\n"
393
+ " return vf.SingleTurnEnv(dataset=dataset, rubric=rubric, **kwargs)\n"
394
+ )
395
+ (root / "README.md").write_text(f"# {args.name}\n\nCustom verifiers environment for AutoSLM.\n")
396
+ print(f"created {root}")
397
+ print(
398
+ f"publish it to the Prime Hub with `slm env push environments/{mod}/{mod}.py`, "
399
+ 'then reference it by id ([environment] id = "owner/name") in your config.'
400
+ )
401
+ return 0
402
+
403
+
404
+ def cmd_env_list(args) -> int:
405
+ from autoslm.envs.registry import list_installed_verifiers_envs
406
+
407
+ installed = list_installed_verifiers_envs()
408
+ if installed:
409
+ print("installed (verifiers / Prime Hub):")
410
+ for env_id in installed:
411
+ print(f" {env_id}")
412
+ local = Path("environments")
413
+ if local.is_dir():
414
+ # Both directory envs (environments/<name>/<name>.py) and top-level single-file
415
+ # modules (environments/<name>.py, e.g. the `slm lab` starter env). These are local
416
+ # env SOURCES — publish one with `slm env push <path>` to run it on the managed
417
+ # service by its Hub id.
418
+ paths: list[str] = []
419
+ for p in local.iterdir():
420
+ if p.name.startswith("__"):
421
+ continue
422
+ if p.is_dir():
423
+ # `slm env init` maps a hyphenated dir to an underscored inner module file
424
+ # (my-env/ -> my-env/my_env.py). List that exact path, and only when it
425
+ # actually exists (an empty/incomplete folder isn't a publishable source).
426
+ stem = p.name.replace("-", "_")
427
+ module = p / f"{stem}.py"
428
+ if module.is_file():
429
+ paths.append(f"environments/{p.name}/{stem}.py")
430
+ elif p.suffix == ".py":
431
+ paths.append(f"environments/{p.name}")
432
+ if paths:
433
+ print("local env sources (publish with `slm env push <path>`):")
434
+ for path in sorted(paths):
435
+ print(f" {path}")
436
+ return 0
437
+
438
+
439
+ # Prime Intellect Environments Hub pip index. Each org's wheels live under ITS OWN namespace
440
+ # (e.g. freesolo-co/autoslm-bench -> .../freesolo-co/simple/), so derive the index from the
441
+ # slug owner — a hardcoded `primeintellect` index 404s on any non-primeintellect env.
442
+ PRIME_HUB_INDEX_TMPL = "https://hub.primeintellect.ai/{owner}/simple/"
443
+
444
+
445
+ def _prime_hub_index(env_id: str) -> str:
446
+ owner = env_id.split("/", 1)[0] if "/" in env_id else "primeintellect"
447
+ return PRIME_HUB_INDEX_TMPL.format(owner=owner)
448
+
449
+
450
+ def cmd_env_install(args) -> int:
451
+ import shutil
452
+ import subprocess
453
+
454
+ from autoslm.envs.registry import _bare_wheel_name, record_installed_env
455
+
456
+ env_id = args.env_id
457
+ # Managed envs are Prime Hub slugs: exactly one `/` with non-empty owner and name. A bare
458
+ # id (`gsm8k`) or a malformed slug can't be resolved on the Hub, so reject it up front
459
+ # rather than letting `prime`/pip fail with an opaque error.
460
+ parts = env_id.split("/")
461
+ if len(parts) != 2 or not parts[0] or not parts[1]:
462
+ print(
463
+ f'env id must be a Prime Hub slug "owner/name" (got {env_id!r})',
464
+ file=sys.stderr,
465
+ )
466
+ return 1
467
+ # `slm env install` is a LOCAL-client convenience: it installs the env into the client's
468
+ # interpreter and records it in ~/.autoslm/envs.json for local authoring/dry-run. The
469
+ # managed worker does NOT reinstall from this record — it installs Hub envs itself via an
470
+ # authenticated `prime env install` on the GPU box. A Hub slug `owner/name` maps to the pip
471
+ # wheel `name` on the Prime Intellect Hub index; we record that index alongside the env.
472
+ extras = {"extra_index_url": _prime_hub_index(env_id)}
473
+ if shutil.which("prime"):
474
+ # The `prime` CLI resolves the Hub + index itself (and is the only path that can fetch a
475
+ # PRIVATE Hub env — autoslm publishes envs PRIVATE).
476
+ cmd = ["prime", "env", "install", env_id]
477
+ else:
478
+ # The pip fallback hits the PUBLIC Hub index only; it cannot fetch PRIVATE Hub envs
479
+ # (the public index never serves private wheels). Be explicit instead of letting a
480
+ # private install fail confusingly, but still attempt pip for the public case.
481
+ print(
482
+ f"note: `prime` CLI not found; attempting a pip install of {env_id} from the "
483
+ "PUBLIC Hub index. PRIVATE Hub envs require the `prime` CLI — install it "
484
+ "(https://docs.primeintellect.ai) to install a private env."
485
+ )
486
+ installer = (
487
+ # `uv pip install` outside an active venv errors with "No virtual environment
488
+ # found"; --python targets the CLI's own interpreter so a global/pipx `slm`
489
+ # install still records the env.
490
+ ["uv", "pip", "install", "--python", sys.executable]
491
+ if shutil.which("uv")
492
+ else [sys.executable, "-m", "pip", "install"]
493
+ )
494
+ cmd = [*installer, _bare_wheel_name(env_id), "--extra-index-url", extras["extra_index_url"]]
495
+ print("running:", " ".join(cmd))
496
+ rc = subprocess.run(cmd).returncode
497
+ if rc != 0:
498
+ print("install failed")
499
+ return rc
500
+ record_installed_env(env_id, package=_bare_wheel_name(env_id), extras=extras)
501
+ print(f"installed {env_id}; recorded in ~/.autoslm/envs.json")
502
+ print(f'use it via: [environment]\\nid = "{env_id}"')
503
+ return 0
504
+
505
+
506
+ # A verifiers env packaged for the Prime Hub is a pyproject + an importable module exposing
507
+ # load_environment(). When `slm env push` is pointed at a bare module (a single `.py`, as the
508
+ # freesolo training agent emits, or a dir without a pyproject), we wrap it in this layout so the
509
+ # push Just Works instead of erroring on "pyproject.toml not found".
510
+ _ENV_PUSH_PYPROJECT = """\
511
+ [project]
512
+ name = "{name}"
513
+ version = "{version}"
514
+ description = "AutoSLM verifiers environment ({name})."
515
+ requires-python = ">=3.10"
516
+ dependencies = ["verifiers"]
517
+
518
+ [build-system]
519
+ requires = ["hatchling"]
520
+ build-backend = "hatchling.build"
521
+
522
+ [tool.hatch.build.targets.wheel]
523
+ packages = ["{module}"]
524
+ """
525
+
526
+ _PUSH_INITIAL_VERSION = "0.1.0"
527
+ _PUSH_MAX_ATTEMPTS = 8
528
+ _PUSH_CONFLICT_MARKERS = ("already exists", "version already", "duplicate", "conflict", "409")
529
+
530
+
531
+ def _push_env_name(raw: str) -> str:
532
+ import re
533
+
534
+ name = re.sub(r"[^a-z0-9]+", "-", raw.lower()).strip("-")
535
+ return name or "autoslm-env"
536
+
537
+
538
+ def _push_is_version_conflict(text: str) -> bool:
539
+ lowered = text.lower()
540
+ return any(marker in lowered for marker in _PUSH_CONFLICT_MARKERS)
541
+
542
+
543
+ def _push_slug_from(env_dir, output: str) -> str | None:
544
+ import re
545
+
546
+ meta = Path(env_dir) / ".prime" / ".env-metadata.json"
547
+ try:
548
+ data = json.loads(meta.read_text())
549
+ owner, name = data.get("owner"), data.get("name")
550
+ if owner and name:
551
+ return f"{owner}/{name}"
552
+ except (OSError, json.JSONDecodeError):
553
+ pass
554
+ match = re.search(r"[Ss]uccessfully pushed\s+([A-Za-z0-9][\w.-]*/[\w.-]+)", output)
555
+ return match.group(1) if match else None
556
+
557
+
558
+ def _config_env_name(config_path) -> str | None:
559
+ """The `name` part of a sibling autoslm.toml's `[environment] id = "owner/name"`, or None.
560
+
561
+ Used so a bare `environment.py` re-publishes under its EXISTING Hub env (minting a new
562
+ version) instead of deriving a fresh name from the file stem. Owner still comes from the
563
+ authenticated Prime account/team, so only the name part is consumed here."""
564
+ import tomllib
565
+
566
+ path = Path(config_path)
567
+ if not path.is_file():
568
+ return None
569
+ try:
570
+ data = tomllib.loads(path.read_text())
571
+ except (OSError, tomllib.TOMLDecodeError):
572
+ return None
573
+ env = data.get("environment")
574
+ env_id = str(env.get("id") or "").strip() if isinstance(env, dict) else ""
575
+ if "/" in env_id:
576
+ name = env_id.split("/", 1)[1].strip()
577
+ return name or None
578
+ return None
579
+
580
+
581
+ def _config_env_name_from_dir(config_dir) -> str | None:
582
+ """The Hub env name declared by the sibling per-phase autoslm configs
583
+ (``autoslm_grpo.toml``/``autoslm_sft.toml``). Without this, pushing ``environment.py`` finds
584
+ no id and mints a brand-new env, so the run trains against the stale id in the configs.
585
+ """
586
+ config_dir = Path(config_dir)
587
+ for cfg in ("autoslm_grpo.toml", "autoslm_sft.toml"):
588
+ name = _config_env_name(config_dir / cfg)
589
+ if name:
590
+ return name
591
+ return None
592
+
593
+
594
+ def _with_syspath_bootstrap(env_source: str) -> str:
595
+ """Prepend a sys.path bootstrap so a published env (run as the package __init__) can resolve
596
+ BARE absolute imports of its shipped sibling helpers (`import config` / `from utils import x`)
597
+ even without its own sys.path.insert — otherwise `prime env install`/load_environment fails
598
+ with ModuleNotFoundError. Inserted AFTER the module docstring and any `from __future__` imports
599
+ (which must stay first). Mirrors the platform hub publisher."""
600
+ bootstrap = (
601
+ "import os as _autoslm_os, sys as _autoslm_sys\n"
602
+ "_autoslm_sys.path.insert(0, _autoslm_os.path.dirname(__file__))\n"
603
+ )
604
+ try:
605
+ tree = ast.parse(env_source)
606
+ except SyntaxError:
607
+ return bootstrap + env_source
608
+ insert_after = 0
609
+ body = tree.body
610
+ i = 0
611
+ if (
612
+ body
613
+ and isinstance(body[0], ast.Expr)
614
+ and isinstance(getattr(body[0], "value", None), ast.Constant)
615
+ and isinstance(body[0].value.value, str)
616
+ ):
617
+ insert_after = body[0].end_lineno or 0
618
+ i = 1
619
+ while i < len(body) and isinstance(body[i], ast.ImportFrom) and body[i].module == "__future__":
620
+ insert_after = body[i].end_lineno or insert_after
621
+ i += 1
622
+ lines = env_source.splitlines(keepends=True)
623
+ return "".join(lines[:insert_after]) + bootstrap + "".join(lines[insert_after:])
624
+
625
+
626
+ def _run_prime_push(env_dir, *, is_new: bool, name: str | None = None) -> int:
627
+ """Run `prime env push` on a packaged env dir (always PRIVATE), climbing past conflicts.
628
+
629
+ When `name` is given it is passed as `--name` so the push targets that exact Hub env."""
630
+ import subprocess
631
+
632
+ # Published environments are always PRIVATE — they can hold proprietary task data.
633
+ base = ["prime", "env", "push", "--plain", "--path", str(env_dir), "--visibility", "PRIVATE"]
634
+ if name:
635
+ base += ["--name", name]
636
+ # Disable prime's interactive version check so a push isn't blocked in non-interactive
637
+ # use (PRIME_API_KEY is inherited from the user's environment).
638
+ env = {**os.environ, "PRIME_DISABLE_VERSION_CHECK": "1"}
639
+ auto_bump = not is_new # a re-publish must land on a fresh version
640
+ for _ in range(_PUSH_MAX_ATTEMPTS):
641
+ cmd = [*base, "--auto-bump"] if auto_bump else list(base)
642
+ proc = subprocess.run(cmd, capture_output=True, text=True, env=env)
643
+ output = f"{proc.stdout or ''}{proc.stderr or ''}"
644
+ if proc.stdout:
645
+ print(proc.stdout, end="")
646
+ if proc.stderr:
647
+ print(proc.stderr, end="")
648
+ if proc.returncode == 0:
649
+ slug = _push_slug_from(env_dir, output)
650
+ if slug:
651
+ print(f"published {slug}")
652
+ else:
653
+ # Don't report a clean success we can't confirm: the push exited 0 but we
654
+ # couldn't parse the owner/name id, so the env reference may be unrecorded.
655
+ print(
656
+ "warning: `prime env push` exited 0 but no owner/name id could be parsed; "
657
+ "verify the environment on the Prime Hub before training against it",
658
+ file=sys.stderr,
659
+ )
660
+ return 0
661
+ if _push_is_version_conflict(output):
662
+ auto_bump = True
663
+ continue
664
+ return proc.returncode
665
+ print(f"push failed after {_PUSH_MAX_ATTEMPTS} version-conflict retries", file=sys.stderr)
666
+ return 1
667
+
668
+
669
+ def cmd_env_push(args) -> int:
670
+ import shutil
671
+ import tempfile
672
+
673
+ if not shutil.which("prime"):
674
+ print("the `prime` CLI is required to publish to the Environments Hub.")
675
+ print("install it (https://docs.primeintellect.ai) then re-run `slm env push`.")
676
+ return 1
677
+
678
+ src = Path(args.path)
679
+ if not src.exists():
680
+ print(f"no such path: {src}", file=sys.stderr)
681
+ return 1
682
+
683
+ # A proper env directory (has a pyproject.toml) is pushed as-is; its name comes from the
684
+ # pyproject. Otherwise the published env name is derived from the env's path.
685
+ if src.is_dir() and (src / "pyproject.toml").is_file():
686
+ # First attempt never forces --auto-bump; the version-conflict retry enables it only
687
+ # when the version actually collides, so a genuine first publish keeps its version.
688
+ return _run_prime_push(src, is_new=True)
689
+
690
+ # Wrap a bare verifiers module (a single .py, or a one-module dir) into a Prime-compatible
691
+ # env package and push that. `--auto-bump` retries handle re-publishes. `data_dir` is a
692
+ # committed `datasets/` sibling of the module (if any); we ship it inside the package so an
693
+ # env that reads a `__file__`-relative data file still resolves once installed.
694
+ if src.is_file() and src.suffix == ".py":
695
+ module_source = src.read_text()
696
+ # Re-publish to the SAME Hub env when a sibling autoslm config names one: use its
697
+ # `[environment] id` name part so an edited environment.py mints a new version of the
698
+ # existing env instead of creating a fresh env from the file stem.
699
+ sibling_name = _config_env_name_from_dir(src.parent)
700
+ env_name = sibling_name or _push_env_name(src.stem)
701
+ data_dir = src.parent / "datasets"
702
+ # Ship the env's sibling helper modules (config.py/utils.py/...) so an environment.py that
703
+ # does `sys.path.insert(0, dir(__file__)); import utils` resolves once installed.
704
+ sibling_modules = [
705
+ p for p in sorted(src.parent.glob("*.py")) if p != src and not p.name.startswith("__")
706
+ ]
707
+ # A sibling config id means we're re-publishing an EXISTING Hub env: auto-bump from the
708
+ # first attempt so it doesn't restart at 0.1.0 and climb through version conflicts.
709
+ is_new = sibling_name is None
710
+ elif src.is_dir():
711
+ modules = [p for p in sorted(src.glob("*.py")) if not p.name.startswith("__")]
712
+ if len(modules) != 1:
713
+ print(
714
+ f"{src} has no pyproject.toml and {'no' if not modules else 'multiple'} "
715
+ "top-level .py module(s); point `slm env push` at the env's .py file or add a "
716
+ "pyproject.toml.",
717
+ file=sys.stderr,
718
+ )
719
+ return 1
720
+ module_source = modules[0].read_text()
721
+ env_name = _push_env_name(src.name)
722
+ data_dir = src / "datasets"
723
+ sibling_modules = []
724
+ is_new = True
725
+ else:
726
+ print(f"cannot publish {src}: expected a verifiers .py module or an env directory.")
727
+ return 1
728
+
729
+ module = env_name.replace("-", "_")
730
+ # A Python package name can't start with a digit, so prefix one (e.g. "2026-task").
731
+ if module[:1].isdigit():
732
+ module = f"env_{module}"
733
+ with tempfile.TemporaryDirectory(prefix="slm-env-push-") as tmp:
734
+ pkg = Path(tmp)
735
+ (pkg / module).mkdir()
736
+ (pkg / module / "__init__.py").write_text(_with_syspath_bootstrap(module_source))
737
+ # Ship committed sibling data inside the package dir (it lands at <module>/datasets/, so a
738
+ # `os.path.dirname(__file__)/datasets/...` read resolves on the worker); the whole package
739
+ # dir ships via `[tool.hatch.build.targets.wheel] packages = ["<module>"]`.
740
+ if data_dir.is_dir() and any(data_dir.iterdir()):
741
+ shutil.copytree(data_dir, pkg / module / "datasets")
742
+ for mod in sibling_modules:
743
+ shutil.copy2(mod, pkg / module / mod.name)
744
+ (pkg / "pyproject.toml").write_text(
745
+ _ENV_PUSH_PYPROJECT.format(name=env_name, module=module, version=_PUSH_INITIAL_VERSION)
746
+ )
747
+ (pkg / "README.md").write_text(f"# {env_name}\n\nAutoSLM verifiers environment.\n")
748
+ return _run_prime_push(pkg, is_new=is_new, name=env_name)
749
+
750
+
751
+ def cmd_train(args) -> int:
752
+ spec = spec_from_file(
753
+ args.config,
754
+ run_id=new_run_id() if args.dry_run else None,
755
+ overrides=getattr(args, "overrides", None),
756
+ extra_configs=getattr(args, "extra_configs", None),
757
+ )
758
+ if args.dry_run:
759
+ # Fully local: validate the id-based config without credentials, a server, or a GPU.
760
+ print(
761
+ json.dumps(
762
+ {"run_id": spec.run_id, "state": "dry_run", "spec": spec.to_dict()}, indent=2
763
+ )
764
+ )
765
+ return 0
766
+ client = client_from_config()
767
+ status = client.create_run(spec_payload(spec))
768
+ run_id = status["run_id"]
769
+ logger.info(
770
+ "submitted run %s: model=%s algorithm=%s gpu=%s seeds=%s",
771
+ run_id,
772
+ spec.model,
773
+ spec.algorithm,
774
+ spec.gpu.type,
775
+ list(spec.train.seeds),
776
+ )
777
+ if args.background:
778
+ print(json.dumps(status, indent=2))
779
+ return 0
780
+ print(
781
+ f"run {run_id} submitted; following logs (Ctrl-C detaches, `slm attach {run_id}` resumes)",
782
+ file=sys.stderr,
783
+ )
784
+ return _follow_run(client, run_id)
785
+
786
+
787
+ def _poll_logs(client: ApiClient, run_id: str, interval: float) -> str:
788
+ """Stream offset-paged logs until the run reaches a terminal state; return that state."""
789
+ offset = 0
790
+ while True:
791
+ page = client.get_logs(run_id, offset=offset)
792
+ if page["logs"]:
793
+ print(page["logs"], end="", flush=True)
794
+ offset = page["offset"]
795
+ if page["state"] in _CLI_DONE_STATES:
796
+ return page["state"]
797
+ time.sleep(interval)
798
+
799
+
800
+ def _follow_run(client: ApiClient, run_id: str) -> int:
801
+ """Poll logs until the run reaches a terminal state, then print the final status."""
802
+ state = _poll_logs(client, run_id, interval=2.0)
803
+ print(json.dumps(client.get_run(run_id), indent=2))
804
+ return 0 if state in _OK_STATES else 1
805
+
806
+
807
+ def cmd_status(args) -> int:
808
+ print(json.dumps(client_from_config().get_run(args.run_id), indent=2))
809
+ return 0
810
+
811
+
812
+ def cmd_attach(args) -> int:
813
+ client = client_from_config()
814
+ return _follow_run(client, args.run_id)
815
+
816
+
817
+ def cmd_ps(args) -> int:
818
+ runs = client_from_config().list_runs()
819
+ if not runs:
820
+ print("no runs yet")
821
+ return 0
822
+ print(f"{'RUN_ID':<32} {'STATE':<11} {'COST($)':>8} {'GPU':<22} MODEL")
823
+ for r in sorted(runs, key=lambda r: r.get("updated_at", 0), reverse=True):
824
+ spec = r.get("spec") or {}
825
+ model = spec.get("model", "")
826
+ remote = r.get("remote") or {}
827
+ # the remote handle knows what actually ran; the spec is the parse-time pick
828
+ provider = remote.get("provider") or (
829
+ "runpod" if remote else (spec.get("gpu") or {}).get("provider", "")
830
+ )
831
+ gpu = remote.get("gpu") or (spec.get("gpu") or {}).get("type", "")
832
+ where = f"{gpu}@{provider}" if provider else gpu
833
+ print(
834
+ f"{r['run_id']:<32} {r['state']:<11} {r.get('cost_usd', 0.0):>8.4f} "
835
+ f"{where:<22} {model}"
836
+ )
837
+ return 0
838
+
839
+
840
+ def cmd_cost(args) -> int:
841
+ status = client_from_config().get_run(args.run_id)
842
+ print(
843
+ json.dumps(
844
+ {
845
+ "run_id": args.run_id,
846
+ "state": status["state"],
847
+ "cost_usd": status.get("cost_usd", 0.0),
848
+ },
849
+ indent=2,
850
+ )
851
+ )
852
+ return 0
853
+
854
+
855
+ def cmd_cancel(args) -> int:
856
+ status = client_from_config().cancel_run(args.run_id)
857
+ print(json.dumps({"run_id": args.run_id, "state": status["state"]}, indent=2))
858
+ return 0
859
+
860
+
861
+ def cmd_logs(args) -> int:
862
+ client = client_from_config()
863
+ if not args.follow:
864
+ print(client.get_logs(args.run_id)["logs"], end="")
865
+ return 0
866
+ _poll_logs(client, args.run_id, interval=1.0)
867
+ return 0
868
+
869
+
870
+ def cmd_deploy(args) -> int:
871
+ dep = client_from_config().deploy(
872
+ args.run_id,
873
+ mode=args.mode,
874
+ idle_timeout_s=args.idle_timeout,
875
+ dry_run=args.dry_run,
876
+ )
877
+ print(json.dumps(dep, indent=2))
878
+ if dep.get("mode") == "always-on":
879
+ print(
880
+ f"note: always-on keeps a {dep.get('gpu')} warm 24/7 "
881
+ f"(~${dep.get('est_idle_cost_usd_per_day')}/day). Use `slm undeploy {args.run_id}` "
882
+ "to stop billing.",
883
+ file=sys.stderr,
884
+ )
885
+ return 0
886
+
887
+
888
+ def cmd_undeploy(args) -> int:
889
+ print(json.dumps(client_from_config().undeploy(args.run_id), indent=2))
890
+ return 0
891
+
892
+
893
+ def cmd_deployments(args) -> int:
894
+ rows = client_from_config().deployments()
895
+ if not rows:
896
+ print("no active deployments")
897
+ return 0
898
+ print(f"{'RUN_ID':<32} {'MODE':<10} {'GPU':<9} {'$/DAY':>7} ENDPOINT")
899
+ for r in rows:
900
+ d = r.get("deployment") or {}
901
+ print(
902
+ f"{r['run_id']:<32} {d.get('mode', '?'):<10} {d.get('gpu', '?'):<9} "
903
+ f"{d.get('est_idle_cost_usd_per_day', 0):>7} {d.get('endpoint_name', '')}"
904
+ )
905
+ return 0
906
+
907
+
908
+ def cmd_chat(args) -> int:
909
+ resp = client_from_config().chat(
910
+ args.run_id,
911
+ messages=[{"role": "user", "content": args.message}],
912
+ temperature=args.temperature,
913
+ max_tokens=args.max_tokens,
914
+ )
915
+ print(resp["choices"][0]["message"]["content"])
916
+ return 0
917
+
918
+
919
+ if __name__ == "__main__":
920
+ sys.exit(main())
code/autoslm/client/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP client for the managed AutoSLM control plane (used by the CLI and MCP bridge)."""
2
+
3
+ from .config import load_credentials, save_credentials
4
+ from .http import ApiClient, ApiError, ClientError, client_from_config, verify_freesolo_key
5
+
6
+ __all__ = [
7
+ "ApiClient",
8
+ "ApiError",
9
+ "ClientError",
10
+ "client_from_config",
11
+ "load_credentials",
12
+ "save_credentials",
13
+ "verify_freesolo_key",
14
+ ]
code/autoslm/client/config.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Client-side credential storage: the AutoSLM API key + control-plane URL.
2
+
3
+ Stored in ``~/.autoslm/config.json`` (dir 0700, file 0600 — it holds a secret).
4
+ Environment variables take precedence so CI/agents can inject credentials without
5
+ touching the file: ``FREESOLO_API_KEY`` for the key, ``AUTOSLM_API_URL`` for the URL.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+
15
+ DEFAULT_API_URL = "https://flash.freesolo.co"
16
+
17
+ CONFIG_DIR = Path.home() / ".autoslm"
18
+ CONFIG_PATH = CONFIG_DIR / "config.json"
19
+
20
+
21
+ def _read_config() -> dict:
22
+ try:
23
+ return json.loads(CONFIG_PATH.read_text())
24
+ except (OSError, ValueError):
25
+ return {}
26
+
27
+
28
+ def load_credentials() -> tuple[str, str | None]:
29
+ """Resolve (api_url, api_key); the key is None when the user hasn't logged in."""
30
+ cfg = _read_config()
31
+ api_url = os.environ.get("AUTOSLM_API_URL") or cfg.get("api_url") or DEFAULT_API_URL
32
+ api_key = os.environ.get("FREESOLO_API_KEY") or cfg.get("api_key")
33
+ return api_url.rstrip("/"), api_key
34
+
35
+
36
+ def save_credentials(api_key: str, api_url: str | None = None) -> Path:
37
+ """Persist the key (and optionally a non-default URL) with private permissions."""
38
+ cfg = _read_config()
39
+ cfg["api_key"] = api_key
40
+ if api_url:
41
+ # Record the plane actually authenticated against. When it's the default, drop any
42
+ # stored url instead of pinning it — this also clears a stale custom url from a
43
+ # previous custom AUTOSLM_API_URL login so later commands don't keep hitting the old host.
44
+ if api_url.rstrip("/") == DEFAULT_API_URL.rstrip("/"):
45
+ cfg.pop("api_url", None)
46
+ else:
47
+ cfg["api_url"] = api_url.rstrip("/")
48
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
49
+ with contextlib.suppress(OSError):
50
+ os.chmod(CONFIG_DIR, 0o700)
51
+ # Create/truncate with 0600 from the start so the key is never briefly world-readable.
52
+ # O_NOFOLLOW (where available): refuse to follow a symlink planted at CONFIG_PATH, so
53
+ # saving the key can't be redirected to clobber an arbitrary file.
54
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0)
55
+ fd = os.open(CONFIG_PATH, flags, 0o600)
56
+ with os.fdopen(fd, "w") as f:
57
+ json.dump(cfg, f, indent=2, sort_keys=True)
58
+ with contextlib.suppress(OSError):
59
+ os.chmod(CONFIG_PATH, 0o600)
60
+ return CONFIG_PATH
code/autoslm/client/http.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stdlib HTTP client for the AutoSLM control plane (no extra dependencies).
2
+
3
+ Every CLI/MCP operation maps to one method here. Server errors (FastAPI's
4
+ ``{"detail": ...}``) surface as ``ApiError`` with the server's message; connection
5
+ problems surface as ``ClientError`` with an actionable hint.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import urllib.error
13
+ import urllib.request
14
+ from typing import Any
15
+
16
+ from .config import load_credentials
17
+
18
+
19
+ class ClientError(RuntimeError):
20
+ """Expected client-side errors (no key, unreachable server) — printed cleanly."""
21
+
22
+
23
+ class ApiError(ClientError):
24
+ def __init__(self, status: int, message: str):
25
+ super().__init__(message)
26
+ self.status = status
27
+
28
+
29
+ # Login is handled by the freesolo backend (not the autoslm control plane): `slm login`
30
+ # verifies the user's freesolo API key here. The same key authenticates the autoslm
31
+ # control plane, which accepts freesolo-issued keys.
32
+ DEFAULT_FREESOLO_BASE_URL = "https://api.freesolo.co"
33
+ FREESOLO_AUTH_VERIFY_PATH = "/api/auth/verify"
34
+
35
+
36
+ def freesolo_base_url(override: str | None = None) -> str:
37
+ return (override or os.environ.get("FREESOLO_BASE_URL") or DEFAULT_FREESOLO_BASE_URL).rstrip(
38
+ "/"
39
+ )
40
+
41
+
42
+ def _detail_from_http_error(exc: urllib.error.HTTPError) -> str:
43
+ """Extract the server's error message from an HTTPError body (FastAPI ``detail``)."""
44
+ body = exc.read()
45
+ try:
46
+ detail = json.loads(body).get("detail") or body.decode()
47
+ except (ValueError, AttributeError):
48
+ detail = body.decode(errors="replace") if body else str(exc)
49
+ return str(detail)
50
+
51
+
52
+ def verify_freesolo_key(api_key: str, base_url: str | None = None) -> None:
53
+ """Verify a freesolo API key against the freesolo backend's ``/api/auth/verify``.
54
+
55
+ Raises :class:`ClientError`/:class:`ApiError` if the key is rejected or the backend is
56
+ unreachable; returns ``None`` on success. Keys are issued from the freesolo dashboard.
57
+ """
58
+ base = freesolo_base_url(base_url)
59
+ url = f"{base}{FREESOLO_AUTH_VERIFY_PATH}"
60
+ req = urllib.request.Request(
61
+ url,
62
+ method="GET",
63
+ headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
64
+ )
65
+ try:
66
+ with urllib.request.urlopen(req, timeout=30) as resp:
67
+ resp.read()
68
+ except urllib.error.HTTPError as exc:
69
+ if exc.code in (401, 403):
70
+ raise ClientError(
71
+ "freesolo rejected this API key — create or copy a valid key from your "
72
+ "freesolo dashboard and pass it with `slm login --api-key` (or FREESOLO_API_KEY)"
73
+ ) from exc
74
+ raise ApiError(exc.code, _detail_from_http_error(exc)) from exc
75
+ except urllib.error.URLError as exc:
76
+ raise ClientError(
77
+ f"cannot reach the freesolo backend at {base} ({exc.reason}); "
78
+ "check your network connection and FREESOLO_BASE_URL"
79
+ ) from exc
80
+
81
+
82
+ class ApiClient:
83
+ def __init__(self, api_url: str, api_key: str | None = None, timeout: float = 60.0):
84
+ self.api_url = api_url.rstrip("/")
85
+ self.api_key = api_key
86
+ self.timeout = timeout
87
+
88
+ def _request(
89
+ self,
90
+ method: str,
91
+ path: str,
92
+ body: dict | None = None,
93
+ timeout: float | None = None,
94
+ ) -> Any:
95
+ headers = {"Content-Type": "application/json"}
96
+ if self.api_key:
97
+ headers["Authorization"] = f"Bearer {self.api_key}"
98
+ req = urllib.request.Request(
99
+ f"{self.api_url}{path}",
100
+ method=method,
101
+ data=json.dumps(body).encode() if body is not None else None,
102
+ headers=headers,
103
+ )
104
+ try:
105
+ with urllib.request.urlopen(req, timeout=timeout or self.timeout) as resp:
106
+ raw = resp.read()
107
+ return json.loads(raw) if raw else {}
108
+ except urllib.error.HTTPError as exc:
109
+ raise ApiError(exc.code, _detail_from_http_error(exc)) from exc
110
+ except urllib.error.URLError as exc:
111
+ raise ClientError(
112
+ f"cannot reach the AutoSLM service at {self.api_url} ({exc.reason}); "
113
+ "check your network connection and AUTOSLM_API_URL"
114
+ ) from exc
115
+
116
+ # -- identity ----------------------------------------------------------------------
117
+ def me(self) -> dict:
118
+ return self._request("GET", "/v1/me")
119
+
120
+ def health(self) -> dict:
121
+ return self._request("GET", "/v1/health", timeout=10.0)
122
+
123
+ # -- runs --------------------------------------------------------------------------
124
+ def create_run(self, spec: dict) -> dict:
125
+ return self._request("POST", "/v1/runs", body={"spec": spec})
126
+
127
+ def list_runs(self) -> list[dict]:
128
+ return self._request("GET", "/v1/runs")["runs"]
129
+
130
+ def get_run(self, run_id: str) -> dict:
131
+ return self._request("GET", f"/v1/runs/{run_id}")
132
+
133
+ def get_logs(self, run_id: str, offset: int = 0) -> dict:
134
+ return self._request("GET", f"/v1/runs/{run_id}/logs?offset={int(offset)}")
135
+
136
+ def cancel_run(self, run_id: str) -> dict:
137
+ return self._request("POST", f"/v1/runs/{run_id}/cancel")
138
+
139
+ # -- serving -----------------------------------------------------------------------
140
+ def deploy(
141
+ self,
142
+ run_id: str,
143
+ mode: str = "dev",
144
+ idle_timeout_s: int = 300,
145
+ dry_run: bool = False,
146
+ ) -> dict:
147
+ # always-on blocks on the server until the worker has downloaded the
148
+ # model/adapter and vLLM is healthy (the no-cold-start guarantee), which can
149
+ # take many minutes — use the serve-scale timeout, not the default 60s.
150
+ deploy_timeout = 30 * 60 if (mode == "always-on" and not dry_run) else None
151
+ return self._request(
152
+ "POST",
153
+ f"/v1/runs/{run_id}/deploy",
154
+ body={"mode": mode, "idle_timeout_s": idle_timeout_s, "dry_run": dry_run},
155
+ timeout=deploy_timeout,
156
+ )
157
+
158
+ def undeploy(self, run_id: str) -> dict:
159
+ return self._request("DELETE", f"/v1/runs/{run_id}/deploy")
160
+
161
+ def deployments(self) -> list[dict]:
162
+ return self._request("GET", "/v1/deployments")["deployments"]
163
+
164
+ def chat(
165
+ self,
166
+ run_id: str,
167
+ messages: list[dict],
168
+ temperature: float = 0.0,
169
+ max_tokens: int = 512,
170
+ ) -> dict:
171
+ # Cold starts in dev mode can take minutes; give inference a generous timeout.
172
+ return self._request(
173
+ "POST",
174
+ f"/v1/runs/{run_id}/chat",
175
+ body={"messages": messages, "temperature": temperature, "max_tokens": max_tokens},
176
+ timeout=30 * 60,
177
+ )
178
+
179
+
180
+ def client_from_config(require_key: bool = True) -> ApiClient:
181
+ """Build a client from the stored credentials; fail with a clear hint when logged out."""
182
+ api_url, api_key = load_credentials()
183
+ if require_key and not api_key:
184
+ raise ClientError(
185
+ "not logged in — run `slm login` with your freesolo API key (or set FREESOLO_API_KEY)"
186
+ )
187
+ return ApiClient(api_url, api_key)
code/autoslm/client/specs.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Turn a locally validated JobSpec into the payload sent to the control plane.
2
+
3
+ The one piece of client-local state a run needs is the pip requirements for installed
4
+ verifiers / Prime Hub environments (recorded in ``~/.autoslm/envs.json`` by
5
+ ``slm env install``). The server has no access to that manifest, so the client resolves
6
+ it here and ships it inside the spec (``environment.pip``); a value already present in
7
+ the config (the documented escape hatch) wins.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from autoslm.spec import JobSpec
13
+
14
+
15
+ def spec_payload(spec: JobSpec) -> dict:
16
+ out = spec.to_dict()
17
+ if not spec.environment.pip:
18
+ from autoslm.envs.registry import worker_pip_for_env
19
+
20
+ pip = worker_pip_for_env(spec.environment.id)
21
+ if pip:
22
+ out["environment"]["pip"] = pip
23
+ return out
code/autoslm/engine/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Substrate-neutral fine-tuning internals for the AutoSLM package.
2
+
3
+ This subpackage holds the shared recipe, data loaders, graders, run accounting,
4
+ and the on-GPU worker entrypoint. It has no dependency on any compute backend; the
5
+ The RunPod provider in ``autoslm.providers.runpod`` invokes ``autoslm.engine.worker`` on the
6
+ provisioned GPU.
7
+ """
code/autoslm/engine/accounting.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cost accounting + the standard run-metrics record for AutoSLM runs.
2
+
3
+ GPU cost = gpu_hours * hourly_rate (per-second billing on the selected provider —
4
+ RunPod or Vast.ai; artifacts go via HF).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from dataclasses import asdict, dataclass, field
11
+
12
+
13
+ @dataclass
14
+ class RunMetrics:
15
+ """Standard metrics record written per phase/seed."""
16
+
17
+ arm: str = "runpod" # compute substrate
18
+ phase: str = "" # "sft" | "rl"
19
+ seed: int = 0
20
+ model_id: str = ""
21
+ # Speed
22
+ wall_seconds: float = 0.0
23
+ setup_seconds: float = 0.0 # cold start / provisioning + model load
24
+ train_throughput_toks_per_s: float = 0.0
25
+ # Token accounting
26
+ train_tokens: int = 0
27
+ generated_tokens: int = 0 # RL: total sampled completion tokens
28
+ # Misc / friction. cost_usd is computed/stamped downstream by the runner from the
29
+ # provider's $/hr (see runner._persist_metrics), not by the worker.
30
+ notes: dict = field(default_factory=dict)
31
+
32
+ def to_json(self) -> str:
33
+ return json.dumps(asdict(self), indent=2)
34
+
35
+ def save(self, path: str):
36
+ with open(path, "w") as f:
37
+ f.write(self.to_json())
code/autoslm/engine/multiturn_rollout.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Multi-turn / tool GRPO rollout for TRL's experimental ``rollout_func`` (colocate vLLM).
2
+
3
+ TRL's ``GRPOTrainer`` generates a single assistant turn per prompt, which cannot drive a
4
+ verifiers ``MultiTurnEnv`` / ``ToolEnv`` turn loop (model turn -> env reply -> ...). This
5
+ module supplies a ``rollout_func`` that:
6
+
7
+ * drives the env's turn loop via the adapter helpers (``new_rollout_state`` /
8
+ ``record_model_turn`` / ``env_reply`` / ``rollout_done``), so the *env* owns tool
9
+ execution, ``StatefulToolEnv`` state threading, and any simulated-user turns;
10
+ * returns the FULL interleaved token sequence as ``completion_ids`` together with an
11
+ ``env_mask`` that marks model-generated tokens (``1``, trained) vs tool/env tokens
12
+ (``0``, masked out of the loss). ``env_mask`` is TRL's documented mechanism for
13
+ multi-turn credit assignment (it is treated internally as the tool mask), so only the
14
+ policy's own tokens get advantage while the env tokens still provide context for the
15
+ forward pass;
16
+ * scores each rollout with the env's weighted rubric (``reward_from_messages``) and returns
17
+ it as an extra field consumed by a pass-through ``reward_func``.
18
+
19
+ Token alignment assumes a **prefix-preserving** chat template: appending a message must not
20
+ retokenize earlier turns (the same assumption TRL's native tool loop documents; auto-patched
21
+ for Qwen3 / DeepSeek-V3). The env segment between two model turns is taken as the suffix of a
22
+ full re-render; if the prefix invariant is violated the rollout raises (fails loudly) rather
23
+ than mis-masking model vs env tokens and silently mistraining.
24
+
25
+ The core (:func:`rollout_one`) is pure Python and takes injected ``render``/``generate``
26
+ callables so it can be unit-tested without a GPU/tokenizer; :func:`build_rollout_func` wires
27
+ the real tokenizer + the colocate vLLM engine into it at runtime.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import json
33
+ from collections.abc import Callable
34
+ from typing import TypedDict
35
+
36
+
37
+ class RolloutResult(TypedDict):
38
+ """Token-aligned fields returned per rollout for TRL's ``rollout_func``."""
39
+
40
+ prompt_ids: list[int]
41
+ completion_ids: list[int]
42
+ logprobs: list[float]
43
+ env_mask: list[int]
44
+ reward: float
45
+
46
+
47
+ # Field names shared between a single RolloutResult and the batched dict-of-lists that
48
+ # build_rollout_func returns. Kept as a plain tuple (not RolloutResult.__annotations__) so
49
+ # the batch accumulator's key source isn't a single-rollout type whose value types (float,
50
+ # list[int], ...) deliberately differ from the accumulator's list-of-those.
51
+ _ROLLOUT_FIELDS: tuple[str, ...] = (
52
+ "prompt_ids",
53
+ "completion_ids",
54
+ "logprobs",
55
+ "env_mask",
56
+ "reward",
57
+ )
58
+
59
+
60
+ def _prompt_key(prompt) -> str:
61
+ """Stable key for mapping a dataset ``prompt`` value back to its example row."""
62
+ try:
63
+ return json.dumps(prompt, sort_keys=True, default=str)
64
+ except (TypeError, ValueError):
65
+ return str(prompt)
66
+
67
+
68
+ def build_examples_index(rows: list[dict], prompt_of: Callable[[dict], object]) -> dict:
69
+ """Map each row's rendered ``prompt`` value to the example row (for reward/answer lookup).
70
+
71
+ Collisions (two rows producing the same prompt) keep the last row and are reported by the
72
+ caller via :func:`index_collisions`; duplicates are rare in training data and only affect
73
+ which ``answer``/``info`` a shared prompt scores against.
74
+ """
75
+ return {_prompt_key(prompt_of(r)): r for r in rows}
76
+
77
+
78
+ def index_collisions(rows: list[dict], prompt_of: Callable[[dict], object]) -> int:
79
+ """Number of rows dropped by prompt-key collisions in :func:`build_examples_index`."""
80
+ return len(rows) - len({_prompt_key(prompt_of(r)) for r in rows})
81
+
82
+
83
+ def rollout_one(
84
+ *,
85
+ example: dict,
86
+ active_env,
87
+ render: Callable[[list, bool], list[int]],
88
+ generate: Callable[[list, int], tuple[list[int], list[float], str]],
89
+ max_turns: int,
90
+ per_turn_max_tokens: int,
91
+ engine_max_len: int | None = None,
92
+ on_warn: Callable[[str], None] | None = None,
93
+ ) -> RolloutResult:
94
+ """Run one multi-turn/tool rollout and return TRL ``rollout_func`` fields for it.
95
+
96
+ Args:
97
+ example: the dataset row (carries ``answer``/``info`` for the rubric).
98
+ active_env: the ``VerifiersEnvironment`` adapter (drives the turn loop + scoring).
99
+ render: ``render(messages, add_generation_prompt) -> token_ids`` (chat template).
100
+ generate: ``generate(prefix_token_ids, max_tokens) -> (token_ids, token_logprobs,
101
+ text)`` for one sampled assistant turn (model tokens + sampling logprobs + text);
102
+ ``max_tokens`` bounds that turn so it can't overflow the engine context.
103
+ max_turns: hard cap on model turns (defense against a non-terminating env).
104
+
105
+ Returns a dict with ``prompt_ids``, ``completion_ids``, ``logprobs``, ``env_mask`` (all
106
+ token-aligned) and the scalar ``reward`` for this rollout.
107
+ """
108
+ state = active_env.new_rollout_state(example)
109
+ messages = [dict(m) for m in state["prompt"]]
110
+ prompt_ids = render(messages, True)
111
+ cur_ids = list(prompt_ids) # invariant: cur_ids == prompt_ids + completion_ids so far
112
+ # Per-rollout completion cap so prompt + accumulated completion never exceeds the colocate
113
+ # engine's context (which would overflow the next generate()); leave a small margin.
114
+ token_budget = (engine_max_len - len(prompt_ids) - 8) if engine_max_len else None
115
+ completion_ids: list[int] = []
116
+ logprobs: list[float] = []
117
+ env_mask: list[int] = []
118
+
119
+ turns = 0
120
+ while True:
121
+ # Bound THIS turn's generation by the remaining engine headroom so even a single
122
+ # generate() can't push prompt+completion past the context (the cap below stops the
123
+ # loop AFTER a turn; this stops the turn itself from overflowing).
124
+ max_new = per_turn_max_tokens
125
+ if token_budget is not None:
126
+ remaining = token_budget - len(completion_ids)
127
+ if remaining <= 0:
128
+ break
129
+ max_new = min(max_new, remaining)
130
+ asst_ids, asst_lp, text = generate(cur_ids, max_new)
131
+ completion_ids.extend(asst_ids)
132
+ logprobs.extend(asst_lp)
133
+ env_mask.extend([1] * len(asst_ids))
134
+ cur_ids.extend(asst_ids)
135
+ active_env.record_model_turn(state, text)
136
+ messages.append({"role": "assistant", "content": text})
137
+ turns += 1
138
+
139
+ if token_budget is not None and len(completion_ids) >= token_budget:
140
+ break
141
+ if turns >= max_turns or active_env.rollout_done(state, max_turns):
142
+ break
143
+ env_msgs = active_env.env_reply(messages, state)
144
+ if not env_msgs:
145
+ break
146
+ messages.extend(env_msgs)
147
+
148
+ # Env-segment tokens = the suffix added by re-rendering the conversation (with the next
149
+ # generation prompt) beyond what we already have. Masked (0) — they are not the
150
+ # policy's tokens — but kept in completion_ids so the next turn conditions on them. This
151
+ # REQUIRES a prefix-preserving template (appending a message must not retokenize earlier
152
+ # turns); otherwise the model/env token boundary is wrong and the loss mask is garbage —
153
+ # so fail loudly rather than silently mis-train.
154
+ new_ids = render(messages, True)
155
+ if new_ids[: len(cur_ids)] != cur_ids:
156
+ msg = (
157
+ "multi-turn rollout requires a prefix-preserving chat template (appending a "
158
+ "message must not retokenize earlier turns); this model's template is not. Use "
159
+ "a single-turn/tool env, or a model whose template is prefix-preserving."
160
+ )
161
+ if on_warn:
162
+ on_warn(msg)
163
+ raise ValueError(msg)
164
+ env_seg = new_ids[len(cur_ids) :]
165
+ completion_ids.extend(env_seg)
166
+ logprobs.extend([0.0] * len(env_seg))
167
+ env_mask.extend([0] * len(env_seg))
168
+ cur_ids = list(new_ids)
169
+
170
+ # Score with the ACTUAL rollout state (not a fresh one) so reward funcs see the tool/env
171
+ # state the rollout accumulated. state["completion"] holds the full transcript.
172
+ reward = active_env.reward("", example, state)
173
+ return {
174
+ "prompt_ids": prompt_ids,
175
+ "completion_ids": completion_ids,
176
+ "logprobs": logprobs,
177
+ "env_mask": env_mask,
178
+ "reward": float(reward),
179
+ }
180
+
181
+
182
+ def build_rollout_func(
183
+ *,
184
+ active_env,
185
+ tok,
186
+ examples_by_key: dict,
187
+ max_completion: int,
188
+ max_turns: int,
189
+ temperature: float,
190
+ top_p: float,
191
+ stop: list[str] | None,
192
+ thinking: bool,
193
+ engine_max_len: int | None = None,
194
+ num_generations_attr: str = "num_generations",
195
+ ):
196
+ """Return a TRL ``rollout_func`` closure that drives ``active_env`` on the colocate engine.
197
+
198
+ The closure reaches the in-process vLLM engine through ``trainer.vllm_generation.llm`` and
199
+ samples each assistant turn with per-token logprobs; ``num_generations`` rollouts are
200
+ produced per prompt (TRL requires the flattened per-prompt grouping).
201
+ """
202
+ from vllm import SamplingParams # gpu-only; imported lazily so the module loads on CPU
203
+
204
+ def render(messages: list, add_generation_prompt: bool) -> list[int]:
205
+ # Render to text first, then tokenize — apply_chat_template(tokenize=True) return
206
+ # shape varies by tokenizer; tok(text).input_ids is reliably a flat list[int]
207
+ # (matches the single-turn render_prompt path). add_special_tokens=False because the
208
+ # template already emits the special tokens.
209
+ text = tok.apply_chat_template(
210
+ messages,
211
+ add_generation_prompt=add_generation_prompt,
212
+ tokenize=False,
213
+ enable_thinking=thinking,
214
+ )
215
+ return [int(t) for t in tok(text, add_special_tokens=False).input_ids]
216
+
217
+ def rollout_func(prompts, trainer):
218
+ engine = trainer.vllm_generation.llm
219
+ num_gen = int(getattr(trainer, num_generations_attr, 1) or 1)
220
+
221
+ def generate(prefix_ids: list[int], max_tokens: int):
222
+ sp = SamplingParams(
223
+ max_tokens=max(1, int(max_tokens)),
224
+ temperature=temperature,
225
+ top_p=top_p,
226
+ logprobs=1, # include the sampled token's logprob at each position
227
+ stop=list(stop) if stop else None,
228
+ )
229
+ # vLLM's LLM.generate takes prompts (TokensPrompt-style dicts), not a
230
+ # `prompt_token_ids` kwarg — pass pre-tokenized ids as {"prompt_token_ids": ...}.
231
+ out = engine.generate(
232
+ [{"prompt_token_ids": list(prefix_ids)}],
233
+ sampling_params=sp,
234
+ use_tqdm=False,
235
+ )
236
+ comp = out[0].outputs[0]
237
+ token_ids = list(comp.token_ids)
238
+ # comp.logprobs is a list (per position) of {token_id: Logprob}; pull the sampled
239
+ # token's logprob at each position.
240
+ lps: list[float] = []
241
+ for pos, tid in enumerate(token_ids):
242
+ entry = (comp.logprobs or [])[pos] if comp.logprobs else None
243
+ lp = entry.get(tid) if entry else None
244
+ lps.append(float(getattr(lp, "logprob", 0.0)) if lp is not None else 0.0)
245
+ return token_ids, lps, comp.text
246
+
247
+ # One accumulator list per rollout field (batched dict-of-lists across all rollouts).
248
+ out: dict[str, list] = {k: [] for k in _ROLLOUT_FIELDS}
249
+ for prompt in prompts:
250
+ example = examples_by_key.get(_prompt_key(prompt), {"prompt": prompt})
251
+ for _ in range(num_gen):
252
+ r = rollout_one(
253
+ example=example,
254
+ active_env=active_env,
255
+ render=render,
256
+ generate=generate,
257
+ max_turns=max_turns,
258
+ per_turn_max_tokens=max_completion,
259
+ engine_max_len=engine_max_len,
260
+ on_warn=print,
261
+ )
262
+ for k in out:
263
+ out[k].append(r[k])
264
+ return out
265
+
266
+ return rollout_func
code/autoslm/engine/recipe.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frozen, shared AutoSLM fine-tuning recipe.
2
+
3
+ Single source of truth for the default fine-tuning hyperparameters: base model,
4
+ tokenizer, data, LoRA config, optimization, token budget, and decoding.
5
+ Per-run TOML configs (parsed into a ``JobSpec``) override the relevant fields.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from dataclasses import dataclass, field
12
+
13
+ # ----------------------------------------------------------------------------
14
+ # Model identity
15
+ # ----------------------------------------------------------------------------
16
+ # Recipe fallback base model. Model selection precedence on the worker is
17
+ # JobSpec.model > env BENCH_HF_MODEL > this recipe default; worker.py resolves
18
+ # JOB_SPEC.model first and only falls back to RECIPE.hf_model_id. The RunPod launcher
19
+ # sets BENCH_HF_MODEL from the spec; Vast carries the model via the full JobSpec
20
+ # (JOB_SPEC.model), which the worker resolves before this fallback. This literal is the
21
+ # last-resort default when neither is present.
22
+ # Keep it in sync with catalog.DEFAULT_MODEL (a proven dense text-only instruction model
23
+ # that loads on the current worker stack: transformers 5.x / TRL 1.x / vLLM 0.19.x; the
24
+ # natively-multimodal Qwen3.5/3.6 checkpoints are also catalog'd, trained/served text-only).
25
+ HF_MODEL_ID = os.environ.get("BENCH_HF_MODEL", "Qwen/Qwen3.5-4B") # catalog DEFAULT_MODEL
26
+
27
+
28
+ # ----------------------------------------------------------------------------
29
+ # LoRA (rank is the main user-controllable knob)
30
+ # ----------------------------------------------------------------------------
31
+ @dataclass(frozen=True)
32
+ class LoRAConfig:
33
+ rank: int = 32
34
+ alpha: int = 64
35
+ dropout: float = 0.0
36
+ # The worker adapts all linear projections, set via the LORA_TARGETS env var
37
+ # (default "all-linear" — see engine.worker); `rank`/`alpha` are the main
38
+ # user-controllable knobs here.
39
+
40
+
41
+ # ----------------------------------------------------------------------------
42
+ # SFT (Phase 1)
43
+ # ----------------------------------------------------------------------------
44
+ @dataclass(frozen=True)
45
+ class SFTConfig:
46
+ max_seq_len: int = 1024
47
+ # Thinking-mode sequence cap: <think> traces in targets need headroom. A deliberate
48
+ # consumer-GPU compromise (SFT cost/VRAM scales with sequence length).
49
+ max_seq_len_thinking: int = 2048
50
+ learning_rate: float = 1e-4
51
+ warmup_frac: float = 0.03
52
+ # Effective batch = per_device_batch * grad_accum (Arm A) / batch of datums (Arm B)
53
+ effective_batch: int = 32
54
+ num_epochs: int = 2
55
+
56
+
57
+ # ----------------------------------------------------------------------------
58
+ # RL / GRPO (Phase 2)
59
+ # ----------------------------------------------------------------------------
60
+ @dataclass(frozen=True)
61
+ class RLConfig:
62
+ learning_rate: float = 1e-5
63
+ # Default engine prompt budget. 512 was too small for real envs with non-trivial system
64
+ # prompts (e.g. a schema/instructions block + the user query), which made every prompt
65
+ # overflow before training started. 2048 fits typical instruction prompts; the run's
66
+ # [train].max_length sets the engine length explicitly when it needs more/less.
67
+ max_prompt_len: int = 2048
68
+ max_completion_len: int = 320
69
+ # Thinking-mode completion budget: <think> blocks consume most of it (phase 0
70
+ # showed 320 is hopeless — every completion hit the cap). 1536 is a consumer-GPU
71
+ # compromise (KV cache + rollout cost scale linearly with completion length, ~5x
72
+ # tokens/step vs non-thinking); the run's [train].max_tokens overrides it explicitly.
73
+ max_completion_len_thinking: int = 1536
74
+ prompts_per_step: int = 64
75
+ group_size: int = 8 # G completions per prompt
76
+ num_steps: int = 150 # overridable per-run via the TOML `train.steps`
77
+ sampling_temperature: float = 1.0 # on-policy sampling for rollouts
78
+ sampling_top_p: float = 1.0
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class Recipe:
83
+ """The complete shared recipe."""
84
+
85
+ hf_model_id: str = HF_MODEL_ID
86
+ lora: LoRAConfig = field(default_factory=LoRAConfig)
87
+ sft: SFTConfig = field(default_factory=SFTConfig)
88
+ rl: RLConfig = field(default_factory=RLConfig)
89
+
90
+
91
+ RECIPE = Recipe()
code/autoslm/engine/rope.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Custom fused Triton RoPE kernel for Qwen3.5/3.6 full-attention layers.
2
+
3
+ Liger ships a RoPE kernel but its qwen3_5 patcher *refuses* to apply it
4
+ (``raise NotImplementedError`` "due to hybrid attention: Gated DeltaNet + Gated
5
+ Attention") — the GDN layers don't call ``apply_rotary_pos_emb`` at all, only the
6
+ full-attention layers do, and Liger's blanket patch couldn't target just those.
7
+
8
+ This module sidesteps that by monkeypatching the module-level
9
+ ``transformers.models.qwen3_5.modeling_qwen3_5.apply_rotary_pos_emb`` function
10
+ itself — which ONLY the ``Qwen3_5Attention`` layers call — so the GDN path is
11
+ untouched. The HF eager version is heavily unfused: ``rotate_half`` allocates a
12
+ full ``cat([-x2, x1])`` tensor and the rotation is ~8 separate elementwise
13
+ kernels + intermediates per attention layer. We fuse the whole rotation into one
14
+ Triton kernel (forward + backward), eliminating those launches/allocations.
15
+
16
+ Correctness is gated by a live-GPU numeric self-test (loss + grad vs the eager
17
+ reference within tolerance); ANY import/compile/self-test failure leaves the
18
+ eager path untouched — correctness over speed. Opt-in via AUTOSLM_ROPE_KERNEL=1.
19
+
20
+ Semantics matched exactly to modeling_qwen3_5.apply_rotary_pos_emb:
21
+ rotate_half(x) = cat(-x[d/2:], x[:d/2]) # GPT-NeoX / non-interleaved
22
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin); q_pass kept as-is
23
+ with rotary_dim = cos.shape[-1] possibly < head_dim (the tail is passed through),
24
+ cos/sin of shape [batch, seq, rotary_dim] (broadcast over heads).
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import os
30
+
31
+ # Populated by install_qwen35_rope/benchmark so the worker can fold the measured speedup
32
+ # into metrics.json's `notes` (RunPod doesn't persist worker stdout, but metrics.json is
33
+ # always uploaded). Empty {} means the kernel was not engaged this run.
34
+ RESULT: dict = {}
35
+
36
+
37
+ def _enabled() -> bool:
38
+ return os.environ.get("AUTOSLM_ROPE_KERNEL", "0").strip().lower() not in (
39
+ "0",
40
+ "false",
41
+ "no",
42
+ "off",
43
+ "none",
44
+ "",
45
+ )
46
+
47
+
48
+ def _build_kernels():
49
+ """Import torch/triton and define the fused RoPE forward+backward kernels + the
50
+ autograd Function. Returns ``apply_fn`` (HF-signature drop-in) or raises on any
51
+ import/compile problem (the caller treats a raise as "keep eager")."""
52
+ import torch
53
+ import triton
54
+ import triton.language as tl
55
+
56
+ @triton.jit
57
+ def _rope_fwd_kernel(
58
+ x_ptr, cos_ptr, sin_ptr, out_ptr,
59
+ H_T, T, head_dim, rotary_dim, half,
60
+ x_row_stride, cs_row_stride,
61
+ BLOCK: tl.constexpr,
62
+ ):
63
+ # one program == one [head_dim] vector for a single (batch, head, token)
64
+ pid = tl.program_id(0)
65
+ b = pid // H_T
66
+ t = pid % T
67
+ cs_row = b * T + t
68
+
69
+ offs = tl.arange(0, BLOCK)
70
+ mask_half = offs < half
71
+ # the two rotary halves of this row
72
+ x1 = tl.load(x_ptr + pid * x_row_stride + offs, mask=mask_half, other=0.0)
73
+ x2 = tl.load(x_ptr + pid * x_row_stride + half + offs, mask=mask_half, other=0.0)
74
+ cos1 = tl.load(cos_ptr + cs_row * cs_row_stride + offs, mask=mask_half, other=0.0)
75
+ sin1 = tl.load(sin_ptr + cs_row * cs_row_stride + offs, mask=mask_half, other=0.0)
76
+ cos2 = tl.load(cos_ptr + cs_row * cs_row_stride + half + offs, mask=mask_half, other=0.0)
77
+ sin2 = tl.load(sin_ptr + cs_row * cs_row_stride + half + offs, mask=mask_half, other=0.0)
78
+ # rotate_half: out1 = x1*cos1 - x2*sin1 ; out2 = x2*cos2 + x1*sin2
79
+ out1 = x1 * cos1 - x2 * sin1
80
+ out2 = x2 * cos2 + x1 * sin2
81
+ tl.store(out_ptr + pid * x_row_stride + offs, out1, mask=mask_half)
82
+ tl.store(out_ptr + pid * x_row_stride + half + offs, out2, mask=mask_half)
83
+ # pass-through tail [rotary_dim : head_dim]
84
+ if head_dim > rotary_dim:
85
+ poffs = tl.arange(0, BLOCK)
86
+ pmask = poffs < (head_dim - rotary_dim)
87
+ xp = tl.load(x_ptr + pid * x_row_stride + rotary_dim + poffs, mask=pmask, other=0.0)
88
+ tl.store(out_ptr + pid * x_row_stride + rotary_dim + poffs, xp, mask=pmask)
89
+
90
+ @triton.jit
91
+ def _rope_bwd_kernel(
92
+ g_ptr, cos_ptr, sin_ptr, dx_ptr,
93
+ H_T, T, head_dim, rotary_dim, half,
94
+ g_row_stride, cs_row_stride,
95
+ BLOCK: tl.constexpr,
96
+ ):
97
+ pid = tl.program_id(0)
98
+ b = pid // H_T
99
+ t = pid % T
100
+ cs_row = b * T + t
101
+ offs = tl.arange(0, BLOCK)
102
+ mask_half = offs < half
103
+ g1 = tl.load(g_ptr + pid * g_row_stride + offs, mask=mask_half, other=0.0)
104
+ g2 = tl.load(g_ptr + pid * g_row_stride + half + offs, mask=mask_half, other=0.0)
105
+ cos1 = tl.load(cos_ptr + cs_row * cs_row_stride + offs, mask=mask_half, other=0.0)
106
+ sin1 = tl.load(sin_ptr + cs_row * cs_row_stride + offs, mask=mask_half, other=0.0)
107
+ cos2 = tl.load(cos_ptr + cs_row * cs_row_stride + half + offs, mask=mask_half, other=0.0)
108
+ sin2 = tl.load(sin_ptr + cs_row * cs_row_stride + half + offs, mask=mask_half, other=0.0)
109
+ # transpose of the forward (orthogonal rotation):
110
+ # dx1 = g1*cos1 + g2*sin2 ; dx2 = -g1*sin1 + g2*cos2
111
+ dx1 = g1 * cos1 + g2 * sin2
112
+ dx2 = -g1 * sin1 + g2 * cos2
113
+ tl.store(dx_ptr + pid * g_row_stride + offs, dx1, mask=mask_half)
114
+ tl.store(dx_ptr + pid * g_row_stride + half + offs, dx2, mask=mask_half)
115
+ if head_dim > rotary_dim:
116
+ poffs = tl.arange(0, BLOCK)
117
+ pmask = poffs < (head_dim - rotary_dim)
118
+ gp = tl.load(g_ptr + pid * g_row_stride + rotary_dim + poffs, mask=pmask, other=0.0)
119
+ tl.store(dx_ptr + pid * g_row_stride + rotary_dim + poffs, gp, mask=pmask)
120
+
121
+ def _next_pow2(n: int) -> int:
122
+ p = 1
123
+ while p < n:
124
+ p <<= 1
125
+ return max(p, 1)
126
+
127
+ def _rope_one(x, cos, sin, forward: bool):
128
+ # x: [B, H, T, D] (contiguous), cos/sin: [B, T, rotary_dim]
129
+ B, H, T, D = x.shape
130
+ rotary_dim = cos.shape[-1]
131
+ half = rotary_dim // 2
132
+ x = x.contiguous()
133
+ out = torch.empty_like(x)
134
+ xf = x.view(B * H * T, D)
135
+ of = out.view(B * H * T, D)
136
+ cosf = cos.contiguous().view(B * T, rotary_dim)
137
+ sinf = sin.contiguous().view(B * T, rotary_dim)
138
+ BLOCK = _next_pow2(max(half, D - rotary_dim, 1))
139
+ grid = (B * H * T,)
140
+ kern = _rope_fwd_kernel if forward else _rope_bwd_kernel
141
+ kern[grid](
142
+ xf, cosf, sinf, of,
143
+ H * T, T, D, rotary_dim, half,
144
+ xf.stride(0), cosf.stride(0),
145
+ BLOCK=BLOCK,
146
+ )
147
+ return out
148
+
149
+ class _RoPEFunction(torch.autograd.Function):
150
+ @staticmethod
151
+ def forward(ctx, q, k, cos, sin):
152
+ ctx.save_for_backward(cos, sin)
153
+ q_embed = _rope_one(q, cos, sin, forward=True)
154
+ k_embed = _rope_one(k, cos, sin, forward=True)
155
+ return q_embed, k_embed
156
+
157
+ @staticmethod
158
+ def backward(ctx, gq, gk):
159
+ cos, sin = ctx.saved_tensors
160
+ # autograd passes None for an unused output grad; return None for that input
161
+ # instead of calling .contiguous() on None (which would AttributeError).
162
+ dq = _rope_one(gq.contiguous(), cos, sin, forward=False) if gq is not None else None
163
+ dk = _rope_one(gk.contiguous(), cos, sin, forward=False) if gk is not None else None
164
+ return dq, dk, None, None
165
+
166
+ def apply_fn(q, k, cos, sin, unsqueeze_dim=1):
167
+ # cos/sin arrive as [B, T, rotary_dim]; HF unsqueezes to broadcast over heads.
168
+ # Our kernel broadcasts over heads internally, so use cos/sin as-is ([B,T,rd]).
169
+ # Fall back to eager for any shape we don't handle (interleaved/odd ranks) AND when
170
+ # cos/sin don't match q's batch/seq exactly: _rope_one indexes them as view(B*T, rd)
171
+ # from q's [B,H,T,D], so a broadcast layout (batch 1 vs q's B, or a seq mismatch) would
172
+ # mis-index angles or fail the view — eager's unsqueeze/broadcast handles those.
173
+ if (
174
+ q.dim() != 4
175
+ or cos.dim() != 3
176
+ or (cos.shape[-1] % 2) != 0
177
+ or cos.shape[0] != q.shape[0]
178
+ or cos.shape[1] != q.shape[2]
179
+ or sin.shape != cos.shape
180
+ ):
181
+ return _eager_apply(q, k, cos, sin, unsqueeze_dim)
182
+ return _RoPEFunction.apply(q, k, cos, sin)
183
+
184
+ return apply_fn
185
+
186
+
187
+ def _eager_apply(q, k, cos, sin, unsqueeze_dim=1):
188
+ """The exact HF reference (used as the self-test oracle and the shape fallback)."""
189
+ import torch
190
+
191
+ cos_u = cos.unsqueeze(unsqueeze_dim)
192
+ sin_u = sin.unsqueeze(unsqueeze_dim)
193
+ rd = cos_u.shape[-1]
194
+ q_rot, q_pass = q[..., :rd], q[..., rd:]
195
+ k_rot, k_pass = k[..., :rd], k[..., rd:]
196
+
197
+ def rh(x):
198
+ x1 = x[..., : x.shape[-1] // 2]
199
+ x2 = x[..., x.shape[-1] // 2 :]
200
+ return torch.cat((-x2, x1), dim=-1)
201
+
202
+ q_embed = torch.cat([(q_rot * cos_u) + (rh(q_rot) * sin_u), q_pass], dim=-1)
203
+ k_embed = torch.cat([(k_rot * cos_u) + (rh(k_rot) * sin_u), k_pass], dim=-1)
204
+ return q_embed, k_embed
205
+
206
+
207
+ def self_test(apply_fn, *, head_dim=128, rotary_dim=128, dtype=None) -> bool:
208
+ """Numeric parity of the fused kernel vs eager HF apply_rotary_pos_emb, on the
209
+ live GPU: forward q/k AND backward dq/dk. Returns True iff within tolerance."""
210
+ import torch
211
+
212
+ if not torch.cuda.is_available():
213
+ return False
214
+ dtype = dtype or torch.bfloat16
215
+ B, Hh, T = 2, 4, 64
216
+ dev = "cuda"
217
+ torch.manual_seed(0)
218
+ q = torch.randn(B, Hh, T, head_dim, device=dev, dtype=dtype, requires_grad=True)
219
+ k = torch.randn(B, Hh, T, head_dim, device=dev, dtype=dtype, requires_grad=True)
220
+ pos = torch.arange(T, device=dev)
221
+ inv = 1.0 / (10000 ** (torch.arange(0, rotary_dim // 2, device=dev).float() / (rotary_dim // 2)))
222
+ ang = pos[:, None].float() * inv[None, :]
223
+ emb = torch.cat([ang, ang], dim=-1) # [T, rotary_dim], duplicated halves (standard RoPE)
224
+ cos = emb.cos()[None].expand(B, T, rotary_dim).to(dtype).contiguous()
225
+ sin = emb.sin()[None].expand(B, T, rotary_dim).to(dtype).contiguous()
226
+
227
+ qe_ref, ke_ref = _eager_apply(q, k, cos, sin)
228
+ (qe_ref.float().square().mean() + ke_ref.float().square().mean()).backward()
229
+ dq_ref, dk_ref = q.grad.clone(), k.grad.clone()
230
+ q.grad = None
231
+ k.grad = None
232
+
233
+ qe, ke = apply_fn(q, k, cos, sin)
234
+ (qe.float().square().mean() + ke.float().square().mean()).backward()
235
+ dq, dk = q.grad.clone(), k.grad.clone()
236
+
237
+ def close(a, b, atol=2e-2, rtol=2e-2):
238
+ return torch.allclose(a.float(), b.float(), atol=atol, rtol=rtol)
239
+
240
+ ok = (
241
+ close(qe, qe_ref) and close(ke, ke_ref) and close(dq, dq_ref) and close(dk, dk_ref)
242
+ )
243
+ if not ok:
244
+ print(
245
+ "[rope] self-test FAILED "
246
+ f"(fwd_q={close(qe, qe_ref)} fwd_k={close(ke, ke_ref)} "
247
+ f"bwd_q={close(dq, dq_ref)} bwd_k={close(dk, dk_ref)}) -> keeping eager",
248
+ flush=True,
249
+ )
250
+ return ok
251
+
252
+
253
+ def benchmark(
254
+ apply_fn, *, head_dim=128, rotary_dim=128, n_heads=16, seqs=(1024, 2048, 4096, 8192), iters=50
255
+ ) -> None:
256
+ """Sweep eager-HF vs the fused kernel (forward+backward) across sequence lengths on the
257
+ live GPU. RoPE cost scales with seq, so this shows whether the fused win grows with scale.
258
+ Records the per-seq curve in RESULT['sweep'] and mirrors the seq=4096 point into the
259
+ top-level fields. Diagnostic only — never raises."""
260
+ import torch
261
+
262
+ try:
263
+ if not torch.cuda.is_available():
264
+ return
265
+ dev, dt, B = "cuda", torch.bfloat16, 1
266
+
267
+ def bench_one(seq):
268
+ pos = torch.arange(seq, device=dev)
269
+ inv = 1.0 / (
270
+ 10000 ** (torch.arange(0, rotary_dim // 2, device=dev).float() / (rotary_dim // 2))
271
+ )
272
+ ang = pos[:, None].float() * inv[None, :]
273
+ emb = torch.cat([ang, ang], dim=-1)
274
+ cos = emb.cos()[None].expand(B, seq, rotary_dim).to(dt).contiguous()
275
+ sin = emb.sin()[None].expand(B, seq, rotary_dim).to(dt).contiguous()
276
+
277
+ def run(fn):
278
+ q = torch.randn(B, n_heads, seq, head_dim, device=dev, dtype=dt, requires_grad=True)
279
+ k = torch.randn(B, n_heads, seq, head_dim, device=dev, dtype=dt, requires_grad=True)
280
+ qe, ke = fn(q, k, cos, sin)
281
+ (qe.float().square().mean() + ke.float().square().mean()).backward()
282
+
283
+ for _ in range(5): # warmup (Triton JIT + autotune)
284
+ run(_eager_apply)
285
+ run(apply_fn)
286
+ torch.cuda.synchronize()
287
+
288
+ def timed(fn):
289
+ s = torch.cuda.Event(enable_timing=True)
290
+ e = torch.cuda.Event(enable_timing=True)
291
+ torch.cuda.synchronize()
292
+ s.record()
293
+ for _ in range(iters):
294
+ run(fn)
295
+ e.record()
296
+ torch.cuda.synchronize()
297
+ return s.elapsed_time(e) / iters # ms/iter
298
+
299
+ te, tk = timed(_eager_apply), timed(apply_fn)
300
+ return {
301
+ "seq": seq,
302
+ "eager_ms": round(te, 4),
303
+ "kernel_ms": round(tk, 4),
304
+ "speedup": round(te / tk if tk > 0 else 0.0, 3),
305
+ }
306
+
307
+ sweep = []
308
+ RESULT["head_dim"] = head_dim
309
+ RESULT["heads"] = n_heads
310
+ for seq in seqs:
311
+ r = bench_one(seq)
312
+ sweep.append(r)
313
+ print(
314
+ f"[rope][bench] head_dim={head_dim} heads={n_heads} seq={seq} fwd+bwd: "
315
+ f"eager={r['eager_ms']:.3f}ms kernel={r['kernel_ms']:.3f}ms -> {r['speedup']:.2f}x",
316
+ flush=True,
317
+ )
318
+ # Publish after EACH seq so a later-length failure (e.g. 8192 OOM once the model is
319
+ # loaded) keeps the timings already computed for shorter sequences, rather than
320
+ # discarding the whole sweep and recording only bench_error.
321
+ RESULT["sweep"] = list(sweep)
322
+ # Mirror the seq closest to 4096 into the top-level fields (back-compat with run #1).
323
+ primary = min(sweep, key=lambda r: abs(r["seq"] - 4096))
324
+ RESULT.update({k: primary[k] for k in ("seq", "eager_ms", "kernel_ms", "speedup")})
325
+ except Exception as e:
326
+ RESULT["bench_error"] = f"{type(e).__name__}: {e}"
327
+ print(f"[rope][bench] skipped: {e}", flush=True)
328
+
329
+
330
+ def install_qwen35_rope(run_benchmark: bool = True) -> bool:
331
+ """Patch ``apply_rotary_pos_emb`` in the qwen3_5/qwen3_6 modeling modules with the
332
+ fused Triton kernel — IFF AUTOSLM_ROPE_KERNEL=1 and the live-GPU self-test passes.
333
+
334
+ Patches the module-level function only the full-attention layers call, so the GDN
335
+ layers are untouched. Never raises: any failure leaves the eager path in place.
336
+ Returns True iff the kernel was installed."""
337
+ if not _enabled():
338
+ return False
339
+ try:
340
+ apply_fn = _build_kernels()
341
+ except Exception as e:
342
+ print(f"[rope] kernel build failed ({type(e).__name__}: {e}); keeping eager", flush=True)
343
+ return False
344
+ # self_test runs a live-GPU parity check; a GPU OOM / Triton compile/launch error there must
345
+ # NOT abort the run (this function promises to keep the eager path on any failure).
346
+ try:
347
+ if not self_test(apply_fn):
348
+ return False
349
+ except Exception as e:
350
+ print(f"[rope] self-test errored ({type(e).__name__}: {e}); keeping eager", flush=True)
351
+ return False
352
+
353
+ patched = []
354
+ for mod_name in ("qwen3_5", "qwen3_6"):
355
+ try:
356
+ import importlib
357
+
358
+ mod = importlib.import_module(f"transformers.models.{mod_name}.modeling_{mod_name}")
359
+ except Exception:
360
+ continue
361
+ if hasattr(mod, "apply_rotary_pos_emb"):
362
+ mod.apply_rotary_pos_emb = apply_fn
363
+ patched.append(mod_name)
364
+ if not patched:
365
+ print("[rope] no qwen3_5/3_6 modeling module to patch; keeping eager", flush=True)
366
+ return False
367
+ RESULT.update({"installed": True, "self_test": "passed", "patched": patched})
368
+ print(f"[rope] fused Triton RoPE installed on {patched} (self-test passed)", flush=True)
369
+ if run_benchmark:
370
+ benchmark(apply_fn)
371
+ return True
code/autoslm/engine/vram.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Coarse VRAM-fit estimation for one-consumer-GPU LoRA jobs.
2
+
3
+ Used by the open-model policy (``model_policy = "allow"``) to sanity-check that an
4
+ unlisted HF model can plausibly run on the requested GPU before provisioning it.
5
+
6
+ These are deliberately coarse heuristics (documented ±20%): they exist to catch
7
+ *provably impossible* configurations (70B bf16 on a 24 GB card) and to warn on tight
8
+ fits — not to guarantee success. Calibrated against the measured catalog entries
9
+ (Qwen3-0.6B/4B/8B, Qwen3.5 dense).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import math
15
+ import os
16
+ import re
17
+ from dataclasses import dataclass
18
+
19
+
20
+ def _gpu_vram_table() -> dict[str, int]:
21
+ try:
22
+ from autoslm.providers.base import GPU_INFO
23
+
24
+ return {name: info.vram_gb for name, info in GPU_INFO.items()}
25
+ except Exception:
26
+ return {"RTX 4090": 24, "RTX 5090": 32}
27
+
28
+
29
+ GPU_VRAM_GB = _gpu_vram_table()
30
+
31
+ _BYTES_PER_PARAM = {
32
+ "bf16": 2.0,
33
+ "fp16": 2.0,
34
+ "4bit-qlora": 0.55, # NF4 weights + quantization constants
35
+ }
36
+
37
+ # Fixed overheads (GB): CUDA context + activations w/ gradient checkpointing +
38
+ # LoRA params/grads/Adam states (tiny at rank<=64) + fragmentation headroom.
39
+ _BASE_OVERHEAD_GB = 4.0
40
+ # Activations with gradient checkpointing scale ~linearly with tokens-in-flight
41
+ # (batch x seq) and model width (~sqrt of params). Coef calibrated so 4.7B SFT at
42
+ # seq 32k / batch 1 lands ~22 GB (measured: fits a 32 GB 5090).
43
+ _ACT_COEF = 0.12
44
+ # Colocated-GRPO vLLM KV pool: grows with the engine's max context (seq) and model
45
+ # width, but vLLM bounds the pool to a fraction of the card and PAGES rather than OOMs,
46
+ # so it's capped (_KV_CAP) instead of growing without bound at long context.
47
+ _KV_COEF = 2.0
48
+ _KV_CAP = 8.0
49
+ # GRPO backward (activations + fp32 logits over the completion micro-batch) per unit
50
+ # context x model width. Grad checkpointing makes this MILD in seq -- calibrated to
51
+ # measured boundaries: 0.8B GRPO fits 24 GB up to seq 32k (seq ~free), while 4.7B GRPO
52
+ # steps off a 32 GB card between seq 16k and 32k. group size scales it sublinearly.
53
+ _TRAIN_COEF = 0.27
54
+ # Fixed floor for colocated-vLLM GRPO: the vLLM engine's CUDA context + KV pool (sized to the
55
+ # CARD's VRAM via gpu_util, not the model) + the 2nd resident weight copy is ~model-independent
56
+ # for small models and dominates their param estimate, so tiny/mid models all need the 32 GB tier.
57
+ # MEASURED at the default group_size=8: 0.8B GRPO OOMs a 20 GB card; 2B GRPO OOMs a 24 GB card
58
+ # (-> both need 32); 4B GRPO fits 32 (param est ~31 already clears this floor, so it's untouched).
59
+ _VLLM_COLOCATE_FLOOR_GB = 28.0
60
+ _VOCAB_DEFAULT = 152_000 # Qwen3.x tokenizer vocab (drives the fp32-logits GRPO term)
61
+ # Matches the worker's RL_LOGITS_BUDGET_GB default: the per-device fp32 logits are capped to this
62
+ # (rl_per_device_comps spills the rest into grad-accum), so the estimator never reserves above it.
63
+ _LOGITS_BUDGET_GB = 6.0
64
+
65
+
66
+ def grpo_seq_escalation_gb(params_b: float | None, seq_len: int) -> int:
67
+ """Extra GB a long-context GRPO run needs beyond its base footprint.
68
+
69
+ Big-model GRPO is tight: colocate holds 2 weight copies + a KV pool, so headroom shrinks
70
+ with model size and long context overflows it. Calibrated on a bf16 9.7B GRPO run (RunPod):
71
+ fits 80 GB to seq 4096 but OOMs at 8192. Safe headroom ~ 48500/params_b tokens; past that
72
+ escalate, STEEPER for bigger models. Applies to both catalog and open-model GRPO so neither
73
+ under-provisions.
74
+ """
75
+ coef = 0.9
76
+ if not params_b:
77
+ return 0
78
+ seq_thresh = 48_500.0 / params_b
79
+ if seq_len <= seq_thresh:
80
+ return 0
81
+ return math.ceil(coef * params_b * (seq_len / seq_thresh - 1))
82
+
83
+
84
+ def params_b_from_str(s: str | None) -> float | None:
85
+ """Leading param count (billions) from a catalog ``params`` string, e.g.
86
+ "4.7B (text-only fine-tune)" -> 4.7, "9.7B (text-only fine-tune)" -> 9.7."""
87
+ if not s:
88
+ return None
89
+ m = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*B", s)
90
+ return float(m.group(1)) if m else None
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class VramEstimate:
95
+ params_b: float | None
96
+ algorithm: str
97
+ quant: str
98
+ est_gb: float | None
99
+ gpu: str
100
+ gpu_gb: int
101
+ verdict: str # "fits" | "tight" | "too_big" | "unknown"
102
+
103
+ def describe(self) -> str:
104
+ if self.est_gb is None:
105
+ return f"{self.gpu}: VRAM need unknown (could not read model size)"
106
+ return (
107
+ f"{self.gpu} ({self.gpu_gb} GB): estimated ~{self.est_gb:.0f} GB needed "
108
+ f"({self.params_b:.1f}B params, {self.quant}, {self.algorithm}) -> {self.verdict}"
109
+ )
110
+
111
+
112
+ def estimate_vram_gb(
113
+ params_b: float,
114
+ algorithm: str,
115
+ quant: str = "bf16",
116
+ *,
117
+ seq_len: int = 1024,
118
+ max_tokens: int | None = None,
119
+ lora_rank: int = 32,
120
+ batch_size: int = 1,
121
+ group_size: int = 8,
122
+ thinking: bool = False,
123
+ use_vllm: bool = True,
124
+ ) -> float:
125
+ """Estimated peak VRAM (GB) for a LoRA job on one GPU, over the full knob matrix.
126
+
127
+ Terms (all in GB):
128
+ weights params x bytes/param (bf16=2, 4bit-qlora=0.55)
129
+ base CUDA context + framework + fragmentation headroom
130
+ lora_opt LoRA adapter + grads + Adam states (rank-linear, model-scaled)
131
+ activations grad-checkpointed activations ~ batch x seq x sqrt(params)
132
+ grpo only:
133
+ +weights colocated vLLM holds a 2nd resident weight copy at the rollout peak
134
+ (sleep mode offloads it BETWEEN steps, not during) -- skipped when
135
+ use_vllm is False (transformers generation, single copy)
136
+ kv vLLM KV pool ~ seq x sqrt(params)
137
+ logits fp32 logits [per_device_comps, completion, vocab]
138
+ """
139
+ bpp = _BYTES_PER_PARAM.get(quant, 2.0)
140
+ weights = params_b * bpp
141
+ algo = "grpo" if (algorithm or "").lower() in ("grpo", "rl") else "sft"
142
+ width = math.sqrt(max(params_b, 0.1))
143
+ lora_opt = (lora_rank / 16.0) * (0.3 + 0.04 * params_b)
144
+ base = weights + _BASE_OVERHEAD_GB + lora_opt
145
+ if algo == "grpo":
146
+ # GRPO alternates two phases that DON'T peak together (sleep mode offloads the
147
+ # vLLM engine during the backward), so peak = max(rollout, train), not the sum:
148
+ # rollout: colocated vLLM 2nd weight copy + KV pool (skipped if use_vllm=False)
149
+ # train: backward activations + fp32 logits -- MILD in seq (grad ckpt)
150
+ rollout = 0.0
151
+ if use_vllm:
152
+ rollout = weights + min(_KV_COEF * (seq_len / 1024.0) * width, _KV_CAP)
153
+ group_factor = max(1.0, (max(1, group_size) / 4.0) ** 0.5)
154
+ think_factor = 1.3 if thinking else 1.0
155
+ activations = _TRAIN_COEF * (seq_len / 1024.0) * width * group_factor * think_factor
156
+ # fp32 logits [per_device, completion, vocab] are the documented GRPO OOM driver. The
157
+ # worker MEMORY-CAPS per_device (rl_per_device_comps) so the live logits never exceed
158
+ # RL_LOGITS_BUDGET_GB and the rest spills into grad-accum -- so the IRREDUCIBLE floor the
159
+ # card must hold is the per_device=1 logits for the completion length: it scales with
160
+ # max_tokens (NOT seq_len) and is capped at the budget. completion defaults to the recipe
161
+ # budget (~min(seq_len, 1024)) when max_tokens is unset.
162
+ completion = max_tokens if max_tokens else min(seq_len, 1024)
163
+ logits = min(completion * _VOCAB_DEFAULT * 4 / 1e9, _LOGITS_BUDGET_GB)
164
+ train = activations + logits
165
+ return base + max(rollout, train)
166
+ return base + _ACT_COEF * max(1, batch_size) * (seq_len / 1024.0) * width
167
+
168
+
169
+ def model_required_vram_gb(
170
+ model_id: str,
171
+ algorithm: str,
172
+ *,
173
+ train=None,
174
+ thinking: bool = False,
175
+ headroom: float = 1.1,
176
+ ) -> int:
177
+ """Cheapest-sufficient VRAM (GB) for a specific run -- the matrix the allocator and
178
+ ``resolve_gpu_policy`` both size against.
179
+
180
+ Catalog models size from their known param count + the run's actual knobs (``train``
181
+ may be a TrainSpec, a dict, or None for recipe defaults). Curated GRPO floors
182
+ (``grpo_min_vram_gb``) stay as HARD floors so we never under-provision a validated
183
+ model; the matrix only ever sizes UP from there. Unlisted open models size from HF
184
+ metadata, falling back to the 24 GB tier when the size can't be read.
185
+ """
186
+
187
+ # Best-effort knob extraction: this provisional sizing runs at parse time BEFORE the
188
+ # dedicated train validators, so malformed knobs (nan/inf/strings/<=0) must fall back
189
+ # to a default here, never crash -- config_schema raises the proper ConfigError next.
190
+ def _g(obj, key):
191
+ if obj is None:
192
+ return None
193
+ return obj.get(key) if isinstance(obj, dict) else getattr(obj, key, None)
194
+
195
+ def _pos_int(v, default):
196
+ try:
197
+ if isinstance(v, bool):
198
+ return default
199
+ f = float(v)
200
+ return int(f) if math.isfinite(f) and f >= 1 else default
201
+ except (TypeError, ValueError):
202
+ return default
203
+
204
+ seq_len = _pos_int(_g(train, "max_length"), 1024)
205
+ max_tokens = _pos_int(_g(train, "max_tokens"), None)
206
+ lora_rank = _pos_int(_g(train, "lora_rank"), 32)
207
+ group_size = _pos_int(_g(train, "group_size"), 8)
208
+ batch_size = _pos_int(_g(train, "batch_size"), 1)
209
+
210
+ def _need(
211
+ params_b: float, algorithm: str, *, quant: str = "bf16", use_vllm: bool = True
212
+ ) -> int:
213
+ # estimate over the run's full knob matrix, then apply the safety headroom. Both the
214
+ # catalog and open-model paths size through here so they stay in sync on the knob set.
215
+ est = estimate_vram_gb(
216
+ params_b,
217
+ algorithm,
218
+ quant,
219
+ seq_len=seq_len,
220
+ max_tokens=max_tokens,
221
+ lora_rank=lora_rank,
222
+ batch_size=batch_size,
223
+ group_size=group_size,
224
+ thinking=thinking,
225
+ use_vllm=use_vllm,
226
+ )
227
+ return math.ceil(est * headroom)
228
+
229
+ from autoslm.catalog import MODELS
230
+
231
+ info = MODELS.get(model_id)
232
+ is_grpo = (algorithm or "").lower() in ("grpo", "rl")
233
+ if info is not None:
234
+ params_b = params_b_from_str(info.params)
235
+ quant = getattr(info, "quant", "bf16") or "bf16"
236
+ # GRPO always runs the rollout on a colocated vLLM engine, so sizing must reserve room for
237
+ # the 2nd (rollout) weight copy on the same card.
238
+ use_vllm = True
239
+ need = _need(params_b or 4.0, algorithm, quant=quant, use_vllm=use_vllm)
240
+ # Hard floor the param-based matrix can't see: a curated GRPO floor.
241
+ floor = 0
242
+ if is_grpo and getattr(info, "grpo_min_vram_gb", 0):
243
+ floor = int(info.grpo_min_vram_gb)
244
+ if quant == "4bit-qlora":
245
+ # GRPO needs the curated grpo_min_vram_gb (2 weight copies + KV); SFT is single-copy and
246
+ # fits the smaller min_vram_gb. Don't leak the GRPO floor into SFT allocations or SFT
247
+ # over-provisions.
248
+ _q_floor = (
249
+ int(getattr(info, "grpo_min_vram_gb", 0) or info.min_vram_gb)
250
+ if is_grpo
251
+ else int(info.min_vram_gb)
252
+ )
253
+ floor = max(floor, _q_floor)
254
+ # Big-model GRPO is TIGHT at its floor (2 weight copies + KV pool), so long context
255
+ # overflows it -> escalate to a bigger tier. See grpo_seq_escalation_gb.
256
+ if is_grpo and floor:
257
+ floor += grpo_seq_escalation_gb(params_b, seq_len)
258
+ need = max(need, floor)
259
+ # vLLM-colocate floor: the engine (CUDA context + KV pool sized to the CARD's VRAM +
260
+ # framework) + the 2nd resident weight copy add a ~constant the param estimate misses,
261
+ # so small-model GRPO under-provisions. MEASURED at the default group_size=8: 0.8B GRPO
262
+ # fits a 24 GB card but OOMs 20 (est ~18, ~6 GB headroom on 24); 2B GRPO OOMs a 24 GB
263
+ # card (est ~20 but the colocate cost tips it past 24 -> needs the 32 tier). So sub-~1B
264
+ # models floor at 24, while larger small-models that the param estimate still under-shoots
265
+ # floor at the 32 tier. 4B+ already exceed this via their param estimate, so untouched.
266
+ if is_grpo and use_vllm:
267
+ floor_gb = 24 if (params_b or 0.0) <= 1.0 else int(_VLLM_COLOCATE_FLOOR_GB)
268
+ need = max(need, floor_gb)
269
+ return need
270
+ # Unlisted open model: size from HF metadata (GRPO is the heavier phase).
271
+ params_b = fetch_hf_params_b(model_id)
272
+ if params_b is None:
273
+ return 24
274
+ # Open models size against the heavier GRPO phase regardless of the requested algorithm.
275
+ need = _need(params_b, "grpo")
276
+ # Same long-context GRPO escalation as the catalog path so a big open model isn't
277
+ # under-provisioned at long context either.
278
+ if is_grpo:
279
+ need += grpo_seq_escalation_gb(params_b, seq_len)
280
+ return need
281
+
282
+
283
+ def fetch_hf_params_b(model_id: str) -> float | None:
284
+ """Total params (billions) from the HF API safetensors metadata (no download)."""
285
+ if os.environ.get("AUTOSLM_SKIP_NET"):
286
+ return None
287
+ try:
288
+ from huggingface_hub import HfApi
289
+
290
+ info = HfApi(token=os.environ.get("HF_TOKEN")).model_info(
291
+ model_id, expand=["safetensors"]
292
+ )
293
+ total = getattr(getattr(info, "safetensors", None), "total", None)
294
+ if total:
295
+ return float(total) / 1e9
296
+ except Exception:
297
+ # Best-effort size probe (network/HF-metadata may be unavailable); fall through
298
+ # to None so callers report "size unknown" rather than failing.
299
+ pass
300
+ return None
301
+
302
+
303
+ def check_fit(
304
+ model_id: str,
305
+ algorithm: str,
306
+ gpu: str,
307
+ quant: str = "bf16",
308
+ params_b: float | None = None,
309
+ ) -> VramEstimate:
310
+ """Estimate whether ``model_id`` plausibly trains on ``gpu``; never raises."""
311
+ gpu_gb = GPU_VRAM_GB.get(gpu, 32)
312
+ if params_b is None:
313
+ params_b = fetch_hf_params_b(model_id)
314
+ if params_b is None:
315
+ return VramEstimate(None, algorithm, quant, None, gpu, gpu_gb, "unknown")
316
+ est = estimate_vram_gb(params_b, algorithm, quant)
317
+ if est > gpu_gb * 1.15:
318
+ verdict = "too_big"
319
+ elif est > gpu_gb * 0.85:
320
+ verdict = "tight"
321
+ else:
322
+ verdict = "fits"
323
+ return VramEstimate(params_b, algorithm, quant, est, gpu, gpu_gb, verdict)
code/autoslm/engine/worker.py ADDED
The diff for this file is too large to render. See raw diff
 
code/autoslm/envs/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pluggable fine-tune/evaluation environments."""
2
+
3
+ from .base import BaseEnvironment, Environment
4
+ from .registry import load_environment
5
+
6
+ __all__ = [
7
+ "BaseEnvironment",
8
+ "Environment",
9
+ "load_environment",
10
+ ]
code/autoslm/envs/adapter.py ADDED
@@ -0,0 +1,706 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adapter that runs Prime Intellect ``verifiers`` / Environments Hub envs on AutoSLM.
2
+
3
+ Wraps a ``verifiers`` ``Environment`` (``SingleTurnEnv``, ``MultiTurnEnv``, ``ToolEnv`` and
4
+ its subclasses) in AutoSLM's small ``Environment`` protocol so Hub environments run unchanged
5
+ on AutoSLM's trainer.
6
+
7
+ GRPO supports all three shapes (the worker routes on ``multi_turn`` / ``is_tool_env``):
8
+ * single-turn — TRL's single-shot generation + per-completion reward;
9
+ * tool (``ToolEnv`` / ``StatefulToolEnv`` / ``SandboxEnv`` / ``PythonEnv``) — TRL drives the
10
+ tool-call loop natively via ``GRPOTrainer(tools=...)`` (:meth:`tools`), masking tool tokens
11
+ itself; the reward scores the full transcript (:meth:`reward_from_messages`);
12
+ * pure multi-turn — ``autoslm.engine.multiturn_rollout`` supplies a ``rollout_func`` that
13
+ drives this env's turn loop on the colocate engine via the adapter rollout helpers
14
+ (:meth:`new_rollout_state` / :meth:`record_model_turn` / :meth:`env_reply` /
15
+ :meth:`rollout_done`) and returns an ``env_mask`` so only model tokens are trained.
16
+
17
+ Caveats:
18
+ * SFT on a multi-turn/tool env only fits the single assistant ``sft_target`` per row and
19
+ ignores tool/env turns, so it should be avoided (see ``run_sft`` / ``sft_target``);
20
+ * a ``StatefulToolEnv`` whose tools need verifiers' state-injection (``update_tool_args``)
21
+ is only fully honored on the rollout path — under TRL's native tool loop the tools are
22
+ called as plain functions.
23
+
24
+ verifiers contract (docs):
25
+ * ``vf.load_environment(env_id, **kwargs) -> Environment``
26
+ * rows have ``prompt`` (chat messages) + ``answer`` (+ optional ``info``)
27
+ * ``env.dataset`` / ``env.get_dataset(n, seed)``, ``env.eval_dataset`` / ``get_eval_dataset``
28
+ * ``env.system_prompt``, ``env.parser``, ``env.rubric`` (weighted reward funcs that take
29
+ ``completion``/``prompt``/``answer``/``info``/``state``/``parser``/``judge`` by name; sync or async)
30
+ * multi-turn: ``env.env_response(messages, state)`` -> env reply messages;
31
+ ``env.is_completed(state)`` -> done flag (both async)
32
+
33
+ Hub conveniences handled here so the *documented* flow (``slm env install owner/name`` +
34
+ ``[environment] id = "owner/name"``) works on real Prime Intellect envs:
35
+ * the ``owner/name`` Hub slug is mapped to the bare ``verifiers`` load id;
36
+ * a ``RubricGroup`` (rubrics-of-rubrics) is flattened so the real reward funcs are found;
37
+ zero-weight monitor funcs still run (for shared-state side effects / logging) with their
38
+ exceptions guarded, but contribute 0 — only weighted funcs count toward the reward;
39
+ * a ``JudgeRubric``'s judge client/model/prompt is supplied to reward funcs that declare a
40
+ ``judge``/``judge_client``/``judge_model``/``judge_prompt`` arg, so judge-based rewards run;
41
+ * named per-scorer breakdowns (``scores_breakdown``) expose each reward func's weighted
42
+ score so the frontend per-scorer view + W&B series survive;
43
+ * an optional separate **eval** Hub env (``eval_env_id``) + a fixed eval subset
44
+ (``eval_examples`` / ``eval_seed``) let you train on one env and evaluate on another.
45
+ """
46
+
47
+ from __future__ import annotations
48
+
49
+ import asyncio
50
+ import contextlib
51
+ import inspect
52
+ import json
53
+ import random
54
+
55
+ from .base import BaseEnvironment
56
+
57
+ # The judge-related kwarg names a reward func may declare, sourced from a JudgeRubric.
58
+ # Single source of truth for both ``_judge_kwargs`` and ``_AVAILABLE_REWARD_KWARGS``.
59
+ _JUDGE_KWARG_NAMES = ("judge", "judge_client", "judge_model", "judge_prompt")
60
+
61
+ # The kwargs this adapter can supply to a reward func. The non-judge keys are exactly the
62
+ # ones built into the ``available`` dict in VerifiersEnvironment._reward_available; the judge
63
+ # keys come from ``_judge_kwargs``. Deriving the frozenset from these shared names avoids the
64
+ # manual "keep in sync" coupling (adding a kwarg below without updating the set would
65
+ # re-trigger the false "requires unavailable arg" failure).
66
+ _BASE_REWARD_KWARG_NAMES = (
67
+ "completion",
68
+ "prompt",
69
+ "answer",
70
+ "info",
71
+ "state",
72
+ "parser",
73
+ "task",
74
+ )
75
+ _AVAILABLE_REWARD_KWARGS = frozenset(_BASE_REWARD_KWARG_NAMES + _JUDGE_KWARG_NAMES)
76
+
77
+
78
+ def _reward_requires_unavailable_args(func) -> str | None:
79
+ """Name of a required arg this adapter cannot supply, or None.
80
+
81
+ Group/batch reward funcs declare plural required params (``completions``,
82
+ ``prompts``, ``answers``, ...). The worker scores one completion at a time and has no
83
+ batch, so such a func would be called without its required argument and silently score
84
+ 0.0 — train/eval on an all-zero signal. Detect it so the caller can fail fast."""
85
+ try:
86
+ params = inspect.signature(func).parameters.values()
87
+ except (TypeError, ValueError):
88
+ return None # builtins/uninspectable: _invoke_reward passes everything
89
+ for p in params:
90
+ if p.kind in (p.VAR_KEYWORD, p.VAR_POSITIONAL):
91
+ continue
92
+ if p.default is inspect.Parameter.empty and p.name not in _AVAILABLE_REWARD_KWARGS:
93
+ return p.name
94
+ return None
95
+
96
+
97
+ def vf_load_id(env_ref: str) -> str:
98
+ """Map a Hub slug (``owner/name``) to the bare ``verifiers`` load id (``name``)."""
99
+ return env_ref.split("/", 1)[1] if "/" in env_ref else env_ref
100
+
101
+
102
+ # AutoSLM-reserved keys that may historically have ridden in [environment.params] but are
103
+ # NOT verifiers ``load_environment`` kwargs. They are handled by the worker/adapter directly
104
+ # (eval_* via named params; GRPO recipe knobs now live in [train]/TrainSpec). A stray one must
105
+ # be dropped before forwarding to ``vf.load_environment`` — passing it through would raise a
106
+ # TypeError in the env's loader (or silently change its behavior). The eval_* keys are also
107
+ # listed here so the catch-all guard never forwards them even if they reach **kwargs.
108
+ _RESERVED_ENV_PARAM_KEYS = frozenset(
109
+ {
110
+ "eval_env_id",
111
+ "eval_examples",
112
+ "eval_seed",
113
+ "grpo_config",
114
+ "sft_config",
115
+ "mode",
116
+ "records",
117
+ "eval_records",
118
+ "reward_command",
119
+ }
120
+ )
121
+
122
+
123
+ def _drop_reserved_kwargs(kwargs: dict) -> dict:
124
+ """Strip AutoSLM-reserved keys so only true verifiers-env kwargs are forwarded."""
125
+ dropped = [k for k in kwargs if k in _RESERVED_ENV_PARAM_KEYS]
126
+ if dropped:
127
+ print(
128
+ "[verifiers-adapter] dropping AutoSLM-reserved [environment.params] keys not "
129
+ f"accepted by vf.load_environment: {', '.join(sorted(dropped))}"
130
+ )
131
+ return {k: v for k, v in kwargs.items() if k not in _RESERVED_ENV_PARAM_KEYS}
132
+
133
+
134
+ def _run_async(coro):
135
+ """Run an awaitable to completion from sync code, even inside a running loop."""
136
+ try:
137
+ asyncio.get_running_loop()
138
+ except RuntimeError:
139
+ return asyncio.run(coro)
140
+ # Already inside a loop (rare for the worker): run in a fresh loop on a thread.
141
+ import concurrent.futures
142
+
143
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as ex:
144
+ return ex.submit(lambda: asyncio.run(coro)).result()
145
+
146
+
147
+ def _call_dataset_getter(obj, method_name: str, *, seed: int):
148
+ """Call a verifiers dataset getter, binding (n, seed) when it declares them.
149
+
150
+ verifiers exposes get_dataset/get_eval_dataset as get_X(n=-1, seed=0); some Hub envs
151
+ declare them WITHOUT defaults, so a no-arg call raised TypeError, swallowed into an empty
152
+ dataset (a paid run over no data). Bind n=-1 (all rows — the adapter does its own fixed
153
+ subset selection) and the seed when the signature declares them; a genuine failure
154
+ propagates (fail loudly) instead of silently emptying the split."""
155
+ fn = getattr(obj, method_name, None)
156
+ if not callable(fn):
157
+ return None
158
+ try:
159
+ param_names = set(inspect.signature(fn).parameters)
160
+ except (TypeError, ValueError):
161
+ param_names = set()
162
+ kwargs = {}
163
+ if "n" in param_names:
164
+ kwargs["n"] = -1
165
+ if "seed" in param_names:
166
+ kwargs["seed"] = seed
167
+ return fn(**kwargs)
168
+
169
+
170
+ def _rows_to_list(ds) -> list[dict]:
171
+ if ds is None:
172
+ return []
173
+ try:
174
+ return [dict(r) for r in ds]
175
+ except Exception:
176
+ return list(ds)
177
+
178
+
179
+ def _flatten_rubric(rubric) -> list[tuple]:
180
+ """Collect ``(func, weight)`` pairs from a rubric, recursing into ``RubricGroup``.
181
+
182
+ verifiers composes rubrics (e.g. a ``RubricGroup`` wrapping a ``MathRubric`` plus a
183
+ ``MultiTurnMonitorRubric``); the real reward funcs live on the *nested* rubrics while the
184
+ group's own ``funcs`` is empty. Flattening finds them all.
185
+ """
186
+ funcs = list(getattr(rubric, "funcs", None) or getattr(rubric, "reward_funcs", None) or [])
187
+ weights = list(
188
+ getattr(rubric, "weights", None) or getattr(rubric, "reward_weights", None) or []
189
+ )
190
+ if len(weights) < len(funcs):
191
+ weights += [1.0] * (len(funcs) - len(weights))
192
+ pairs = list(zip(funcs, weights, strict=False))
193
+ for sub in getattr(rubric, "rubrics", None) or []:
194
+ pairs.extend(_flatten_rubric(sub))
195
+ return pairs
196
+
197
+
198
+ def _find_judge_rubric(rubric):
199
+ """Return the first ``JudgeRubric`` in a rubric tree (or None), for judge-arg injection."""
200
+ if rubric is None:
201
+ return None
202
+ try:
203
+ import verifiers as vf
204
+
205
+ judge_cls = getattr(vf, "JudgeRubric", None)
206
+ except ImportError:
207
+ judge_cls = None
208
+ if judge_cls is not None and isinstance(rubric, judge_cls):
209
+ return rubric
210
+ # Duck-type fallback: anything exposing a `judge` method + a judge_client attr.
211
+ if callable(getattr(rubric, "judge", None)) and hasattr(rubric, "judge_client"):
212
+ return rubric
213
+ for sub in getattr(rubric, "rubrics", None) or []:
214
+ found = _find_judge_rubric(sub)
215
+ if found is not None:
216
+ return found
217
+ return None
218
+
219
+
220
+ def _judge_kwargs(judge_rubric) -> dict:
221
+ """The judge-related kwargs a reward func may declare, sourced from a JudgeRubric."""
222
+ if judge_rubric is None:
223
+ return {}
224
+ return {name: getattr(judge_rubric, name, None) for name in _JUDGE_KWARG_NAMES}
225
+
226
+
227
+ def _invoke_reward(func, available: dict) -> float:
228
+ """Call a verifiers reward func passing only the kwargs it declares; await if async.
229
+
230
+ Exceptions PROPAGATE. ``scores_breakdown`` invokes this for *weighted* reward funcs, so an
231
+ exception here is a real (weighted) reward func genuinely failing (e.g. a JudgeRubric judge
232
+ raising on an API/rate-limit error, or a parse error on row data). Swallowing it as 0.0
233
+ would silently train/score on an all-zero signal and waste a paid run, so we fail loudly
234
+ instead. Zero-weight (optional/monitor) funcs are run through ``_run_zero_weight_reward``,
235
+ which swallows their exceptions — they contribute 0 either way and may exist only for their
236
+ side effects (mutating shared ``state`` / logging), so a thrown monitor must not fail a run.
237
+ """
238
+ try:
239
+ params = inspect.signature(func).parameters
240
+ if any(p.kind == p.VAR_KEYWORD for p in params.values()):
241
+ kwargs = dict(available)
242
+ else:
243
+ kwargs = {k: v for k, v in available.items() if k in params}
244
+ except (TypeError, ValueError):
245
+ kwargs = dict(available)
246
+ result = func(**kwargs)
247
+ if inspect.isawaitable(result):
248
+ result = _run_async(result)
249
+ return float(result or 0.0)
250
+
251
+
252
+ def _run_zero_weight_reward(func, available: dict) -> None:
253
+ """Run a zero-weight monitor/diagnostic reward func, swallowing any exception.
254
+
255
+ Per verifiers semantics every reward func RUNS, even weight-0 ones: they may mutate the
256
+ shared ``state`` (so a later weighted func sees their work) or simply be logged. They never
257
+ contribute to the reward (weight is 0), so their result is discarded and a failure must NOT
258
+ fail the run — guard the exception. Weighted funcs go through ``_invoke_reward`` instead,
259
+ where exceptions propagate.
260
+ """
261
+ with contextlib.suppress(Exception):
262
+ _invoke_reward(func, available)
263
+
264
+
265
+ def _is_multi_turn(vf_env) -> bool:
266
+ """True for a tool/multi-turn verifiers env (NOT a plain SingleTurnEnv)."""
267
+ try:
268
+ import verifiers as vf
269
+ except ImportError:
270
+ return False
271
+ tool = getattr(vf, "ToolEnv", None)
272
+ multi = getattr(vf, "MultiTurnEnv", None)
273
+ single = getattr(vf, "SingleTurnEnv", None)
274
+ if tool is not None and isinstance(vf_env, tool):
275
+ return True
276
+ if multi is not None and isinstance(vf_env, multi):
277
+ # SingleTurnEnv subclasses MultiTurnEnv in verifiers; exempt it.
278
+ return not (single is not None and isinstance(vf_env, single))
279
+ return False
280
+
281
+
282
+ def _is_tool_env(vf_env) -> bool:
283
+ """True for a verifiers ``ToolEnv`` or any subclass (Stateful/Sandbox/Python).
284
+
285
+ Tool envs expose Python tool callables; the worker hands those to TRL's
286
+ ``GRPOTrainer(tools=...)`` so TRL drives the tool-call loop natively (it owns generation,
287
+ tool execution, and assistant-only token masking). A *pure* ``MultiTurnEnv`` (env turns are
288
+ arbitrary content, e.g. a simulated user) is multi-turn but NOT a tool env, and takes the
289
+ ``rollout_func`` path instead."""
290
+ try:
291
+ import verifiers as vf
292
+ except ImportError:
293
+ return False
294
+ tool = getattr(vf, "ToolEnv", None)
295
+ return tool is not None and isinstance(vf_env, tool)
296
+
297
+
298
+ class VerifiersEnvironment(BaseEnvironment):
299
+ """AutoSLM environment backed by a verifiers ``Environment`` instance.
300
+
301
+ GRPO training supports three env shapes (the worker routes on these flags):
302
+ * **single-turn** (``multi_turn`` False) — TRL's single-shot rollout (original path);
303
+ * **tool** (``is_tool_env`` True) — TRL drives the tool-call loop natively via
304
+ ``GRPOTrainer(tools=...)`` (:meth:`tools`); the reward scores the full transcript
305
+ (:meth:`reward_from_messages`);
306
+ * **pure multi-turn** (``multi_turn`` True, ``is_tool_env`` False) — TRL's
307
+ ``rollout_func`` drives this env's turn loop (:meth:`new_rollout_state` /
308
+ :meth:`record_model_turn` / :meth:`env_reply` / :meth:`rollout_done`).
309
+ """
310
+
311
+ def __init__(
312
+ self,
313
+ vf_env,
314
+ env_id: str,
315
+ eval_vf_env=None,
316
+ eval_examples: int | None = None,
317
+ eval_seed: int = 12345,
318
+ ):
319
+ super().__init__(id=env_id)
320
+ self._env = vf_env
321
+ self._eval_env = eval_vf_env # optional separate eval Hub env
322
+ self._eval_examples = int(eval_examples) if eval_examples else 0
323
+ self._eval_seed = int(eval_seed)
324
+ self.multi_turn = _is_multi_turn(vf_env)
325
+ self.is_tool_env = _is_tool_env(vf_env)
326
+ # Turn cap for the tool / multi-turn rollout loop (verifiers ToolEnv defaults to 10).
327
+ self.max_turns = int(getattr(vf_env, "max_turns", 10) or 10)
328
+ # The shared scorer is the TRAIN env's (flattened) rubric + parser, so the reward used
329
+ # for RL and the grader used at eval are byte-for-byte identical.
330
+ rubric = getattr(vf_env, "rubric", None)
331
+ self._reward_pairs = _flatten_rubric(rubric) if rubric is not None else []
332
+ self._judge_rubric = _find_judge_rubric(rubric)
333
+ # Fail fast on a group/batch reward func: the worker scores one completion at a time
334
+ # and cannot supply its plural batch args, so it would silently score 0.0 and train a
335
+ # paid run on an all-zero signal. Only weighted funcs matter (zero-weight ones skip).
336
+ for func, weight in self._reward_pairs:
337
+ if not weight:
338
+ continue
339
+ missing = _reward_requires_unavailable_args(func)
340
+ if missing:
341
+ raise ValueError(
342
+ f"verifiers reward function {getattr(func, '__name__', func)!r} requires "
343
+ f"argument {missing!r}, which the AutoSLM adapter cannot supply (it scores "
344
+ "one completion at a time, with no group/batch context such as "
345
+ "completions/prompts/answers). This environment uses a group-based reward "
346
+ "not supported on AutoSLM; use a per-completion reward."
347
+ )
348
+ self._parser = getattr(vf_env, "parser", None)
349
+
350
+ # -- data -------------------------------------------------------------
351
+ def dataset(self, split: str) -> list[dict]:
352
+ is_eval = split in {"eval", "validation", "test"}
353
+ if is_eval:
354
+ src = self._eval_env or self._env
355
+ # Resolve the eval source with explicit ``is None`` checks (NOT ``or``): an
356
+ # empty-but-configured eval split (``[]``) is falsy, so ``or`` would wrongly
357
+ # fall through to the next source and ultimately to the TRAIN split — evaluating
358
+ # on training data. Only fall back when the eval source is genuinely *absent*
359
+ # (None), not merely empty. ``get_eval_dataset``/``eval_dataset`` returning [] is
360
+ # a deliberate empty eval set and must be honored as such.
361
+ eval_ds = _call_dataset_getter(src, "get_eval_dataset", seed=self._eval_seed)
362
+ if eval_ds is None:
363
+ eval_ds = getattr(src, "eval_dataset", None)
364
+ if eval_ds is None: # no eval split configured at all: use the env's train split
365
+ eval_ds = _call_dataset_getter(src, "get_dataset", seed=self._eval_seed)
366
+ if eval_ds is None:
367
+ eval_ds = getattr(src, "dataset", None)
368
+ rows = _rows_to_list(eval_ds)
369
+ return self._fixed_subset(rows)
370
+ ds = _call_dataset_getter(self._env, "get_dataset", seed=0)
371
+ if ds is None:
372
+ ds = getattr(self._env, "dataset", None)
373
+ return _rows_to_list(ds)
374
+
375
+ def _fixed_subset(self, rows: list[dict]) -> list[dict]:
376
+ n = self._eval_examples
377
+ if n <= 0 or n >= len(rows):
378
+ return rows
379
+ idx = sorted(random.Random(self._eval_seed).sample(range(len(rows)), n))
380
+ return [rows[i] for i in idx]
381
+
382
+ # -- task interface ---------------------------------------------------
383
+ def prompt_messages(self, example: dict) -> list[dict]:
384
+ prompt = example.get("prompt")
385
+ if isinstance(prompt, list) and prompt:
386
+ msgs = [dict(m) for m in prompt]
387
+ else:
388
+ question = example.get("question") or example.get("prompt") or ""
389
+ msgs = [{"role": "user", "content": str(question)}]
390
+ system_prompt = getattr(self._env, "system_prompt", None)
391
+ if system_prompt and not any(m.get("role") == "system" for m in msgs):
392
+ msgs = [{"role": "system", "content": system_prompt}, *msgs]
393
+ return msgs
394
+
395
+ def sft_target(self, example: dict) -> str:
396
+ for key in ("answer", "completion", "target", "response"):
397
+ value = example.get(key)
398
+ if value:
399
+ if isinstance(value, list): # chat messages
400
+ return str(value[-1].get("content", ""))
401
+ return str(value)
402
+ return ""
403
+
404
+ # -- reward / scoring -------------------------------------------------
405
+ def _normalize_info(self, example: dict) -> dict:
406
+ # Hub rows may store `info` as a JSON string (a supported Verifiers row shape);
407
+ # parse it so reward funcs that do `info[...]` get a dict, not a str (which would
408
+ # raise TypeError, be swallowed as 0.0, and poison the signal).
409
+ info = example.get("info") or {}
410
+ if isinstance(info, str):
411
+ try:
412
+ info = json.loads(info)
413
+ except (ValueError, TypeError):
414
+ info = {}
415
+ return info
416
+
417
+ def _reward_available(self, completion: str, example: dict, state: dict | None) -> dict:
418
+ # In multi-turn/tool mode the accumulated transcript lives on ``state`` (built by the
419
+ # rollout helpers): ``state["completion"]`` is the full assistant + tool/env message
420
+ # list and ``state["prompt"]`` is the initial prompt. Reward/tool funcs that inspect the
421
+ # whole message list need that transcript, not the scalar ``completion`` string wrapped
422
+ # as a lone synthesized assistant message. Single-turn falls back to wrapping the scalar.
423
+ completion_msgs: list[dict] | None = None
424
+ prompt_msgs = None
425
+ if self.multi_turn and state:
426
+ transcript = state.get("completion")
427
+ if isinstance(transcript, list) and transcript:
428
+ completion_msgs = [dict(m) for m in transcript]
429
+ state_prompt = state.get("prompt")
430
+ if isinstance(state_prompt, list) and state_prompt:
431
+ prompt_msgs = [dict(m) for m in state_prompt]
432
+ if completion_msgs is None:
433
+ completion_msgs = [{"role": "assistant", "content": completion}]
434
+ if prompt_msgs is None:
435
+ prompt_msgs = example.get("prompt") or self.prompt_messages(example)
436
+ available = {
437
+ "completion": completion_msgs,
438
+ "prompt": prompt_msgs,
439
+ "answer": example.get("answer"),
440
+ "info": self._normalize_info(example),
441
+ "state": state if state is not None else {},
442
+ "parser": self._parser,
443
+ "task": example,
444
+ }
445
+ available.update(_judge_kwargs(self._judge_rubric))
446
+ return available
447
+
448
+ def scores_breakdown(
449
+ self, completion: str, example: dict, state: dict | None = None
450
+ ) -> dict[str, float]:
451
+ """Per-scorer weighted scores: ``{func_name: weighted_score, ..., "total": sum}``.
452
+
453
+ Every WEIGHTED rubric func contributes one entry (by ``func.__name__``); the
454
+ ``"total"`` is their sum (== :meth:`reward`). Used to preserve the frontend per-scorer
455
+ breakdown + W&B series instead of collapsing to a single binary ``correct``.
456
+
457
+ Per verifiers semantics EVERY reward func runs, including zero-weight ones — they may
458
+ mutate the shared ``state`` (so a subsequent weighted func sees their work) or exist
459
+ only to be logged. Zero-weight funcs run with GUARDED exceptions (a thrown monitor must
460
+ not fail the run) and contribute 0, so they are not added to the breakdown/total; the
461
+ order is preserved so a zero-weight func can prepare state for a later weighted one.
462
+ Weighted funcs propagate exceptions (a thrown weighted reward fails the run).
463
+ """
464
+ breakdown: dict[str, float] = {}
465
+ if not self._reward_pairs:
466
+ answer = str(example.get("answer") or "")
467
+ score = 1.0 if answer and answer in (completion or "") else 0.0
468
+ return {"answer_match": score, "total": score}
469
+ available = self._reward_available(completion, example, state)
470
+ total = 0.0
471
+ for func, weight in self._reward_pairs:
472
+ if not weight:
473
+ # Zero-weight monitor/diagnostic func: RUN it (for its side effects on shared
474
+ # state / logging) with guarded exceptions, but it contributes 0 and is not in
475
+ # the named breakdown.
476
+ _run_zero_weight_reward(func, available)
477
+ continue
478
+ name = getattr(func, "__name__", str(func))
479
+ score = float(weight) * _invoke_reward(func, available)
480
+ # Collisions (two funcs share a name): keep them distinct so neither is lost.
481
+ # Probe for an unused exact key — a prefix/length heuristic can recompute a
482
+ # suffix that collides with an already-recorded key (e.g. ``score`` vs
483
+ # ``score_detail``) and silently overwrite a scorer.
484
+ if name in breakdown:
485
+ base = name
486
+ i = 1
487
+ while name in breakdown:
488
+ name = f"{base}_{i}"
489
+ i += 1
490
+ breakdown[name] = score
491
+ total += score
492
+ breakdown["total"] = total
493
+ return breakdown
494
+
495
+ def reward(self, completion: str, example: dict, state: dict | None = None) -> float:
496
+ return float(self.scores_breakdown(completion, example, state)["total"])
497
+
498
+ def tools(self) -> list:
499
+ """The underlying ToolEnv's Python tool callables (``[]`` for non-tool envs).
500
+
501
+ Handed to ``GRPOTrainer(tools=...)`` so TRL runs the tool-call loop and does the
502
+ assistant-only token masking itself. Each is a plain function with type hints + a
503
+ Google-style docstring (verifiers and TRL share that requirement)."""
504
+ return list(getattr(self._env, "tools", None) or [])
505
+
506
+ def reward_from_messages(
507
+ self, completion_msgs: list[dict], example: dict, prompt_msgs: list[dict] | None = None
508
+ ) -> float:
509
+ """Reward for a full transcript (assistant + tool/env messages) via the rubric.
510
+
511
+ The tool / multi-turn training path produces a *message list* rollout rather than a
512
+ single completion string; this routes it through the same weighted-rubric scoring as
513
+ :meth:`reward` by handing the transcript to the env's reward funcs as ``state``."""
514
+ state: dict = {"completion": [dict(m) for m in completion_msgs]}
515
+ if prompt_msgs:
516
+ state["prompt"] = [dict(m) for m in prompt_msgs]
517
+ return self.reward("", example, state)
518
+
519
+ def grade(self, completion: str, example: dict, state: dict | None = None) -> bool:
520
+ threshold = getattr(self._env, "pass_threshold", 0.5)
521
+ return self.reward(completion, example, state) >= threshold
522
+
523
+ # -- multi-turn rollout (driven by the worker) ------------------------
524
+ def new_rollout_state(self, example: dict) -> dict:
525
+ """A fresh per-rollout ``state`` dict, threaded through env_reply/reward.
526
+
527
+ Mirrors the verifiers rollout ``state``: holds the running ``prompt``, the
528
+ accumulated ``completion`` (assistant + tool/env turns), the ``answer``/``info``, and
529
+ a ``turn`` counter. Reward funcs that read ``state`` see this dict.
530
+ """
531
+ prompt = self.prompt_messages(example)
532
+ state = {
533
+ "prompt": [dict(m) for m in prompt],
534
+ "completion": [],
535
+ "answer": example.get("answer"),
536
+ "info": self._normalize_info(example),
537
+ "responses": [],
538
+ "turn": 0,
539
+ }
540
+ setup = getattr(self._env, "setup_state", None)
541
+ if callable(setup):
542
+ with contextlib.suppress(Exception):
543
+ state = _run_async(setup(state)) or state
544
+ return state
545
+
546
+ def env_reply(self, messages: list[dict], state: dict) -> list[dict]:
547
+ """One environment turn: given the conversation so far (incl. the latest model
548
+ message), return the env's reply messages (tool results / next user turn) and advance
549
+ ``state``. Empty list when the env has nothing to add. Single-turn envs return []."""
550
+ if not self.multi_turn:
551
+ return []
552
+ fn = getattr(self._env, "env_response", None)
553
+ if not callable(fn):
554
+ return []
555
+ try:
556
+ reply = _run_async(fn(messages, state))
557
+ except NotImplementedError:
558
+ # Legitimate "this env has no env turn" signal -> no env reply.
559
+ return []
560
+ except Exception as exc:
561
+ # Mirror `_invoke_reward`: a genuine bug in the env's `env_response` must
562
+ # NOT be swallowed. Silently returning [] would collapse every multi-turn
563
+ # rollout to a single turn and train a paid GRPO run on degenerate
564
+ # transcripts. The rollout loop (multiturn_rollout.py) calls this directly
565
+ # with no surrounding swallow, so re-raising propagates and fails the run
566
+ # fast (and the context is printed first so it never vanishes silently).
567
+ print(f"[env_reply] env_response failed (turn={state.get('turn', 0)}): {exc!r}")
568
+ raise
569
+ if reply is None:
570
+ return []
571
+ if isinstance(reply, dict):
572
+ reply = [reply]
573
+ out = [dict(m) for m in reply]
574
+ state["completion"].extend(out)
575
+ state["turn"] = int(state.get("turn", 0)) + 1
576
+ return out
577
+
578
+ def rollout_done(self, state: dict, max_turns: int | None = None) -> bool:
579
+ """Whether the multi-turn rollout should stop (env says completed, or turn cap hit)."""
580
+ if not self.multi_turn:
581
+ return True
582
+ if max_turns is not None and int(state.get("turn", 0)) >= int(max_turns):
583
+ return True
584
+ fn = getattr(self._env, "is_completed", None)
585
+ if not callable(fn):
586
+ return True
587
+ try:
588
+ return bool(_run_async(fn(state)))
589
+ except NotImplementedError:
590
+ # Env doesn't implement a completion check -> rely on the turn cap only.
591
+ return True
592
+ except Exception as exc:
593
+ # Mirror `_invoke_reward` / `env_reply`: a real bug in `is_completed` must
594
+ # not be silently treated as "done" (which would truncate every rollout and
595
+ # train on degenerate transcripts). Print context, then re-raise so the run
596
+ # fails fast (the rollout loop calls this directly with no surrounding swallow).
597
+ print(f"[rollout_done] is_completed failed (turn={state.get('turn', 0)}): {exc!r}")
598
+ raise
599
+
600
+ def record_model_turn(self, state: dict, content: str) -> dict:
601
+ """Append a model (assistant) turn to ``state`` before calling ``env_reply``."""
602
+ msg = {"role": "assistant", "content": content}
603
+ state["completion"].append(msg)
604
+ state.setdefault("responses", []).append(content)
605
+ return msg
606
+
607
+
608
+ def _import_vf():
609
+ try:
610
+ import verifiers as vf
611
+
612
+ return vf
613
+ except ImportError as exc:
614
+ raise ImportError(
615
+ "the 'verifiers' package is required to run Prime Hub environments; "
616
+ "install it (e.g. `uv pip install verifiers`) or run `slm env install <env>`"
617
+ ) from exc
618
+
619
+
620
+ def _ensure_hub_module_importable(load_id: str) -> None:
621
+ """Make ``vf.load_environment(load_id)`` importable when the installed env package's
622
+ top-level module name has drifted from the slug.
623
+
624
+ ``vf.load_environment`` imports the slug as a module (``name`` -> ``name.replace("-","_")``).
625
+ Repeated Prime Hub re-publishes can leave a distribution whose *dist* name matches the slug
626
+ but whose *module* name is from an earlier push, so the expected import fails. When that
627
+ happens, locate the installed distribution for the slug, import its real top-level module,
628
+ and alias it under the expected name so the load succeeds.
629
+ """
630
+ import importlib
631
+ import importlib.util
632
+ import re as _re
633
+ import sys as _sys
634
+ from importlib import metadata as _md
635
+
636
+ expected = _re.sub(r"[^0-9A-Za-z_]", "_", load_id.replace("-", "_"))
637
+ if expected[:1].isdigit():
638
+ expected = "env_" + expected
639
+ try:
640
+ if importlib.util.find_spec(expected) is not None:
641
+ return
642
+ except (ImportError, ValueError):
643
+ pass
644
+ try:
645
+ dist = _md.distribution(load_id)
646
+ except _md.PackageNotFoundError:
647
+ return
648
+ # Top-level modules: prefer top_level.txt, else derive from the dist's file list (modern
649
+ # wheels often omit top_level.txt). A top-level ``foo.py`` -> module ``foo``; a top-level
650
+ # ``foo/__init__.py`` -> package ``foo``.
651
+ tops: list[str] = [t for t in (dist.read_text("top_level.txt") or "").split() if t]
652
+ if not tops:
653
+ seen: set[str] = set()
654
+ for f in dist.files or []:
655
+ parts = str(f).split("/")
656
+ if len(parts) == 1 and parts[0].endswith(".py") and parts[0] != "__init__.py":
657
+ mod = parts[0][:-3]
658
+ elif len(parts) >= 2 and parts[1] == "__init__.py" and not parts[0].endswith(
659
+ ".dist-info"
660
+ ):
661
+ mod = parts[0]
662
+ else:
663
+ continue
664
+ if mod not in seen:
665
+ seen.add(mod)
666
+ tops.append(mod)
667
+ # Prefer a specific module name over a generic ``environment`` shim if both ship one.
668
+ tops.sort(key=lambda m: m == "environment")
669
+ for mod in tops:
670
+ try:
671
+ real = importlib.import_module(mod)
672
+ except Exception:
673
+ continue
674
+ if hasattr(real, "load_environment"):
675
+ _sys.modules.setdefault(expected, real)
676
+ return
677
+
678
+
679
+ def load_verifiers_environment(
680
+ env_id: str,
681
+ eval_env_id: str | None = None,
682
+ eval_examples: int | None = None,
683
+ eval_seed: int = 12345,
684
+ **kwargs,
685
+ ) -> VerifiersEnvironment:
686
+ """Load an installed / Hub verifiers environment by id and wrap it for AutoSLM.
687
+
688
+ ``env_id`` may be a Hub slug (``owner/name``); it is mapped to the bare verifiers load id.
689
+ Pass ``eval_env_id`` to evaluate on a *different* Hub env, with ``eval_examples`` /
690
+ ``eval_seed`` selecting a fixed eval subset. Remaining ``kwargs`` are forwarded to the train
691
+ env's ``vf.load_environment``.
692
+ """
693
+ vf = _import_vf()
694
+ _ensure_hub_module_importable(vf_load_id(env_id))
695
+ vf_env = vf.load_environment(vf_load_id(env_id), **_drop_reserved_kwargs(kwargs))
696
+ eval_ref = eval_env_id
697
+ if eval_ref:
698
+ _ensure_hub_module_importable(vf_load_id(eval_ref))
699
+ eval_vf_env = vf.load_environment(vf_load_id(eval_ref)) if eval_ref else None
700
+ return VerifiersEnvironment(
701
+ vf_env,
702
+ env_id,
703
+ eval_vf_env=eval_vf_env,
704
+ eval_examples=eval_examples,
705
+ eval_seed=eval_seed,
706
+ )
code/autoslm/envs/base.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small, serializable environment interface for SFT/RL jobs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Protocol
7
+
8
+
9
+ class Environment(Protocol):
10
+ id: str
11
+
12
+ def dataset(self, split: str) -> list[dict]:
13
+ """Return the rows for ``split`` (e.g. ``"train"``)."""
14
+
15
+ def prompt_messages(self, example: dict) -> list[dict]:
16
+ """Chat messages fed to the model for one example."""
17
+
18
+ def sft_target(self, example: dict) -> str:
19
+ """Assistant target text for an SFT example."""
20
+
21
+ def reward(self, completion: str, example: dict, state: dict | None = None) -> float:
22
+ """Scalar RL reward for a completion."""
23
+
24
+ def grade(self, completion: str, example: dict, state: dict | None = None) -> bool:
25
+ """Boolean correctness scorer the reward can build on."""
26
+
27
+
28
+ @dataclass
29
+ class BaseEnvironment:
30
+ id: str
31
+
32
+ def dataset(self, split: str) -> list[dict]:
33
+ raise NotImplementedError
34
+
35
+ def prompt_messages(self, example: dict) -> list[dict]:
36
+ question = example.get("question") or example.get("prompt") or ""
37
+ return [{"role": "user", "content": question}]
38
+
39
+ def sft_target(self, example: dict) -> str:
40
+ return str(example.get("target") or example.get("answer") or "")
41
+
42
+ def reward(self, completion: str, example: dict, state: dict | None = None) -> float:
43
+ return 1.0 if self.grade(completion, example, state) else 0.0
44
+
45
+ def grade(self, completion: str, example: dict, state: dict | None = None) -> bool:
46
+ gold = str(example.get("gold") or example.get("answer") or "").strip()
47
+ # A missing/empty gold must NOT grade every completion correct (`"" in x` is
48
+ # always True) — treat it as unscorable -> incorrect.
49
+ return bool(gold) and gold in (completion or "")
code/autoslm/envs/registry.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Environment registry used by specs, worker, CLI, and server.
2
+
3
+ Verifiers-only: every environment is a Prime Intellect ``verifiers`` env. There are no
4
+ built-in task environments and no local-file environment mode (``schema.py`` rejects a
5
+ ``path`` key outright). ``load_environment`` resolves a single source: an installed /
6
+ Prime Hub verifiers env referenced by its slug (``env_id``, ``owner/name``), resolvable
7
+ by ``verifiers`` (installed via ``slm env install owner/name`` and recorded in the
8
+ manifest below).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import contextlib
14
+ import json
15
+ import os
16
+ from pathlib import Path
17
+
18
+ from .base import Environment
19
+
20
+ # Manifest of installed verifiers / Prime Hub environments (written by `slm env install`).
21
+ INSTALLED_MANIFEST = Path(
22
+ os.environ.get("AUTOSLM_ENVS_MANIFEST", str(Path.home() / ".autoslm" / "envs.json"))
23
+ )
24
+
25
+
26
+ def load_installed_manifest() -> dict:
27
+ try:
28
+ return json.loads(INSTALLED_MANIFEST.read_text())
29
+ except (OSError, ValueError):
30
+ return {}
31
+
32
+
33
+ def list_installed_verifiers_envs() -> list[str]:
34
+ """Names of verifiers/Hub environments installed via `slm env install`."""
35
+ return sorted(load_installed_manifest())
36
+
37
+
38
+ def record_installed_env(env_id: str, package: str, extras: dict | None = None) -> None:
39
+ manifest = load_installed_manifest()
40
+ manifest[env_id] = {"package": package, **(extras or {})}
41
+ INSTALLED_MANIFEST.parent.mkdir(parents=True, exist_ok=True)
42
+ # The manifest can hold a credentialed --extra-index-url. Create/truncate with 0600
43
+ # from the start (not write_text + chmod, which leaves it umask-readable in between);
44
+ # O_NOFOLLOW refuses a symlink planted at the path. chmod after covers a pre-existing
45
+ # file created before this code path.
46
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0)
47
+ fd = os.open(INSTALLED_MANIFEST, flags, 0o600)
48
+ with os.fdopen(fd, "w") as f:
49
+ json.dump(manifest, f, indent=2, sort_keys=True)
50
+ with contextlib.suppress(OSError):
51
+ os.chmod(INSTALLED_MANIFEST, 0o600)
52
+
53
+
54
+ def _bare_wheel_name(env_ref: str) -> str:
55
+ """``owner/name`` Hub slug -> the bare pip wheel name (``name``)."""
56
+ return env_ref.split("/", 1)[1] if "/" in env_ref else env_ref
57
+
58
+
59
+ def worker_pip_for_env(env_id: str) -> list[str]:
60
+ """Pip deps the GPU worker needs to run ``env_id`` (a verifiers/Hub env): just ``verifiers``.
61
+
62
+ The environment itself (and any separate eval env) is installed on the worker via the
63
+ authenticated ``prime env install`` (see :func:`worker_hub_env_ids`), not pip — the public
64
+ pip index does not serve private env wheels. Override with ``[environment] pip`` if a run
65
+ needs extra packages.
66
+ """
67
+ return ["verifiers"]
68
+
69
+
70
+ def worker_hub_env_ids(env_id: str, params: dict | None = None) -> list[str]:
71
+ """The Prime Hub env ids the worker must ``prime env install`` for this run.
72
+
73
+ The training env plus a separate **eval** Hub env (``[environment.params] eval_env_id``)
74
+ when configured. ``prime env install`` is authenticated by ``PRIME_API_KEY`` and installs
75
+ public and private envs alike.
76
+ """
77
+ params = params or {}
78
+ ids = [env_id, params.get("eval_env_id")]
79
+ return list(dict.fromkeys(str(i) for i in ids if i))
80
+
81
+
82
+ def load_environment(env_id: str, params: dict | None = None) -> Environment:
83
+ """Load a verifiers environment and wrap it in AutoSLM's protocol.
84
+
85
+ ``env_id`` is resolved as an installed / Prime Hub verifiers env slug.
86
+ """
87
+ params = params or {}
88
+ from .adapter import load_verifiers_environment
89
+
90
+ if not env_id:
91
+ raise ValueError(
92
+ "no environment specified: set [environment] id to a verifiers/Prime Hub env "
93
+ "slug (e.g. 'owner/name')"
94
+ )
95
+ return load_verifiers_environment(env_id, **params)
code/autoslm/mcp/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """MCP integration package."""
code/autoslm/mcp/server.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Minimal stdio MCP-style bridge for coding agents.
2
+
3
+ This intentionally avoids a hard dependency on a specific MCP SDK while exposing
4
+ the stable JSON tools that agents need. Requests are newline-delimited JSON:
5
+ {"tool": "list_models", "args": {...}}.
6
+
7
+ Run-lifecycle tools call the managed AutoSLM control plane with the same stored
8
+ credentials as the CLI (`slm login`); dry-run validation stays local.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import sys
15
+ from collections.abc import Callable
16
+
17
+ from autoslm.catalog import public_model_rows
18
+ from autoslm.client import client_from_config
19
+ from autoslm.client.specs import spec_payload
20
+ from autoslm.schema import spec_from_dict
21
+
22
+
23
+ def list_models(args: dict) -> dict:
24
+ return {"models": public_model_rows()}
25
+
26
+
27
+ def create_train_run(args: dict) -> dict:
28
+ spec = spec_from_dict(args, run_id=args.get("run_id"))
29
+ if args.get("dry_run"):
30
+ # Fully local: validate without credentials, a server, or a GPU.
31
+ return {"run_id": spec.run_id, "state": "dry_run", "spec": spec.to_dict()}
32
+ return client_from_config().create_run(spec_payload(spec))
33
+
34
+
35
+ def get_run_status(args: dict) -> dict:
36
+ return client_from_config().get_run(args["run_id"])
37
+
38
+
39
+ def get_run_logs(args: dict) -> dict:
40
+ page = client_from_config().get_logs(args["run_id"], offset=int(args.get("offset", 0)))
41
+ return {"run_id": args["run_id"], **{k: page[k] for k in ("logs", "offset", "state")}}
42
+
43
+
44
+ def deploy_adapter_tool(args: dict) -> dict:
45
+ return client_from_config().deploy(
46
+ args["run_id"],
47
+ mode=args.get("mode", "dev"),
48
+ idle_timeout_s=int(args.get("idle_timeout_s", 300)),
49
+ dry_run=bool(args.get("dry_run", False)),
50
+ )
51
+
52
+
53
+ TOOLS: dict[str, Callable[[dict], dict]] = {
54
+ "list_models": list_models,
55
+ "create_training_run": create_train_run,
56
+ "get_run_status": get_run_status,
57
+ "get_run_logs": get_run_logs,
58
+ "deploy_adapter": deploy_adapter_tool,
59
+ }
60
+
61
+
62
+ def handle(payload: dict) -> dict:
63
+ tool = payload.get("tool")
64
+ if tool not in TOOLS:
65
+ raise ValueError(f"unknown tool {tool!r}; choose one of {sorted(TOOLS)}")
66
+ return TOOLS[tool](payload.get("args") or {})
67
+
68
+
69
+ def main() -> int:
70
+ for line in sys.stdin:
71
+ try:
72
+ line = line.strip()
73
+ if not line:
74
+ continue
75
+ response = {"ok": True, "result": handle(json.loads(line))}
76
+ except Exception as exc:
77
+ response = {"ok": False, "error": str(exc)}
78
+ print(json.dumps(response), flush=True)
79
+ return 0
80
+
81
+
82
+ if __name__ == "__main__":
83
+ raise SystemExit(main())
code/autoslm/providers/__init__.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pluggable GPU substrates (RunPod Flash + Vast.ai verified datacenters).
2
+
3
+ The training worker (``autoslm.engine.worker``) is substrate-neutral — it reads a
4
+ JobSpec from the environment, pulls code from the HF dataset repo, and streams
5
+ artifacts/heartbeats/metrics back to it. Providers differ only in HOW a GPU is priced,
6
+ provisioned, and torn down. Every provider implements the SAME ``base.Provider``
7
+ protocol — that protocol, not the file set, is what makes them interchangeable — and
8
+ each shares a broadly similar module layout (``providers/<name>/{api,auth,pricing,
9
+ gpus,jobs,train,preflight}.py``), with provider-specific additions where needed (e.g.
10
+ ``vast/_bootstrap.py``, which has no RunPod analog):
11
+
12
+ runpod serverless Flash endpoints (the original substrate)
13
+ vast verified-datacenter instances (REST only)
14
+
15
+ This module is the registry: ``get_provider(name)`` / ``PROVIDER_NAMES``.
16
+ ``allocator.allocate`` is the cross-provider "cheapest GPU that fits" policy that
17
+ iterates every registered provider.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from functools import cache
23
+
24
+ from autoslm.providers.base import Provider
25
+
26
+ # Registry order is also the tie-break preference (runpod is the longest-validated
27
+ # substrate, so an equal-priced tie prefers it — see allocator.py).
28
+ PROVIDER_NAMES: tuple[str, ...] = ("runpod", "vast")
29
+
30
+
31
+ def get_provider(name: str) -> Provider:
32
+ """The ``Provider`` singleton for a registered name (raises on unknown)."""
33
+ # Normalize BEFORE the cache so "RunPod"/"runpod"/" runpod " share one cache entry.
34
+ return _get_provider((name or "").strip().lower())
35
+
36
+
37
+ @cache
38
+ def _get_provider(key: str) -> Provider:
39
+ if key == "runpod":
40
+ from autoslm.providers.runpod import PROVIDER
41
+
42
+ return PROVIDER
43
+ if key == "vast":
44
+ from autoslm.providers.vast import PROVIDER
45
+
46
+ return PROVIDER
47
+ raise KeyError(f"unknown provider {key!r} (known: {', '.join(PROVIDER_NAMES)})")
48
+
49
+
50
+ def available_providers() -> tuple[str, ...]:
51
+ """Provider NAMES usable from this control plane right now: a provider is available when it
52
+ ``is_configured()`` (creds present + net path). RunPod is the always-on default; Vast needs
53
+ ``VAST_API_KEY`` (and AUTOSLM_SKIP_NET disables both live paths, keeping offline allocation
54
+ deterministic)."""
55
+ return tuple(n for n in PROVIDER_NAMES if get_provider(n).is_configured())
56
+
57
+
58
+ def configured_providers() -> list[Provider]:
59
+ """The ``Provider`` objects available right now (see ``available_providers``)."""
60
+ return [get_provider(n) for n in available_providers()]
code/autoslm/providers/_http.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared stdlib REST client for the provider API modules.
2
+
3
+ Both ``providers/runpod/api.py`` and ``providers/vast/api.py`` are thin, no-SDK-state
4
+ clients with the SAME hardened-retry shape: a Bearer/Content-Type urllib request, a
5
+ jittered exponential backoff that retries 5xx/429 and fast-fails other 4xx with the
6
+ response body as the actionable detail, and a "failed after N attempts" raise. They
7
+ differ only in: the env var that holds the key, the error class, and whether the caller
8
+ passes a full URL (RunPod) or a path joined onto a base (Vast). This module factors that
9
+ common core out so the backoff math lives in one place.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import contextlib
15
+ import json
16
+ import os
17
+ import random
18
+ import time
19
+ import urllib.error
20
+ import urllib.request
21
+ from typing import Any
22
+
23
+
24
+ class RestClient:
25
+ """Parametrized urllib REST client with jittered-backoff retries.
26
+
27
+ ``base_url`` is prefixed onto the ``target`` passed to each call (empty for the
28
+ RunPod client, which passes full URLs; the Vast base for the Vast client). The key
29
+ is read from ``env_var`` on each request (env-only by design — never persisted) and
30
+ failures raise ``error_cls``.
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ *,
36
+ env_var: str,
37
+ error_cls: type[Exception],
38
+ base_url: str = "",
39
+ missing_key_message: str | None = None,
40
+ ) -> None:
41
+ self.env_var = env_var
42
+ self.error_cls = error_cls
43
+ self.base_url = base_url
44
+ self.missing_key_message = (
45
+ missing_key_message or f"{env_var} not configured on the control-plane host"
46
+ )
47
+
48
+ def api_key(self) -> str:
49
+ key = os.environ.get(self.env_var)
50
+ if not key:
51
+ raise self.error_cls(self.missing_key_message)
52
+ return key
53
+
54
+ def request(
55
+ self, target: str, method: str = "GET", body: dict | None = None, timeout: float = 30.0
56
+ ) -> Any:
57
+ req = urllib.request.Request(
58
+ f"{self.base_url}{target}",
59
+ method=method,
60
+ data=json.dumps(body).encode() if body is not None else None,
61
+ headers={
62
+ "Authorization": f"Bearer {self.api_key()}",
63
+ "Content-Type": "application/json",
64
+ },
65
+ )
66
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
67
+ raw = resp.read()
68
+ return json.loads(raw) if raw else {}
69
+
70
+ def request_with_retries(
71
+ self,
72
+ target: str,
73
+ method: str = "GET",
74
+ body: dict | None = None,
75
+ retries: int = 4,
76
+ base_delay: float = 2.0,
77
+ ) -> Any:
78
+ """REST call hardened against transient network/5xx blips (jittered backoff)."""
79
+ last: Exception | None = None
80
+ for attempt in range(retries + 1):
81
+ try:
82
+ return self.request(target, method=method, body=body)
83
+ except urllib.error.HTTPError as e:
84
+ if e.code < 500 and e.code != 429:
85
+ # The response body usually carries the actionable error detail; e.reason
86
+ # alone (e.g. "Bad Request") is rarely enough to debug a 4xx.
87
+ detail = ""
88
+ with contextlib.suppress(Exception):
89
+ detail = e.read().decode("utf-8", "replace")[:500].strip()
90
+ suffix = f": {detail}" if detail else ""
91
+ raise self.error_cls(
92
+ f"{method} {target} -> HTTP {e.code}: {e.reason}{suffix}"
93
+ ) from e
94
+ last = e
95
+ except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as e:
96
+ last = e
97
+ if attempt < retries:
98
+ delay = min(base_delay * (2 ** min(attempt, 6)), 30.0)
99
+ time.sleep(delay * random.uniform(0.7, 1.3))
100
+ raise self.error_cls(f"{method} {target} failed after {retries + 1} attempts: {last}")
code/autoslm/providers/_poll.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared poll-loop scaffolding for the provider job pollers.
2
+
3
+ ``runpod/jobs.py:poll_job`` and ``vast/jobs.py:poll_vast_job`` are independent live
4
+ poll loops with provider-specific terminal-state logic, but they share three verbatim
5
+ blocks: a timestamped ``say()`` logger, a consecutive-poll-error retry/give-up counter,
6
+ and the heartbeat progress-surfacing block (key on (stage, step, ts), log
7
+ ``worker: stage=… step=… reward=…``). Only those provider-neutral pieces live here; each
8
+ poller keeps its own status/terminal handling inline.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import time
14
+ from collections.abc import Callable
15
+ from typing import Any
16
+
17
+
18
+ def make_say(log) -> Callable[[str], None]:
19
+ """A timestamped line logger that no-ops when ``log`` is None."""
20
+
21
+ def say(msg: str) -> None:
22
+ if log is not None:
23
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", file=log, flush=True)
24
+
25
+ return say
26
+
27
+
28
+ class PollErrorTracker:
29
+ """Counts consecutive poll errors and decides when to give up.
30
+
31
+ Encapsulates the identical retry block both pollers use: on a transient fetch
32
+ error, log it, give up after ``max_errors`` consecutive failures, otherwise sleep
33
+ a linear backoff (capped at 60 s) before the caller retries.
34
+ """
35
+
36
+ def __init__(self, say: Callable[[str], None], interval_s: float, max_errors: int = 8) -> None:
37
+ self._say = say
38
+ self._interval_s = interval_s
39
+ self._max_errors = max_errors
40
+ self._count = 0
41
+
42
+ def reset(self) -> None:
43
+ self._count = 0
44
+
45
+ def record(self, exc: Exception) -> bool:
46
+ """Register a poll error. Returns True if the caller should give up (too many),
47
+ else sleeps the backoff and returns False (caller should ``continue``)."""
48
+ self._count += 1
49
+ self._say(f"poll error ({self._count}): {exc}")
50
+ if self._count >= self._max_errors:
51
+ return True
52
+ time.sleep(min(60, self._interval_s * self._count))
53
+ return False
54
+
55
+
56
+ def surface_heartbeat(
57
+ heartbeat_reader: Callable[[], Any] | None,
58
+ last_hb_key: tuple | None,
59
+ say: Callable[[str], None],
60
+ ) -> tuple[tuple | None, str | None]:
61
+ """Read a heartbeat and, if it advanced, log worker progress.
62
+
63
+ Returns ``(hb_key, stage)`` where ``hb_key`` is the new (stage, step, ts) key (or the
64
+ unchanged ``last_hb_key`` when nothing advanced) and ``stage`` is the stage of the new
65
+ heartbeat when it advanced (else None). Callers use the returned ``stage`` for their
66
+ own setup-vs-training stall bookkeeping.
67
+ """
68
+ if heartbeat_reader is None:
69
+ return last_hb_key, None
70
+ try:
71
+ hb = heartbeat_reader()
72
+ except Exception:
73
+ hb = None
74
+ if not hb:
75
+ return last_hb_key, None
76
+ key = (hb.get("stage"), hb.get("step"), hb.get("ts"))
77
+ if key == last_hb_key:
78
+ return last_hb_key, None
79
+ stage = hb.get("stage")
80
+ step = hb.get("step")
81
+ reward = hb.get("reward")
82
+ say(
83
+ f"worker: stage={stage}"
84
+ + (f" step={step}" if step is not None else "")
85
+ + (f" reward={reward:.3f}" if isinstance(reward, (int, float)) else "")
86
+ )
87
+ return key, stage
code/autoslm/providers/allocator.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cross-provider GPU allocation: the cheapest class that comfortably fits the run.
2
+
3
+ Given a base model (+ algorithm), compute the VRAM the FULL run needs — sized for the
4
+ heavier phase, GRPO, since the typical pipeline is SFT followed by GRPO — then rank
5
+ every provisionable candidate across ALL registered providers by live $/hr and pick the
6
+ cheapest:
7
+
8
+ runpod every Flash-provisionable class (live pricing, cached; static fallback)
9
+ vast live verified-datacenter offers (usable_offers' quality floors applied)
10
+
11
+ Allocation happens at SUBMIT time in the runner (offers are a volatile market);
12
+ the parse-time resolution in schema is a RunPod-static provisional for
13
+ validation/dry-run display. Offline (AUTOSLM_SKIP_NET) the allocator degrades to exactly
14
+ ``cheapest_gpu``'s deterministic static-rate answer (RunPod only — Vast is offline-off).
15
+
16
+ Provider-agnostic by construction: it walks the registered providers and asks each for
17
+ its ``gpu_classes()`` + ``hourly_rate()``; the only provider-specific knowledge is that
18
+ Vast classes come from a live offer book (collected through the provider's
19
+ ``usable_offers`` and carried opaquely on ``Candidate.offer``).
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from autoslm._logging import get_logger
25
+ from autoslm.providers import PROVIDER_NAMES, available_providers, get_provider
26
+ from autoslm.providers.base import (
27
+ Allocation,
28
+ Candidate,
29
+ UnsupportedGpuError,
30
+ canonical_gpu,
31
+ unvalidated_allowed,
32
+ )
33
+
34
+ logger = get_logger(__name__)
35
+
36
+ # "Comfortably" = the open-model VRAM estimate plus headroom, so a full SFT+GRPO run
37
+ # never lands in check_fit's "tight" band by construction. Curated catalog entries
38
+ # already carry measured minimums and are used as-is. The headroom (default 1.1 ==
39
+ # model_required_vram_gb's own default) is read at call time via vram_headroom() so allocate()
40
+ # and resolve_gpu_policy size identically and pick up a value exported after import.
41
+
42
+
43
+ def vram_headroom() -> float:
44
+ """The sizing headroom multiplier, honored by both the submit-time allocator and the
45
+ parse-time resolve_gpu_policy so they never disagree (PR #176 review). A validated constant."""
46
+ return 1.1
47
+
48
+
49
+ def required_vram_gb(
50
+ model_id: str,
51
+ algorithm: str,
52
+ *,
53
+ train=None,
54
+ thinking: bool = False,
55
+ ) -> int:
56
+ """VRAM the full run needs, sized to the run's actual knobs (context length, LoRA
57
+ rank, batch / group size, thinking) via the shared ``model_required_vram_gb`` matrix.
58
+
59
+ Catalog GRPO floors stay hard floors (never under-provision a validated model); the
60
+ matrix sizes up from there for big contexts/groups and down to a cheaper card for
61
+ small runs. Unlisted open models size from HF metadata, falling back to the 24 GB tier
62
+ when unreadable (handled inside model_required_vram_gb)."""
63
+ from autoslm.engine.vram import model_required_vram_gb
64
+
65
+ return model_required_vram_gb(
66
+ model_id,
67
+ algorithm,
68
+ train=train,
69
+ thinking=thinking,
70
+ headroom=vram_headroom(),
71
+ )
72
+
73
+
74
+ def _runpod_candidates(need: int, pinned_gpu: str | None, allow_unval: bool) -> list[Candidate]:
75
+ """RunPod's fitting classes priced live (static fallback)."""
76
+ provider = get_provider("runpod")
77
+ out: list[Candidate] = []
78
+ for g in provider.gpu_classes():
79
+ if g.vram_gb < need:
80
+ continue
81
+ if pinned_gpu and g.name != pinned_gpu:
82
+ continue
83
+ if "runpod" not in g.validated_on and not allow_unval:
84
+ continue
85
+ out.append(
86
+ Candidate(
87
+ "runpod",
88
+ g.name,
89
+ provider.hourly_rate(g.name),
90
+ g.vram_gb,
91
+ "runpod" in g.validated_on,
92
+ )
93
+ )
94
+ return out
95
+
96
+
97
+ def _vast_candidates(
98
+ need: int,
99
+ pinned_gpu: str | None,
100
+ allow_unval: bool,
101
+ disk_gb: int,
102
+ exclude_machine_ids,
103
+ *,
104
+ required: bool,
105
+ ) -> tuple[list[Candidate], tuple]:
106
+ """Vast's fitting classes from the live offer book (cheapest per class).
107
+
108
+ Returns (candidates, full_offer_book). ``required`` (a hard ``provider="vast"``
109
+ pin) re-raises a search failure; otherwise it degrades to RunPod-only.
110
+ """
111
+ from autoslm.providers.base import GPU_INFO
112
+ from autoslm.providers.vast.jobs import MIN_DISK_GB, usable_offers
113
+
114
+ # When a larger class is pinned for a small model, search at the PINNED class's VRAM,
115
+ # not the (smaller) model requirement: the offer search returns the cheapest ``limit``
116
+ # offers from a VRAM floor, so a search at ``need`` can fill that window entirely with
117
+ # small cheap cards and never surface the pinned larger class. ``need`` is still the
118
+ # validity floor (allocate() rejects an undersized pin before we get here).
119
+ search_vram = max(need, GPU_INFO[pinned_gpu].vram_gb) if pinned_gpu else need
120
+ book: list = []
121
+ try:
122
+ # The offer search must use the SAME disk floor instances are actually
123
+ # provisioned with (``create_instance``/``_effective_disk_gb``); searching at a
124
+ # smaller requested ``disk_gb`` would surface offers that then fail to rent.
125
+ book = usable_offers(
126
+ search_vram, max(float(disk_gb), MIN_DISK_GB), exclude_machine_ids=exclude_machine_ids
127
+ )
128
+ except Exception as exc:
129
+ if required:
130
+ raise UnsupportedGpuError(f"vast offer search failed: {exc}") from exc
131
+ logger.warning("vast offer search failed (%s); allocating on runpod only", exc)
132
+ out: list[Candidate] = []
133
+ seen: set[str] = set()
134
+ for o in book:
135
+ if pinned_gpu and o.gpu != pinned_gpu:
136
+ continue
137
+ info = GPU_INFO[o.gpu]
138
+ if "vast" not in info.validated_on and not allow_unval:
139
+ continue
140
+ if o.gpu in seen: # offers are price-sorted; keep the cheapest per class
141
+ continue
142
+ seen.add(o.gpu)
143
+ out.append(
144
+ Candidate(
145
+ "vast", o.gpu, o.dph_total, info.vram_gb, "vast" in info.validated_on, offer=o
146
+ )
147
+ )
148
+ return out, tuple(book)
149
+
150
+
151
+ def allocate(
152
+ model_id: str,
153
+ algorithm: str,
154
+ *,
155
+ gpu: str | None = None,
156
+ provider: str = "auto",
157
+ disk_gb: int = 60,
158
+ allow_unvalidated: bool | None = None,
159
+ exclude_machine_ids: set[int] | frozenset[int] = frozenset(),
160
+ train=None,
161
+ thinking: bool = False,
162
+ ) -> Allocation:
163
+ """Pick the cheapest (provider, GPU class) able to run the job across providers.
164
+
165
+ ``gpu`` pins the class (the allocator then only picks the provider); ``provider``
166
+ pins the substrate ("auto"/"runpod"/"vast"). Both default to fully automatic.
167
+ ``train``/``thinking`` size the requirement to the run's actual knobs (context, group,
168
+ rank, batch) via the matrix — long context / large group route up, small runs down.
169
+ """
170
+ if provider not in ("auto", *PROVIDER_NAMES):
171
+ raise UnsupportedGpuError(
172
+ f"unknown provider {provider!r} (auto, {', '.join(PROVIDER_NAMES)})"
173
+ )
174
+ pinned_gpu = canonical_gpu(gpu) if gpu else None
175
+ # The model's requirement is the floor regardless of a pin: an undersized concrete
176
+ # pin (e.g. Qwen3-8B on a 24 GB card) must drop out of the candidate filter and
177
+ # raise here, not provision a paid worker that OOMs. The pin only narrows WHICH
178
+ # fitting class is chosen, never lowers the VRAM bar.
179
+ need = required_vram_gb(model_id, algorithm, train=train, thinking=thinking)
180
+ allow_unval = unvalidated_allowed(allow_unvalidated)
181
+ live = available_providers()
182
+ if provider != "auto" and provider not in live:
183
+ raise UnsupportedGpuError(
184
+ f"provider {provider!r} requested but not available on this control plane "
185
+ f"(available: {', '.join(live) or '(none)'}; vast needs VAST_API_KEY)"
186
+ )
187
+
188
+ def _gather(pin: str | None) -> tuple[list[Candidate], tuple]:
189
+ cands: list[Candidate] = []
190
+ book: tuple = ()
191
+ if provider in ("auto", "runpod") and "runpod" in live:
192
+ cands += _runpod_candidates(need, pin, allow_unval)
193
+ if provider in ("auto", "vast") and "vast" in live:
194
+ vcands, book = _vast_candidates(
195
+ need, pin, allow_unval, disk_gb, exclude_machine_ids, required=(provider == "vast")
196
+ )
197
+ cands += vcands
198
+ return cands, book
199
+
200
+ candidates, offer_book = _gather(pinned_gpu)
201
+ # NEVER hard-fail on availability: a pin that no live provider can serve (the class isn't
202
+ # offered right now, or is below ``need`` so it's filtered out) escalates to the cheapest
203
+ # FITTING class across providers instead of raising -- "one spot larger, and so on". The
204
+ # ``need`` floor is still absolute (we never drop below it -> no OOM), and the pin is only a
205
+ # preference. We only raise when NOTHING >= need is available anywhere (truly unsatisfiable).
206
+ escalated_from = None
207
+ if not candidates and pinned_gpu is not None:
208
+ escalated_from = pinned_gpu
209
+ candidates, offer_book = _gather(None)
210
+ if not candidates:
211
+ raise UnsupportedGpuError(
212
+ f"no allocatable GPU (>= {need} GB VRAM for {model_id}, provider={provider}, "
213
+ f"validated_only={not allow_unval}); widen with gpu.allow_unvalidated = true, add a "
214
+ f"provider (VAST_API_KEY), or the run genuinely exceeds every available GPU class"
215
+ )
216
+ if escalated_from is not None:
217
+ order0 = {n: i for i, n in enumerate(PROVIDER_NAMES)}
218
+ _cheapest = sorted(candidates, key=lambda c: (c.hourly_usd, c.vram_gb, order0.get(c.provider, 99)))[0]
219
+ # WARNING level so it surfaces at default `slm train` verbosity (configure_logging is
220
+ # WARNING) — a silently-escalated pin changes cost/hardware and operators must see it;
221
+ # still routed through the logger (stderr), so machine-readable stdout stays clean.
222
+ logger.warning(
223
+ "pinned GPU %r unavailable or below need (%s GB) on provider=%s; "
224
+ "escalated to cheapest fitting class %s (%s GB, %s)",
225
+ escalated_from,
226
+ need,
227
+ provider,
228
+ _cheapest.gpu,
229
+ _cheapest.vram_gb,
230
+ _cheapest.provider,
231
+ )
232
+ # Cheapest first; equal rates prefer less VRAM (don't burn a big card on a small
233
+ # job), then registry order (runpod is the longest-validated substrate).
234
+ order = {n: i for i, n in enumerate(PROVIDER_NAMES)}
235
+ ranked = sorted(candidates, key=lambda c: (c.hourly_usd, c.vram_gb, order.get(c.provider, 99)))
236
+ best = ranked[0]
237
+ return Allocation(
238
+ provider=best.provider,
239
+ gpu=best.gpu,
240
+ hourly_usd=best.hourly_usd,
241
+ min_vram_gb=need,
242
+ candidates=tuple(ranked),
243
+ offer=best.offer,
244
+ provider_offers=offer_book,
245
+ )
246
+
247
+
248
+ def allocation_summary(a: Allocation) -> str:
249
+ head = (
250
+ f"allocated {a.gpu} on {a.provider} at ${a.hourly_usd:.2f}/hr "
251
+ f"(need >= {a.min_vram_gb} GB VRAM"
252
+ )
253
+ # ``a.offer`` is an OPAQUE per-provider provisioning hint, not necessarily a Vast
254
+ # offer — only format Vast specifics when the chosen provider is vast, so a future
255
+ # provider's hint never misformats or raises on a missing attribute.
256
+ if a.provider == "vast" and a.offer is not None:
257
+ head += f", vast offer {a.offer.offer_id} in {a.offer.geolocation}"
258
+ head += ")"
259
+ if len(a.candidates) > 1:
260
+ nxt = a.candidates[1]
261
+ head += f"; next-best: {nxt.gpu}@{nxt.provider} ${nxt.hourly_usd:.2f}/hr"
262
+ return head
code/autoslm/providers/base.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared GPU-provider interface + the provider-agnostic GPU registry.
2
+
3
+ Both substrates (RunPod Flash, Vast.ai verified datacenters) implement the SAME
4
+ ``Provider`` protocol and expose the SAME module set under ``providers/<name>/`` so a
5
+ provider is pluggable/swappable. This module owns the parts that are NOT provider
6
+ specific:
7
+
8
+ * ``GpuClass`` — one managed GPU class with its per-provider identity
9
+ (``enum_member`` for RunPod, ``vast_name`` for Vast) and per-provider
10
+ ``validated_on``. Each provider owns *which* classes it lists (its ``gpus.py``
11
+ carves its rows out of ``GPU_CLASSES``), but the class table itself is shared so a
12
+ friendly name canonicalizes to one identity everywhere (catalog, config, serving).
13
+ * ``JobHandle`` / ``PollResult`` — the persisted-handle + poll-outcome shapes the
14
+ orchestrator round-trips through any provider.
15
+ * ``Candidate`` / ``Allocation`` — the cross-provider allocation result.
16
+ * The canonicalization / alias / policy helpers every call site already used.
17
+
18
+ The ``Provider`` protocol is the FIXED method set both providers implement; the
19
+ orchestrator dispatches cancel/poll/destroy generically through the persisted
20
+ handle's ``provider`` key. The post-run GC backstop is the deliberate exception:
21
+ RunPod's ``gc`` runs unconditionally (a name-reconstruction backstop for rN-suffixed
22
+ endpoints the persisted handle can't name) and Vast's ``gc`` is called by name only
23
+ when Vast is available (its billing-leak reap), so that path branches per provider.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import os
29
+ from dataclasses import dataclass, field
30
+ from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
31
+
32
+ if TYPE_CHECKING:
33
+ from autoslm.spec import JobSpec
34
+
35
+
36
+ # ---------------------------------------------------------------------------
37
+ # GPU class registry (provider-agnostic identity + per-provider validation)
38
+ # ---------------------------------------------------------------------------
39
+ @dataclass(frozen=True)
40
+ class GpuClass:
41
+ """One managed GPU class: a friendly name + per-provider identity/metadata.
42
+
43
+ Provider-agnostic by design — the identity columns (``enum_member`` for RunPod's
44
+ Flash ``GpuType``; ``vast_name`` for the Vast offer ``gpu_name``) and
45
+ ``validated_on`` carry the per-provider facts, but a class is a single canonical
46
+ row so the catalog / config / serving all agree on what e.g. "RTX 5090" is.
47
+ """
48
+
49
+ name: str # canonical friendly name used in configs / the catalog
50
+ enum_member: str | None # runpod_flash GpuType member name; None -> not on RunPod
51
+ vram_gb: int
52
+ short: str # endpoint-name-safe token (e.g. "4090", "a5000")
53
+ sm: str # CUDA arch (informational; sm80+ only)
54
+ hourly_usd: float # static fallback rate; live pricing overrides (pricing.py)
55
+ # Providers where this class passed AutoSLM's live train+eval smoke. Validation is
56
+ # per-provider: the same silicon behind a different provisioning path (Flash deps
57
+ # install vs a Vast docker image) is a different failure surface.
58
+ validated_on: tuple[str, ...] = ()
59
+ # Min host CUDA (driver) on the modern stack. None -> 12.8. Blackwell (sm120/sm100)
60
+ # needs CUDA-13 drivers to JIT the wheels' PTX (no SASS shipped).
61
+ min_cuda_modern: str | None = None
62
+ # Vast.ai offer ``gpu_name`` for this class; None -> not provisionable on Vast.
63
+ # A100 SXM4 boards exist in 40 GB and 80 GB variants under ONE Vast name — offers
64
+ # are disambiguated by ``gpu_ram`` (see ``vast_gpu_for_offer``).
65
+ vast_name: str | None = None
66
+
67
+ @property
68
+ def validated(self) -> bool: # validated on ANY provider
69
+ return bool(self.validated_on)
70
+
71
+
72
+ # Fallback hourly rates are RunPod secure-cloud on-demand (snapshot 2026-06-11); live
73
+ # rates from the provider pricing module override them. Vast-only classes
74
+ # (enum_member=None) carry a Vast verified-datacenter snapshot instead.
75
+ GPU_CLASSES: tuple[GpuClass, ...] = (
76
+ # ---- validated: passed the full train+eval matrix (bench/results/phase1) ----
77
+ GpuClass(
78
+ "RTX 4090",
79
+ "NVIDIA_GEFORCE_RTX_4090",
80
+ 24,
81
+ "4090",
82
+ "sm89",
83
+ 0.69,
84
+ validated_on=("runpod",),
85
+ vast_name="RTX 4090",
86
+ ),
87
+ # Vast-validated 2026-06-12: Qwen3-0.6B SFT train+eval smoke on a verified
88
+ # datacenter ($0.60/hr South Korea), incl. vLLM eval on a CUDA-13 driver.
89
+ GpuClass(
90
+ "RTX 5090",
91
+ "NVIDIA_GEFORCE_RTX_5090",
92
+ 32,
93
+ "5090",
94
+ "sm120",
95
+ 0.99,
96
+ validated_on=("runpod", "vast"),
97
+ min_cuda_modern="13.0",
98
+ vast_name="RTX 5090",
99
+ ),
100
+ # ---- Ampere/Ada workstation + datacenter cards (cheap capacity pools) ----
101
+ GpuClass("RTX A4000", "NVIDIA_RTX_A4000", 16, "a4000", "sm86", 0.25, vast_name="RTX A4000"),
102
+ GpuClass(
103
+ "RTX 2000 Ada",
104
+ "NVIDIA_RTX_2000_ADA_GENERATION",
105
+ 16,
106
+ "2000ada",
107
+ "sm89",
108
+ 0.24,
109
+ vast_name="RTX 2000Ada",
110
+ ),
111
+ GpuClass("RTX A4500", "NVIDIA_RTX_A4500", 20, "a4500", "sm86", 0.25, vast_name="RTX A4500"),
112
+ GpuClass(
113
+ "RTX 4000 Ada",
114
+ "NVIDIA_RTX_4000_ADA_GENERATION",
115
+ 20,
116
+ "4000ada",
117
+ "sm89",
118
+ 0.26,
119
+ vast_name="RTX 4000Ada",
120
+ ),
121
+ # Validated 2026-06-11: Qwen3-0.6B SFT + GRPO smokes passed — cheapest 24 GB class.
122
+ GpuClass(
123
+ "RTX A5000",
124
+ "NVIDIA_RTX_A5000",
125
+ 24,
126
+ "a5000",
127
+ "sm86",
128
+ 0.27,
129
+ validated_on=("runpod",),
130
+ vast_name="RTX A5000",
131
+ ),
132
+ # Vast-validated 2026-06-12: Qwen3-0.6B SFT train+eval smoke ($0.25/hr Czechia).
133
+ GpuClass(
134
+ "RTX 3090",
135
+ "NVIDIA_GEFORCE_RTX_3090",
136
+ 24,
137
+ "3090",
138
+ "sm86",
139
+ 0.46,
140
+ validated_on=("vast",),
141
+ vast_name="RTX 3090",
142
+ ),
143
+ GpuClass("L4", "NVIDIA_L4", 24, "l4", "sm89", 0.39, vast_name="L4"),
144
+ # Blackwell workstation card; cheap verified-datacenter capacity on Vast.
145
+ # Vast-validated 2026-06-12: Qwen3-0.6B SFT train+eval smoke incl. vLLM eval on a
146
+ # CUDA-13 driver with the cu128 stack image ($0.34/hr Hungary). Vast-only.
147
+ GpuClass(
148
+ "RTX Pro 4000",
149
+ None,
150
+ 24,
151
+ "pro4000",
152
+ "sm120",
153
+ 0.34,
154
+ validated_on=("vast",),
155
+ min_cuda_modern="13.0",
156
+ vast_name="RTX PRO 4000",
157
+ ),
158
+ GpuClass("RTX A6000", "NVIDIA_RTX_A6000", 48, "a6000", "sm86", 0.49, vast_name="RTX A6000"),
159
+ GpuClass("A40", "NVIDIA_A40", 48, "a40", "sm86", 0.44, vast_name="A40"),
160
+ GpuClass(
161
+ "RTX 6000 Ada",
162
+ "NVIDIA_RTX_6000_ADA_GENERATION",
163
+ 48,
164
+ "6000ada",
165
+ "sm89",
166
+ 0.77,
167
+ vast_name="RTX 6000Ada",
168
+ ),
169
+ # L40S exists at RunPod but not in the Flash SDK's GpuType enum -> Vast-only.
170
+ GpuClass("L40S", None, 48, "l40s", "sm89", 0.87, vast_name="L40S"),
171
+ # ---- big-VRAM tier (large-MoE QLoRA, future >9B bf16) ----
172
+ # 40 GB SXM4 boards share Vast's "A100 SXM4" name with the 80 GB variant; offers
173
+ # are split by gpu_ram (vast_gpu_for_offer). Not a RunPod Flash class -> Vast-only.
174
+ GpuClass("A100 SXM 40GB", None, 40, "a100sxm40", "sm80", 0.89, vast_name="A100 SXM4"),
175
+ # Validated 2026-06-11: 0.6B SFT smoke (phase6).
176
+ GpuClass(
177
+ "A100 PCIe",
178
+ "NVIDIA_A100_80GB_PCIe",
179
+ 80,
180
+ "a100pcie",
181
+ "sm80",
182
+ 1.39,
183
+ validated_on=("runpod",),
184
+ vast_name="A100 PCIE",
185
+ ),
186
+ GpuClass(
187
+ "A100 SXM", "NVIDIA_A100_SXM4_80GB", 80, "a100sxm", "sm80", 1.49, vast_name="A100 SXM4"
188
+ ),
189
+ GpuClass("H100", "NVIDIA_H100_80GB_HBM3", 80, "h100", "sm90", 3.29, vast_name="H100 SXM"),
190
+ # H100 NVL (94 GB) has no RunPod Flash GpuType member -> Vast-only. Cheaper than the
191
+ # 80 GB SXM H100 on the live market and carries 14 GB more VRAM, so it's a strong
192
+ # cost/VRAM pick for big-context GRPO tiers.
193
+ GpuClass(
194
+ "H100 NVL", None, 94, "h100nvl", "sm90", 2.39, validated_on=("vast",), vast_name="H100 NVL"
195
+ ),
196
+ GpuClass(
197
+ "RTX Pro 6000",
198
+ "NVIDIA_RTX_PRO_6000_BLACKWELL_SERVER_EDITION",
199
+ 96,
200
+ "pro6000",
201
+ "sm120",
202
+ 2.09,
203
+ min_cuda_modern="13.0",
204
+ ),
205
+ # RTX Pro 6000 Blackwell Workstation Edition: same 96 GB die as the Server Edition,
206
+ # a distinct RunPod GpuType, typically a touch cheaper. Also offered on Vast. The
207
+ # single biggest non-datacenter 96 GB option -> cheapest 80 GB-floor GRPO host.
208
+ GpuClass(
209
+ "RTX Pro 6000 WK",
210
+ "NVIDIA_RTX_PRO_6000_BLACKWELL_WORKSTATION_EDITION",
211
+ 96,
212
+ "pro6000wk",
213
+ "sm120",
214
+ 1.79,
215
+ validated_on=("runpod", "vast"),
216
+ min_cuda_modern="13.0",
217
+ vast_name="RTX PRO 6000",
218
+ ),
219
+ )
220
+
221
+ GPU_INFO: dict[str, GpuClass] = {g.name: g for g in GPU_CLASSES}
222
+
223
+ # Canonical friendly names AutoSLM exposes in configs / the catalog.
224
+ KNOWN = tuple(GPU_INFO)
225
+ # Classes proven by a live train+eval smoke (the default selection pool).
226
+ SUPPORTED = tuple(g.name for g in GPU_INFO.values() if g.validated)
227
+
228
+ # GPU-policy keywords accepted in ``gpu.type`` (resolved to a concrete class at parse
229
+ # time by ``resolve_gpu_policy``; the submit-time allocator re-resolves them live).
230
+ POLICY_NAMES = ("cheapest", "auto")
231
+
232
+
233
+ def _alias_keys(name: str) -> set[str]:
234
+ """All accepted spellings of a friendly name (lowercased)."""
235
+ base = name.lower()
236
+ keys = {base, base.replace(" ", ""), base.replace(" ", "_"), base.replace(" ", "-")}
237
+ if base.startswith("rtx "):
238
+ tail = base[4:]
239
+ keys |= {tail, tail.replace(" ", ""), tail.replace(" ", "_")}
240
+ keys.add(f"nvidia {base}")
241
+ return keys
242
+
243
+
244
+ _ALIASES: dict[str, str] = {}
245
+ for _info in GPU_INFO.values():
246
+ for _k in _alias_keys(_info.name):
247
+ _ALIASES[_k] = _info.name
248
+ # Spellings that don't fall out of the generic rules: full marketing names (what
249
+ # nvidia-smi / the RunPod API print) and historical AutoSLM aliases.
250
+ _ALIASES.update(
251
+ {
252
+ "nvidia geforce rtx 4090": "RTX 4090",
253
+ "nvidia geforce rtx 5090": "RTX 5090",
254
+ "nvidia geforce rtx 3090": "RTX 3090",
255
+ "nvidia l4": "L4",
256
+ "nvidia a40": "A40",
257
+ "nvidia rtx 6000 ada generation": "RTX 6000 Ada",
258
+ "rtx 6000 ada generation": "RTX 6000 Ada",
259
+ "nvidia rtx 4000 ada generation": "RTX 4000 Ada",
260
+ "nvidia rtx 2000 ada generation": "RTX 2000 Ada",
261
+ "nvidia a100 80gb pcie": "A100 PCIe",
262
+ "a100 80gb pcie": "A100 PCIe",
263
+ "a100-80g-pcie": "A100 PCIe",
264
+ "nvidia a100-sxm4-80gb": "A100 SXM",
265
+ "a100-sxm4-80gb": "A100 SXM",
266
+ "a100": "A100 PCIe",
267
+ "nvidia h100 80gb hbm3": "H100",
268
+ "h100 80gb hbm3": "H100",
269
+ "rtx pro 6000 blackwell": "RTX Pro 6000",
270
+ "nvidia rtx pro 6000 blackwell server edition": "RTX Pro 6000",
271
+ }
272
+ )
273
+
274
+
275
+ class UnsupportedGpuError(ValueError):
276
+ pass
277
+
278
+
279
+ def canonical_gpu(name: str) -> str:
280
+ """Normalize a friendly GPU name to one of ``KNOWN``; raise otherwise."""
281
+ key = (name or "").strip().lower()
282
+ if key in _ALIASES:
283
+ return _ALIASES[key]
284
+ raise UnsupportedGpuError(
285
+ f'unsupported gpu {name!r}; AutoSLM manages {", ".join(KNOWN)} (or gpu.type = "cheapest")'
286
+ )
287
+
288
+
289
+ def get_gpu_info(name: str) -> GpuClass:
290
+ return GPU_INFO[canonical_gpu(name)]
291
+
292
+
293
+ def is_validated(name: str, provider: str | None = None) -> bool:
294
+ """Validated on ``provider`` (when given) or on any provider (provider=None)."""
295
+ info = get_gpu_info(name)
296
+ if provider is None or provider == "auto":
297
+ return info.validated
298
+ return provider in info.validated_on
299
+
300
+
301
+ def providers_for(name: str) -> tuple[str, ...]:
302
+ """Providers that can provision this GPU class."""
303
+ info = get_gpu_info(name)
304
+ out = []
305
+ if info.enum_member:
306
+ out.append("runpod")
307
+ if info.vast_name:
308
+ out.append("vast")
309
+ return tuple(out)
310
+
311
+
312
+ # Boards under-report usable VRAM vs the class's nominal size (measured live: L4
313
+ # offers carry 23034 MB for the 24 GB class, A40 offers 46068 MB for the 48 GB
314
+ # class — ~3 GB under), so class matching gets a tolerance. Safe at 3.5 GB: names
315
+ # shared across VRAM variants differ by >= 40 GB (A100 SXM4 40/80).
316
+ _VRAM_MATCH_TOLERANCE_GB = 3.5
317
+
318
+
319
+ def vast_gpu_for_offer(gpu_name: str, gpu_ram_mb: float) -> str | None:
320
+ """Map a Vast offer (``gpu_name`` + ``gpu_ram`` MB) to a canonical GPU class.
321
+
322
+ Returns None for anything not in the managed table — that's the hard Ampere+
323
+ floor (T4/2080 Ti/Quadro RTX offers never match). Names shared across VRAM
324
+ variants (A100 SXM4 40/80 GB) resolve to the largest class the board's actual
325
+ RAM covers.
326
+ """
327
+ fitting = [
328
+ g
329
+ for g in GPU_INFO.values()
330
+ if g.vast_name == gpu_name and g.vram_gb <= gpu_ram_mb / 1024 + _VRAM_MATCH_TOLERANCE_GB
331
+ ]
332
+ if not fitting:
333
+ return None
334
+ return max(fitting, key=lambda g: g.vram_gb).name
335
+
336
+
337
+ def unvalidated_allowed(explicit: bool | None = None) -> bool:
338
+ """Whether configs may target a non-``validated`` GPU class."""
339
+ if explicit is not None:
340
+ return explicit
341
+ # Truthy allowlist (not a falsey denylist): only an explicit truthy value opts in, so
342
+ # "false"/"False"/"no"/"off"/"0"/"" all correctly leave unvalidated GPUs disabled.
343
+ return os.environ.get("AUTOSLM_GPU_ALLOW_UNVALIDATED", "").strip().lower() in (
344
+ "1",
345
+ "true",
346
+ "yes",
347
+ "on",
348
+ )
349
+
350
+
351
+ def gpu_short(name: str) -> str:
352
+ """Short, endpoint-name-safe token for a GPU (e.g. '4090')."""
353
+ return get_gpu_info(name).short
354
+
355
+
356
+ def min_cuda_modern(name: str) -> str:
357
+ """Minimum host CUDA (driver) version for this GPU class on the modern stack."""
358
+ return get_gpu_info(name).min_cuda_modern or "12.8"
359
+
360
+
361
+ def cheapest_gpu(min_vram_gb: int, include_unvalidated: bool = False) -> str:
362
+ """Cheapest RunPod GPU class with at least ``min_vram_gb`` VRAM (live rates, cached).
363
+
364
+ RunPod-static by design (the cross-provider equivalent lives in
365
+ ``autoslm.providers.allocator``): Vast-only classes are excluded so the result is
366
+ always deployable via Flash, and offline resolution stays deterministic.
367
+ """
368
+ pool = [
369
+ g
370
+ for g in GPU_INFO.values()
371
+ if g.enum_member
372
+ and g.vram_gb >= min_vram_gb
373
+ and (include_unvalidated or "runpod" in g.validated_on)
374
+ ]
375
+ if not pool:
376
+ raise UnsupportedGpuError(
377
+ f"no {'known' if include_unvalidated else 'validated'} GPU has >= {min_vram_gb} GB VRAM"
378
+ )
379
+ from autoslm.providers.runpod.pricing import hourly_rate
380
+
381
+ return min(pool, key=lambda g: (hourly_rate(g.name), g.vram_gb)).name
382
+
383
+
384
+ def resolve_gpu_policy(
385
+ requested: str,
386
+ model_id: str,
387
+ allow_unvalidated: bool | None = None,
388
+ algorithm: str = "sft",
389
+ *,
390
+ train=None,
391
+ thinking: bool = False,
392
+ ) -> str:
393
+ """Resolve ``gpu.type`` (a concrete class or a policy word) to a friendly name.
394
+
395
+ Parse-time, RunPod-static provisional: "cheapest"/"auto" pick the cheapest
396
+ RunPod-validated class whose VRAM covers the model; concrete names are
397
+ canonicalized. The submit-time allocator (``autoslm.providers.allocator``)
398
+ re-resolves policy words live across providers.
399
+ """
400
+ key = (requested or "").strip().lower()
401
+ if key not in POLICY_NAMES:
402
+ return canonical_gpu(requested)
403
+ from autoslm.engine.vram import model_required_vram_gb
404
+ from autoslm.providers.allocator import vram_headroom
405
+
406
+ # Honor AUTOSLM_VRAM_HEADROOM here too so parse-time sizing matches the submit-time
407
+ # allocator exactly (PR #176 review: they previously diverged on the headroom knob).
408
+ min_vram = model_required_vram_gb(
409
+ model_id, algorithm, train=train, thinking=thinking, headroom=vram_headroom()
410
+ )
411
+ return cheapest_gpu(min_vram, include_unvalidated=unvalidated_allowed(allow_unvalidated))
412
+
413
+
414
+ # ---------------------------------------------------------------------------
415
+ # Handles + poll outcomes (round-tripped through any provider)
416
+ # ---------------------------------------------------------------------------
417
+ @dataclass
418
+ class JobHandle:
419
+ """Provider-tagged, persisted handle: enough to reattach/cancel from any process.
420
+
421
+ Each provider owns the rest of its handle shape (RunPod: endpoint_id/job_id; Vast:
422
+ instance_id/offer_id/...). ``provider`` is the routing key the orchestrator uses to
423
+ dispatch poll/cancel/destroy generically through the registry.
424
+ """
425
+
426
+ provider: str
427
+ data: dict = field(default_factory=dict)
428
+
429
+ def to_dict(self) -> dict:
430
+ return {"provider": self.provider, **self.data}
431
+
432
+ @classmethod
433
+ def from_dict(cls, d: dict) -> JobHandle:
434
+ d = dict(d)
435
+ provider = d.pop("provider", "runpod")
436
+ return cls(provider=provider, data=d)
437
+
438
+
439
+ @dataclass
440
+ class PollResult:
441
+ ok: bool
442
+ metrics: dict | None = None
443
+ failure: str | None = None # "job_failed" | "stalled" | "poll_error"
444
+ detail: str | None = None
445
+
446
+
447
+ # ---------------------------------------------------------------------------
448
+ # Allocation result (cross-provider)
449
+ # ---------------------------------------------------------------------------
450
+ @dataclass(frozen=True)
451
+ class Candidate:
452
+ provider: str
453
+ gpu: str
454
+ hourly_usd: float
455
+ vram_gb: int
456
+ validated: bool
457
+ # Opaque per-provider provisioning hint (e.g. the chosen Vast offer). The
458
+ # allocator stays provider-agnostic; the provider interprets it at submit time.
459
+ offer: Any = None
460
+
461
+
462
+ @dataclass(frozen=True)
463
+ class Allocation:
464
+ provider: str
465
+ gpu: str
466
+ hourly_usd: float
467
+ min_vram_gb: int
468
+ candidates: tuple[Candidate, ...] # full ranked list (retry walks this)
469
+ offer: Any = None # the chosen provider's provisioning hint (vast offer | None)
470
+ # Per-provider book of provisioning hints for the live-market walk (vast offers).
471
+ provider_offers: tuple[Any, ...] = ()
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # The provider interface (FIXED method set both providers implement)
476
+ # ---------------------------------------------------------------------------
477
+ @runtime_checkable
478
+ class Provider(Protocol):
479
+ """The pluggable GPU-substrate interface.
480
+
481
+ Both ``providers/runpod`` and ``providers/vast`` expose ``PROVIDER`` implementing
482
+ this protocol with an identical module layout (api/auth/pricing/gpus/jobs/
483
+ train/preflight). The orchestrator/allocator only ever talk to these methods, so a
484
+ provider is swappable without touching the control plane.
485
+ """
486
+
487
+ name: str
488
+
489
+ def is_configured(self) -> bool:
490
+ """Whether this provider is usable right now (creds present, net reachable)."""
491
+ ...
492
+
493
+ def preflight(self, require_hf: bool = True) -> list[str]:
494
+ """Missing-config problems (empty list == ready). The control plane aggregates
495
+ these into one fail-fast error at startup."""
496
+ ...
497
+
498
+ def gpu_classes(self) -> list[GpuClass]:
499
+ """The GPU classes this provider can provision (its rows of the shared table)."""
500
+ ...
501
+
502
+ def hourly_rate(self, gpu: str) -> float:
503
+ """$/hr for one friendly GPU name (live if available, else static)."""
504
+ ...
505
+
506
+ def submit_run(
507
+ self,
508
+ spec: JobSpec,
509
+ seed: int,
510
+ *,
511
+ log: Any = None,
512
+ on_handle: Any = None,
513
+ attempt: int = 0,
514
+ offers: Any = None,
515
+ exclude_machine_ids: Any = frozenset(),
516
+ ) -> PollResult:
517
+ """Deploy/rent -> submit -> persist handle (via ``on_handle``) -> poll.
518
+
519
+ ``exclude_machine_ids`` is the run's blacklist (machines that already failed
520
+ this run); a provider that re-searches the live market mid-submit (Vast) must
521
+ keep them excluded so a stalled/sick machine is never re-picked. RunPod ignores
522
+ it (no in-provider market re-search)."""
523
+ ...
524
+
525
+ def poll(self, handle: JobHandle, spec: JobSpec, seed: int, *, log: Any = None) -> PollResult:
526
+ """Reattach to a persisted handle and poll it to a terminal state."""
527
+ ...
528
+
529
+ def cancel(self, handle: JobHandle) -> None:
530
+ """Stop the exact remote worker for this handle (cross-process)."""
531
+ ...
532
+
533
+ def destroy(self, handle: JobHandle) -> None:
534
+ """Tear down the billable resource this handle owns (idempotent)."""
535
+ ...
536
+
537
+ def gc(self, spec: JobSpec) -> None:
538
+ """Best-effort: reap any resource this run may have left registered."""
539
+ ...
540
+
541
+ def sweep_orphans(self, active_labels: set[str] | None = None) -> list[int]:
542
+ """Destroy any billable resource this provider owns that no live run claims.
543
+
544
+ Crash recovery: run at server startup (and after runs). ``active_labels`` is the
545
+ set of instance-label PREFIXES still owned by recoverable runs — anything this
546
+ provider rented that matches none of them is an orphan. Returns the destroyed
547
+ resource ids. Providers without a standing-billing substrate (RunPod's
548
+ serverless endpoints self-reap) implement this as a no-op."""
549
+ ...
code/autoslm/providers/preflight.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cross-provider startup preflight.
2
+
3
+ ``check_run_preflight`` aggregates EVERY selected provider's missing-config problems
4
+ (RunPod is the default substrate; Vast only when configured/pinned) plus the shared
5
+ Hugging Face dataset-repo requirements, so a single startup error lists everything
6
+ missing. The per-provider key checks live in ``autoslm.providers.<name>.preflight``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+
13
+ from autoslm.providers.runpod.preflight import (
14
+ PreflightError,
15
+ missing_credentials,
16
+ )
17
+
18
+ __all__ = [
19
+ "PreflightError",
20
+ "check_run_preflight",
21
+ ]
22
+
23
+
24
+ def _missing_hf_credentials() -> list[str]:
25
+ """Shared run infra every substrate needs: the HF write token, plus PRIME_API_KEY (the
26
+ worker ``prime env install``s the run's Hub env regardless of the GPU provider). The HF
27
+ dataset repo is per-run (``[train] hf_repo``), not an operator var."""
28
+ problems: list[str] = []
29
+ if not os.environ.get("PRIME_API_KEY"):
30
+ problems.append(
31
+ " - PRIME_API_KEY: a Prime Intellect API key; the GPU worker uses it to "
32
+ "`prime env install` the run's Hub environment (public + private), e.g. "
33
+ "`export PRIME_API_KEY=pit_...`"
34
+ )
35
+ if not os.environ.get("HF_TOKEN"):
36
+ problems.append(
37
+ " - HF_TOKEN: a token with write access to each run's "
38
+ "`[train] hf_repo`, e.g. `export HF_TOKEN=hf_...`"
39
+ )
40
+ return problems
41
+
42
+
43
+ def _preflight_provider_names() -> set[str]:
44
+ """The providers whose operator config this control plane must satisfy. RunPod is always
45
+ required (the default substrate); Vast is opt-in (preflighted only when VAST_API_KEY signals
46
+ intent)."""
47
+ names = {"runpod"} # always-on default substrate
48
+ if os.environ.get("VAST_API_KEY"):
49
+ names.add("vast") # opt-in: a partial vast config signals intent
50
+ return names
51
+
52
+
53
+ def check_run_preflight(require_hf: bool = True) -> None:
54
+ """Validate operator config across the configured providers; raise on missing.
55
+
56
+ Only the providers this control plane actually uses are checked: RunPod's requirements
57
+ (RUNPOD_API_KEY + the shared PRIME_API_KEY/HF_TOKEN) are always checked, and a configured
58
+ Vast key (VAST_API_KEY) adds its own check. The HF dataset repo is per-run
59
+ (``[train] hf_repo``), not an operator var.
60
+ """
61
+ selected = _preflight_provider_names()
62
+ problems: list[str] = []
63
+ # The HF write token is SHARED run infra (every substrate streams artifacts through HF),
64
+ # so it is checked once regardless of which providers are selected — a Vast-only plane
65
+ # still needs it. Each provider check is asked for its keys only (require_hf=False) so HF
66
+ # isn't double-reported. The HF dataset repo itself is per-run (``[train] hf_repo``).
67
+ if "runpod" in selected:
68
+ problems += missing_credentials(require_hf=False)
69
+ if "vast" in selected:
70
+ from autoslm.providers.vast.preflight import missing_credentials as vast_missing
71
+
72
+ problems += vast_missing(require_hf=False)
73
+ if require_hf:
74
+ problems += _missing_hf_credentials()
75
+ if problems:
76
+ raise PreflightError(
77
+ "the AutoSLM control plane is missing required operator configuration:\n"
78
+ + "\n".join(problems)
79
+ + "\n\nSet these on the control-plane host."
80
+ )
code/autoslm/providers/runpod/__init__.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RunPod Flash provider: managed, serverless GPUs (no Docker) for AutoSLM.
2
+
3
+ Fine-tuning runs on a dedicated RunPod GPU provisioned by Flash. A decorated Python
4
+ handler (``train._train_body``) executes ``autoslm.engine.worker`` on the GPU; Flash
5
+ handles provisioning, dependency install, execution, and scale-to-zero teardown.
6
+ Serving exposes an OpenAI-compatible endpoint for a trained LoRA adapter.
7
+
8
+ ``PROVIDER`` is the ``base.Provider`` implementation the registry hands out; the
9
+ orchestrator/allocator only talk to its interface, never these modules directly.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Any
15
+
16
+ from autoslm.providers.base import GpuClass, JobHandle, PollResult, Provider
17
+
18
+
19
+ class RunpodProvider:
20
+ """``base.Provider`` for the RunPod Flash substrate."""
21
+
22
+ name = "runpod"
23
+
24
+ def is_configured(self) -> bool:
25
+ # RunPod is the ALWAYS-ON default substrate, so it is always "available" for
26
+ # allocation (offline pricing degrades to the static snapshot, and a missing
27
+ # RUNPOD_API_KEY surfaces at provision time via ensure_auth / the preflight —
28
+ # never as a silent empty candidate list). This matches the historical
29
+ # ``available_providers()`` which listed runpod unconditionally.
30
+ return True
31
+
32
+ def preflight(self, require_hf: bool = True) -> list[str]:
33
+ from autoslm.providers.runpod.preflight import missing_credentials
34
+
35
+ return missing_credentials(require_hf=require_hf)
36
+
37
+ def gpu_classes(self) -> list[GpuClass]:
38
+ from autoslm.providers.runpod.gpus import gpu_classes
39
+
40
+ return gpu_classes()
41
+
42
+ def hourly_rate(self, gpu: str) -> float:
43
+ from autoslm.providers.runpod.pricing import hourly_rate
44
+
45
+ return hourly_rate(gpu)
46
+
47
+ def submit_run(
48
+ self,
49
+ spec,
50
+ seed: int,
51
+ *,
52
+ log: Any = None,
53
+ on_handle: Any = None,
54
+ attempt: int = 0,
55
+ offers: Any = None,
56
+ exclude_machine_ids: Any = frozenset(),
57
+ ) -> PollResult:
58
+ # ``offers``/``exclude_machine_ids`` are Vast live-market concerns; RunPod
59
+ # provisions a fresh serverless endpoint and never re-searches a market, so it
60
+ # ignores both (kept in the signature for cross-provider symmetry).
61
+ from autoslm.providers.runpod.jobs import submit_run
62
+
63
+ return submit_run(spec, seed, log=log, on_handle=on_handle, attempt=attempt)
64
+
65
+ def poll(self, handle: JobHandle, spec, seed: int, *, log: Any = None) -> PollResult:
66
+ from autoslm.providers.runpod.jobs import JobHandle as RunpodJobHandle
67
+ from autoslm.providers.runpod.jobs import (
68
+ make_hf_heartbeat_reader,
69
+ poll_job,
70
+ stall_kwargs,
71
+ )
72
+
73
+ hf_repo = spec.train.hf_repo
74
+ prefix = f"{spec.phase}/{spec.run_id}/seed{seed}"
75
+ reader = make_hf_heartbeat_reader(hf_repo, prefix) if hf_repo else None
76
+ rh = RunpodJobHandle.from_dict(handle.to_dict())
77
+ if log is not None:
78
+ print(f"attaching: job={rh.job_id} endpoint={rh.endpoint_name}", file=log, flush=True)
79
+ # Same stall tuning as the submit path so a reattached run isn't judged differently.
80
+ return poll_job(rh, log=log, heartbeat_reader=reader, **stall_kwargs())
81
+
82
+ def cancel(self, handle: JobHandle) -> None:
83
+ from autoslm.providers.runpod import api as runpod_api
84
+
85
+ d = handle.to_dict()
86
+ if d.get("endpoint_id") and d.get("job_id"):
87
+ runpod_api.cancel_job(d["endpoint_id"], d["job_id"])
88
+
89
+ def destroy(self, handle: JobHandle) -> None:
90
+ from autoslm.providers.runpod import api as runpod_api
91
+
92
+ d = handle.to_dict()
93
+ if d.get("endpoint_id"):
94
+ runpod_api.delete_endpoint(d["endpoint_id"])
95
+
96
+ def gc(self, spec) -> None:
97
+ from autoslm.providers.runpod.train import terminate_endpoint
98
+
99
+ terminate_endpoint(spec.gpu.type, spec.run_id)
100
+
101
+ def sweep_orphans(self, active_labels: set[str] | None = None) -> list[int]:
102
+ # No-op: RunPod serverless endpoints have no standing per-run billing to reap on
103
+ # crash recovery (a failed-before-submit endpoint is GC'd by reconstructed name in
104
+ # recover_runs). Present for ``base.Provider`` symmetry with Vast's instance sweep.
105
+ return []
106
+
107
+
108
+ PROVIDER: Provider = RunpodProvider()
code/autoslm/providers/runpod/api.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Thin RunPod REST client (no SDK state): endpoints, queue jobs, health.
2
+
3
+ Used by the run supervisor and endpoint GC so that a *fresh process* can
4
+ reattach to / clean up after any run using only the persisted ids + RUNPOD_API_KEY —
5
+ independent of the Flash SDK's local resource registry (which is per-directory,
6
+ whole-dict, last-writer-wins and therefore unreliable across processes).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import urllib.error
12
+ from typing import Any
13
+
14
+ from autoslm.providers._http import RestClient
15
+
16
+ REST_BASE = "https://rest.runpod.io/v1"
17
+ QUEUE_BASE = "https://api.runpod.ai/v2"
18
+
19
+
20
+ class RunpodApiError(RuntimeError):
21
+ pass
22
+
23
+
24
+ # Shared urllib client (full-URL form: callers pass absolute REST/QUEUE urls).
25
+ # Env-only by design: ~/.autoslm/config.json holds the *AutoSLM* key (client-side),
26
+ # never the RunPod key — the operator sets RUNPOD_API_KEY on the control-plane host.
27
+ _CLIENT = RestClient(env_var="RUNPOD_API_KEY", error_cls=RunpodApiError)
28
+
29
+
30
+ def _api_key() -> str:
31
+ return _CLIENT.api_key()
32
+
33
+
34
+ def _request(url: str, method: str = "GET", body: dict | None = None, timeout: float = 30.0):
35
+ return _CLIENT.request(url, method=method, body=body, timeout=timeout)
36
+
37
+
38
+ def request_with_retries(
39
+ url: str,
40
+ method: str = "GET",
41
+ body: dict | None = None,
42
+ retries: int = 4,
43
+ base_delay: float = 2.0,
44
+ ) -> Any:
45
+ """REST call hardened against transient network/5xx blips (jittered backoff)."""
46
+ return _CLIENT.request_with_retries(
47
+ url, method=method, body=body, retries=retries, base_delay=base_delay
48
+ )
49
+
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # Endpoints
53
+ # ---------------------------------------------------------------------------
54
+ def list_endpoints() -> list[dict]:
55
+ out = request_with_retries(f"{REST_BASE}/endpoints")
56
+ return out if isinstance(out, list) else []
57
+
58
+
59
+ def find_endpoints_by_name(substr: str) -> list[dict]:
60
+ return [e for e in list_endpoints() if substr in (e.get("name") or "")]
61
+
62
+
63
+ def delete_endpoint(endpoint_id: str) -> bool:
64
+ try:
65
+ request_with_retries(f"{REST_BASE}/endpoints/{endpoint_id}", method="DELETE", retries=2)
66
+ return True
67
+ except RunpodApiError as e:
68
+ # An already-gone endpoint is a clean teardown, not a failure: a 404 (or a body
69
+ # saying the endpoint "does not exist") means the desired end state — no such
70
+ # endpoint — already holds. Reporting False here makes undeploy_adapter surface a
71
+ # misleading "may still be running" 502 for something that's provably gone.
72
+ return _is_not_found(e)
73
+
74
+
75
+ def _is_not_found(err: RunpodApiError) -> bool:
76
+ """True only when a RunpodApiError represents a genuine 404 (endpoint already gone).
77
+
78
+ request_with_retries chains the original urllib HTTPError as ``__cause__`` for every
79
+ fast-failed 4xx (``raise ... from e``), so the status code is authoritative when a
80
+ cause is present: a 404 is "already gone", anything else (403/401/5xx) is a real
81
+ failure and must NOT be swallowed — a body that merely *mentions* "does not exist" on a
82
+ 403 is still a 403. We only fall back to a text match when there is no HTTPError cause
83
+ (e.g. the "failed after N attempts" path), and even then only on an unambiguous 404.
84
+ """
85
+ cause = err.__cause__
86
+ if isinstance(cause, urllib.error.HTTPError):
87
+ return cause.code == 404
88
+ return "http 404" in str(err).lower()
89
+
90
+
91
+ def endpoint_health(endpoint_id: str) -> dict:
92
+ return request_with_retries(f"{QUEUE_BASE}/{endpoint_id}/health")
93
+
94
+
95
+ # ---------------------------------------------------------------------------
96
+ # Queue jobs
97
+ # ---------------------------------------------------------------------------
98
+ def submit_job(endpoint_id: str, input_payload: dict) -> str:
99
+ """POST /run -> job id (async queue submission)."""
100
+ out = request_with_retries(
101
+ f"{QUEUE_BASE}/{endpoint_id}/run", method="POST", body={"input": input_payload}
102
+ )
103
+ job_id = out.get("id")
104
+ if not job_id:
105
+ raise RunpodApiError(f"submit_job: no job id in response: {out}")
106
+ return job_id
107
+
108
+
109
+ def job_status(endpoint_id: str, job_id: str) -> dict:
110
+ """GET /status/<job_id> -> {status, output?, error?, ...}."""
111
+ return request_with_retries(f"{QUEUE_BASE}/{endpoint_id}/status/{job_id}")
112
+
113
+
114
+ def cancel_job(endpoint_id: str, job_id: str) -> dict:
115
+ return request_with_retries(
116
+ f"{QUEUE_BASE}/{endpoint_id}/cancel/{job_id}", method="POST", retries=2
117
+ )
code/autoslm/providers/runpod/auth.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RunPod credential handling for the managed Flash backend (operator-side).
2
+
3
+ The Flash SDK authenticates via the ``RUNPOD_API_KEY`` environment variable, set by
4
+ the **operator** on the control-plane host. End users never
5
+ provide provider credentials — they authenticate to the control plane with an AutoSLM
6
+ key. Deliberately env-only: ``~/.autoslm/config.json`` holds the *AutoSLM* key, which
7
+ must never be mistaken for a RunPod key.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+
14
+
15
+ def load_api_key() -> str | None:
16
+ """RunPod API key from the environment (operator configuration)."""
17
+ return os.environ.get("RUNPOD_API_KEY") or None
18
+
19
+
20
+ def ensure_auth() -> str:
21
+ """Ensure ``RUNPOD_API_KEY`` is set for the Flash SDK; raise if unavailable."""
22
+ key = load_api_key()
23
+ if not key:
24
+ raise RuntimeError("no RunPod API key found; set RUNPOD_API_KEY on the control-plane host")
25
+ return key
code/autoslm/providers/runpod/gpus.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RunPod's GPU classes + the Flash-specific bits of the shared GPU table.
2
+
3
+ The class table itself is provider-agnostic and lives in ``providers/base.py`` (one
4
+ canonical row per friendly name). This module carves out RunPod's rows
5
+ (``gpu_classes()`` == every class with a Flash ``enum_member``) and owns the
6
+ RunPod-only translation: friendly name -> Flash ``GpuType``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from autoslm.providers.base import (
12
+ GpuClass,
13
+ UnsupportedGpuError,
14
+ get_gpu_info,
15
+ providers_for,
16
+ )
17
+
18
+
19
+ # Lazy import so unit tests that only exercise the mapping don't pull the whole SDK
20
+ # graph unless needed. ``runpod_flash`` is a hard dependency, so this import is safe.
21
+ def _gpu_enum():
22
+ from runpod_flash import GpuType
23
+
24
+ return GpuType
25
+
26
+
27
+ def gpu_classes() -> list[GpuClass]:
28
+ """The GPU classes RunPod Flash can provision (those with a ``GpuType`` member)."""
29
+ from autoslm.providers.base import GPU_INFO
30
+
31
+ return [g for g in GPU_INFO.values() if g.enum_member]
32
+
33
+
34
+ def flash_gpu(name: str):
35
+ """Return the RunPod Flash ``GpuType`` for a friendly GPU name."""
36
+ info = get_gpu_info(name)
37
+ if not info.enum_member:
38
+ raise UnsupportedGpuError(
39
+ f"{info.name} is not available on RunPod (providers: {', '.join(providers_for(name))})"
40
+ )
41
+ return getattr(_gpu_enum(), info.enum_member)
42
+
43
+
44
+ def gpu_api_id(name: str) -> str:
45
+ """RunPod API GPU id (the ``GpuType`` enum value, e.g. 'NVIDIA GeForce RTX 4090')."""
46
+ return flash_gpu(name).value
code/autoslm/providers/runpod/jobs.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Durable run primitives: explicit deploy -> submit -> poll with a persisted job handle.
2
+
3
+ Calling `runpod_flash`'s all-in-one blocking handler directly would tie a run's life to
4
+ one client process and one HTTP poll loop: a client crash/network blip orphans an
5
+ otherwise-healthy GPU job (no job id is ever persisted), and any SDK polling bug kills
6
+ the run. This module owns the lifecycle instead:
7
+
8
+ deploy_train_endpoint() -> endpoint_id (Flash SDK deploy, same worker template)
9
+ build_function_input() -> the exact FunctionRequest payload Flash workers expect
10
+ submit + poll_job() -> REST queue API with hardened retries; the job handle
11
+ {endpoint_id, job_id} is persisted by the runner so
12
+ any process can re-attach (`slm attach`).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import base64
19
+ import contextlib
20
+ import json
21
+ import os
22
+ import time
23
+ from dataclasses import dataclass
24
+
25
+ from autoslm._logging import get_logger
26
+ from autoslm.providers._poll import PollErrorTracker, make_say, surface_heartbeat
27
+ from autoslm.providers.base import PollResult, canonical_gpu
28
+ from autoslm.providers.runpod import api as runpod_api
29
+ from autoslm.providers.runpod.gpus import flash_gpu
30
+ from autoslm.providers.runpod.train import (
31
+ DEFAULT_EXECUTION_TIMEOUT_MS,
32
+ FLASH_SDK_LOCK,
33
+ WORKER_IMAGE,
34
+ WORKER_SYSTEM_DEPS,
35
+ _patch_runpod_backoff,
36
+ _train_body,
37
+ endpoint_name,
38
+ isolate_flash_state,
39
+ min_cuda_for,
40
+ resolve_worker_deps,
41
+ )
42
+
43
+ logger = get_logger(__name__)
44
+
45
+ # Re-export so callers/tests that did ``from ...jobs import PollResult`` keep working.
46
+ __all__ = [
47
+ "JobHandle",
48
+ "PollResult",
49
+ "apply_disk_gb",
50
+ "build_function_input",
51
+ "decode_output",
52
+ "deploy_train_endpoint",
53
+ "make_hf_heartbeat_reader",
54
+ "make_hf_text_reader",
55
+ "poll_job",
56
+ "submit_run",
57
+ "volume_endpoint_kwargs",
58
+ ]
59
+
60
+ TERMINAL_OK = {"COMPLETED"}
61
+ TERMINAL_FAIL = {"FAILED", "CANCELLED", "TIMED_OUT"}
62
+
63
+ # Heartbeat stages the worker emits DURING cold start, BEFORE the model is loaded and the
64
+ # training loop begins (boot -> sft_start/rl_start, then later sft_model_load/rl_train_start).
65
+ # Receiving one proves the worker is alive but NOT that the slow setup (model download +
66
+ # vLLM init) finished, so they must not flip stall detection to the tight training window.
67
+ _SETUP_HEARTBEAT_STAGES = frozenset(
68
+ {"boot", "sft_start", "rl_start", "sft_model_load", "rl_train_start"}
69
+ )
70
+
71
+
72
+ def stall_kwargs() -> dict:
73
+ """``poll_job`` stall-window kwargs, shared by the submit and reattach paths so a recovered
74
+ run uses the same tuning as the original submit. ``stall_after_s`` = post-training-heartbeat
75
+ window; ``setup_grace_s`` = the larger cold-start window before the first training heartbeat.
76
+ """
77
+ return {"stall_after_s": 1500.0, "setup_grace_s": 3000.0}
78
+
79
+
80
+ def volume_endpoint_kwargs(spec) -> dict:
81
+ """Endpoint kwargs for the OPT-IN persistent network volume (cross-run HF cache).
82
+
83
+ Returns {} unless ``gpu.network_volume`` is set. The volume pins the endpoint to
84
+ one datacenter (``gpu.datacenter``, default EU-RO-1 — the SDK's storage default),
85
+ which shrinks the available GPU pool; that trade-off is why this is opt-in.
86
+ """
87
+ nv = getattr(spec.gpu, "network_volume", None) if spec is not None else None
88
+ if not nv:
89
+ return {}
90
+ from runpod_flash import NetworkVolume
91
+ from runpod_flash.core.resources.datacenter import DataCenter
92
+
93
+ dc = DataCenter.from_string(spec.gpu.datacenter) if spec.gpu.datacenter else None
94
+ volume = NetworkVolume(
95
+ name=str(nv),
96
+ size=int(getattr(spec.gpu, "network_volume_gb", 100) or 100),
97
+ **({"datacenter": dc} if dc else {}),
98
+ )
99
+ kwargs: dict = {"volume": volume}
100
+ if dc:
101
+ kwargs["datacenter"] = dc
102
+ return kwargs
103
+
104
+
105
+ def apply_disk_gb(config, disk_gb: int | None) -> None:
106
+ """Raise the worker's container disk on a built endpoint config.
107
+
108
+ The Flash SDK's ``PodTemplate.containerDiskInGb`` defaults to 64 GB and the
109
+ ``Endpoint`` wrapper exposes no disk knob, which is what blocked models whose
110
+ checkpoint alone exceeds 64 GB. The template
111
+ is already populated by the SDK's validators when the resource config is built, so
112
+ raising the field here is the supported injection point. Raise-only: shrinking
113
+ below the SDK default buys nothing (serverless disk isn't billed separately) and
114
+ would regress runs whose configs carry the historical ``disk_gb = 60`` default.
115
+ """
116
+ if not disk_gb:
117
+ return
118
+ template = getattr(config, "template", None)
119
+ if template is None:
120
+ logger.warning("disk_gb=%s requested but endpoint config has no template", disk_gb)
121
+ return
122
+ template.containerDiskInGb = max(int(disk_gb), int(template.containerDiskInGb or 0))
123
+
124
+
125
+ @dataclass
126
+ class JobHandle:
127
+ endpoint_id: str
128
+ endpoint_name: str
129
+ job_id: str
130
+
131
+ def to_dict(self) -> dict:
132
+ return {
133
+ "provider": "runpod",
134
+ "endpoint_id": self.endpoint_id,
135
+ "endpoint_name": self.endpoint_name,
136
+ "job_id": self.job_id,
137
+ }
138
+
139
+ @classmethod
140
+ def from_dict(cls, d: dict) -> JobHandle:
141
+ # `provider` is routing metadata consumed upstream (runner); handles
142
+ # persisted before it existed default to runpod there.
143
+ return cls(d["endpoint_id"], d.get("endpoint_name", ""), d["job_id"])
144
+
145
+
146
+ def deploy_train_endpoint(
147
+ friendly_gpu: str,
148
+ execution_timeout_ms: int | None = None,
149
+ name_suffix: str | None = None,
150
+ disk_gb: int | None = None,
151
+ spec=None,
152
+ ) -> tuple[str, str]:
153
+ """Deploy (or reuse) the run's uniquely-named worker endpoint; return (id, name)."""
154
+ os.environ["FLASH_IS_LIVE_PROVISIONING"] = "true"
155
+ from runpod_flash import Endpoint
156
+
157
+ from autoslm.providers.runpod.auth import ensure_auth
158
+
159
+ ensure_auth()
160
+ _patch_runpod_backoff()
161
+ friendly = canonical_gpu(friendly_gpu)
162
+ name = endpoint_name(friendly, name_suffix)
163
+ image = WORKER_IMAGE
164
+ from runpod_flash.core.resources.resource_manager import ResourceManager
165
+
166
+ # isolate_flash_state mutates runpod_flash's process-wide registry globals for this run's
167
+ # suffix, and ResourceManager + the deploy share the SDK's asyncio singleton. Hold the
168
+ # lock across the whole critical section so a concurrent run can't swap the registry
169
+ # scope or race the event loop mid-deploy.
170
+ with FLASH_SDK_LOCK:
171
+ isolate_flash_state(name_suffix)
172
+ kwargs = dict(
173
+ name=name,
174
+ gpu=flash_gpu(friendly),
175
+ gpu_count=1,
176
+ min_cuda_version=min_cuda_for(friendly),
177
+ execution_timeout_ms=execution_timeout_ms or DEFAULT_EXECUTION_TIMEOUT_MS,
178
+ workers=(0, 1),
179
+ **volume_endpoint_kwargs(spec),
180
+ )
181
+ if image:
182
+ kwargs["image"] = image
183
+ else:
184
+ # Pass the resolved GPU so Hopper (sm90) gets its fla-drop treatment (resolve_worker_deps
185
+ # is GPU-scoped); a bare call would ship the generic deps and run fla's #640-buggy GDN
186
+ # Triton kernel on an H100 instead of the correct pure-PyTorch delta rule.
187
+ kwargs["dependencies"] = resolve_worker_deps(friendly)
188
+ kwargs["system_dependencies"] = WORKER_SYSTEM_DEPS
189
+ ep = Endpoint(**kwargs)
190
+ ep._qb_target = _train_body
191
+ config = ep._build_resource_config()
192
+ apply_disk_gb(config, disk_gb)
193
+ # Worker image is PUBLIC, so no container-registry credential is needed to pull it.
194
+ rm = ResourceManager()
195
+ resource = asyncio.run(rm.get_or_deploy_resource(config))
196
+ endpoint_id = getattr(resource, "id", None)
197
+ if not endpoint_id:
198
+ raise RuntimeError(f"deploy_train_endpoint: no endpoint id on resource {resource!r}")
199
+ return endpoint_id, name
200
+
201
+
202
+ def build_function_input(payload: dict, friendly_gpu: str | None = None) -> dict:
203
+ """The FunctionRequest dict a Flash queue worker expects for `_train_body(payload)`.
204
+
205
+ ``friendly_gpu`` is threaded into ``resolve_worker_deps`` so the request-level dependency
206
+ list is GPU-scoped exactly like the endpoint config (deploy_train_endpoint): on Hopper (sm90)
207
+ it must drop ``flash-linear-attention`` so the worker uses the pure-PyTorch delta rule instead
208
+ of fla's #640-buggy GDN Triton kernel. A bare call would reinstall the generic deps and
209
+ reintroduce that sm90 correctness issue even when the endpoint was configured correctly.
210
+ """
211
+ from runpod_flash.runtime.serialization import serialize_args
212
+ from runpod_flash.stubs.live_serverless import get_function_source
213
+
214
+ source, _src_hash = get_function_source(_train_body)
215
+ req: dict = {
216
+ "function_name": "_train_body",
217
+ "function_code": source,
218
+ "args": serialize_args((payload,)),
219
+ "accelerate_downloads": True,
220
+ }
221
+ if not WORKER_IMAGE:
222
+ req["dependencies"] = resolve_worker_deps(canonical_gpu(friendly_gpu) if friendly_gpu else None)
223
+ req["system_dependencies"] = WORKER_SYSTEM_DEPS
224
+ return req
225
+
226
+
227
+ def decode_output(output) -> dict:
228
+ """Decode a Flash FunctionResponse job output into the worker's metrics dict."""
229
+ if isinstance(output, str):
230
+ try:
231
+ output = json.loads(output)
232
+ except json.JSONDecodeError as exc:
233
+ raise RuntimeError(f"unexpected job output: {output[:200]}") from exc
234
+ if not isinstance(output, dict):
235
+ raise RuntimeError(f"unexpected job output type: {type(output)}")
236
+ if output.get("success") and output.get("result") is not None:
237
+ import cloudpickle
238
+
239
+ result = cloudpickle.loads(base64.b64decode(output["result"]))
240
+ if not isinstance(result, dict):
241
+ raise RuntimeError(f"flash job returned no metrics: {result!r}")
242
+ return result
243
+ err = output.get("error") or "unknown worker error"
244
+ stdout_tail = (output.get("stdout") or "")[-1500:]
245
+ raise RuntimeError(f"Remote execution failed: {err}\n--- worker stdout tail ---\n{stdout_tail}")
246
+
247
+
248
+ def poll_job(
249
+ handle: JobHandle,
250
+ log=None,
251
+ interval_s: float = 10.0,
252
+ heartbeat_reader=None,
253
+ stall_after_s: float = 1200.0,
254
+ setup_grace_s: float = 3000.0,
255
+ deadline_s: float | None = None,
256
+ ) -> PollResult:
257
+ """Poll a queue job to completion; resilient to transient API errors.
258
+
259
+ Two stall windows: the cold-start phase (dep install, per-run env pip, model download,
260
+ vLLM init) is slow and only emits *setup* heartbeats (``_SETUP_HEARTBEAT_STAGES``).
261
+ Until a *training* heartbeat arrives we apply the larger ``setup_grace_s`` budget so a
262
+ slow cold start isn't misread as a stall; after it we use the tight ``stall_after_s``.
263
+ Needs a ``heartbeat_reader`` to tell the phases apart — without one we keep
264
+ ``stall_after_s`` throughout (no regression).
265
+ """
266
+
267
+ say = make_say(log)
268
+ poll_errors = PollErrorTracker(say, interval_s)
269
+
270
+ start = time.time()
271
+ last_status = None
272
+ last_hb_key = None
273
+ last_progress = time.time()
274
+ seen_heartbeat = False
275
+ last_health_probe = 0.0
276
+ while True:
277
+ if deadline_s is not None and time.time() - start > deadline_s:
278
+ return PollResult(False, failure="stalled", detail="client-side deadline exceeded")
279
+ try:
280
+ st = runpod_api.job_status(handle.endpoint_id, handle.job_id)
281
+ poll_errors.reset()
282
+ except runpod_api.RunpodApiError as e:
283
+ if poll_errors.record(e):
284
+ return PollResult(False, failure="poll_error", detail=str(e))
285
+ continue
286
+ status = st.get("status")
287
+ if status != last_status:
288
+ say(f"job {handle.job_id}: {status}")
289
+ last_status = status
290
+ last_progress = time.time()
291
+ if status in TERMINAL_OK:
292
+ try:
293
+ return PollResult(True, metrics=decode_output(st.get("output")))
294
+ except RuntimeError as e:
295
+ return PollResult(False, failure="job_failed", detail=str(e))
296
+ if status in TERMINAL_FAIL:
297
+ detail = str(st.get("error") or "")[:1500]
298
+ out = st.get("output")
299
+ if isinstance(out, dict) and out.get("stdout"):
300
+ # Worker stdout tail is the only place the REAL root cause lives for
301
+ # crashes inside subprocesses (e.g. vLLM EngineCore deaths).
302
+ detail += "\n--- worker stdout tail ---\n" + str(out["stdout"])[-2000:]
303
+ elif not detail:
304
+ detail = str(out)[:1500]
305
+ # Prefix the terminal status so the runner's infra-retry markers
306
+ # (e.g. TIMED_OUT) match even when RunPod sets no error/output text.
307
+ return PollResult(False, failure="job_failed", detail=f"[{status}] {detail}")
308
+ # While queued, surface worker availability (throttled hosts are the common
309
+ # cause of silent multi-minute waits — make them visible in the run log).
310
+ if status == "IN_QUEUE" and time.time() - last_health_probe > 90:
311
+ last_health_probe = time.time()
312
+ try:
313
+ h = runpod_api.endpoint_health(handle.endpoint_id)
314
+ workers = h.get("workers") or {}
315
+ if any(workers.get(k) for k in ("throttled", "unhealthy", "initializing")) or not (
316
+ workers.get("running") or workers.get("ready") or workers.get("idle")
317
+ ):
318
+ say(f"queued; workers: {workers}")
319
+ except Exception:
320
+ # Health surfacing is diagnostic only; a probe failure must not stop polling.
321
+ pass
322
+ # heartbeat progress surfacing + stall detection
323
+ new_key, stage = surface_heartbeat(heartbeat_reader, last_hb_key, say)
324
+ if new_key != last_hb_key:
325
+ last_hb_key = new_key
326
+ last_progress = time.time()
327
+ # Only a training-phase heartbeat means cold-start setup is done and we
328
+ # can switch to the tight window; setup heartbeats keep the grace budget.
329
+ if stage not in _SETUP_HEARTBEAT_STAGES:
330
+ seen_heartbeat = True
331
+ # Cold start (before any training-phase heartbeat) gets the larger setup_grace_s,
332
+ # but only when a heartbeat_reader lets us tell setup from training; without one we
333
+ # can't, so stay on stall_after_s (no regression).
334
+ in_setup = heartbeat_reader is not None and not seen_heartbeat
335
+ stall_limit = setup_grace_s if in_setup else stall_after_s
336
+ if time.time() - last_progress > stall_limit:
337
+ phase = "setup (pre-training)" if in_setup else "training"
338
+ return PollResult(
339
+ False,
340
+ failure="stalled",
341
+ detail=f"no worker progress for {int(time.time() - last_progress)}s "
342
+ f"during {phase} (job status {status}, limit {int(stall_limit)}s)",
343
+ )
344
+ time.sleep(interval_s)
345
+
346
+
347
+ def submit_run(spec, seed: int, log=None, on_handle=None, attempt: int = 0) -> PollResult:
348
+ """Durable equivalent of ``submit_train``: deploy, submit, persist handle, poll.
349
+
350
+ ``on_handle(handle_dict)`` is invoked as soon as the job is queued so the
351
+ runner can persist {endpoint_id, job_id} for cross-process reattach.
352
+ """
353
+ from autoslm.envs.registry import worker_hub_env_ids, worker_pip_for_env
354
+ from autoslm.providers.runpod.train import _run_suffix, build_worker_env
355
+
356
+ timeout_s = max(60, int(spec.gpu.max_wall_seconds))
357
+ # Per-attempt endpoint name: a retry must land on a genuinely fresh endpoint —
358
+ # reusing the name lets the SDK/platform pin the job back onto the same
359
+ # (possibly throttled/sick) host.
360
+ suffix = _run_suffix(spec.run_id)
361
+ if attempt:
362
+ suffix = f"{suffix}r{attempt}"
363
+ # Resolve the worker env BEFORE provisioning: an unrecorded Hub env raises here, and
364
+ # doing it after deploy_train_endpoint() would leak the just-created endpoint (its
365
+ # rN-suffixed name can't be reconstructed from the run id later) against the account
366
+ # quota — the runner would also treat the raise as a retryable poll_error.
367
+ extra_pip = list(spec.environment.pip) or worker_pip_for_env(spec.environment.id)
368
+ worker_env = build_worker_env(spec, seed)
369
+ endpoint_id, name = deploy_train_endpoint(
370
+ spec.gpu.type,
371
+ execution_timeout_ms=timeout_s * 1000,
372
+ name_suffix=suffix,
373
+ disk_gb=spec.gpu.disk_gb,
374
+ spec=spec,
375
+ )
376
+ payload = {
377
+ "hf_repo": spec.train.hf_repo,
378
+ "job_spec_json": spec.to_json(),
379
+ "phase": spec.phase,
380
+ "seed": int(seed),
381
+ "env": worker_env,
382
+ "extra_pip": extra_pip,
383
+ "hub_env_ids": worker_hub_env_ids(spec.environment.id, spec.environment.params),
384
+ }
385
+ try:
386
+ job_id = runpod_api.submit_job(endpoint_id, build_function_input(payload, spec.gpu.type))
387
+ except Exception:
388
+ # The endpoint is registered but no run handle exists yet, and a
389
+ # retry endpoint's rN-suffixed name can't be reconstructed from the run
390
+ # id later — delete it now so a transient submit failure doesn't leak a
391
+ # serverless endpoint against the account quota.
392
+ with contextlib.suppress(Exception):
393
+ runpod_api.delete_endpoint(endpoint_id)
394
+ raise
395
+ handle = JobHandle(endpoint_id, name, job_id)
396
+ if log is not None:
397
+ print(
398
+ f"submitted job: endpoint={name} ({endpoint_id}) job={job_id} "
399
+ f"attempt={attempt} gpu={spec.gpu.type} phase={spec.phase} seed={seed}",
400
+ file=log,
401
+ flush=True,
402
+ )
403
+ if on_handle is not None:
404
+ on_handle(handle.to_dict())
405
+ hf_repo = spec.train.hf_repo
406
+ prefix = f"{spec.phase}/{spec.run_id}/seed{seed}"
407
+ reader = make_hf_heartbeat_reader(hf_repo, prefix) if hf_repo else None
408
+ return poll_job(handle, log=log, heartbeat_reader=reader, **stall_kwargs())
409
+
410
+
411
+ def make_hf_text_reader(hf_repo: str, path_in_repo: str, min_interval_s: float = 45.0):
412
+ """Rate-limited reader for one HF artifact's text content (None until it exists).
413
+
414
+ Generic helper shared by both providers' pollers (runpod heartbeats + vast's
415
+ DONE/metrics/error artifacts). ``read(force=False)`` re-downloads at most once per
416
+ ``min_interval_s`` (``force=True`` bypasses the gate); it never raises — any HF error
417
+ (artifact absent, network) returns None.
418
+ """
419
+ state = {"last": 0.0}
420
+
421
+ def read(force: bool = False) -> str | None:
422
+ if not hf_repo:
423
+ return None
424
+ if not force and time.time() - state["last"] < min_interval_s:
425
+ return None
426
+ state["last"] = time.time()
427
+ try:
428
+ from huggingface_hub import hf_hub_download
429
+
430
+ p = hf_hub_download(
431
+ hf_repo,
432
+ path_in_repo,
433
+ repo_type="dataset",
434
+ token=os.environ.get("HF_TOKEN"),
435
+ force_download=True,
436
+ )
437
+ with open(p) as f:
438
+ return f.read()
439
+ except Exception:
440
+ return None
441
+
442
+ return read
443
+
444
+
445
+ def make_hf_heartbeat_reader(hf_repo: str, prefix: str, min_interval_s: float = 30.0):
446
+ """Reader for the worker's heartbeat.json on HF (rate-limited, never raises).
447
+
448
+ Thin JSON-parsing wrapper over :func:`make_hf_text_reader` bound to ``{prefix}/heartbeat.json``.
449
+ """
450
+ text_reader = make_hf_text_reader(hf_repo, f"{prefix}/heartbeat.json", min_interval_s)
451
+
452
+ def read() -> dict | None:
453
+ raw = text_reader()
454
+ if raw is None:
455
+ return None
456
+ try:
457
+ return json.loads(raw)
458
+ except (ValueError, TypeError):
459
+ return None
460
+
461
+ return read
code/autoslm/providers/runpod/preflight.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fail-fast credential checks for the RunPod substrate (operator-side).
2
+
3
+ These run when the AutoSLM server starts (and before any RunPod Flash provisioning) so
4
+ missing operator configuration produces one clear, actionable error instead of a
5
+ partial run that dies mid-provisioning. End users never see these — their preflight is
6
+ client-side ("do I have an AutoSLM key?", see autoslm/client).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+
13
+ from autoslm.providers.runpod.auth import load_api_key
14
+
15
+
16
+ class PreflightError(RuntimeError):
17
+ """Raised when required operator credentials/configuration are missing."""
18
+
19
+
20
+ def missing_credentials(require_hf: bool = True) -> list[str]:
21
+ """RunPod-related operator config that is missing (empty list == ready)."""
22
+ problems: list[str] = []
23
+ if not load_api_key():
24
+ problems.append(" - RUNPOD_API_KEY: the operator's RunPod API key")
25
+ if require_hf and not os.environ.get("HF_TOKEN"):
26
+ problems.append(
27
+ " - HF_TOKEN: a token with write access to each run's "
28
+ "`[train] hf_repo`, e.g. `export HF_TOKEN=hf_...`"
29
+ )
30
+ return problems
code/autoslm/providers/runpod/pricing.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-GPU hourly rates: RunPod live pricing with a static fallback.
2
+
3
+ Cost projection (runner, serve) and the ``gpu.type = "cheapest"`` policy both
4
+ need $/hr per GPU class. Rates move with the market, so we read them live from the
5
+ RunPod pricing API (the ``runpod`` SDK's GraphQL wrapper — the plain REST surface has
6
+ no GPU-types route and direct GraphQL is 403 for scoped keys) and cache them on disk;
7
+ any failure falls back to the static snapshot in ``providers.base.GPU_INFO``.
8
+
9
+ Rates are RunPod secure-cloud on-demand — representative for ranking and projection,
10
+ not an exact serverless invoice (the worker also records wall time; real cost comes
11
+ from RunPod billing).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ import time
19
+ from pathlib import Path
20
+
21
+ from autoslm._logging import get_logger
22
+
23
+ logger = get_logger(__name__)
24
+
25
+ CACHE_TTL_S = float(os.environ.get("AUTOSLM_PRICE_TTL_S", str(6 * 3600)))
26
+ _CACHE_PATH = Path.home() / ".autoslm" / "gpu_rates.json"
27
+ _MEM: dict = {"ts": 0.0, "rates": {}}
28
+
29
+
30
+ def _static_rates() -> dict[str, float]:
31
+ from autoslm.providers.base import GPU_INFO
32
+
33
+ return {name: info.hourly_usd for name, info in GPU_INFO.items()}
34
+
35
+
36
+ def _pick_rate(detail: dict) -> float | None:
37
+ """Best representative on-demand rate from a RunPod gpuTypes detail row."""
38
+ for key in ("securePrice", "communityPrice"):
39
+ v = detail.get(key)
40
+ if v:
41
+ return float(v)
42
+ v = (detail.get("lowestPrice") or {}).get("uninterruptablePrice")
43
+ return float(v) if v else None
44
+
45
+
46
+ def _fetch_live_rates() -> dict[str, float]:
47
+ """One pricing call per managed GPU class (the list query carries no prices)."""
48
+ import runpod
49
+
50
+ from autoslm.providers.base import GPU_INFO
51
+ from autoslm.providers.runpod.gpus import gpu_api_id
52
+
53
+ if not runpod.api_key:
54
+ runpod.api_key = os.environ.get("RUNPOD_API_KEY")
55
+ rates: dict[str, float] = {}
56
+ for name, info in GPU_INFO.items():
57
+ if not info.enum_member: # Vast-only class -> no RunPod pricing route
58
+ continue
59
+ try:
60
+ rate = _pick_rate(runpod.get_gpu(gpu_api_id(name)) or {})
61
+ except Exception as exc:
62
+ logger.debug("live rate fetch failed for %s: %s", name, exc)
63
+ continue
64
+ if rate:
65
+ rates[name] = rate
66
+ return rates
67
+
68
+
69
+ def live_rates(refresh: bool = False) -> dict[str, float]:
70
+ """Friendly-name -> $/hr. Live (cached ``CACHE_TTL_S``) over the static snapshot.
71
+
72
+ Offline-safe: AUTOSLM_SKIP_NET (or any fetch failure) returns the static rates.
73
+ """
74
+ static = _static_rates()
75
+ if os.environ.get("AUTOSLM_SKIP_NET"):
76
+ return static
77
+ now = time.time()
78
+ if not refresh:
79
+ if _MEM["rates"] and now - _MEM["ts"] < CACHE_TTL_S:
80
+ return {**static, **_MEM["rates"]}
81
+ try:
82
+ disk = json.loads(_CACHE_PATH.read_text())
83
+ if now - float(disk.get("ts", 0)) < CACHE_TTL_S and disk.get("rates"):
84
+ _MEM.update(ts=float(disk["ts"]), rates=dict(disk["rates"]))
85
+ return {**static, **_MEM["rates"]}
86
+ except Exception:
87
+ # Corrupt/unreadable cache: ignore and fall through to a live fetch.
88
+ pass
89
+ try:
90
+ fetched = _fetch_live_rates()
91
+ except Exception as exc:
92
+ logger.warning("live GPU pricing unavailable (%s); using static rates", exc)
93
+ fetched = {}
94
+ if fetched:
95
+ _MEM.update(ts=now, rates=fetched)
96
+ try:
97
+ _CACHE_PATH.parent.mkdir(parents=True, exist_ok=True)
98
+ _CACHE_PATH.write_text(json.dumps({"ts": now, "rates": fetched}))
99
+ except Exception:
100
+ # Cache write is an optimization; a read-only/full FS shouldn't fail pricing.
101
+ pass
102
+ return {**static, **_MEM["rates"]}
103
+
104
+
105
+ def hourly_rate(gpu_name: str) -> float:
106
+ """$/hr for one friendly GPU name (live if available, else static)."""
107
+ from autoslm.providers.base import canonical_gpu
108
+
109
+ name = canonical_gpu(gpu_name)
110
+ return live_rates().get(name) or _static_rates()[name]
code/autoslm/providers/runpod/train.py ADDED
@@ -0,0 +1,820 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RunPod Flash fine-tuning endpoints (queue-based, one dedicated GPU per run).
2
+
3
+ Flash provisions a dedicated RunPod GPU (RTX 4090 / 5090, no Docker), installs
4
+ ``WORKER_DEPS``, runs the handler, returns the metrics dict, and scales to zero.
5
+
6
+ Flash's live ("ad-hoc") provisioning does not bundle local project code, so the
7
+ handler fetches the ``autoslm`` package from the HF dataset repo (uploaded by
8
+ ``upload_code`` before submit), adds it to ``PYTHONPATH``, and runs
9
+ ``autoslm.engine.worker`` to train. The worker streams the adapter + checkpoints to
10
+ the same HF repo for serving and preemption-resilient resume.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import asyncio
16
+ import contextlib
17
+ import inspect
18
+ import os
19
+ import threading
20
+ from typing import Any
21
+
22
+ from autoslm._logging import get_logger
23
+ from autoslm.providers.base import canonical_gpu, gpu_short
24
+ from autoslm.providers.runpod.gpus import flash_gpu
25
+ from autoslm.spec import JobSpec
26
+
27
+ logger = get_logger(__name__)
28
+
29
+ # The control plane runs each training run in its own thread. All runpod_flash deploy/
30
+ # undeploy work goes through a shared asyncio singleton whose Lock binds to the first event
31
+ # loop that touches it; two threads each calling asyncio.run() get distinct loops and the
32
+ # second fails with "Lock ... is bound to a different event loop". Serialize every Flash SDK
33
+ # async section (deploy AND undeploy) behind this one process-wide lock. Deploys/teardowns
34
+ # are infrequent vs training, so the serialization cost is negligible.
35
+ FLASH_SDK_LOCK = threading.Lock()
36
+
37
+
38
+ # Worker stack: trl 1.6 (colocate default; adds the GRPO `tools=` / `rollout_func`
39
+ # multi-turn hooks used for verifiers ToolEnv / MultiTurnEnv training), vllm 0.19.1
40
+ # (Qwen3.5/3.6 archs, native RL APIs, transformers-5
41
+ # compatible metadata), transformers 5.x (qwen3_5/qwen3_5_moe model types),
42
+ # bitsandbytes (4-bit NF4 QLoRA tier). trl 1.6 requires transformers>=4.56,
43
+ # satisfied by the 5.6+ pin; GRPOConfig is field-compatible with the 1.5 usage here.
44
+ # Resolver/driver notes: vllm 0.17/0.18 hard-pin transformers<5 (uv refuses the
45
+ # combo), so the first transformers-5-compatible vllm line is 0.19.1. vllm >=0.20
46
+ # pins torch 2.11 whose default pypi wheels are CUDA-13 builds — RunPod 4090/5090
47
+ # hosts filtered at min_cuda 12.8 often run 12.8/12.9 drivers where cu13 torch sees
48
+ # NO GPU (observed: "cuda not available" + vLLM "cumem allocator not supported").
49
+ # vllm 0.19.1 pins torch 2.10 (cu128 default) which matches those drivers.
50
+ # trl's *optional* [vllm] extra caps at 0.18, but we install plain trl, so the only
51
+ # constraint that matters is runtime API compat — validated per-model on real
52
+ # RTX 4090/5090 workers before promotion to default (see bench/results/phase1).
53
+ WORKER_DEPS = [
54
+ "torch==2.10.0",
55
+ "transformers>=5.6,<5.13",
56
+ "trl>=1.6,<1.7",
57
+ "peft>=0.19",
58
+ "vllm==0.19.1",
59
+ "bitsandbytes>=0.49",
60
+ "datasets>=4.7,<6",
61
+ "huggingface_hub>=0.25",
62
+ "accelerate>=1.4",
63
+ # NB: the HF `kernels` Hub package is intentionally NOT pinned here — the versions
64
+ # compatible with torch2.10 break transformers 5.6-5.10's hub_kernels integration at IMPORT
65
+ # (LayerRepository now requires a version; transformers passes none -> ValueError on every
66
+ # `import transformers`). FlashAttention via the Hub is therefore disabled; attention uses
67
+ # SDPA (already a flash/efficient backend on Ampere/Ada) + the Liger fused kernels below,
68
+ # which are the dominant LoRA speedup anyway. (FA via a pinned flash-attn wheel is a future
69
+ # per-arch experiment, kept out of the default deps to avoid a fragile cold-start install.)
70
+ # Liger fused Triton kernels (pure Triton -> JITs on every arch incl. Blackwell): fused
71
+ # linear cross-entropy for SFT (use_liger_kernel) and the chunked GRPO loss
72
+ # (use_liger_loss) — the big large-vocab (Qwen ~152k) memory/throughput win.
73
+ "wandb>=0.17",
74
+ "liger-kernel>=0.5",
75
+ # Fused Triton kernels for Gated-DeltaNet (Qwen3.5/3.6 family): without this,
76
+ # transformers falls back to a pure-PyTorch delta rule and GRPO trainer steps are
77
+ # 2-3x slower (measured A/B on Qwen3.5-2B: ~65 s/step -> ~20 s/step steady).
78
+ "flash-linear-attention==0.5.0",
79
+ # NB: fla's gated chunk_bwd is broken on HOPPER (H100) with Triton >= 3.4 (fla #640), so
80
+ # resolve_worker_deps DROPS fla on sm90 (the correct pure-PyTorch delta rule runs instead). The
81
+ # dense Qwen3.5 GDN models route to consumer cards by default, where fla works.
82
+ ]
83
+ # NOTE on download speed: Flash's runtime already ships hf_transfer and exports
84
+ # HF_HUB_ENABLE_HF_TRANSFER=1 on workers (measured: Qwen3-4B's ~8 GB pulled in 6.3 s,
85
+ # NIC-saturated — bench/results/phase6). Adding hf_transfer here is redundant; don't.
86
+ # Override the whole pinned stack per-run with AUTOSLM_WORKER_DEPS="pkgA==1 pkgB>=2"
87
+ # (whitespace-separated, or a JSON list for specs containing commas).
88
+ WORKER_SYSTEM_DEPS = ["build-essential"] # Triton/Inductor need a C compiler
89
+
90
+ # The prebuilt worker image (full training stack baked in; built by Dockerfile.worker /
91
+ # .github/workflows/worker-image.yml). PUBLIC under the org namespace, so no registry login is
92
+ # ever needed. Used on both Vast and RunPod. AUTOSLM_WORKER_IMAGE overrides it; set it to "" to
93
+ # blank the image and fall back to installing WORKER_DEPS at runtime on the default Flash runtime
94
+ # (slower cold start, but survives a transiently-unhealthy/unpublished baked image). NOTE: the
95
+ # blank-image fallback is RunPod-Flash-only — Vast has no bare default runtime, so vast_image()
96
+ # substitutes DEFAULT_WORKER_IMAGE when this is blank (create_instance requires a real image).
97
+ DEFAULT_WORKER_IMAGE = "ghcr.io/freesolo-co/autoslm-worker:cu128"
98
+ WORKER_IMAGE = os.environ.get("AUTOSLM_WORKER_IMAGE", DEFAULT_WORKER_IMAGE)
99
+
100
+
101
+ def resolve_worker_deps(friendly_gpu: str | None = None) -> list[str]:
102
+ """The dependency list Flash installs on the GPU worker for this run.
103
+
104
+ Precedence: AUTOSLM_WORKER_DEPS (explicit list) > the pinned ``WORKER_DEPS``.
105
+
106
+ GPU-specific: on HOPPER (sm90, H100), DROP flash-linear-attention — its gated
107
+ chunk_bwd Triton kernel is miscomputed there (Triton>=3.4, fla #640). Without fla,
108
+ transformers uses the correct pure-PyTorch delta rule (slower but correct).
109
+ Ampere/Ada/Blackwell keep fla for the speedup.
110
+ """
111
+ explicit = os.environ.get("AUTOSLM_WORKER_DEPS")
112
+ if explicit:
113
+ # JSON list (use this for specs containing commas, e.g.
114
+ # "transformers>=5.6,<5.13") or a whitespace-separated string.
115
+ if explicit.strip().startswith("["):
116
+ import json as _json
117
+
118
+ deps = [str(d).strip() for d in _json.loads(explicit) if str(d).strip()]
119
+ else:
120
+ # shlex (whitespace) splitting, NOT comma: a comma is part of a PEP 440
121
+ # range like `transformers>=5.6,<5.11` and must not be split.
122
+ import shlex
123
+
124
+ deps = [d for d in shlex.split(explicit) if d.strip()]
125
+ if deps:
126
+ return deps
127
+ deps = list(WORKER_DEPS)
128
+ # Hopper (sm90) fla strategy: DROP flash-linear-attention -> the correct pure-PyTorch delta
129
+ # rule. fla's gated chunk_bwd Triton kernel is miscomputed on Hopper (Triton>=3.4, fla #640),
130
+ # so on H100 we run without it (the dense Qwen3.5 GDN models route to consumer cards by
131
+ # default, where fla stays). Ampere/Ada/Blackwell keep fla for the speedup.
132
+ if friendly_gpu:
133
+ try:
134
+ from autoslm.providers.base import get_gpu_info
135
+
136
+ if get_gpu_info(friendly_gpu).sm == "sm90":
137
+ deps = [d for d in deps if not d.startswith("flash-linear-attention")]
138
+ except Exception:
139
+ pass
140
+ # Additive per-run extras (e.g. an extra pinned wheel for an A/B) without
141
+ # restating the whole pinned stack the way AUTOSLM_WORKER_DEPS requires.
142
+ extra = os.environ.get("AUTOSLM_WORKER_EXTRA_DEPS")
143
+ if extra:
144
+ import shlex
145
+
146
+ deps = deps + [d for d in shlex.split(extra) if d.strip()]
147
+ return deps
148
+
149
+
150
+ DEFAULT_EXECUTION_TIMEOUT_MS = 6 * 3600 * 1000 # 6h RunPod worker execution cap
151
+
152
+ _ENDPOINT_CACHE: dict[str, Any] = {}
153
+
154
+
155
+ def upload_code(repo: str | None = None) -> str:
156
+ """Upload the ``autoslm`` package to the run's HF artifact repo.
157
+
158
+ ``repo`` is the per-run artifact repo (``spec.train.hf_repo``); the worker fetches
159
+ ``code/**`` from the same repo it is given in the submit payload, so the code must land in
160
+ that per-run repo.
161
+
162
+ The worker downloads ``code/**`` to ``/runcode``. Verifiers-only: there are no built-in
163
+ example environments to ship — Hub/installed envs are pip-installed on the worker (see
164
+ ``registry.worker_pip_for_env``).
165
+
166
+ Only the ``autoslm`` package is uploaded, NOT the client's project tree. Managed runs must
167
+ reference a published Hub env by ``id`` (``slm env push`` to publish a local env first); the
168
+ worker pip-installs the env wheel.
169
+ """
170
+ from huggingface_hub import HfApi
171
+
172
+ import autoslm
173
+
174
+ if not repo:
175
+ raise RuntimeError(
176
+ "hf_repo must be set (the run's [train] hf_repo: HF dataset repo for code + artifacts)"
177
+ )
178
+ token = os.environ.get("HF_TOKEN")
179
+ pkg_dir = os.path.dirname(os.path.abspath(autoslm.__file__))
180
+ api = HfApi(token=token)
181
+ # Worker pulls code/** by HTTP; HF FREE-TIER accounts cannot serve PRIVATE dataset
182
+ # downloads (worker gets 403), so operators on a free tier must publish artifact repos
183
+ # public. Default private (paid-tier safe); set AUTOSLM_HF_REPO_PRIVATE=0 to create public.
184
+ private = os.environ.get("AUTOSLM_HF_REPO_PRIVATE", "1") not in ("0", "false", "False")
185
+ api.create_repo(repo, repo_type="dataset", exist_ok=True, private=private)
186
+ # create_repo(exist_ok=True) is a no-op on an EXISTING repo, so it never flips a repo that
187
+ # already exists private back to public. When the operator wants public (free-tier: workers
188
+ # 403 on private downloads), force visibility explicitly so a reused private repo is fixed.
189
+ if not private:
190
+ try:
191
+ api.update_repo_settings(repo_id=repo, repo_type="dataset", private=False)
192
+ except Exception as e:
193
+ logger.warning("could not ensure %s is public (free-tier worker may 403): %s", repo, e)
194
+ api.upload_folder(
195
+ folder_path=pkg_dir,
196
+ path_in_repo="code/autoslm",
197
+ repo_id=repo,
198
+ repo_type="dataset",
199
+ ignore_patterns=["__pycache__/*", "*.pyc"],
200
+ )
201
+ return repo
202
+
203
+
204
+ def _train_body(input_data: dict) -> dict:
205
+ """Runs ON the RunPod GPU worker: fetch code, train (phase), return metrics.
206
+
207
+ NOTE: Flash serializes this handler and runs it standalone, so every name it uses
208
+ must be imported INSIDE the function body (module-level imports are not in scope).
209
+ """
210
+ import contextlib
211
+ import json
212
+ import os
213
+ import shutil
214
+ import subprocess
215
+ import sys
216
+
217
+ from huggingface_hub import snapshot_download
218
+
219
+ # NB: the Hopper fla guard lives in engine.worker._drop_fla_on_hopper (runs in the worker
220
+ # process AFTER all installs, before any model import) — doing it here would be undone by a
221
+ # later extra_pip / `prime env install` that pulls fla back, and depends on a handler redeploy.
222
+
223
+ # Extra pip deps for verifiers / Prime Hub environments (installed per-run).
224
+ extra_pip = input_data.get("extra_pip") or []
225
+ if extra_pip:
226
+ # check=True: a deterministic dependency failure should fail fast here,
227
+ # not after model download + worker startup with a less actionable error.
228
+ subprocess.run([sys.executable, "-m", "pip", "install", *extra_pip], check=True)
229
+
230
+ # NB: fla is dropped on Hopper (sm90) automatically — resolve_worker_deps omits it from the
231
+ # install list, and engine.worker._drop_fla_on_hopper removes any baked-in copy at worker
232
+ # startup (fla's GDN backward is miscomputed on sm90, #640). No env toggle: fla only ever runs
233
+ # on the consumer archs where its Triton kernel is correct.
234
+
235
+ # Install the run's verifiers environment(s) from the Prime Hub via the authenticated
236
+ # `prime` CLI. The public pip index does not serve PRIVATE env wheels, so a plain pip
237
+ # install can't fetch them; `prime env install` pulls/builds/installs public + private
238
+ # alike, authenticated by PRIME_API_KEY forwarded from the control plane.
239
+ hub_env_ids = input_data.get("hub_env_ids") or []
240
+ if hub_env_ids:
241
+ worker_env = {k: str(v) for k, v in (input_data.get("env") or {}).items()}
242
+ prime_key = worker_env.get("PRIME_API_KEY") or os.environ.get("PRIME_API_KEY")
243
+ if not prime_key:
244
+ raise RuntimeError(
245
+ "PRIME_API_KEY is required to install the Prime Hub environment on the worker"
246
+ )
247
+ # Only install `prime` when it isn't already on the worker (it's often baked into
248
+ # the worker image) — an unconditional install adds latency and a per-run PyPI
249
+ # failure point every run.
250
+ if shutil.which("prime") is None:
251
+ subprocess.run([sys.executable, "-m", "pip", "install", "prime"], check=True)
252
+ # --with pip: install the env into THIS (the trainer's) python via pip. The default
253
+ # (`--with uv`) installs into prime's own isolated uv env, so the trainer then can't
254
+ # import the env module (ModuleNotFoundError at load_environment). PIP_BREAK_SYSTEM_PACKAGES
255
+ # lets pip write to a PEP-668 "externally-managed" base python (the worker image's).
256
+ install_env = {
257
+ **os.environ,
258
+ "PRIME_API_KEY": prime_key,
259
+ "PRIME_DISABLE_VERSION_CHECK": "1",
260
+ "PIP_BREAK_SYSTEM_PACKAGES": "1",
261
+ }
262
+ for env_id in hub_env_ids:
263
+ subprocess.run(
264
+ ["prime", "env", "install", env_id, "--with", "pip"], check=True, env=install_env
265
+ )
266
+
267
+ overrides = {k: str(v) for k, v in (input_data.get("env") or {}).items()}
268
+ snapshot_download(
269
+ repo_id=input_data["hf_repo"],
270
+ repo_type="dataset",
271
+ allow_patterns=["code/**"],
272
+ local_dir="/runcode",
273
+ token=overrides.get("HF_TOKEN"),
274
+ )
275
+ code_dir = "/runcode/code"
276
+
277
+ env = dict(os.environ)
278
+ env.update(overrides)
279
+ # A large job_spec_json (e.g. many inline params/dataset refs) can blow past the
280
+ # ~128 KiB per-env-string exec limit ("Argument list too long"). Pass a large spec
281
+ # via a file (AUTOSLM_JOB_SPEC_PATH); keep the inline env var for small specs.
282
+ # load_job_spec_from_env reads either.
283
+ spec_json = input_data["job_spec_json"]
284
+ if len(spec_json) > 96_000:
285
+ spec_path = "/tmp/job_spec.json"
286
+ with open(spec_path, "w") as sf:
287
+ sf.write(spec_json)
288
+ env["AUTOSLM_JOB_SPEC_PATH"] = spec_path
289
+ env.pop("AUTOSLM_JOB_SPEC_JSON", None)
290
+ else:
291
+ env["AUTOSLM_JOB_SPEC_JSON"] = spec_json
292
+ env["PHASE"] = input_data["phase"]
293
+ env["SEED"] = str(input_data["seed"])
294
+ env["PYTHONPATH"] = code_dir + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
295
+
296
+ def run_mode(mode: str, check: bool) -> int:
297
+ """Run one worker process, tee its console to a file, and on failure upload the
298
+ tail to HF as console_<mode>.txt — the engine-core root cause of crashes like
299
+ vLLM EngineDeadError only ever appears on the subprocess console, never in the
300
+ Python traceback."""
301
+ console = f"/tmp/console_{mode}.txt"
302
+ with open(console, "w") as cf:
303
+ proc = subprocess.Popen(
304
+ [sys.executable, "-m", "autoslm.engine.worker"],
305
+ cwd=code_dir,
306
+ env={**env, "RUN_MODE": mode},
307
+ stdout=subprocess.PIPE,
308
+ stderr=subprocess.STDOUT,
309
+ text=True,
310
+ )
311
+ for line in proc.stdout:
312
+ print(line, end="") # keep streaming to the platform console
313
+ cf.write(line)
314
+ proc.wait()
315
+ if proc.returncode != 0:
316
+ try:
317
+ from huggingface_hub import HfApi
318
+
319
+ spec = json.loads(input_data["job_spec_json"])
320
+ phase_ns = "rl" if spec.get("algorithm") == "grpo" else spec["algorithm"]
321
+ prefix = f"{phase_ns}/{spec['run_id']}/seed{input_data['seed']}"
322
+ with open(console) as f:
323
+ tail = f.read()[-64_000:]
324
+ with open(console + ".tail", "w") as f:
325
+ f.write(tail)
326
+ HfApi(token=env.get("HF_TOKEN")).upload_file(
327
+ path_or_fileobj=console + ".tail",
328
+ path_in_repo=f"{prefix}/console_{mode}.txt",
329
+ repo_id=input_data["hf_repo"],
330
+ repo_type="dataset",
331
+ )
332
+ except Exception as up_err:
333
+ print("console upload warn:", up_err)
334
+ if check:
335
+ raise RuntimeError(
336
+ f"worker mode '{mode}' exited {proc.returncode}; see console_{mode}.txt "
337
+ f"and error_{mode}.txt in the HF dataset repo"
338
+ )
339
+ return proc.returncode
340
+
341
+ # A warm worker can carry a previous seed's metrics files; a stale metrics.json
342
+ # would let a crashed train phase report the previous run's numbers. Clear before
343
+ # training.
344
+ for stale in ("/tmp/train_meta.json", "/tmp/metrics.json"):
345
+ with contextlib.suppress(FileNotFoundError):
346
+ os.remove(stale)
347
+ # Train. check=False — RL's colocated vLLM can segfault at interpreter exit AFTER
348
+ # the adapter + metrics.json + DONE are saved; don't treat that as a failure.
349
+ run_mode(input_data["phase"], check=False)
350
+ # The train phase writes metrics.json + the DONE sentinel itself (RunPod can also
351
+ # redeliver a completed job, whose worker restores metrics.json from DONE). If it
352
+ # is missing, the train phase crashed before finishing — fail fast with the real
353
+ # cause (full traceback in error_<phase>.txt / console_<phase>.txt in the HF repo).
354
+ if not os.path.exists("/tmp/metrics.json"):
355
+ phase = input_data["phase"]
356
+ raise RuntimeError(
357
+ f"train phase '{phase}' produced no /tmp/metrics.json (it crashed before "
358
+ f"finishing); see error_{phase}.txt and console_{phase}.txt in the HF "
359
+ f"dataset repo for the full traceback"
360
+ )
361
+ with open("/tmp/metrics.json") as f:
362
+ return json.load(f)
363
+
364
+
365
+ def isolate_flash_state(scope: str | None = None) -> None:
366
+ """Point the Flash SDK's resource registry at a per-process/private directory.
367
+
368
+ The SDK persists its registry to ``./.flash/resources.pkl`` — shared, whole-dict,
369
+ last-writer-wins across every process in the CWD. Observed failure modes: stale
370
+ entries resurrecting long-dead endpoints on later syncs, and concurrent processes
371
+ clobbering each other's bookkeeping. Each AutoSLM process gets its own registry
372
+ under ``~/.autoslm/flash-state/<scope>``; remote cleanup never relies on the
373
+ registry anyway (REST by id/name — see api.py).
374
+ """
375
+ try:
376
+ from pathlib import Path
377
+
378
+ import runpod_flash.core.resources.resource_manager as rm
379
+
380
+ scope = scope or f"pid{os.getpid()}"
381
+ state_dir = Path.home() / ".autoslm" / "flash-state" / scope
382
+ state_dir.mkdir(parents=True, exist_ok=True)
383
+ rm.FLASH_STATE_DIR = state_dir
384
+ rm.RESOURCE_STATE_FILE = state_dir / "resources.pkl"
385
+ except Exception as exc: # never block a run on this
386
+ logger.warning("flash state isolation skipped: %s", exc)
387
+
388
+
389
+ def _patch_runpod_backoff() -> None:
390
+ """Work around a runpod_flash bug that aborts long-running jobs.
391
+
392
+ The SDK polls a synchronous job with exponential backoff computed as
393
+ ``base * (2 ** attempt)`` and only clamps to ``max_seconds`` afterwards. On a long
394
+ run the poll ``attempt`` grows without bound, so ``2 ** attempt`` becomes a huge int
395
+ and the float multiply raises ``OverflowError: int too large to convert to float``
396
+ (observed ~80 min in), killing an otherwise-healthy job mid-run. We patch the symbol
397
+ to cap the exponent before the power so the delay still saturates at ``max_seconds``.
398
+ """
399
+ try:
400
+ import math
401
+ import random
402
+
403
+ from runpod_flash.core.utils import backoff as _bo
404
+
405
+ if getattr(_bo, "_autoslm_backoff_patched", False):
406
+ return
407
+
408
+ def _safe_get_backoff_delay(
409
+ attempt,
410
+ base=0.1,
411
+ max_seconds=10.0,
412
+ jitter=0.2,
413
+ strategy=_bo.BackoffStrategy.EXPONENTIAL,
414
+ ):
415
+ a = min(int(attempt), 30) # cap exponent: 2**30 is plenty; delay saturates anyway
416
+ if strategy == _bo.BackoffStrategy.EXPONENTIAL:
417
+ delay = base * (2**a)
418
+ elif strategy == _bo.BackoffStrategy.LINEAR:
419
+ delay = base + (attempt * base)
420
+ elif strategy == _bo.BackoffStrategy.LOGARITHMIC:
421
+ delay = base * math.log2(attempt + 2)
422
+ else:
423
+ raise ValueError(f"Unsupported backoff strategy: {strategy}")
424
+ delay = min(delay, max_seconds)
425
+ return delay * random.uniform(1 - jitter, 1 + jitter)
426
+
427
+ _bo.get_backoff_delay = _safe_get_backoff_delay
428
+ _bo._autoslm_backoff_patched = True
429
+ # serverless.py did `from ..utils.backoff import get_backoff_delay`, so patch its ref too.
430
+ try:
431
+ from runpod_flash.core.resources import serverless as _sl
432
+
433
+ _sl.get_backoff_delay = _safe_get_backoff_delay
434
+ except Exception:
435
+ # serverless.py may not import the symbol in this SDK version; the primary
436
+ # patch above still applies, so a missing alias is fine to ignore.
437
+ pass
438
+ except Exception as exc: # never let the patch break submission
439
+ logger.warning("runpod backoff patch skipped: %s", exc)
440
+
441
+
442
+ def min_cuda_for(friendly_gpu: str) -> str:
443
+ """Minimum host CUDA (driver) version for this GPU class on the active stack.
444
+
445
+ Blackwell classes (sm_120 — RTX 5090, RTX Pro 6000): pypi wheels for
446
+ the modern stack (vllm 0.19) ship no Blackwell SASS, so every custom CUDA kernel
447
+ is PTX-JIT'd by the driver — and their PTX is built with a newer toolchain than
448
+ CUDA-12.8-era drivers can JIT (observed: "the provided PTX was compiled with an
449
+ unsupported toolchain" on driver 570.x). CUDA-13 drivers JIT it fine, so those
450
+ classes are pinned to >=13.0 on the modern stack (per-GPU ``min_cuda_modern`` in
451
+ providers.base.GPU_INFO). Ampere/Ada/Hopper have SASS in the wheels and run on 12.8.
452
+ Override with AUTOSLM_MIN_CUDA.
453
+ """
454
+ explicit = os.environ.get("AUTOSLM_MIN_CUDA")
455
+ if explicit:
456
+ return explicit
457
+ from autoslm.providers.base import min_cuda_modern
458
+
459
+ return min_cuda_modern(friendly_gpu)
460
+
461
+
462
+ def endpoint_name(friendly_gpu: str, suffix: str | None = None) -> str:
463
+ """Flash endpoint/template name for a GPU class, optionally made unique per run.
464
+
465
+ A fixed name (``autoslm-train-5090``) collides across back-to-back runs: runpod_flash's
466
+ ``get_or_deploy_resource`` finds the prior run's still-registered resource and tries to
467
+ *update* it, which fails with ``GraphQL errors: Template name must be unique`` (there is
468
+ no endpoint GC/reuse). A per-run ``suffix`` (the run id tail) gives each run its own
469
+ endpoint so it deploys fresh instead of colliding. RunPod scales each to zero when idle.
470
+ """
471
+ base = f"autoslm-train-{gpu_short(friendly_gpu)}"
472
+ if not suffix:
473
+ return base
474
+ safe = "".join(c for c in str(suffix) if c.isalnum() or c == "-").strip("-")[:24]
475
+ return f"{base}-{safe}" if safe else base
476
+
477
+
478
+ def get_train_endpoint(
479
+ friendly_gpu: str,
480
+ execution_timeout_ms: int | None = None,
481
+ name_suffix: str | None = None,
482
+ disk_gb: int | None = None,
483
+ spec=None,
484
+ ):
485
+ """Build (and cache) the live Flash endpoint handler for a GPU class."""
486
+ # Live ("ad-hoc") provisioning: provision on call, no separate `flash deploy`.
487
+ os.environ["FLASH_IS_LIVE_PROVISIONING"] = "true"
488
+ from runpod_flash import Endpoint
489
+
490
+ from autoslm.providers.runpod.auth import ensure_auth
491
+ from autoslm.providers.runpod.jobs import volume_endpoint_kwargs
492
+
493
+ ensure_auth()
494
+ _patch_runpod_backoff()
495
+ isolate_flash_state(name_suffix)
496
+
497
+ friendly = canonical_gpu(friendly_gpu)
498
+ name = endpoint_name(friendly, name_suffix)
499
+ if name in _ENDPOINT_CACHE:
500
+ return _ENDPOINT_CACHE[name]
501
+ kwargs = dict(
502
+ name=name,
503
+ gpu=flash_gpu(friendly),
504
+ gpu_count=1,
505
+ min_cuda_version=min_cuda_for(friendly),
506
+ execution_timeout_ms=execution_timeout_ms or DEFAULT_EXECUTION_TIMEOUT_MS,
507
+ workers=(0, 1), # one dedicated worker per run; scale to zero when idle
508
+ **volume_endpoint_kwargs(spec),
509
+ )
510
+ # Prebuilt worker image (deps baked in) cuts the cold-start dep install. It's PUBLIC, so no
511
+ # registry login is needed. If WORKER_IMAGE is ever blanked, fall back to installing
512
+ # WORKER_DEPS on first use (cached as a Flash artifact across calls).
513
+ if WORKER_IMAGE:
514
+ kwargs["image"] = WORKER_IMAGE
515
+ else:
516
+ kwargs["dependencies"] = resolve_worker_deps(friendly)
517
+ kwargs["system_dependencies"] = WORKER_SYSTEM_DEPS
518
+ ep = Endpoint(**kwargs)
519
+ handler = ep(_train_body) # register the queue-based handler; returns the callable
520
+ # The resource config is cached on the Endpoint, so raising the disk on it here
521
+ # carries through to the deploy that the first handler call triggers.
522
+ from autoslm.providers.runpod.jobs import apply_disk_gb
523
+
524
+ cfg = ep._build_resource_config()
525
+ apply_disk_gb(cfg, disk_gb)
526
+ _ENDPOINT_CACHE[name] = handler
527
+ return handler
528
+
529
+
530
+ def _run_suffix(run_id: str | None) -> str | None:
531
+ """Short, COLLISION-FREE per-run endpoint suffix.
532
+
533
+ Must be unique per run_id: the endpoint name is ``endpoint_name(friendly, suffix)`` and
534
+ RunPod reuses an endpoint by name -- two runs with the same suffix share one endpoint (and
535
+ its cached image/deps/registry-auth/template), so a later run silently reuses the earlier
536
+ one's config. The old ``run_id.split("-")[-1]`` only worked for hash-tailed default ids; a
537
+ descriptive run_id ending in e.g. the card name (``...-a100``) collided across every run.
538
+ Use a stable short hash of the WHOLE run_id, with a sanitized prefix for readability."""
539
+ if not run_id:
540
+ return None
541
+ import hashlib
542
+ import re
543
+
544
+ h = hashlib.sha1(run_id.encode()).hexdigest()[:8]
545
+ prefix = re.sub(r"[^a-z0-9]", "", run_id.lower())[-12:]
546
+ return f"{prefix}{h}" if prefix else h
547
+
548
+
549
+ def stop_endpoint(friendly_gpu: str, name: str | None = None) -> None:
550
+ """Best-effort: scale cached endpoint(s) to zero / drop them.
551
+
552
+ With ``name`` only that run's cached endpoint is dropped; without it, every
553
+ cached endpoint of the GPU class is — so a per-run teardown passes ``name``
554
+ to avoid evicting a concurrent run's handler in the same process.
555
+
556
+ NOTE: this only touches THIS process's in-memory cache, so it does nothing in a fresh
557
+ ``slm cancel`` process. Use ``terminate_endpoint`` to actually delete the remote endpoint.
558
+ """
559
+ friendly = canonical_gpu(friendly_gpu)
560
+ prefix = f"autoslm-train-{gpu_short(friendly)}"
561
+ if name:
562
+ match = [k for k in _ENDPOINT_CACHE if k == name]
563
+ else:
564
+ match = [k for k in _ENDPOINT_CACHE if k.startswith(prefix)]
565
+ for key in match:
566
+ handler = _ENDPOINT_CACHE.pop(key, None)
567
+ ep = getattr(handler, "__self__", None) or getattr(handler, "endpoint", None)
568
+ for meth in ("scale_to_zero", "stop", "delete"):
569
+ fn = getattr(ep, meth, None)
570
+ if callable(fn):
571
+ try:
572
+ fn()
573
+ break
574
+ except Exception:
575
+ continue
576
+
577
+
578
+ def _select_endpoint_resources(resources: dict, target: str) -> list[str]:
579
+ """Resource ids whose resource ``.name`` contains ``target``.
580
+
581
+ The live-provisioned resource is named ``live-<endpoint_name>``, so we match by substring
582
+ to catch the prefix. ``target`` is the endpoint name (``autoslm-train-<gpu>[-<run>]``).
583
+ """
584
+ if not target:
585
+ return []
586
+ out = []
587
+ for uid, res in (resources or {}).items():
588
+ name = str(getattr(res, "name", "") or "")
589
+ if target in name:
590
+ out.append(uid)
591
+ return out
592
+
593
+
594
+ def terminate_endpoint(friendly_gpu: str, run_id: str | None = None) -> list[dict]:
595
+ """Reliably tear down the remote Flash endpoint(s) for a run — cross-process.
596
+
597
+ Unlike ``stop_endpoint`` (which only touches this process's in-memory cache), this looks
598
+ the endpoint up by name in runpod_flash's *persisted* resource registry and deletes it via
599
+ the RunPod API (``ResourceManager.undeploy_resource`` -> ``delete_endpoint``), which stops
600
+ any running worker. Best-effort: never raises. Returns the per-resource undeploy results.
601
+
602
+ With ``run_id`` it targets exactly that run's uniquely-named endpoint; without it, the
603
+ bare ``autoslm-train-<gpu>`` prefix matches every endpoint of that GPU class.
604
+ """
605
+ friendly = canonical_gpu(friendly_gpu)
606
+ target = endpoint_name(friendly, _run_suffix(run_id))
607
+ # Hold FLASH_SDK_LOCK across the ENTIRE Flash critical section, not just the undeploy.
608
+ # isolate_flash_state() swaps runpod_flash's process-wide registry globals and
609
+ # ResourceManager shares the SDK's asyncio singleton, so a concurrent deploy/undeploy on
610
+ # another thread could swap the registry scope between our lookup and our undeploy and tear
611
+ # down the wrong run's resources. Serialize isolation + lookup + undeploy together.
612
+ with FLASH_SDK_LOCK:
613
+ try:
614
+ from autoslm.providers.runpod.auth import ensure_auth
615
+
616
+ ensure_auth()
617
+ isolate_flash_state(_run_suffix(run_id))
618
+ from runpod_flash.core.resources.resource_manager import ResourceManager
619
+ except Exception as exc: # SDK/auth unavailable
620
+ return [{"success": False, "name": target, "message": f"flash unavailable: {exc}"}]
621
+
622
+ try:
623
+ rm = ResourceManager()
624
+ resources = rm.list_all_resources()
625
+ uids = _select_endpoint_resources(resources, target)
626
+ except Exception as exc:
627
+ return [{"success": False, "name": target, "message": f"resource lookup failed: {exc}"}]
628
+
629
+ async def _undeploy_all() -> list:
630
+ out = []
631
+ for uid in uids:
632
+ res = resources.get(uid)
633
+ name = getattr(res, "name", None)
634
+ try:
635
+ out.append(
636
+ await rm.undeploy_resource(uid, resource_name=name, force_remove=True)
637
+ )
638
+ except Exception as exc:
639
+ out.append({"success": False, "name": name, "message": str(exc)})
640
+ return out
641
+
642
+ try:
643
+ results = asyncio.run(_undeploy_all())
644
+ except Exception as exc:
645
+ results = [{"success": False, "name": target, "message": str(exc)}]
646
+
647
+ # Registry-less fallback: isolate_flash_state() keeps the Flash SDK's resource
648
+ # registry per-process under ~/.autoslm, so a recreated container (or a crash before
649
+ # on_handle() persisted the endpoint id) leaves the live endpoint invisible to the
650
+ # lookup above. Delete it via the RunPod REST API by its reconstructed name so it
651
+ # can't keep a paid worker alive.
652
+ if not uids:
653
+ with contextlib.suppress(Exception):
654
+ from autoslm.providers.runpod import api as runpod_api
655
+
656
+ for ep in runpod_api.find_endpoints_by_name(target):
657
+ if ep.get("name") == target and runpod_api.delete_endpoint(ep["id"]):
658
+ results.append(
659
+ {"success": True, "name": target, "message": "deleted via REST API"}
660
+ )
661
+
662
+ # also drop the in-process cached handler for THIS run only (a class-wide
663
+ # drop would evict a concurrent run's endpoint on the same GPU class).
664
+ with contextlib.suppress(Exception):
665
+ stop_endpoint(friendly, name=target)
666
+ return results
667
+
668
+
669
+ def build_worker_env(spec: JobSpec, seed: int) -> dict:
670
+ """Per-run env passed to the worker (secrets + recipe overrides)."""
671
+ # CUDA allocator conf. Colocate (TRL trainer + vLLM on one GPU) fragments over a long run,
672
+ # so expandable_segments (which reclaims fragmentation) is the right default — EXCEPT under
673
+ # GRPO vLLM sleep mode, whose CuMemAllocator memory pool is incompatible with
674
+ # expandable_segments (vLLM asserts and the run crashes at engine init). So for RL with
675
+ # sleep mode ON (the default), default to a non-expandable conf instead; SFT and
676
+ # sleep-off RL keep expandable_segments. An explicit operator override always wins.
677
+ _is_rl = str(getattr(spec, "algorithm", "")).lower() not in ("sft",)
678
+ # RL_VLLM_SLEEP may be pinned per-run via [worker_env] (highest precedence, merged into the
679
+ # worker env later) OR via the control-plane process env. Resolve it from BOTH here — with
680
+ # worker_env winning — so a per-run explicit pin counts as explicit: otherwise _sleep_set stays
681
+ # false, AUTOSLM_ALLOC_AUTO=1 is sent, and the worker can upgrade to expandable_segments while
682
+ # run_rl still enables vLLM sleep, hitting the CuMemAllocator incompatibility after provisioning.
683
+ _sleep_raw = (spec.worker_env or {}).get("RL_VLLM_SLEEP", os.environ.get("RL_VLLM_SLEEP"))
684
+ _sleep_set = _sleep_raw is not None
685
+ _sleep_on = (_sleep_raw if _sleep_raw is not None else "1") not in ("0", "false", "False")
686
+ _alloc_default = (
687
+ "garbage_collection_threshold:0.8,max_split_size_mb:256"
688
+ if (_is_rl and _sleep_on)
689
+ else "expandable_segments:True"
690
+ )
691
+ # torch >= 2.10 renamed the env to PYTORCH_ALLOC_CONF — set BOTH names for either stack.
692
+ _alloc_override = os.environ.get("PYTORCH_ALLOC_CONF") or os.environ.get(
693
+ "PYTORCH_CUDA_ALLOC_CONF"
694
+ )
695
+ _alloc_conf = _alloc_override or _alloc_default
696
+ env: dict[str, str] = {
697
+ "RUN_ID": spec.run_id,
698
+ # Compute substrate, read back by engine.worker for the RunMetrics record. Vast's
699
+ # on-instance bootstrap overrides this to "vast" (it reuses this same env builder).
700
+ "AUTOSLM_ARM": "runpod",
701
+ "BENCH_HF_MODEL": spec.model,
702
+ "PYTORCH_CUDA_ALLOC_CONF": _alloc_conf,
703
+ "PYTORCH_ALLOC_CONF": _alloc_conf,
704
+ # We picked a DEFAULT alloc conf above without knowing the worker's resolved vLLM sleep
705
+ # decision (RL + RL_VLLM_SLEEP unset + no operator override). Cede the final choice to the
706
+ # worker, which resolves sleep from the model config and upgrades to expandable_segments
707
+ # when sleep is OFF (engine.worker.finalize_alloc_conf_for_sleep). Never set when the
708
+ # operator pinned an alloc conf or RL_VLLM_SLEEP explicitly — their choice is authoritative.
709
+ **(
710
+ {"AUTOSLM_ALLOC_AUTO": "1"}
711
+ if (_is_rl and not _sleep_set and not _alloc_override)
712
+ else {}
713
+ ),
714
+ # Escape hatch for torch.compile/inductor spikes (Qwen3.5 DeltaNet kernels
715
+ # compile at first forward and can OOM a tight colocate budget).
716
+ **(
717
+ {"TORCHDYNAMO_DISABLE": os.environ["TORCHDYNAMO_DISABLE"]}
718
+ if os.environ.get("TORCHDYNAMO_DISABLE")
719
+ else {}
720
+ ),
721
+ }
722
+ # HF artifact creds + PRIME_API_KEY (the worker `prime env install`s the run's Hub
723
+ # env(s), public + private) + optional reward-judge creds: a verifiers env whose rubric
724
+ # calls an LLM judge (e.g. OpenRouter gpt-oss-120b) needs the API key ON THE WORKER,
725
+ # where the reward runs. Forward any that the operator has set; absent ones are simply
726
+ # not passed.
727
+ for key in (
728
+ "HF_TOKEN",
729
+ "PRIME_API_KEY",
730
+ "OPENROUTER_API_KEY",
731
+ "OPENAI_API_KEY",
732
+ ):
733
+ if os.environ.get(key):
734
+ env[key] = os.environ[key]
735
+ # Seed the worker's own HF_REPO env from the run's [train] hf_repo (adapter/checkpoint/
736
+ # code storage + heartbeats). The worker reads HF_REPO from its own process env; that env
737
+ # is now sourced from the spec, not the operator's HF_REPO.
738
+ env["HF_REPO"] = spec.train.hf_repo
739
+ # Opt-in network volume: point the whole HF cache at the persistent mount so
740
+ # model weights survive across runs (the download becomes a one-time cost per
741
+ # volume instead of per run).
742
+ if getattr(spec.gpu, "network_volume", None):
743
+ env["HF_HOME"] = "/runpod-volume/hf-cache"
744
+ if spec.train.steps is not None:
745
+ env["RL_STEPS"] = str(spec.train.steps)
746
+ if spec.train.epochs is not None:
747
+ env["SFT_EPOCHS"] = str(spec.train.epochs)
748
+ # Forward the documented worker-tuning knobs so they actually reach the GPU worker.
749
+ # RL_VLLM_GPU_UTIL / RL_PER_DEVICE_PROMPTS are the colocate-memory knobs the docs tell
750
+ # users to set to fix vLLM OOM/KV-cache errors; they were previously dropped here.
751
+ for k in (
752
+ "SFT_PER_DEVICE_BS",
753
+ "SFT_PACKING",
754
+ # Colocate-memory knobs the docs tell users to set to fix vLLM OOM / KV-cache errors.
755
+ "RL_VLLM_GPU_UTIL",
756
+ "RL_VLLM_SLEEP",
757
+ "RL_PER_DEVICE_PROMPTS",
758
+ "VLLM_USE_V1",
759
+ # Attention-backend escape hatch: vllm's bundled flash-attn PTX can be newer
760
+ # than the host driver's JIT (sm_120 + 12.8 drivers); TRITON_ATTN/FLASHINFER
761
+ # sidestep it without restricting the host pool to CUDA-13 drivers.
762
+ "VLLM_ATTENTION_BACKEND",
763
+ "AUTOSLM_QUANT",
764
+ # Opt-in fused Triton RoPE for Qwen3.5/3.6 full-attention layers (engine.rope); the
765
+ # worker self-tests it on the live GPU and keeps eager on any mismatch.
766
+ "AUTOSLM_ROPE_KERNEL",
767
+ "WANDB_API_KEY",
768
+ "WANDB_ENTITY",
769
+ "LORA_TARGETS",
770
+ ):
771
+ # Forward when SET, even if empty: an explicit "" is a meaningful override.
772
+ if os.environ.get(k) is not None:
773
+ env[k] = os.environ[k]
774
+ # Per-run worker_env overrides win over the global os.environ allowlist: this is what lets
775
+ # ONE run differ (e.g. a per-run optimizer or LoRA-init A/B) while every other concurrent run
776
+ # keeps the global default.
777
+ for k, v in (getattr(spec, "worker_env", None) or {}).items():
778
+ env[str(k)] = str(v)
779
+ return env
780
+
781
+
782
+ def submit_train(spec: JobSpec, seed: int, log=None) -> dict:
783
+ """Provision a dedicated GPU via Flash, run training, return the metrics dict."""
784
+ timeout_s = max(60, int(spec.gpu.max_wall_seconds))
785
+ from autoslm.envs.registry import worker_hub_env_ids, worker_pip_for_env
786
+
787
+ handler = get_train_endpoint(
788
+ spec.gpu.type,
789
+ execution_timeout_ms=timeout_s * 1000,
790
+ name_suffix=_run_suffix(spec.run_id),
791
+ disk_gb=spec.gpu.disk_gb,
792
+ spec=spec,
793
+ )
794
+ payload = {
795
+ "hf_repo": spec.train.hf_repo,
796
+ "job_spec_json": spec.to_json(),
797
+ "phase": spec.phase,
798
+ "seed": int(seed),
799
+ "env": build_worker_env(spec, seed),
800
+ "extra_pip": list(spec.environment.pip) or worker_pip_for_env(spec.environment.id),
801
+ "hub_env_ids": worker_hub_env_ids(spec.environment.id, spec.environment.params),
802
+ }
803
+ if log is not None:
804
+ print(
805
+ f"submitting Flash job: gpu={spec.gpu.type} phase={spec.phase} "
806
+ f"seed={seed} model={spec.model}",
807
+ file=log,
808
+ flush=True,
809
+ )
810
+
811
+ async def _call():
812
+ res = handler(payload)
813
+ if inspect.isawaitable(res):
814
+ res = await res
815
+ return res
816
+
817
+ out = asyncio.run(_call())
818
+ if not isinstance(out, dict):
819
+ raise RuntimeError(f"flash job returned no metrics: {out!r}")
820
+ return out
code/autoslm/providers/vast/__init__.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vast.ai provider: verified-datacenter single-GPU instances (REST only).
2
+
3
+ The Vast substrate rents a single-GPU instance from a verified-datacenter offer, ships
4
+ a self-contained bootstrap through the onstart script, and detects completion purely
5
+ from the worker's HF artifacts (no inbound network, no serverless queue). It implements
6
+ the SAME ``base.Provider`` interface behind the SAME module layout as RunPod, so the
7
+ orchestrator/allocator treat the two interchangeably.
8
+
9
+ ``PROVIDER`` is the ``base.Provider`` implementation the registry hands out.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ from typing import Any
16
+
17
+ from autoslm.providers.base import GpuClass, JobHandle, PollResult, Provider
18
+
19
+
20
+ class VastProvider:
21
+ """``base.Provider`` for the Vast.ai verified-datacenter substrate."""
22
+
23
+ name = "vast"
24
+
25
+ def is_configured(self) -> bool:
26
+ from autoslm.providers.vast.auth import load_api_key
27
+
28
+ # Vast needs its operator key AND a live network path: it is a live-market
29
+ # substrate (offer search), so AUTOSLM_SKIP_NET (offline/CI) disables Vast
30
+ # entirely; offline allocation then degrades deterministically to RunPod's
31
+ # static catalog.
32
+ if os.environ.get("AUTOSLM_SKIP_NET"):
33
+ return False
34
+ return load_api_key() is not None
35
+
36
+ def preflight(self, require_hf: bool = True) -> list[str]:
37
+ from autoslm.providers.vast.preflight import missing_credentials
38
+
39
+ return missing_credentials(require_hf=require_hf)
40
+
41
+ def gpu_classes(self) -> list[GpuClass]:
42
+ from autoslm.providers.vast.gpus import gpu_classes
43
+
44
+ return gpu_classes()
45
+
46
+ def hourly_rate(self, gpu: str) -> float:
47
+ from autoslm.providers.vast.pricing import hourly_rate
48
+
49
+ return hourly_rate(gpu)
50
+
51
+ def submit_run(
52
+ self,
53
+ spec,
54
+ seed: int,
55
+ *,
56
+ log: Any = None,
57
+ on_handle: Any = None,
58
+ attempt: int = 0,
59
+ offers: Any = None,
60
+ exclude_machine_ids: Any = frozenset(),
61
+ ) -> PollResult:
62
+ from autoslm.providers.vast.jobs import submit_run_vast
63
+
64
+ return submit_run_vast(
65
+ spec,
66
+ seed,
67
+ log=log,
68
+ on_handle=on_handle,
69
+ attempt=attempt,
70
+ offers=offers,
71
+ exclude_machine_ids=exclude_machine_ids,
72
+ )
73
+
74
+ def poll(self, handle: JobHandle, spec, seed: int, *, log: Any = None) -> PollResult:
75
+ from autoslm.providers.runpod.jobs import make_hf_heartbeat_reader
76
+ from autoslm.providers.vast.jobs import VastJobHandle, poll_vast_job
77
+
78
+ hf_repo = spec.train.hf_repo
79
+ prefix = f"{spec.phase}/{spec.run_id}/seed{seed}"
80
+ reader = make_hf_heartbeat_reader(hf_repo, prefix) if hf_repo else None
81
+ vh = VastJobHandle.from_dict(handle.to_dict())
82
+ if log is not None:
83
+ print(f"attaching: vast instance={vh.instance_id}", file=log, flush=True)
84
+ # Reattach must apply the SAME stall tuning + wall-cap deadline as submit_run_vast
85
+ # (see jobs.py), mirroring RunPod's reattach (runpod/__init__.py). Vast has no
86
+ # server-side execution timeout, so a recovered run that dropped the client-side
87
+ # deadline could bill unbounded.
88
+ stall = 1500.0
89
+ deadline = max(60, int(spec.gpu.max_wall_seconds)) + 1800
90
+ return poll_vast_job(
91
+ vh,
92
+ spec,
93
+ seed,
94
+ log=log,
95
+ heartbeat_reader=reader,
96
+ stall_after_s=stall,
97
+ deadline_s=deadline,
98
+ )
99
+
100
+ def cancel(self, handle: JobHandle) -> None:
101
+ from autoslm.providers.vast.jobs import cancel
102
+
103
+ cancel(handle.to_dict())
104
+
105
+ def destroy(self, handle: JobHandle) -> None:
106
+ from autoslm.providers.vast import api as vast_api
107
+
108
+ d = handle.to_dict()
109
+ if d.get("instance_id"):
110
+ vast_api.destroy_instance(int(d["instance_id"]))
111
+
112
+ def gc(self, spec) -> None:
113
+ from autoslm.providers.vast.jobs import destroy_run_instances
114
+
115
+ destroy_run_instances(spec.run_id)
116
+
117
+ def sweep_orphans(self, active_labels: set[str] | None = None) -> list[int]:
118
+ """Vast-only crash-recovery sweep (called via the provider object at startup)."""
119
+ from autoslm.providers.vast.jobs import sweep_orphans
120
+
121
+ return sweep_orphans(active_labels=active_labels)
122
+
123
+
124
+ PROVIDER: Provider = VastProvider()
code/autoslm/providers/vast/_bootstrap.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-contained bootstrap that runs ON a Vast.ai instance.
2
+
3
+ Replicates ``providers/runpod/train.py:_train_body`` semantics on the Vast substrate: install
4
+ extra pip deps, fetch the autoslm package from the HF dataset repo, then run the
5
+ substrate-neutral worker (``autoslm.engine.worker``) to train, uploading the console
6
+ tail on failure. There is NO return channel
7
+ from the instance: the worker's HF artifacts (DONE/metrics.json/heartbeat.json) are
8
+ the success signal, and this bootstrap's attempt-scoped ``vast_attempt<N>.json`` is
9
+ the terminal marker the control plane keys failures on.
10
+
11
+ This file is shipped verbatim inside the instance's onstart script (see
12
+ ``providers/vast/jobs.py:build_onstart``), so it must stay self-contained: stdlib +
13
+ huggingface_hub (installed with the worker deps) only — never import autoslm here.
14
+ It reads its payload from ``/root/autoslm/payload.json``.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import contextlib
20
+ import json
21
+ import os
22
+ import shutil
23
+ import signal
24
+ import subprocess
25
+ import sys
26
+ import threading
27
+ import time
28
+
29
+ PAYLOAD_PATH = "/root/autoslm/payload.json"
30
+ CODE_ROOT = "/runcode"
31
+ CODE_DIR = "/runcode/code"
32
+
33
+
34
+ def load_payload(path: str = PAYLOAD_PATH) -> dict:
35
+ with open(path) as f:
36
+ return json.load(f)
37
+
38
+
39
+ def hf_upload(payload: dict, local_path: str, repo_subpath: str) -> None:
40
+ """Upload one artifact under the run's HF prefix; never raises."""
41
+ try:
42
+ from huggingface_hub import HfApi
43
+
44
+ HfApi(token=(payload.get("env") or {}).get("HF_TOKEN")).upload_file(
45
+ path_or_fileobj=local_path,
46
+ path_in_repo=f"{payload['hf_prefix']}/{repo_subpath}",
47
+ repo_id=payload["hf_repo"],
48
+ repo_type="dataset",
49
+ )
50
+ except Exception as exc:
51
+ print(f"hf upload warn ({repo_subpath}): {exc}", flush=True)
52
+
53
+
54
+ def build_worker_env(payload: dict) -> dict:
55
+ env = dict(os.environ)
56
+ env.update({k: str(v) for k, v in (payload.get("env") or {}).items()})
57
+ # Pass a large spec via a file, not the environment: a job spec with large inline
58
+ # params can reach multiple hundred KB, and that big an env var trips execve's
59
+ # "Argument list too long" when the worker subprocess starts. Mirrors
60
+ # runpod/train.py:_train_body.
61
+ spec_json = payload["job_spec_json"]
62
+ if len(spec_json) > 96_000:
63
+ with open("/tmp/job_spec.json", "w") as f:
64
+ f.write(spec_json)
65
+ env["AUTOSLM_JOB_SPEC_PATH"] = "/tmp/job_spec.json"
66
+ env.pop("AUTOSLM_JOB_SPEC_JSON", None)
67
+ else:
68
+ env["AUTOSLM_JOB_SPEC_JSON"] = spec_json
69
+ env["PHASE"] = payload["phase"]
70
+ env["SEED"] = str(payload["seed"])
71
+ # Compute substrate for the RunMetrics record (engine.worker reads AUTOSLM_ARM). The
72
+ # payload env was built by the shared runpod env builder, which stamps "runpod"; this
73
+ # bootstrap runs on the Vast instance, so override it to the real backend.
74
+ env["AUTOSLM_ARM"] = "vast"
75
+ env["PYTHONPATH"] = CODE_DIR + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
76
+ return env
77
+
78
+
79
+ def fetch_code(payload: dict) -> None:
80
+ from huggingface_hub import snapshot_download
81
+
82
+ snapshot_download(
83
+ repo_id=payload["hf_repo"],
84
+ repo_type="dataset",
85
+ allow_patterns=["code/**"],
86
+ local_dir=CODE_ROOT,
87
+ token=(payload.get("env") or {}).get("HF_TOKEN"),
88
+ )
89
+
90
+
91
+ def run_mode(payload: dict, env: dict, mode: str, deadline_ts: float) -> int:
92
+ """One worker process; console teed to a file and streamed to the instance log.
93
+
94
+ On failure the console tail is uploaded as console_<mode>.txt — like _train_body,
95
+ because subprocess consoles are the only place engine-core crashes surface. On
96
+ deadline the process is killed and we return a sentinel nonzero rc.
97
+ """
98
+ console = f"/tmp/console_{mode}.txt"
99
+ timed_out = False
100
+ with open(console, "w") as cf:
101
+ proc = subprocess.Popen(
102
+ [sys.executable, "-m", "autoslm.engine.worker"],
103
+ cwd=CODE_DIR,
104
+ env={**env, "RUN_MODE": mode},
105
+ stdout=subprocess.PIPE,
106
+ stderr=subprocess.STDOUT,
107
+ text=True,
108
+ )
109
+
110
+ def pump():
111
+ for line in proc.stdout:
112
+ print(line, end="", flush=True)
113
+ cf.write(line)
114
+
115
+ t = threading.Thread(target=pump, daemon=True)
116
+ t.start()
117
+ try:
118
+ proc.wait(timeout=max(10.0, deadline_ts - time.time()))
119
+ except subprocess.TimeoutExpired:
120
+ timed_out = True
121
+ proc.kill()
122
+ proc.wait()
123
+ t.join(timeout=10)
124
+ if proc.returncode != 0 or timed_out:
125
+ try:
126
+ tail_path = console + ".tail"
127
+ with open(console) as f:
128
+ tail = f.read()[-64_000:]
129
+ if timed_out:
130
+ tail += f"\n--- bootstrap: mode '{mode}' hit the wall-clock cap; killed ---\n"
131
+ with open(tail_path, "w") as f:
132
+ f.write(tail)
133
+ hf_upload(payload, tail_path, f"console_{mode}.txt")
134
+ except Exception as exc:
135
+ print(f"console upload warn: {exc}", flush=True)
136
+ if timed_out:
137
+ raise TimeoutError(f"worker mode '{mode}' exceeded the wall-clock cap")
138
+ return proc.returncode
139
+
140
+
141
+ def write_attempt_marker(payload: dict, ok: bool, error: str = "") -> None:
142
+ """Attempt-scoped terminal marker: how the control plane distinguishes THIS
143
+ attempt's failure from a prior attempt's leftovers under the same prefix."""
144
+ marker = {
145
+ "ok": bool(ok),
146
+ "ts": time.time(),
147
+ "attempt": int(payload.get("attempt") or 0),
148
+ "error": error[:2000],
149
+ }
150
+ p = "/tmp/vast_attempt.json"
151
+ with open(p, "w") as f:
152
+ json.dump(marker, f)
153
+ hf_upload(payload, p, f"vast_attempt{marker['attempt']}.json")
154
+
155
+
156
+ def main() -> int:
157
+ # Make SIGTERM (vast stop / bash `timeout`) unwind through finally so the
158
+ # terminal marker still gets uploaded.
159
+ signal.signal(signal.SIGTERM, lambda *a: sys.exit(1))
160
+ payload = load_payload()
161
+ ok = False
162
+ error = ""
163
+ try:
164
+ # Fast model downloads on Vast: RunPod's Flash runtime ships hf_transfer + sets
165
+ # HF_HUB_ENABLE_HF_TRANSFER, but Vast hosts don't — so a cold model pull is serial and
166
+ # slow (measured ~84s for a 2 GB model vs ~6s on RunPod, where setup is now the dominant
167
+ # cost). Install it + enable so snapshot_download/from_pretrained saturate the NIC.
168
+ # Best-effort: only enable the flag if the package is present (enabling it WITHOUT the
169
+ # package makes huggingface_hub hard-error).
170
+ try:
171
+ import importlib.util
172
+
173
+ if importlib.util.find_spec("hf_transfer") is None:
174
+ subprocess.run([sys.executable, "-m", "pip", "install", "hf_transfer"], check=True)
175
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
176
+ except Exception as _e:
177
+ print("hf_transfer setup skipped (slow downloads):", _e)
178
+ # W&B logging (restored post-autoslm-migration): the prebuilt image predates wandb being
179
+ # added to the stack, so install it on-demand when a W&B key is present. The worker's
180
+ # wandb_report_to() gates report_to on the package actually importing, so this is what makes
181
+ # W&B logging real on the current image without a rebuild.
182
+ try:
183
+ import importlib.util # local: the hf_transfer block above may fail before importing it
184
+
185
+ _penv = payload.get("env") or {}
186
+ if (_penv.get("WANDB_API_KEY") or os.environ.get("WANDB_API_KEY")) and (
187
+ importlib.util.find_spec("wandb") is None
188
+ ):
189
+ subprocess.run([sys.executable, "-m", "pip", "install", "wandb>=0.17"], check=False)
190
+ print("[wandb] installed wandb on-demand for W&B logging")
191
+ except Exception as _e:
192
+ print("wandb setup skipped:", _e)
193
+ # NB: the Hopper fla guard lives in engine.worker._drop_fla_on_hopper (runs in the worker
194
+ # process after all installs, before any model import) — not here, where a later
195
+ # install could pull fla back in. The bootstrap just fetches code and runs the worker.
196
+
197
+ extra_pip = payload.get("extra_pip") or []
198
+ if extra_pip:
199
+ # check=True: a deterministic dependency failure (GRPO / Prime Hub
200
+ # / verifiers extras) must stop NOW with an actionable error, not proceed to
201
+ # a later import crash while the paid instance runs (matches the RunPod path).
202
+ subprocess.run([sys.executable, "-m", "pip", "install", *extra_pip], check=True)
203
+ _wenv = payload.get("env") or {}
204
+ # NB: fla is dropped on Hopper (sm90) automatically by engine.worker._drop_fla_on_hopper at
205
+ # worker startup (fla's GDN backward is miscomputed on sm90, #640) — no bootstrap uninstall
206
+ # or env toggle. fla only ever runs on the consumer archs where its Triton kernel is correct.
207
+ # Install the run's verifiers environment(s) from the Prime Hub via the
208
+ # authenticated `prime` CLI (mirrors runpod/train.py:_train_body). The public pip
209
+ # index does not serve PRIVATE env wheels; `prime env install` pulls/builds/installs
210
+ # public + private alike, authenticated by PRIME_API_KEY forwarded in the payload env.
211
+ hub_env_ids = payload.get("hub_env_ids") or []
212
+ if hub_env_ids:
213
+ worker_env = {k: str(v) for k, v in (payload.get("env") or {}).items()}
214
+ prime_key = worker_env.get("PRIME_API_KEY") or os.environ.get("PRIME_API_KEY")
215
+ if not prime_key:
216
+ raise RuntimeError(
217
+ "PRIME_API_KEY is required to install the Prime Hub environment on the worker"
218
+ )
219
+ # Only install `prime` when it isn't already present (it's often baked into the
220
+ # instance image) — an unconditional install adds latency and a per-run PyPI
221
+ # failure point every run.
222
+ if shutil.which("prime") is None:
223
+ subprocess.run([sys.executable, "-m", "pip", "install", "prime"], check=True)
224
+ # Resolve the prime binary (located path if present, else the bare name) so the env
225
+ # install runs through the actually-installed CLI.
226
+ prime_bin = shutil.which("prime") or "prime"
227
+ install_env = {
228
+ **os.environ,
229
+ "PRIME_API_KEY": prime_key,
230
+ "PRIME_DISABLE_VERSION_CHECK": "1",
231
+ "PIP_BREAK_SYSTEM_PACKAGES": "1",
232
+ }
233
+ # --with pip: install the env into THIS python via pip, not prime's isolated uv env
234
+ # (the default), so the trainer can import the env module at load_environment.
235
+ for env_id in hub_env_ids:
236
+ subprocess.run(
237
+ [prime_bin, "env", "install", env_id, "--with", "pip"],
238
+ check=True,
239
+ env=install_env,
240
+ )
241
+ fetch_code(payload)
242
+ env = build_worker_env(payload)
243
+ deadline = time.time() + float(payload.get("max_wall_s") or 24 * 3600)
244
+ phase = payload["phase"]
245
+ # A warm/retried Vast instance can carry a previous attempt's metrics file; a
246
+ # stale one would let a crashed train phase report the previous run's metrics.
247
+ # Clear before training (mirrors the RunPod Flash handler in runpod/train.py).
248
+ for stale in ("/tmp/train_meta.json", "/tmp/metrics.json"):
249
+ with contextlib.suppress(FileNotFoundError):
250
+ os.remove(stale)
251
+ # Train. Nonzero rc tolerated — RL's colocated vLLM can segfault at interpreter
252
+ # exit AFTER the adapter + metrics.json + DONE are saved. The train phase writes
253
+ # metrics.json + DONE itself (or restores them from an earlier attempt's DONE).
254
+ run_mode(payload, env, phase, deadline)
255
+ if not os.path.exists("/tmp/metrics.json"):
256
+ raise RuntimeError(
257
+ f"train phase '{phase}' produced no /tmp/metrics.json (it crashed before "
258
+ f"finishing); see error_{phase}.txt and console_{phase}.txt in the HF "
259
+ f"dataset repo"
260
+ )
261
+ ok = True
262
+ except Exception as exc:
263
+ # Record genuine failures in the attempt marker (written in `finally`). Don't catch
264
+ # BaseException — KeyboardInterrupt/SystemExit must propagate after the marker write
265
+ # rather than be swallowed into a `return 1`.
266
+ error = f"{type(exc).__name__}: {exc}"
267
+ print(f"bootstrap failed: {error}", flush=True)
268
+ finally:
269
+ write_attempt_marker(payload, ok, error)
270
+ return 0 if ok else 1
271
+
272
+
273
+ if __name__ == "__main__":
274
+ sys.exit(main())
code/autoslm/providers/vast/api.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Thin Vast.ai REST client (no SDK state): offer search + instance lifecycle.
2
+
3
+ Mirrors ``providers/runpod/api.py``: stdlib urllib only, hardened retries, and nothing
4
+ persisted locally — a fresh process can list/destroy any instance using only the
5
+ persisted ids + VAST_API_KEY. Only ``verified`` offers are searched (the datacenter-only
6
+ filter is NOT applied, so verified community/marketplace hosts are included too); callers
7
+ re-check hosting_type + verification + the reliability floor client-side.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import time
13
+ import urllib.error
14
+ import urllib.request
15
+ from typing import Any
16
+
17
+ from autoslm.providers._http import RestClient
18
+
19
+ VAST_BASE = "https://console.vast.ai/api"
20
+
21
+
22
+ class VastApiError(RuntimeError):
23
+ pass
24
+
25
+
26
+ # Shared urllib client (path form: callers pass paths joined onto VAST_BASE).
27
+ # Env-only by design, like RUNPOD_API_KEY: the operator sets VAST_API_KEY on the
28
+ # control-plane host; it is never written to config files or shipped to workers.
29
+ _CLIENT = RestClient(
30
+ env_var="VAST_API_KEY",
31
+ error_cls=VastApiError,
32
+ base_url=VAST_BASE,
33
+ missing_key_message=("VAST_API_KEY not configured on the control-plane host"),
34
+ )
35
+
36
+
37
+ def _api_key() -> str:
38
+ return _CLIENT.api_key()
39
+
40
+
41
+ def _request(path: str, method: str = "GET", body: dict | None = None, timeout: float = 30.0):
42
+ return _CLIENT.request(path, method=method, body=body, timeout=timeout)
43
+
44
+
45
+ def request_with_retries(
46
+ path: str,
47
+ method: str = "GET",
48
+ body: dict | None = None,
49
+ retries: int = 4,
50
+ base_delay: float = 2.0,
51
+ ) -> Any:
52
+ """REST call hardened against transient network/5xx blips (jittered backoff)."""
53
+ return _CLIENT.request_with_retries(
54
+ path, method=method, body=body, retries=retries, base_delay=base_delay
55
+ )
56
+
57
+
58
+ # ---------------------------------------------------------------------------
59
+ # Offer search
60
+ # ---------------------------------------------------------------------------
61
+ def search_offers(
62
+ min_vram_mb: int,
63
+ *,
64
+ min_disk_gb: float = 0,
65
+ min_reliability: float = 0.95,
66
+ limit: int = 64,
67
+ extra_q: dict | None = None,
68
+ ) -> list[dict]:
69
+ """Rentable single-GPU offers from verified hosts, cheapest first. We drop the server-side
70
+ datacenter-only filter so verified COMMUNITY/marketplace hosts are returned alongside
71
+ datacenter ones (usable_offers still re-checks hosting_type + verification + the reliability
72
+ floor, so quality is enforced downstream).
73
+
74
+ ``datacenter`` here is Vast's hosting-type filter (professional datacenters vs
75
+ consumer/hobbyist machines); results additionally carry ``hosting_type`` which
76
+ callers must re-check (``usable_offers``) — never trust one filter layer alone.
77
+ """
78
+ # We intentionally do NOT apply Vast's server-side datacenter-only filter: verified
79
+ # COMMUNITY/marketplace hosts are included too (scarce classes often have no verified-datacenter
80
+ # supply), and usable_offers re-checks hosting_type + verification + the reliability floor.
81
+ q: dict[str, Any] = {
82
+ "verified": {"eq": True},
83
+ "rentable": {"eq": True},
84
+ "num_gpus": {"eq": 1},
85
+ "gpu_ram": {"gte": int(min_vram_mb)},
86
+ "reliability2": {"gte": float(min_reliability)},
87
+ "type": "ask",
88
+ "order": [["dph_total", "asc"]],
89
+ "limit": int(limit),
90
+ }
91
+ if min_disk_gb:
92
+ q["disk_space"] = {"gte": float(min_disk_gb)}
93
+ if extra_q:
94
+ q.update(extra_q)
95
+ out = request_with_retries("/v0/search/asks/", method="PUT", body={"q": q})
96
+ offers = out.get("offers") if isinstance(out, dict) else None
97
+ return offers if isinstance(offers, list) else []
98
+
99
+
100
+ # ---------------------------------------------------------------------------
101
+ # Instances
102
+ # ---------------------------------------------------------------------------
103
+ def create_instance(
104
+ offer_id: int,
105
+ *,
106
+ image: str,
107
+ disk_gb: float,
108
+ env: dict[str, str],
109
+ onstart: str,
110
+ label: str,
111
+ runtype: str = "args",
112
+ ) -> int:
113
+ """Rent an offer -> instance id. Raises VastApiError on rejection (offer taken).
114
+
115
+ Default ``args`` runtype (verified live): the script IS the container command
116
+ (``bash -c``), so the job needs no SSH key on the account, the container's
117
+ lifecycle is the job's lifecycle, and the Vast-injected CONTAINER_API_KEY /
118
+ CONTAINER_ID env vars are available for the self-destroy backstop. ``ssh``
119
+ runtype requires an SSH key attached to the Vast account.
120
+ """
121
+ body = {
122
+ "client_id": "me",
123
+ "image": image,
124
+ "disk": float(disk_gb),
125
+ "env": dict(env),
126
+ "label": label,
127
+ "runtype": runtype,
128
+ }
129
+ # The worker image is PUBLIC, so Vast pulls it with no docker-login (no image_login / pull
130
+ # token is ever shipped to the untrusted host).
131
+ if runtype == "args":
132
+ body["args"] = ["bash", "-c", onstart]
133
+ else:
134
+ body["onstart"] = onstart
135
+ # NON-IDEMPOTENT: ``PUT /asks/{id}`` rents a NEW instance every time it succeeds.
136
+ # A blind retry on a timeout where Vast actually accepted the first request would
137
+ # double-provision (two billed instances, one invisible to our handle). So this
138
+ # call is NOT retried — a transient failure surfaces to deploy_and_submit, which
139
+ # walks to the next offer, and to the orchestrator, which consumes a run retry; a
140
+ # duplicate paid instance is the worse failure. (Idempotent calls — search,
141
+ # detail, destroy — keep their retries.)
142
+ out = request_with_retries(f"/v0/asks/{int(offer_id)}/", method="PUT", body=body, retries=0)
143
+ if not isinstance(out, dict) or not out.get("success"):
144
+ raise VastApiError(f"create_instance({offer_id}) rejected: {out}")
145
+ instance_id = out.get("new_contract")
146
+ if not instance_id:
147
+ raise VastApiError(f"create_instance({offer_id}): no instance id in response: {out}")
148
+ return int(instance_id)
149
+
150
+
151
+ def get_instance(instance_id: int) -> dict | None:
152
+ """Instance detail dict, or None once it no longer exists (destroyed).
153
+
154
+ The v0 detail route answers 200 with ``{"instances": null}`` for unknown ids
155
+ (verified live) — that is the "gone" signal, not a 404.
156
+ """
157
+ try:
158
+ out = request_with_retries(f"/v0/instances/{int(instance_id)}/")
159
+ except VastApiError as e:
160
+ if "404" in str(e):
161
+ return None
162
+ raise
163
+ if isinstance(out, dict):
164
+ if "instances" in out:
165
+ inst = out["instances"]
166
+ return inst if isinstance(inst, dict) else None
167
+ return out
168
+ return None
169
+
170
+
171
+ def list_instances() -> list[dict]:
172
+ # The v0 list route is deprecated (410 "use /api/v1/instances/", verified live);
173
+ # detail/destroy remain on v0.
174
+ out = request_with_retries("/v1/instances/")
175
+ inst = out.get("instances") if isinstance(out, dict) else None
176
+ return inst if isinstance(inst, list) else []
177
+
178
+
179
+ def instance_logs(instance_id: int, tail: int = 400, wait_s: float = 20.0) -> str | None:
180
+ """Container log tail via the logs API (request -> poll the result URL).
181
+
182
+ The only place early-bootstrap failures (pip/env errors before the worker can
183
+ reach HF) are visible. Best-effort: returns None when logs are unavailable
184
+ (e.g. the instance is already destroyed); never raises.
185
+ """
186
+ try:
187
+ out = request_with_retries(
188
+ f"/v0/instances/request_logs/{int(instance_id)}/",
189
+ method="PUT",
190
+ body={"tail": str(int(tail))},
191
+ retries=1,
192
+ )
193
+ url = out.get("result_url") if isinstance(out, dict) else None
194
+ if not url:
195
+ return None
196
+ deadline = time.time() + wait_s
197
+ while time.time() < deadline:
198
+ try:
199
+ with urllib.request.urlopen(url, timeout=15) as resp:
200
+ body = resp.read().decode(errors="replace")
201
+ if body.strip():
202
+ return body
203
+ except urllib.error.HTTPError as e:
204
+ if e.code != 404: # 404 = not materialized yet
205
+ return None
206
+ time.sleep(2.0)
207
+ except Exception:
208
+ return None
209
+ return None
210
+
211
+
212
+ def destroy_instance(instance_id: int) -> bool:
213
+ """Destroy (and stop billing for) an instance. Best-effort: never raises."""
214
+ try:
215
+ request_with_retries(f"/v0/instances/{int(instance_id)}/", method="DELETE", retries=2)
216
+ return True
217
+ except Exception:
218
+ return False
code/autoslm/providers/vast/auth.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vast.ai credential handling (operator-side), mirroring the RunPod auth module.
2
+
3
+ The Vast REST client authenticates via the ``VAST_API_KEY`` environment variable, set
4
+ by the **operator** on the control-plane host. Env-only by
5
+ design, exactly like ``RUNPOD_API_KEY``: it is never written to config files or shipped
6
+ to workers (the instance self-destroy backstop uses the Vast-injected, instance-scoped
7
+ ``CONTAINER_API_KEY`` instead).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+
14
+
15
+ def load_api_key() -> str | None:
16
+ """Vast API key from the environment (operator configuration)."""
17
+ return os.environ.get("VAST_API_KEY") or None
18
+
19
+
20
+ def ensure_auth() -> str:
21
+ """Ensure ``VAST_API_KEY`` is set; raise if unavailable."""
22
+ key = load_api_key()
23
+ if not key:
24
+ raise RuntimeError("no Vast API key found; set VAST_API_KEY on the control-plane host")
25
+ return key
code/autoslm/providers/vast/gpus.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vast's GPU classes + the offer->class mapping.
2
+
3
+ The class table is provider-agnostic and lives in ``providers/base.py``. This module
4
+ carves out Vast's rows (``gpu_classes()`` == every class with a ``vast_name``,
5
+ including the Vast-only classes L40S / RTX Pro 4000 / A100 SXM 40GB). The offer->class
6
+ mapping (``vast_gpu_for_offer``) lives in ``providers/base.py`` and the job path imports
7
+ it from there directly.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from autoslm.providers.base import GpuClass
13
+
14
+ __all__ = ["gpu_classes"]
15
+
16
+
17
+ def gpu_classes() -> list[GpuClass]:
18
+ """The GPU classes Vast can provision (those with a ``vast_name``)."""
19
+ from autoslm.providers.base import GPU_INFO
20
+
21
+ return [g for g in GPU_INFO.values() if g.vast_name]
code/autoslm/providers/vast/jobs.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vast.ai run lifecycle: verified offers -> instance -> HF-artifact poll.
2
+
3
+ The Vast equivalent of ``providers/runpod/jobs.py``. Vast has no serverless queue:
4
+ we rent a single-GPU instance from a VERIFIED offer (datacenter or community), ship a self-contained
5
+ bootstrap (the private ``_bootstrap`` module) through the onstart script, and detect
6
+ completion purely via the worker's HF artifacts (DONE/metrics.json/heartbeat.json) +
7
+ the instance's status — no inbound network to the box is ever needed.
8
+
9
+ The instance bootstrap is an INTERNAL detail of this module (``build_onstart`` reads
10
+ ``_bootstrap.py``), so the public per-provider module set stays identical to RunPod's.
11
+
12
+ Cost-safety invariant: a rented instance is ALWAYS destroyed — the runner's
13
+ ``finally``, the onstart's self-destroy backstop, the cancel path, and
14
+ ``sweep_orphans`` (server startup / post-run) each independently guarantee it.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import base64
20
+ import contextlib
21
+ import json
22
+ import shlex
23
+ import time
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+
27
+ from autoslm._logging import get_logger
28
+ from autoslm.providers._poll import PollErrorTracker, make_say, surface_heartbeat
29
+ from autoslm.providers.base import GPU_INFO, PollResult, min_cuda_modern, vast_gpu_for_offer
30
+ from autoslm.providers.runpod.jobs import make_hf_heartbeat_reader, make_hf_text_reader
31
+ from autoslm.providers.vast import api as vast_api
32
+
33
+ logger = get_logger(__name__)
34
+
35
+ # Offer-quality floors (beyond verified+datacenter, which are non-negotiable). reliability2 is
36
+ # Vast's host-uptime/health score: 0.95 let ~1-in-20 long runs die mid-train ("worker terminated
37
+ # without a DONE sentinel" when the host went down); 0.995 (~1-in-200) keeps supply usable (the
38
+ # >=0.995 datacenter pool measured 67 offers) while nearly eliminating mid-run host deaths. These
39
+ # are fixed correctness floors, not operator-tunable.
40
+ RELIABILITY_FLOOR = 0.995
41
+ MIN_INET_MBPS = 200.0
42
+ # How long an instance may sit in a non-running state (image pull) before we give up.
43
+ LOAD_TIMEOUT_S = 900.0
44
+ # Boards under-report VRAM vs the class nominal (measured live: L4 23034 MB / 24 GB,
45
+ # A40 46068 MB / 48 GB = 0.938 of nominal); the server-side gpu_ram filter gets this
46
+ # slack, the class gate stays exact (vast_gpu_for_offer).
47
+ _SEARCH_VRAM_SLACK = 0.92
48
+
49
+ # Minimum disk Vast instances are provisioned with (the bootstrap + worker stack +
50
+ # weights need headroom regardless of the spec's request). The offer search MUST use
51
+ # this same floor so offers with <60 GB disk don't pass the search and then get
52
+ # rejected at create time (``create_instance`` enforces the same max).
53
+ MIN_DISK_GB = 60.0
54
+
55
+
56
+ def _effective_disk_gb(spec) -> float:
57
+ """The disk size an instance is actually provisioned with (the create-time floor).
58
+
59
+ Both the offer search and ``create_instance`` must agree on this, or offers with a
60
+ disk between ``spec.gpu.disk_gb`` and the floor pass the search then fail to rent.
61
+ """
62
+ return max(float(spec.gpu.disk_gb), MIN_DISK_GB)
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class VastOffer:
67
+ """A normalized, fully-vetted offer (passed every ``usable_offers`` filter)."""
68
+
69
+ offer_id: int
70
+ machine_id: int
71
+ gpu: str # canonical class name (GPU_INFO key)
72
+ vram_gb: int
73
+ dph_total: float
74
+ cuda_max_good: float
75
+ disk_space: float
76
+ reliability: float
77
+ inet_down: float
78
+ geolocation: str
79
+
80
+
81
+ def usable_offers(
82
+ min_vram_gb: int,
83
+ disk_gb: float,
84
+ exclude_machine_ids: set[int] | frozenset[int] = frozenset(),
85
+ ) -> list[VastOffer]:
86
+ """Verified offers (datacenter or community) able to run the job, cheapest first.
87
+
88
+ Server-side filters do the heavy lifting; everything load-bearing is re-checked
89
+ client-side (belt and suspenders — the result rows carry the proof fields).
90
+ """
91
+ rows = vast_api.search_offers(
92
+ int(min_vram_gb * 1024 * _SEARCH_VRAM_SLACK),
93
+ min_disk_gb=disk_gb,
94
+ min_reliability=RELIABILITY_FLOOR,
95
+ )
96
+ # Always include Vast-VERIFIED marketplace hosts (hosting_type 0) alongside datacenter-only
97
+ # (hosting_type==1): they are still verified and reliability-floored (RELIABILITY_FLOOR above),
98
+ # just not datacenter-tier. Scarce classes are often only offered by community hosts while the
99
+ # RunPod equivalent is capacity-throttled, so as long as the reliability floor is met we take them.
100
+ allow_community = True
101
+ out: list[VastOffer] = []
102
+ for r in rows:
103
+ gpu = vast_gpu_for_offer(str(r.get("gpu_name") or ""), float(r.get("gpu_ram") or 0))
104
+ if gpu is None: # not a managed class (Ampere+ floor)
105
+ continue
106
+ info = GPU_INFO[gpu]
107
+ dph = float(r.get("dph_total") or 0)
108
+ cuda = float(r.get("cuda_max_good") or 0)
109
+ # Host tier: accept verified datacenter (hosting_type==1) AND verified community
110
+ # (hosting_type==0) hosts — community is always allowed, still gated by the reliability
111
+ # floor + verification below; any other hosting_type is rejected.
112
+ _bad_host = r.get("hosting_type") != 1 and not (
113
+ allow_community and r.get("hosting_type") == 0
114
+ )
115
+ if (
116
+ _bad_host
117
+ or r.get("verification") != "verified"
118
+ # Exact class gate: guard against a board whose canonical class nominal VRAM
119
+ # is below the request (e.g. asking for 48 GB but the mapping landed on a
120
+ # 24 GB class) — the server-side gpu_ram filter only carries slack.
121
+ or info.vram_gb < min_vram_gb
122
+ or float(r.get("reliability2") or 0) < RELIABILITY_FLOOR
123
+ or float(r.get("disk_space") or 0) < float(disk_gb)
124
+ or float(r.get("inet_down") or 0) < MIN_INET_MBPS
125
+ or cuda < float(min_cuda_modern(gpu)) # Blackwell needs CUDA-13 drivers
126
+ or dph <= 0
127
+ or int(r.get("machine_id") or 0) in exclude_machine_ids
128
+ ):
129
+ continue
130
+ out.append(
131
+ VastOffer(
132
+ offer_id=int(r["id"]),
133
+ machine_id=int(r.get("machine_id") or 0),
134
+ gpu=gpu,
135
+ vram_gb=info.vram_gb,
136
+ dph_total=dph,
137
+ cuda_max_good=cuda,
138
+ disk_space=float(r.get("disk_space") or 0),
139
+ reliability=float(r.get("reliability2") or 0),
140
+ inet_down=float(r.get("inet_down") or 0),
141
+ geolocation=str(r.get("geolocation") or ""),
142
+ )
143
+ )
144
+ return sorted(out, key=lambda o: (o.dph_total, o.vram_gb))
145
+
146
+
147
+ def vast_image() -> str:
148
+ """Docker image for the worker: the prebuilt, PUBLIC WORKER_IMAGE (full training stack baked
149
+ in). Used for every GPU class — the Blackwell driver floor lives in the ``cuda_max_good`` offer
150
+ filter, not the image.
151
+
152
+ If WORKER_IMAGE is blank (AUTOSLM_WORKER_IMAGE=""), that is a RunPod-Flash-only request to
153
+ install deps on the bare default runtime; Vast has no bare runtime and ``create_instance``
154
+ rejects an empty image, so fall back to DEFAULT_WORKER_IMAGE here."""
155
+ from autoslm.providers.runpod.train import DEFAULT_WORKER_IMAGE, WORKER_IMAGE
156
+
157
+ return WORKER_IMAGE or DEFAULT_WORKER_IMAGE
158
+
159
+
160
+ @dataclass
161
+ class VastJobHandle:
162
+ """Persisted in RunStatus.remote so any process can reattach/cancel (cf. JobHandle)."""
163
+
164
+ instance_id: int
165
+ offer_id: int
166
+ machine_id: int
167
+ label: str
168
+ gpu: str
169
+ hourly_usd: float
170
+ attempt: int
171
+ started_ts: float
172
+
173
+ def to_dict(self) -> dict:
174
+ return {
175
+ "provider": "vast",
176
+ "instance_id": self.instance_id,
177
+ "offer_id": self.offer_id,
178
+ "machine_id": self.machine_id,
179
+ "label": self.label,
180
+ "gpu": self.gpu,
181
+ "hourly_usd": self.hourly_usd,
182
+ "attempt": self.attempt,
183
+ "started_ts": self.started_ts,
184
+ }
185
+
186
+ @classmethod
187
+ def from_dict(cls, d: dict) -> VastJobHandle:
188
+ return cls(
189
+ instance_id=int(d["instance_id"]),
190
+ offer_id=int(d.get("offer_id") or 0),
191
+ machine_id=int(d.get("machine_id") or 0),
192
+ label=str(d.get("label") or ""),
193
+ gpu=str(d.get("gpu") or ""),
194
+ hourly_usd=float(d.get("hourly_usd") or 0),
195
+ attempt=int(d.get("attempt") or 0),
196
+ started_ts=float(d.get("started_ts") or 0),
197
+ )
198
+
199
+
200
+ def run_label_prefix(run_id: str) -> str:
201
+ """The prefix EVERY instance label for ``run_id`` starts with.
202
+
203
+ ``instance_label`` forces the ``autoslm-`` prefix onto run ids that lack it, so the
204
+ orphan-sweep allowlist must apply the SAME transform: a raw run id (e.g. a
205
+ "fail-fast" test id) would otherwise never match its own ``autoslm-…`` labels and a
206
+ live run's instance could be swept (or fail to be protected)."""
207
+ return f"autoslm-{run_id}" if not run_id.startswith("autoslm-") else run_id
208
+
209
+
210
+ def instance_label(run_id: str, seed: int, attempt: int) -> str:
211
+ """Instance label: run-derived so ``sweep_orphans`` can tell ours from anything
212
+ else on the account. Platform run ids already start with ``autoslm-``; anything else
213
+ (direct-API callers, tests) gets the prefix forced — an instance we rented must NEVER
214
+ be invisible to the orphan sweep."""
215
+ return f"{run_label_prefix(run_id)}-s{seed}-a{attempt}"
216
+
217
+
218
+ def build_payload(spec, seed: int, attempt: int) -> dict:
219
+ """The bootstrap's input — field-compatible with _train_body's, plus the bits the
220
+ instance can't infer (HF prefix for markers, wall cap, attempt)."""
221
+ from autoslm.envs.registry import worker_hub_env_ids, worker_pip_for_env
222
+ from autoslm.providers.runpod.train import build_worker_env
223
+
224
+ return {
225
+ "hf_repo": spec.train.hf_repo,
226
+ "job_spec_json": spec.to_json(),
227
+ "phase": spec.phase,
228
+ "seed": int(seed),
229
+ "env": build_worker_env(spec, seed),
230
+ "extra_pip": list(spec.environment.pip) or worker_pip_for_env(spec.environment.id),
231
+ "hub_env_ids": worker_hub_env_ids(spec.environment.id, spec.environment.params),
232
+ "hf_prefix": f"{spec.phase}/{spec.run_id}/seed{seed}",
233
+ "max_wall_s": max(60, int(spec.gpu.max_wall_seconds)),
234
+ "attempt": int(attempt),
235
+ }
236
+
237
+
238
+ def build_onstart(payload: dict, install_deps: bool = True) -> str:
239
+ """The instance's onstart script: payload + bootstrap shipped as quoted heredocs.
240
+
241
+ Everything dynamic travels base64-encoded inside the script — never interpolated
242
+ into shell syntax and never through Vast's env plumbing — so the job-spec JSON
243
+ (quotes, spaces, anything) survives byte-exact. Secrets-wise the script carries
244
+ the same content as the worker env on RunPod (HF token; never provider keys).
245
+
246
+ The bootstrap source is the private ``_bootstrap.py`` sibling — an internal detail
247
+ of this provider, not a public module.
248
+ """
249
+ from autoslm.providers.runpod.train import resolve_worker_deps
250
+
251
+ payload_b64 = base64.encodebytes(json.dumps(payload).encode()).decode()
252
+ bootstrap_src = (Path(__file__).parent / "_bootstrap.py").read_text()
253
+ if install_deps:
254
+ deps = " ".join(shlex.quote(d) for d in resolve_worker_deps())
255
+ # Vast cold-start is dominated by this dep install (torch/vllm/transformers cu128 stack) on
256
+ # fresh hosts — RunPod caches it as a Flash artifact, but Vast reinstalls per host, so use
257
+ # `uv pip` (validated in the worker image: resolves + installs the full pinned cu128 stack
258
+ # in ~12s, ~10x faster than pip). --break-system-packages: PYBIN is the image's
259
+ # externally-managed system python (newer pytorch images dropped /opt/conda); uv refuses it
260
+ # without this flag (and ignores pip's PIP_BREAK_SYSTEM_PACKAGES), which is what silently
261
+ # broke the earlier uv attempt. The flag is a no-op on a conda/venv python, so it's safe
262
+ # across image variants.
263
+ pip_line = (
264
+ '"$PYBIN" -m pip install --no-cache-dir uv '
265
+ f'&& "$PYBIN" -m uv pip install --python "$PYBIN" --break-system-packages --no-cache {deps}'
266
+ )
267
+ else:
268
+ pip_line = ": # deps baked into the image (WORKER_IMAGE)"
269
+ # Verified live: Vast's args-mode wrapper resets PATH, so `python3` resolves to
270
+ # the OS python (Ubuntu 24.04 = PEP 668 externally-managed -> pip refuses), not
271
+ # the image's conda env. Prefer the conda python when present (torch baked in),
272
+ # and let pip install into whichever interpreter won.
273
+ return f"""#!/bin/bash
274
+ # AutoSLM vast worker (generated by autoslm.providers.vast.jobs.build_onstart)
275
+ set -x
276
+ export PIP_BREAK_SYSTEM_PACKAGES=1
277
+ PYBIN=/opt/conda/bin/python; [ -x "$PYBIN" ] || PYBIN=/usr/local/bin/python; [ -x "$PYBIN" ] || PYBIN=$(command -v python3)
278
+ mkdir -p /root/autoslm
279
+ cat > /root/autoslm/payload.b64 <<'AUTOSLM_PAYLOAD_EOF'
280
+ {payload_b64}AUTOSLM_PAYLOAD_EOF
281
+ base64 -d /root/autoslm/payload.b64 > /root/autoslm/payload.json
282
+ cat > /root/autoslm/bootstrap.py <<'AUTOSLM_BOOTSTRAP_EOF'
283
+ {bootstrap_src}AUTOSLM_BOOTSTRAP_EOF
284
+ # A base worker-stack install failure must STOP the script: continuing into
285
+ # bootstrap.py with a partially installed env turns a deterministic dependency
286
+ # failure into a later import/model crash (or a missing HF marker if
287
+ # huggingface_hub never installed). Hold the box first so the control plane can
288
+ # pull the log tail (mirrors the bootstrap-failure path below and the extra-pip
289
+ # check=True path). The no-deps branch (":") always succeeds, so this is a no-op there.
290
+ {pip_line} || {{ echo "AUTOSLM: base worker dependency install failed" >&2; sleep 600; exit 1; }}
291
+ "$PYBIN" /root/autoslm/bootstrap.py
292
+ AUTOSLM_RC=$?
293
+ # On failure, hold the box for 10 min so the control plane can pull the container
294
+ # log tail (the only home of early-bootstrap errors); it destroys us much sooner
295
+ # when alive. Success self-destroys immediately.
296
+ [ "$AUTOSLM_RC" -ne 0 ] && sleep 600
297
+ # Self-destroy backstop (the control plane's destroy is primary). CONTAINER_API_KEY
298
+ # is the Vast-injected instance-scoped key — the operator key never ships here.
299
+ # python, not curl: the worker image is not guaranteed to carry curl.
300
+ "$PYBIN" - <<'AUTOSLM_DESTROY_EOF'
301
+ import os, urllib.request
302
+ iid, key = os.environ.get("CONTAINER_ID"), os.environ.get("CONTAINER_API_KEY")
303
+ if iid and key:
304
+ req = urllib.request.Request(
305
+ f"https://console.vast.ai/api/v0/instances/{{iid}}/",
306
+ method="DELETE",
307
+ headers={{"Authorization": f"Bearer {{key}}"}},
308
+ )
309
+ try:
310
+ urllib.request.urlopen(req, timeout=30)
311
+ except Exception as exc:
312
+ print("self-destroy warn:", exc)
313
+ AUTOSLM_DESTROY_EOF
314
+ exit $AUTOSLM_RC
315
+ """
316
+
317
+
318
+ def deploy_and_submit(
319
+ spec,
320
+ seed: int,
321
+ offers: list[VastOffer],
322
+ attempt: int = 0,
323
+ log=None,
324
+ exclude_machine_ids: set[int] | frozenset[int] = frozenset(),
325
+ ) -> VastJobHandle:
326
+ """Rent the cheapest offer that will actually take the job; walk on rejection.
327
+
328
+ Offers are a live market — between search and rent the cheapest one is often
329
+ gone. We walk up to 5 ranked offers, then refresh the search once.
330
+
331
+ ``exclude_machine_ids`` is the run's blacklist (machines that stalled/failed this
332
+ run earlier). The refresh re-search MUST keep them excluded — otherwise a sick
333
+ machine the orchestrator just blacklisted gets re-selected from the fresh market.
334
+ """
335
+
336
+ def say(msg: str):
337
+ if log is not None:
338
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", file=log, flush=True)
339
+
340
+ if not offers:
341
+ raise vast_api.VastApiError("no usable vast offers (verified datacenter pool empty)")
342
+ payload = build_payload(spec, seed, attempt)
343
+ label = instance_label(spec.run_id, seed, attempt)
344
+ # Gate the runtime dep-install on the EFFECTIVE image (vast_image()), not on the raw
345
+ # WORKER_IMAGE: blanking AUTOSLM_WORKER_IMAGE is a RunPod-Flash-only "install at runtime"
346
+ # signal, but on Vast vast_image() substitutes the baked DEFAULT_WORKER_IMAGE (deps already
347
+ # in it). Keying off WORKER_IMAGE here would reinstall the whole pinned stack on top of the
348
+ # baked image — wasted cold-start time. vast_image() is never empty, so Vast uses baked deps.
349
+ install_deps = not vast_image()
350
+ tried: list[VastOffer] = []
351
+ candidates = list(offers[:5])
352
+ refreshed = False
353
+ last_err: Exception | None = None
354
+ while candidates:
355
+ offer = candidates.pop(0)
356
+ tried.append(offer)
357
+ onstart = build_onstart(payload, install_deps=install_deps)
358
+ try:
359
+ instance_id = vast_api.create_instance(
360
+ offer.offer_id,
361
+ image=vast_image(),
362
+ disk_gb=_effective_disk_gb(spec),
363
+ env={},
364
+ onstart=onstart,
365
+ label=label,
366
+ runtype="args",
367
+ )
368
+ except vast_api.VastApiError as e:
369
+ last_err = e
370
+ say(f"offer {offer.offer_id} ({offer.gpu} ${offer.dph_total:.2f}/hr) rejected: {e}")
371
+ if not candidates and not refreshed:
372
+ refreshed = True
373
+ # Exclude both the machines we just tried this attempt AND the run's
374
+ # standing blacklist (machines that stalled/failed earlier attempts) —
375
+ # otherwise the fresh search can re-select a sick machine the
376
+ # orchestrator deliberately excluded.
377
+ taken = {o.machine_id for o in tried} | set(exclude_machine_ids)
378
+ # Stay within the allocator-approved class pool: the original `offers`
379
+ # are already filtered to the allocated/pinned + validated classes, so
380
+ # the refresh must not widen to any usable offer (which could rent a
381
+ # different or unvalidated GPU than the run spec assumes).
382
+ allowed = {o.gpu for o in offers}
383
+ candidates = [
384
+ o
385
+ for o in usable_offers(
386
+ min(o.vram_gb for o in offers),
387
+ _effective_disk_gb(spec),
388
+ exclude_machine_ids=taken,
389
+ )
390
+ if o.gpu in allowed
391
+ ][:5]
392
+ continue
393
+ say(
394
+ f"rented vast instance {instance_id}: {offer.gpu} ${offer.dph_total:.2f}/hr "
395
+ f"(offer {offer.offer_id}, {offer.geolocation}, reliability "
396
+ f"{offer.reliability:.3f}) attempt={attempt} seed={seed}"
397
+ )
398
+ return VastJobHandle(
399
+ instance_id=instance_id,
400
+ offer_id=offer.offer_id,
401
+ machine_id=offer.machine_id,
402
+ label=label,
403
+ gpu=offer.gpu,
404
+ hourly_usd=offer.dph_total,
405
+ attempt=attempt,
406
+ started_ts=time.time(),
407
+ )
408
+ raise vast_api.VastApiError(f"all {len(tried)} vast offers rejected the job: {last_err}")
409
+
410
+
411
+ # Rate-limited reader for one HF artifact's text content (None until it exists). Shared
412
+ # with runpod's poller via make_hf_text_reader; kept under this module-local name because
413
+ # tests monkeypatch ``vast.jobs._make_hf_file_reader`` and the poll/failure paths below
414
+ # resolve it as a module global (so a monkeypatch still takes effect).
415
+ _make_hf_file_reader = make_hf_text_reader
416
+
417
+
418
+ def _failure_detail(
419
+ hf_repo: str, prefix: str, phase: str, marker: dict | None, instance_id: int | None = None
420
+ ) -> str:
421
+ """Best root-cause detail we can assemble from the HF artifacts."""
422
+ parts = []
423
+ if marker and marker.get("error"):
424
+ parts.append(str(marker["error"]))
425
+ content = _make_hf_file_reader(hf_repo, f"{prefix}/error_{phase}.txt")(force=True)
426
+ if content:
427
+ parts.append(f"--- error_{phase}.txt ---\n{content[-2000:]}")
428
+ if instance_id:
429
+ # Early-bootstrap failures (pip/env errors before the worker can reach HF)
430
+ # only ever appear on the container console.
431
+ logs = vast_api.instance_logs(int(instance_id))
432
+ if logs:
433
+ parts.append(f"--- instance log tail ---\n{logs[-3000:]}")
434
+ return "\n".join(parts) or "vast worker terminated without a DONE sentinel"
435
+
436
+
437
+ # Vast instance states that mean "the container is gone / will not progress".
438
+ _DEAD_STATES = {"exited", "stopped", "offline", "deleted"}
439
+
440
+
441
+ def poll_vast_job(
442
+ handle: VastJobHandle,
443
+ spec,
444
+ seed: int,
445
+ log=None,
446
+ interval_s: float = 15.0,
447
+ heartbeat_reader=None,
448
+ stall_after_s: float = 1500.0,
449
+ deadline_s: float | None = None,
450
+ ) -> PollResult:
451
+ """Poll instance status + HF artifacts to a terminal state (cf. jobs.poll_job).
452
+
453
+ COMPLETED fresh DONE sentinel on HF -> metrics.json (cost stamped from the
454
+ offer's real $/hr).
455
+ FAILED attempt marker with ok=false, or instance dead without DONE.
456
+ STALLED never left loading within LOAD_TIMEOUT_S, heartbeat frozen for
457
+ stall_after_s, or the client-side deadline passed.
458
+ """
459
+
460
+ say = make_say(log)
461
+
462
+ hf_repo = spec.train.hf_repo
463
+ prefix = f"{spec.phase}/{spec.run_id}/seed{seed}"
464
+ done_reader = _make_hf_file_reader(hf_repo, f"{prefix}/DONE")
465
+ marker_reader = _make_hf_file_reader(
466
+ hf_repo, f"{prefix}/vast_attempt{handle.attempt}.json", min_interval_s=60.0
467
+ )
468
+ metrics_reader = _make_hf_file_reader(hf_repo, f"{prefix}/metrics.json")
469
+
470
+ def finish_ok(done_content: str | None = None) -> PollResult:
471
+ raw = metrics_reader(force=True)
472
+ if raw is None:
473
+ return PollResult(False, failure="job_failed", detail="DONE without metrics.json")
474
+ metrics = json.loads(raw)
475
+ # Prefer the worker's DONE timestamp when present and sane; fall back to now.
476
+ # On delayed recovery the control plane may call this hours after the instance
477
+ # wrote DONE and self-destroyed, so billing to now would over-bill by the
478
+ # downtime — accepted because a missing/garbled DONE timestamp is rare. DONE
479
+ # carries the worker's time.time().
480
+ end_ts = time.time()
481
+ if done_content:
482
+ try:
483
+ done_ts = float(done_content.strip())
484
+ if handle.started_ts <= done_ts <= end_ts:
485
+ end_ts = done_ts
486
+ except ValueError:
487
+ # Malformed DONE timestamp: keep end_ts = now rather than trusting garbage.
488
+ pass
489
+ wall_h = (end_ts - handle.started_ts) / 3600.0
490
+ metrics["cost_usd"] = round(wall_h * handle.hourly_usd, 6)
491
+ notes = metrics.get("notes") if isinstance(metrics.get("notes"), dict) else {}
492
+ notes.update(
493
+ {
494
+ "provider": "vast",
495
+ "vast_rate_usd_hr": handle.hourly_usd,
496
+ "vast_gpu": handle.gpu,
497
+ "vast_offer_id": handle.offer_id,
498
+ }
499
+ )
500
+ metrics["notes"] = notes
501
+ return PollResult(True, metrics=metrics)
502
+
503
+ def done_is_fresh(content: str) -> bool:
504
+ # DONE carries the worker's time.time(); 120 s of clock-skew grace. Anything
505
+ # older predates this attempt (leftover from a prior attempt's resume).
506
+ try:
507
+ return float(content.strip()) > handle.started_ts - 120.0
508
+ except ValueError:
509
+ return False
510
+
511
+ poll_errors = PollErrorTracker(say, interval_s)
512
+
513
+ start = time.time()
514
+ last_status = None
515
+ last_hb_key = None
516
+ last_progress = time.time()
517
+ became_running = False
518
+ missing_streak = 0
519
+ while True:
520
+ if deadline_s is not None and time.time() - start > deadline_s:
521
+ return PollResult(False, failure="stalled", detail="client-side deadline exceeded")
522
+ try:
523
+ inst = vast_api.get_instance(handle.instance_id)
524
+ poll_errors.reset()
525
+ except vast_api.VastApiError as e:
526
+ if poll_errors.record(e):
527
+ return PollResult(False, failure="poll_error", detail=str(e))
528
+ continue
529
+ # Verified live: the instance-detail route TRANSIENTLY answers
530
+ # {"instances": null} for perfectly healthy instances (and for brand-new ones
531
+ # before they materialize). A single missing read means nothing — only a
532
+ # sustained streak is a real disappearance.
533
+ missing_streak = missing_streak + 1 if inst is None else 0
534
+
535
+ status = (inst or {}).get("actual_status") or ("missing" if inst is None else "unknown")
536
+ if status != last_status:
537
+ say(f"instance {handle.instance_id}: {status}")
538
+ last_status = status
539
+ last_progress = time.time()
540
+ if status == "running":
541
+ became_running = True
542
+
543
+ done = done_reader()
544
+ if done is not None and done_is_fresh(done):
545
+ return finish_ok(done)
546
+
547
+ if missing_streak >= 4 or status in _DEAD_STATES:
548
+ # One forced final read: the worker may have finished right before the
549
+ # instance self-destroyed (the normal success order on this substrate).
550
+ done = done_reader(force=True)
551
+ if done is not None and done_is_fresh(done):
552
+ return finish_ok(done)
553
+ raw_marker = marker_reader(force=True)
554
+ marker = None
555
+ if raw_marker:
556
+ with contextlib.suppress(ValueError):
557
+ marker = json.loads(raw_marker)
558
+ return PollResult(
559
+ False,
560
+ failure="job_failed",
561
+ detail=_failure_detail(hf_repo, prefix, spec.phase, marker, handle.instance_id),
562
+ )
563
+
564
+ raw_marker = marker_reader()
565
+ if raw_marker:
566
+ try:
567
+ marker = json.loads(raw_marker)
568
+ except ValueError:
569
+ marker = None
570
+ if marker and not marker.get("ok"):
571
+ return PollResult(
572
+ False,
573
+ failure="job_failed",
574
+ detail=_failure_detail(hf_repo, prefix, spec.phase, marker, handle.instance_id),
575
+ )
576
+ if marker and marker.get("ok"):
577
+ done = done_reader(force=True)
578
+ if done is not None and done_is_fresh(done):
579
+ return finish_ok(done)
580
+
581
+ if not became_running and time.time() - start > LOAD_TIMEOUT_S:
582
+ return PollResult(
583
+ False,
584
+ failure="stalled",
585
+ detail=f"instance stuck in '{status}' for {int(time.time() - start)}s "
586
+ f"(image pull / host issue)",
587
+ )
588
+
589
+ new_key, _stage = surface_heartbeat(heartbeat_reader, last_hb_key, say)
590
+ if new_key != last_hb_key:
591
+ last_hb_key = new_key
592
+ last_progress = time.time()
593
+ if became_running and time.time() - last_progress > stall_after_s:
594
+ return PollResult(
595
+ False,
596
+ failure="stalled",
597
+ detail=f"no worker progress for {int(time.time() - last_progress)}s "
598
+ f"(instance status {status})",
599
+ )
600
+ time.sleep(interval_s)
601
+
602
+
603
+ def submit_run_vast(
604
+ spec,
605
+ seed: int,
606
+ log=None,
607
+ on_handle=None,
608
+ attempt: int = 0,
609
+ offers: list[VastOffer] | None = None,
610
+ exclude_machine_ids: set[int] | frozenset[int] = frozenset(),
611
+ ) -> PollResult:
612
+ """Vast equivalent of ``runpod.jobs.submit_run``: rent, persist, poll.
613
+
614
+ The ``finally`` destroy is the cost-safety primary: every exit path — success,
615
+ failure, stall, exception, KeyboardInterrupt — tears the paid instance down.
616
+ """
617
+ if offers is None:
618
+ # GPU_INFO is keyed by concrete GPU class; a policy word ("cheapest"/"auto") would
619
+ # KeyError opaquely here. The allocator resolves policy words to a concrete class
620
+ # upstream, so reaching this fallback with one is a caller bug — name it clearly.
621
+ if spec.gpu.type not in GPU_INFO:
622
+ raise vast_api.VastApiError(
623
+ f"submit_run_vast needs a concrete gpu class, got {spec.gpu.type!r}"
624
+ )
625
+ info = GPU_INFO[spec.gpu.type]
626
+ offers = [
627
+ o
628
+ for o in usable_offers(
629
+ info.vram_gb,
630
+ _effective_disk_gb(spec),
631
+ exclude_machine_ids=exclude_machine_ids,
632
+ )
633
+ if o.gpu == spec.gpu.type
634
+ ]
635
+ handle = deploy_and_submit(
636
+ spec, seed, offers, attempt=attempt, log=log, exclude_machine_ids=exclude_machine_ids
637
+ )
638
+ # The instance is rented and billing the MOMENT deploy_and_submit returns; the
639
+ # teardown ``finally`` must guard EVERYTHING after that point — including
640
+ # ``on_handle`` (persisting the remote handle can itself raise). Entering the try
641
+ # before on_handle guarantees the paid instance is destroyed even if the handle is
642
+ # never persisted, closing the rent->persist crash window's billing leak.
643
+ try:
644
+ if on_handle is not None:
645
+ on_handle(handle.to_dict())
646
+ hf_repo = spec.train.hf_repo
647
+ prefix = f"{spec.phase}/{spec.run_id}/seed{seed}"
648
+ reader = make_hf_heartbeat_reader(hf_repo, prefix) if hf_repo else None
649
+ stall = 1500.0
650
+ # Wall cap + provision/install grace; Vast has no server-side execution
651
+ # timeout, so the client deadline (and the bootstrap's own cap) bound spend.
652
+ deadline = max(60, int(spec.gpu.max_wall_seconds)) + 1800
653
+ return poll_vast_job(
654
+ handle,
655
+ spec,
656
+ seed,
657
+ log=log,
658
+ heartbeat_reader=reader,
659
+ stall_after_s=stall,
660
+ deadline_s=deadline,
661
+ )
662
+ finally:
663
+ vast_api.destroy_instance(handle.instance_id)
664
+
665
+
666
+ def cancel(remote: dict) -> None:
667
+ """Cross-process cancel: destroy the persisted instance (stops billing)."""
668
+ instance_id = remote.get("instance_id")
669
+ if instance_id:
670
+ vast_api.destroy_instance(int(instance_id))
671
+
672
+
673
+ def destroy_run_instances(run_id: str) -> list[int]:
674
+ """Destroy every instance belonging to ONE run (labels start with its run id).
675
+
676
+ Cancel/GC path: unlike ``sweep_orphans`` this never looks at other runs, so it
677
+ is safe to call while they are in flight. Best-effort: never raises.
678
+ """
679
+ destroyed: list[int] = []
680
+ if not run_id:
681
+ return destroyed
682
+ try:
683
+ instances = vast_api.list_instances()
684
+ except Exception:
685
+ return destroyed
686
+ prefixes = (run_id, f"autoslm-{run_id}") # instance_label may force the prefix
687
+ for inst in instances:
688
+ iid = inst.get("id")
689
+ label = str(inst.get("label") or "")
690
+ # Match on the label boundary, not a raw string prefix (see ``sweep_orphans``):
691
+ # an instance label is ``f"{run_label_prefix(run_id)}-s{seed}-a{attempt}"``, so a
692
+ # run's prefix must equal the label or be followed by the ``-s`` seed boundary.
693
+ # A bare ``startswith`` would let run ``100`` also destroy run ``1000``'s instances.
694
+ if (
695
+ iid
696
+ and any(label == p or label.startswith(p + "-s") for p in prefixes)
697
+ and vast_api.destroy_instance(int(iid))
698
+ ):
699
+ destroyed.append(int(iid))
700
+ return destroyed
701
+
702
+
703
+ def sweep_orphans(active_labels: set[str] | None = None) -> list[int]:
704
+ """Destroy AutoSLM-labeled instances that no live run owns; return destroyed ids.
705
+
706
+ Run at server startup (crash recovery) and after runs (belt and suspenders).
707
+ Only labels carrying the run-id prefix are ever touched — nothing else on the
708
+ account is ours to destroy. Best-effort: never raises.
709
+
710
+ ``active_labels`` may be RAW run ids (what the server tracks) — each is passed
711
+ through ``run_label_prefix`` so it matches the SAME forced-``autoslm-`` prefix the
712
+ instance labels carry. Passing an already-prefixed label is fine (idempotent), so a
713
+ live run whose id lacks the prefix is still correctly protected.
714
+ """
715
+ destroyed: list[int] = []
716
+ try:
717
+ instances = vast_api.list_instances()
718
+ except Exception as exc:
719
+ logger.warning("vast orphan sweep skipped: %s", exc)
720
+ return destroyed
721
+ active = {run_label_prefix(a) for a in (active_labels or set())}
722
+ for inst in instances:
723
+ label = str(inst.get("label") or "")
724
+ if not label.startswith("autoslm-"):
725
+ continue
726
+ # Match on the label boundary, not a raw string prefix: an instance label is
727
+ # ``f"{run_label_prefix(run_id)}-s{seed}-a{attempt}"`` (see ``instance_label``),
728
+ # so a live run's prefix must equal the label or be followed by the ``-s`` seed
729
+ # boundary. A bare ``startswith`` would let one run's prefix (e.g. ``autoslm-100``)
730
+ # shield another run's orphan (``autoslm-1000-...``) from the sweep.
731
+ if any(label == a or label.startswith(a + "-s") for a in active):
732
+ continue
733
+ iid = inst.get("id")
734
+ if iid and vast_api.destroy_instance(int(iid)):
735
+ destroyed.append(int(iid))
736
+ logger.warning("destroyed orphaned vast instance %s (label %s)", iid, label)
737
+ return destroyed
code/autoslm/providers/vast/preflight.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fail-fast credential checks for the Vast.ai substrate (operator-side).
2
+
3
+ Mirrors ``providers/runpod/preflight.py``: surfaces missing operator config as a clear
4
+ problem list the control plane aggregates into one startup error. Vast is opt-in (it is
5
+ only required when a run pins ``gpu.provider = "vast"`` or the operator enables it), so
6
+ the only Vast-specific requirement is ``VAST_API_KEY``; HF_TOKEN is a shared run
7
+ requirement checked once by the RunPod preflight (the HF dataset repo is per-run via
8
+ ``[train] hf_repo``).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from autoslm.providers.vast.auth import load_api_key
14
+
15
+
16
+ def missing_credentials(require_hf: bool = True) -> list[str]:
17
+ """Vast-related operator config that is missing (empty list == ready).
18
+
19
+ ``require_hf`` is accepted only for signature parity with the RunPod check and is
20
+ intentionally ignored: Vast has no provider-owned HF requirement (the shared
21
+ HF_TOKEN is checked once centrally in ``providers.preflight``).
22
+ """
23
+ problems: list[str] = []
24
+ if not load_api_key():
25
+ problems.append(" - VAST_API_KEY: the operator's Vast.ai API key (for the vast provider)")
26
+ return problems
code/autoslm/providers/vast/pricing.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vast.ai $/hr: cheapest live verified-datacenter offer per class, static fallback.
2
+
3
+ RunPod prices a fixed class catalog; Vast is a live market, so a class's "rate" is the
4
+ cheapest currently-usable offer for it (``usable_offers``). This module gives the
5
+ provider interface a uniform ``hourly_rate(gpu)`` and a ``live_rates()`` map for the
6
+ ``slm gpus`` table. Offline-safe: AUTOSLM_SKIP_NET (or any failure) falls back to the
7
+ static Vast snapshot carried on ``GpuClass.hourly_usd``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+
14
+ from autoslm._logging import get_logger
15
+
16
+ logger = get_logger(__name__)
17
+
18
+
19
+ def _static_rates() -> dict[str, float]:
20
+ """Static Vast snapshot rate per class with a ``vast_name`` (display-only fallback)."""
21
+ from autoslm.providers.base import GPU_INFO
22
+
23
+ return {name: info.hourly_usd for name, info in GPU_INFO.items() if info.vast_name}
24
+
25
+
26
+ def live_rates(refresh: bool = False) -> dict[str, float]:
27
+ """Friendly-name -> cheapest live verified-datacenter $/hr (static fallback).
28
+
29
+ Offline-safe: AUTOSLM_SKIP_NET (or any fetch failure) returns the static rates.
30
+ """
31
+ static = _static_rates()
32
+ if os.environ.get("AUTOSLM_SKIP_NET") or not os.environ.get("VAST_API_KEY"):
33
+ return static
34
+ try:
35
+ from autoslm.providers.vast.jobs import usable_offers
36
+
37
+ rates: dict[str, float] = {}
38
+ for offer in usable_offers(0, 0): # offers are price-sorted, cheapest first
39
+ rates.setdefault(offer.gpu, offer.dph_total)
40
+ return {**static, **rates}
41
+ except Exception as exc:
42
+ logger.warning("live vast pricing unavailable (%s); using static rates", exc)
43
+ return static
44
+
45
+
46
+ def hourly_rate(gpu_name: str) -> float:
47
+ """$/hr for one friendly GPU name (cheapest live offer if available, else static)."""
48
+ from autoslm.providers.base import canonical_gpu
49
+
50
+ name = canonical_gpu(gpu_name)
51
+ return live_rates().get(name) or _static_rates().get(name, 0.0)
code/autoslm/providers/vast/train.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vast.ai train submission: build the instance payload + submit a run.
2
+
3
+ The worker stack/env is substrate-neutral, so the per-run worker env and dependency
4
+ resolution are shared with RunPod (``providers/runpod/train.py``); this module owns the
5
+ Vast-specific submission entrypoint and the instance payload shape. Provisioning,
6
+ polling, and teardown live in ``providers/vast/jobs.py``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ # Shared, substrate-neutral worker stack (single source of truth on RunPod's module).
12
+ from autoslm.providers.runpod.train import (
13
+ WORKER_DEPS,
14
+ WORKER_SYSTEM_DEPS,
15
+ build_worker_env,
16
+ resolve_worker_deps,
17
+ )
18
+ from autoslm.providers.vast.jobs import build_payload, submit_run_vast
19
+
20
+ __all__ = [
21
+ "WORKER_DEPS",
22
+ "WORKER_SYSTEM_DEPS",
23
+ "build_payload",
24
+ "build_worker_env",
25
+ "resolve_worker_deps",
26
+ "submit_run_vast",
27
+ ]
code/autoslm/py.typed ADDED
File without changes
code/autoslm/runner.py ADDED
@@ -0,0 +1,994 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Platform runner: drives managed GPUs across providers (RunPod Flash + Vast), one allocation per seed."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import json
7
+ import os
8
+ import re
9
+ import tempfile
10
+ import threading
11
+ import time
12
+ import uuid
13
+ from dataclasses import asdict, dataclass, field
14
+
15
+ from .catalog import ModelInfo, resolve_model
16
+ from .spec import JobSpec
17
+
18
+ # Fixed local storage roots (not operator-configurable): run-state JSON + result artifacts,
19
+ # both under the ~/.autoslm state dir (same root as server/db.py's DB_PATH) so a single
20
+ # directory holds all control-plane state — mount one volume at ~/.autoslm to persist it.
21
+ # Tests redirect them via monkeypatch.setattr(runner, "RUNS_DIR"/"RESULTS_DIR").
22
+ _STATE_DIR = os.path.join(os.path.expanduser("~"), ".autoslm")
23
+ RUNS_DIR = os.path.join(_STATE_DIR, "runs")
24
+ RESULTS_DIR = os.path.join(_STATE_DIR, "results")
25
+ TERMINAL_STATES = frozenset({"done", "failed", "cancelled", "dry_run"})
26
+ # Terminal states a deploy must NOT overwrite. `done` is terminal but IS deployable
27
+ # (deploying a finished run is the whole point), so it's excluded here; cancelled/failed/
28
+ # dry_run must never be flipped to `deployed`.
29
+ _UNDEPLOYABLE_STATES = TERMINAL_STATES - {"done"}
30
+ # Serializes the read-check-write in _update so a status transition is an atomic
31
+ # compare-and-set (the control plane is single-instance with per-run threads).
32
+ _STATUS_LOCK = threading.Lock()
33
+
34
+
35
+ def artifacts_dir(spec: JobSpec) -> str:
36
+ """Run-scoped artifact root: results/runpod/<phase>/<run_id>."""
37
+ return os.path.join(RESULTS_DIR, "runpod", spec.phase, spec.run_id)
38
+
39
+
40
+ def adapter_prefix(spec: JobSpec, seed: int | None = None) -> str:
41
+ """A run's adapter location on the HF artifact store."""
42
+ chosen = spec.train.seeds[0] if seed is None else seed
43
+ return f"{spec.phase}/{spec.run_id}/seed{chosen}"
44
+
45
+
46
+ def _gpu_rate(gpu_type: str) -> float:
47
+ """Representative $/hr for cost projection (live RunPod pricing, static fallback);
48
+ the worker also records wall time so cost = wall_hours * rate."""
49
+ try:
50
+ from autoslm.providers.runpod.pricing import hourly_rate
51
+
52
+ return hourly_rate(gpu_type)
53
+ except Exception:
54
+ return 0.80
55
+
56
+
57
+ @dataclass
58
+ class RunStatus:
59
+ run_id: str
60
+ state: str
61
+ spec: dict
62
+ created_at: float = field(default_factory=time.time)
63
+ updated_at: float = field(default_factory=time.time)
64
+ cost_usd: float = 0.0
65
+ error: str | None = None
66
+ artifacts_dir: str | None = None
67
+ deployment: dict | None = None
68
+ # Durable job handle {endpoint_id, endpoint_name, job_id} — lets any process
69
+ # reattach to / cancel the remote job (see `slm attach`).
70
+ remote: dict | None = None
71
+ # Index of the next seed to run for a multi-seed job, set while the remote handle
72
+ # is cleared in the gap between seeds. Lets recover_runs resume the remaining seeds
73
+ # after an inter-seed restart instead of failing the run (losing completed work).
74
+ resume_seed_index: int | None = None
75
+
76
+ def to_dict(self) -> dict:
77
+ return asdict(self)
78
+
79
+
80
+ class _RunCancelled(RuntimeError):
81
+ """User cancellation observed mid-run; terminal, never retried/overwritten."""
82
+
83
+
84
+ def new_run_id(prefix: str = "autoslm") -> str:
85
+ return f"{prefix}-{int(time.time())}-{uuid.uuid4().hex[:8]}"
86
+
87
+
88
+ _RUN_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
89
+
90
+
91
+ def require_safe_run_id(run_id: str) -> str:
92
+ """Reject run ids that could traverse outside the runs directory.
93
+
94
+ Run ids flow from API path params into filesystem paths (status json,
95
+ log files); restrict them to a conservative filename alphabet.
96
+ """
97
+ if not _RUN_ID_RE.match(run_id or ""):
98
+ raise ValueError(f"invalid run_id: {run_id!r}")
99
+ return run_id
100
+
101
+
102
+ def runs_file_path(run_id: str, suffix: str) -> str:
103
+ """Containment-checked path for a run's file under RUNS_DIR.
104
+
105
+ Belt and braces with require_safe_run_id: the resolved path must stay
106
+ inside the runs directory even if the alphabet check ever regresses.
107
+ """
108
+ base = os.path.abspath(RUNS_DIR)
109
+ path = os.path.normpath(os.path.join(base, f"{require_safe_run_id(run_id)}{suffix}"))
110
+ if not path.startswith(base + os.sep):
111
+ raise ValueError(f"invalid run_id: {run_id!r}")
112
+ return path
113
+
114
+
115
+ def _with_model_disk(spec: JobSpec, info: ModelInfo) -> dict:
116
+ """Spec dict with gpu.disk_gb raised to the model's min_disk_gb (catalog).
117
+
118
+ Big-checkpoint models (whose weights alone exceed the default) need more container
119
+ disk than the platform's 64 GB default; this makes them work without users having
120
+ to know the right ``gpu.disk_gb``.
121
+ """
122
+ d = spec.to_dict()
123
+ need = int(getattr(info, "min_disk_gb", 0) or 0)
124
+ if need > int(d["gpu"].get("disk_gb") or 0):
125
+ d["gpu"] = {**d["gpu"], "disk_gb": need}
126
+ return d
127
+
128
+
129
+ def submit_job(spec: JobSpec, dry_run: bool = False, background: bool = False) -> RunStatus:
130
+ """Submit a job. In real mode this allocates and provisions the cheapest validated GPU class
131
+ across the configured providers (RunPod Flash or Vast); dry-run only records state."""
132
+ info = resolve_model(spec.model, spec.algorithm, policy=spec.model_policy, gpu=spec.gpu.type)
133
+ spec = JobSpec.from_dict(
134
+ {**_with_model_disk(spec, info), "run_id": spec.run_id or new_run_id()}
135
+ )
136
+ status = RunStatus(run_id=spec.run_id, state="queued", spec=spec.to_dict())
137
+ _save_status(status)
138
+ if dry_run:
139
+ status.state = "dry_run"
140
+ _save_status(status)
141
+ return status
142
+ if background:
143
+ threading.Thread(target=_run_job, args=(spec,), daemon=True).start()
144
+ return get_status(spec.run_id)
145
+ _run_job(spec)
146
+ return get_status(spec.run_id)
147
+
148
+
149
+ def get_status(run_id: str) -> RunStatus:
150
+ path = runs_file_path(run_id, ".json")
151
+ if not os.path.exists(path):
152
+ raise FileNotFoundError(f"unknown run_id: {run_id}")
153
+ with open(path) as f:
154
+ return RunStatus(**json.load(f))
155
+
156
+
157
+ def list_runs() -> list[RunStatus]:
158
+ os.makedirs(RUNS_DIR, exist_ok=True)
159
+ runs = []
160
+ for name in sorted(os.listdir(RUNS_DIR)):
161
+ if name.endswith(".json"):
162
+ with open(os.path.join(RUNS_DIR, name)) as f:
163
+ runs.append(RunStatus(**json.load(f)))
164
+ return runs
165
+
166
+
167
+ def get_logs(run_id: str) -> str:
168
+ log_path = runs_file_path(run_id, ".log")
169
+ if not os.path.exists(log_path):
170
+ return ""
171
+ with open(log_path) as f:
172
+ return f.read()
173
+
174
+
175
+ def cancel_run(run_id: str) -> RunStatus:
176
+ """Cancel a run: delete its remote Flash endpoint (stopping the worker), then mark it
177
+ cancelled.
178
+
179
+ Uses ``terminate_endpoint`` (reconstructs the run's uniquely-named endpoint and deletes it
180
+ via the RunPod API) so the cancel works **cross-process** — a fresh ``slm cancel`` actually
181
+ stops the GPU worker, instead of leaving it running until the wall cap. Best-effort: any
182
+ teardown error is recorded but still flips the run to ``cancelled``.
183
+ """
184
+ status = get_status(run_id)
185
+ if status.state in TERMINAL_STATES:
186
+ return status
187
+ # Whether the run was a live `deployed` serving run at cancel entry. This scopes the
188
+ # final `cancelled` transition's terminal override below: only a `deployed` run can have
189
+ # a concurrent undeploy (`mark_undeployed`) race this teardown and write a non-completion
190
+ # terminal `done`. A non-deployed run (running/provisioning/queued) has an in-flight
191
+ # TRAINING thread whose only terminal `done` is a GENUINE completion — which cancel must
192
+ # never clobber. See the final _update call for how this gates the override.
193
+ entered_deployed = status.state == "deployed"
194
+ spec = JobSpec.from_dict(status.spec)
195
+ remote = status.remote or {}
196
+ # A deployed run also owns a serving endpoint (autoslm-serve-*) that the
197
+ # training-endpoint GC below does not touch; tear it down too so a
198
+ # cancelled run can't leave a billable deployment registered. Serving is
199
+ # RunPod-only, so use the class actually deployed (a Vast-only training class
200
+ # falls back to a RunPod class at deploy time).
201
+ if status.state == "deployed":
202
+ try:
203
+ from autoslm.serve.deploy import undeploy_adapter
204
+
205
+ deployed_gpu = (status.deployment or {}).get("gpu") or spec.gpu.type
206
+ deleted = undeploy_adapter(run_id, gpu_name=deployed_gpu)
207
+ # Mark the deployment inactive so /v1/deployments and /chat (which gate only
208
+ # on the deployment record's state) stop treating the cancelled run as
209
+ # active. dev mode is scale-to-zero: a never-chatted dev deployment has no
210
+ # endpoint yet, so an empty deletion is still a clean teardown — don't leave
211
+ # it "ready". always-on provisions at deploy time, so only mark it inactive
212
+ # once a deletion is confirmed (an empty deletion there is suspicious).
213
+ dev_mode = (status.deployment or {}).get("mode", "dev") == "dev"
214
+ if status.deployment and (deleted or dev_mode):
215
+ # Mark the deployment inactive through the lock-guarded path so this write
216
+ # participates in the same _STATUS_LOCK as the rest of the runner. A bare
217
+ # _save_status here would persist a stale pre-teardown snapshot OUTSIDE the
218
+ # lock, bypassing serialization and potentially clobbering a concurrent field
219
+ # update. We mark ONLY the deployment field and leave the run's state alone
220
+ # (no state re-assert): a concurrent mark_undeployed can move the run to
221
+ # terminal `done` between our get_status read and this write, and _update's
222
+ # compare-and-set rejects ANY transition off a terminal state (even a
223
+ # same-field re-assert of the stale `deployed`), which would silently leave
224
+ # the deployment advertised as `ready`. mark_deployment_undeployed flips the
225
+ # deployment regardless of (and without disturbing) the current state.
226
+ mark_deployment_undeployed(run_id)
227
+ except Exception:
228
+ # Best-effort serving teardown: a failure here must not block the cancel
229
+ # below (the run still flips to cancelled and the training endpoint is GC'd).
230
+ pass
231
+ # Durable path first: stop the exact remote worker via the handle's provider
232
+ # (works from any process); endpoint/instance teardown is shared with the GC.
233
+ # Dispatched generically through the registry — never a hardcoded per-provider branch.
234
+ if remote:
235
+ try:
236
+ from autoslm.providers import get_provider
237
+ from autoslm.providers.base import JobHandle
238
+
239
+ handle = JobHandle.from_dict(remote)
240
+ provider = get_provider(handle.provider)
241
+ provider.cancel(handle)
242
+ # Vast bills until destroyed, so also belt-and-suspenders destroy the
243
+ # instance (a no-op cost-wise for runpod, whose endpoint GC follows).
244
+ provider.destroy(handle)
245
+ except Exception:
246
+ # Best-effort remote stop; _gc_run_endpoints below still tears the endpoint down.
247
+ pass
248
+ _gc_run_endpoints(spec)
249
+ # Final transition to `cancelled`. The run was NON-terminal at entry, but teardown takes
250
+ # time and a terminal state can race in mid-teardown. We must distinguish two cases:
251
+ #
252
+ # - A concurrent mark_undeployed() (an external `DELETE /v1/runs/{id}/deploy`) flipped a
253
+ # `deployed` run to terminal `done`. That `done` is NOT a fresh result — it just
254
+ # restored the run's pre-deploy completion marker while retiring serving. The user
255
+ # explicitly asked to cancel, so this must be OVERRIDDEN to `cancelled`.
256
+ # - A genuine training-COMPLETION `done` from the run's own training thread
257
+ # (_run_job_inner / attach_run), which persisted real metrics+cost+artifacts. Cancel
258
+ # must NEVER clobber that — the run finished, so the real result is preserved.
259
+ #
260
+ # These two races are mutually exclusive on the entry state: only a `deployed` run owns a
261
+ # deployment that mark_undeployed can race, and only a non-deployed (running/provisioning/
262
+ # queued) run has an in-flight training thread that can complete mid-teardown. So scope the
263
+ # terminal override to runs that were `deployed` at entry — there a racing `done` is always
264
+ # an undeploy artifact (cancel wins); elsewhere a racing `done` is a genuine completion that
265
+ # _update's CAS correctly protects (cancel loses to a real finish).
266
+ _update(run_id, "cancelled", allow_from_terminal=entered_deployed)
267
+ return get_status(run_id)
268
+
269
+
270
+ def attach_run(run_id: str, log_stream=None) -> RunStatus:
271
+ """Re-attach to a run's remote job from ANY process (after a client crash/restart).
272
+
273
+ Uses the persisted {endpoint_id, job_id} handle to resume polling; on completion,
274
+ persists metrics exactly like the original client would have, flips the state, and
275
+ GCs the endpoint. Raises if the run has no persisted handle (it failed or was
276
+ cancelled before a worker was provisioned).
277
+ """
278
+ import sys
279
+
280
+ status = get_status(run_id)
281
+ if status.state in TERMINAL_STATES:
282
+ return status
283
+ if not status.remote:
284
+ raise ValueError(f"run {run_id} has no persisted job handle; cannot reattach")
285
+
286
+ spec = JobSpec.from_dict(status.spec)
287
+ remote = dict(status.remote)
288
+ seed = int(remote.pop("seed", spec.train.seeds[0]))
289
+ # The class the run actually provisioned (a policy retry may have walked past the
290
+ # provisional spec.gpu.type). The in-process success path stamps this into metrics;
291
+ # on recovery the worker output carries no such field, so recover it from the handle
292
+ # to cost the right card.
293
+ allocated_gpu = remote.pop("allocated_gpu", None)
294
+ log = log_stream or sys.stderr
295
+ # Dispatch the poll generically via the handle's provider (the provider owns its
296
+ # heartbeat reader + poll loop); the orchestrator stays provider-agnostic.
297
+ from autoslm.providers import get_provider
298
+ from autoslm.providers.base import JobHandle
299
+
300
+ handle = JobHandle.from_dict(remote)
301
+ print(f"attaching to {run_id}: provider={handle.provider} {handle.data}", file=log)
302
+ res = get_provider(handle.provider).poll(handle, spec, seed, log=log)
303
+ try:
304
+ # A best-effort cancel deletes the job/instance, which the poller reports as a
305
+ # failure (or a late worker may still succeed) — either way, re-read the state
306
+ # first so a recovery thread can't overwrite the user's terminal `cancelled`.
307
+ if get_status(run_id).state == "cancelled":
308
+ return get_status(run_id)
309
+ if not res.ok:
310
+ _update(run_id, "failed", error=f"{res.failure}: {res.detail}")
311
+ return get_status(run_id)
312
+ # Carry the provisioned class into metrics so _persist_metrics costs the card the
313
+ # run actually used (the in-process path stamps this; recovery must restore it).
314
+ if allocated_gpu and isinstance(res.metrics, dict):
315
+ res.metrics.setdefault("allocated_gpu", allocated_gpu)
316
+ # Earlier seeds of a multi-seed run already persisted their cost into
317
+ # status.cost_usd; add this seed's so recovery doesn't underreport spend.
318
+ total = float(status.cost_usd or 0.0) + _persist_metrics(spec, seed, res.metrics)
319
+ # A cancel can land while this thread persists the recovered seed's metrics
320
+ # (after the late-cancel check above). Re-read before the post-seed writes so
321
+ # the "running" update and the terminal "done" below can't resurrect a
322
+ # user-cancelled run (mirrors the fresh seed loop). _RunCancelled is caught
323
+ # below, leaving the cancellation intact.
324
+ if get_status(run_id).state == "cancelled":
325
+ raise _RunCancelled(f"run {run_id} was cancelled")
326
+ # The remote handle only identifies the seed that was in flight. For a
327
+ # multi-seed run, resume the remaining seeds instead of terminally
328
+ # completing the whole run after just this one.
329
+ try:
330
+ resumed_index = list(spec.train.seeds).index(seed) + 1
331
+ except ValueError:
332
+ resumed_index = len(spec.train.seeds)
333
+ more_seeds = resumed_index < len(spec.train.seeds)
334
+ # Clear the now-stale completed handle before resuming. In the
335
+ # allocation/provisioning gap before the next seed's on_handle() persists a
336
+ # fresh handle, a server restart must not reattach recovery to this finished
337
+ # job — that would double-count its cost and replay the wrong seed. Record the
338
+ # next seed index so a restart in that gap resumes the remaining seeds rather
339
+ # than failing the run. (The last seed keeps its handle for post-run
340
+ # observability, mirroring the fresh-submit seed loop.)
341
+ _update(
342
+ run_id,
343
+ "running",
344
+ cost_usd=total,
345
+ artifacts_dir=artifacts_dir(spec),
346
+ **({"remote": None, "resume_seed_index": resumed_index} if more_seeds else {}),
347
+ )
348
+ if more_seeds:
349
+ _run_seed_loop(spec, log, start_index=resumed_index, prior_cost=total)
350
+ else:
351
+ _update(run_id, "done", cost_usd=total, artifacts_dir=artifacts_dir(spec))
352
+ except _RunCancelled:
353
+ # Intentional: cancel_run already wrote the terminal `cancelled` state; leave it.
354
+ pass
355
+ except Exception as exc:
356
+ if get_status(run_id).state != "cancelled":
357
+ _update(run_id, "failed", error=str(exc))
358
+ finally:
359
+ _gc_run_endpoints(spec)
360
+ return get_status(run_id)
361
+
362
+
363
+ def resume_run(run_id: str, log_stream=None) -> RunStatus:
364
+ """Resume the remaining seeds of a multi-seed run after a restart in the inter-seed gap.
365
+
366
+ Between two seeds the completed seed's handle is cleared and ``resume_seed_index`` is
367
+ recorded (see ``_run_seed_loop``). A control-plane restart in that handle-less window
368
+ must RESUME from that index rather than fail the run and discard the finished seeds.
369
+ Unlike ``attach_run`` there is no live job to poll — the prior process already tore the
370
+ seed's endpoint down — so we start a fresh seed loop from the recorded index. The slm
371
+ package was uploaded to HF on the original submit, so the worker can still fetch it; no
372
+ re-upload is needed.
373
+ """
374
+ import sys
375
+
376
+ status = get_status(run_id)
377
+ if status.state in TERMINAL_STATES:
378
+ return status
379
+ if status.resume_seed_index is None:
380
+ raise ValueError(f"run {run_id} has no resume_seed_index; cannot resume")
381
+ spec = JobSpec.from_dict(status.spec)
382
+ log = log_stream or sys.stderr
383
+ print(f"resuming {run_id}: remaining seeds from index {status.resume_seed_index}", file=log)
384
+ try:
385
+ _run_seed_loop(
386
+ spec,
387
+ log,
388
+ start_index=status.resume_seed_index,
389
+ prior_cost=float(status.cost_usd or 0.0),
390
+ )
391
+ except _RunCancelled:
392
+ pass # cancel_run already set the terminal state
393
+ except Exception as exc:
394
+ if get_status(run_id).state != "cancelled":
395
+ _update(run_id, "failed", error=str(exc))
396
+ finally:
397
+ # Mirror _run_job: GC any endpoint a transient destroy left behind rather than
398
+ # leaking a billable RunPod endpoint.
399
+ _gc_run_endpoints(spec)
400
+ return get_status(run_id)
401
+
402
+
403
+ def mark_deployed(run_id: str, deployment: dict, expect_state: str | None = None) -> RunStatus:
404
+ # Atomic + terminal-respecting (same guard as _update): a /cancel landing during
405
+ # always-on provisioning/warmup writes `cancelled`; this must NOT overwrite it with
406
+ # `deployed` and resurrect the run as an active deployment. `done` is deployable
407
+ # though (the common case: deploy a finished run), so only the non-`done` terminal
408
+ # states block here — otherwise a freshly finished run could never be deployed.
409
+ #
410
+ # expect_state is a compare-and-set: the deploy flow passes the state it expects the
411
+ # run to still be in (the pre-deploy snapshot, or "deployed" after the provisional
412
+ # mark). If an undeploy raced finalization — deleting the endpoint and writing `done`
413
+ # with deployment.state="undeployed" mid-warmup — the state no longer matches and we
414
+ # refuse to re-advertise the just-deleted endpoint.
415
+ with _STATUS_LOCK:
416
+ status = get_status(run_id)
417
+ if status.state in _UNDEPLOYABLE_STATES:
418
+ return status
419
+ if expect_state is not None and status.state != expect_state:
420
+ return status
421
+ status.deployment = deployment
422
+ status.state = "deployed"
423
+ status.updated_at = time.time()
424
+ _save_status(status)
425
+ return status
426
+
427
+
428
+ def mark_undeployed(run_id: str) -> RunStatus:
429
+ """Record an explicit undeploy (endpoint torn down -> run back to `done`).
430
+
431
+ Lock-guarded so it serializes with a racing deploy finalization: the raw read +
432
+ _save_status the endpoint used to do could interleave with mark_deployed and be
433
+ clobbered. With this under the same lock, mark_deployed's expect_state CAS then sees
434
+ the `done`/undeployed write and won't re-advertise the deleted endpoint.
435
+ """
436
+ with _STATUS_LOCK:
437
+ status = get_status(run_id)
438
+ if status.deployment:
439
+ status.deployment = {**status.deployment, "state": "undeployed"}
440
+ # Record the teardown but don't resurrect a terminal run: undeploying a
441
+ # cancelled/failed run keeps its terminal state (only a live `deployed` run goes
442
+ # back to `done`). `done` is terminal too, so this naturally no-ops the state.
443
+ if status.state not in TERMINAL_STATES:
444
+ status.state = "done"
445
+ status.updated_at = time.time()
446
+ _save_status(status)
447
+ return status
448
+
449
+
450
+ def mark_deployment_undeployed(run_id: str) -> RunStatus:
451
+ """Flip ONLY the deployment field to ``undeployed``, leaving the run's state untouched.
452
+
453
+ Used by ``cancel_run`` to retire a deployed run's serving record. Unlike
454
+ ``mark_undeployed`` (which is a state transition: a live `deployed` run goes back to
455
+ `done`), this never asserts or changes the run state. That matters under the cancel
456
+ race: a concurrent ``mark_undeployed`` may have already moved the run to terminal
457
+ `done`, and ``_update``'s compare-and-set rejects any transition off a terminal state —
458
+ even re-asserting `deployed` to carry the deployment field — which would leave the
459
+ deployment advertised as `ready`. Marking the field directly (lock-guarded for
460
+ serialization) sidesteps the CAS so the deployment reliably ends `undeployed`, while the
461
+ trailing ``cancelled`` transition is left to ``_update``.
462
+ """
463
+ with _STATUS_LOCK:
464
+ status = get_status(run_id)
465
+ if status.deployment:
466
+ status.deployment = {**status.deployment, "state": "undeployed"}
467
+ status.updated_at = time.time()
468
+ _save_status(status)
469
+ return status
470
+
471
+
472
+ def rollback_deploy(run_id: str, snapshot: RunStatus) -> None:
473
+ """Restore the pre-deploy state/deployment after always-on provisioning fails.
474
+
475
+ Lock-guarded + terminal-respecting (same guard as _update/mark_deployed): a /cancel
476
+ that landed during provisioning/warmup already persisted `cancelled`; restoring the
477
+ pre-deploy snapshot must NOT overwrite it and resurrect the run as `done`/`deployed`.
478
+ """
479
+ with _STATUS_LOCK:
480
+ status = get_status(run_id)
481
+ if status.state in TERMINAL_STATES:
482
+ return
483
+ status.state = snapshot.state
484
+ status.deployment = snapshot.deployment
485
+ status.updated_at = time.time()
486
+ _save_status(status)
487
+
488
+
489
+ def _run_job(spec: JobSpec) -> None:
490
+ # Lazy import so dry-run / unit tests never construct a Flash endpoint.
491
+ from autoslm.providers.runpod.train import upload_code
492
+
493
+ # A cancel can land between the queued status being returned to the client and
494
+ # this background thread starting; don't overwrite a terminal state (cancelled)
495
+ # with provisioning and then launch a paid seed as if the cancel never happened.
496
+ if get_status(spec.run_id).state in TERMINAL_STATES:
497
+ return
498
+ _update(spec.run_id, "provisioning")
499
+ log_path = os.path.join(RUNS_DIR, f"{spec.run_id}.log")
500
+ try:
501
+ _run_job_inner(spec, log_path, upload_code)
502
+ finally:
503
+ # Endpoint GC: every run leaves its uniquely-named endpoint registered, and the
504
+ # account-wide *max workers quota* (5 by default) counts registered endpoints —
505
+ # after a handful of runs, ALL new submissions fail with "Max workers across all
506
+ # endpoints must not exceed your workers quota". Tear ours down on any terminal
507
+ # state (best-effort; never raises).
508
+ _gc_run_endpoints(spec)
509
+
510
+
511
+ def _spec_with_gpu(spec: JobSpec, gpu_type: str) -> JobSpec:
512
+ """The spec the workers/loggers see for THIS attempt's allocated class."""
513
+ if spec.gpu.type == gpu_type:
514
+ return spec
515
+ d = spec.to_dict()
516
+ d["gpu"] = {**d["gpu"], "type": gpu_type}
517
+ return JobSpec.from_dict(d)
518
+
519
+
520
+ def _submit_seed_supervised(spec: JobSpec, seed: int, log) -> dict:
521
+ """Run one seed with the job submit/poll path + bounded auto-retry.
522
+
523
+ Each attempt first ALLOCATES the GPU: the cheapest class across providers (RunPod
524
+ live pricing + Vast verified-datacenter offers) that fits the model — re-resolved
525
+ fresh per attempt because offers are a live market. A policy ``gpu.requested``
526
+ ("cheapest"/"auto") lets the allocator pick the class; a concrete ``gpu.requested``
527
+ pins the class (the allocator then only picks the provider); ``gpu.provider`` pins
528
+ the substrate.
529
+
530
+ Retries (fresh job on a fresh host; worker resumes from the latest HF
531
+ checkpoint) when the failure looks infra-shaped: a stall (heartbeat frozen), a
532
+ client polling breakdown, or a platform TIMED_OUT/worker-loss. Sick Vast machines
533
+ are blacklisted for the run; failover naturally crosses providers.
534
+ Genuine worker errors (the run's code crashed; traceback persisted to HF) fail
535
+ immediately. The offline test/CI marker AUTOSLM_SKIP_NET takes the blocking
536
+ in-process submit instead (the job poll path is network-only).
537
+ """
538
+ from autoslm.providers.base import PollResult
539
+ from autoslm.providers.runpod.train import submit_train
540
+
541
+ if os.environ.get("AUTOSLM_SKIP_NET"):
542
+ return submit_train(spec, seed, log=log)
543
+
544
+ from autoslm.providers import get_provider
545
+ from autoslm.providers.allocator import allocate, allocation_summary
546
+ from autoslm.providers.base import POLICY_NAMES
547
+
548
+ last_handle: dict = {}
549
+ # The friendly GPU class the CURRENT attempt provisioned (set right before each submit),
550
+ # so on_handle persists it into the run handle and a recovery via attach_run costs the
551
+ # class actually used rather than the parse-time provisional spec.gpu.type.
552
+ current_gpu: dict = {}
553
+ # Every RunPod endpoint id this run registered across attempts. Retries run on
554
+ # rN-suffixed endpoints whose names _gc_run_endpoints cannot reconstruct, and a
555
+ # failed delete during the next attempt's teardown would otherwise lose the id;
556
+ # GC the whole set at exit so no retry endpoint leaks against the worker quota.
557
+ seen_endpoints: set[str] = set()
558
+
559
+ def on_handle(handle: dict):
560
+ last_handle.clear()
561
+ last_handle.update(handle)
562
+ if handle.get("endpoint_id"):
563
+ seen_endpoints.add(handle["endpoint_id"])
564
+ _update(
565
+ spec.run_id,
566
+ "running",
567
+ remote={**handle, "seed": int(seed), "allocated_gpu": current_gpu.get("name")},
568
+ )
569
+
570
+ def _gc_seen_endpoints() -> None:
571
+ if not seen_endpoints:
572
+ return
573
+ from autoslm.providers.runpod import api as runpod_api
574
+
575
+ for eid in seen_endpoints:
576
+ with contextlib.suppress(Exception):
577
+ runpod_api.delete_endpoint(eid)
578
+
579
+ max_retries = int(spec.gpu.max_retries)
580
+ last_detail = None
581
+ bad_machines: set[int] = set()
582
+ # Re-allocate freely for policy requests ("cheapest"/"auto"); honor a concrete
583
+ # user pin by passing it through as the only candidate class.
584
+ requested = (spec.gpu.requested or "").strip().lower()
585
+ pinned_gpu = None if requested in POLICY_NAMES else spec.gpu.type
586
+ # Index into the ranked candidate list. It advances only after an attempt that
587
+ # actually provisioned a class lost it to an infra failure (see the retry tail), so a
588
+ # failed allocation — which never tried a card — can't skip past the cheapest class.
589
+ gpu_walk_offset = 0
590
+ for attempt in range(max_retries + 1):
591
+ if attempt > 0 and last_handle:
592
+ # A stalled/timed-out attempt often means the worker is pinned to a
593
+ # throttled/sick host; tear it down so the fresh deploy lands elsewhere.
594
+ # Dispatched generically via the handle's provider.
595
+ if last_handle.get("provider") == "vast":
596
+ with contextlib.suppress(Exception):
597
+ from autoslm.providers import get_provider
598
+ from autoslm.providers.base import JobHandle
599
+
600
+ get_provider("vast").destroy(JobHandle.from_dict(last_handle))
601
+ if last_handle.get("machine_id"):
602
+ bad_machines.add(int(last_handle["machine_id"]))
603
+ print(
604
+ f"retry {attempt}: destroyed vast instance "
605
+ f"{last_handle.get('instance_id')} (machine "
606
+ f"{last_handle.get('machine_id')} blacklisted for this run)",
607
+ file=log,
608
+ flush=True,
609
+ )
610
+ elif last_handle.get("endpoint_id"):
611
+ try:
612
+ from autoslm.providers.runpod import api as runpod_api
613
+
614
+ runpod_api.cancel_job(last_handle["endpoint_id"], last_handle["job_id"])
615
+ runpod_api.delete_endpoint(last_handle["endpoint_id"])
616
+ print(
617
+ f"retry {attempt}: deleted endpoint {last_handle['endpoint_id']} "
618
+ "(escaping throttled/sick host)",
619
+ file=log,
620
+ flush=True,
621
+ )
622
+ except Exception:
623
+ # Logging the host-escape note is cosmetic; never let it abort the retry.
624
+ pass
625
+ # The previous endpoint is now deleted; clear the persisted handle so a cancel
626
+ # or control-plane restart during the fresh deploy doesn't operate on (or get
627
+ # shielded by) the dead handle. The next on_handle() records the new one.
628
+ with contextlib.suppress(FileNotFoundError):
629
+ st = get_status(spec.run_id)
630
+ if st.state not in TERMINAL_STATES and st.remote is not None:
631
+ _update(spec.run_id, st.state, remote=None)
632
+ res = None
633
+ alloc = None
634
+ chosen = None
635
+ # A cancel can land after _run_seed_loop's pre-submit check but while
636
+ # allocation/pricing runs, when no handle exists yet for cancel_run() to
637
+ # delete. Re-read state right before paid provisioning so a cancelled run
638
+ # never launches a worker (the later checks only stop the final-state
639
+ # overwrite, after the GPU has already run and billed).
640
+ with contextlib.suppress(FileNotFoundError):
641
+ if get_status(spec.run_id).state == "cancelled":
642
+ raise _RunCancelled(f"run {spec.run_id} was cancelled")
643
+ try:
644
+ alloc = allocate(
645
+ spec.model,
646
+ spec.algorithm,
647
+ gpu=pinned_gpu,
648
+ provider=spec.gpu.provider,
649
+ disk_gb=spec.gpu.disk_gb,
650
+ allow_unvalidated=spec.gpu.allow_unvalidated,
651
+ exclude_machine_ids=frozenset(bad_machines),
652
+ # Pass the run's train knobs + thinking so the VRAM estimate reflects THIS job's
653
+ # max_length / group_size / batch_size / lora_rank (and the seq escalation) instead
654
+ # of the generic defaults — else a long-context / big-group run is sized at seq=1024
655
+ # and OOMs the card it picks.
656
+ train=spec.train,
657
+ thinking=spec.thinking,
658
+ )
659
+ except Exception as exc:
660
+ from autoslm.providers.base import UnsupportedGpuError
661
+
662
+ if isinstance(exc, UnsupportedGpuError):
663
+ raise # config-shaped: no GPU anywhere can run this job
664
+ res = PollResult(False, failure="poll_error", detail=f"allocation: {exc}")
665
+ if alloc is not None:
666
+ # allocate() above ran a live-market price walk; re-check cancellation
667
+ # right before provisioning so a cancel during allocation doesn't still
668
+ # launch a paid worker.
669
+ with contextlib.suppress(FileNotFoundError):
670
+ if get_status(spec.run_id).state == "cancelled":
671
+ raise _RunCancelled(f"run {spec.run_id} was cancelled")
672
+ # Walk down the ranked candidates by the walk offset (clamped to the last): the
673
+ # first attempt takes the cheapest; each retry that provisioned a class and lost
674
+ # it to an infra failure steps to the next-cheapest, so a capacity-starved class
675
+ # can't burn the whole budget. A concrete pin yields a single candidate, so the
676
+ # clamp keeps a pinned run on its class.
677
+ chosen = alloc.candidates[min(gpu_walk_offset, len(alloc.candidates) - 1)]
678
+ print(allocation_summary(alloc), file=log, flush=True)
679
+ if chosen.gpu != alloc.gpu:
680
+ print(
681
+ f"retry {attempt}: walking past the cheapest class to {chosen.gpu} "
682
+ f"@ ${chosen.hourly_usd:.2f}/hr",
683
+ file=log,
684
+ flush=True,
685
+ )
686
+ run_spec = _spec_with_gpu(spec, chosen.gpu)
687
+ current_gpu["name"] = chosen.gpu
688
+ provider = get_provider(chosen.provider)
689
+ # Vast needs the live-market offer book for the chosen class first, then the
690
+ # other allocator-approved classes by price; RunPod ignores ``offers``.
691
+ offers = None
692
+ if chosen.provider == "vast":
693
+ ok_classes = {c.gpu for c in alloc.candidates if c.provider == "vast"}
694
+ offers = sorted(
695
+ (o for o in alloc.provider_offers if o.gpu in ok_classes),
696
+ key=lambda o: (o.gpu != chosen.gpu, o.dph_total),
697
+ )
698
+ try:
699
+ res = provider.submit_run(
700
+ run_spec,
701
+ seed,
702
+ log=log,
703
+ on_handle=on_handle,
704
+ attempt=attempt,
705
+ offers=offers,
706
+ # The run's machine blacklist must reach the provider so an in-provider
707
+ # offer REFRESH (Vast) keeps stalled/sick machines excluded.
708
+ exclude_machine_ids=frozenset(bad_machines),
709
+ )
710
+ except Exception as exc:
711
+ # Deploy/submit themselves can fail transiently (observed: RunPod
712
+ # GraphQL "Something went wrong" x3 during a retry deploy; a vast offer
713
+ # pool emptying between search and rent). That must consume a retry, not
714
+ # kill the run — the budget exists precisely for flakes.
715
+ res = PollResult(False, failure="poll_error", detail=f"deploy/submit: {exc}")
716
+ if attempt < max_retries:
717
+ time.sleep(10 * (attempt + 1)) # let the transient clear
718
+ if res.ok:
719
+ # A best-effort cancel may fail to stop the worker, which then completes
720
+ # successfully after cancel_run() persisted `cancelled`. Don't let a late
721
+ # worker success resurrect the run into running/done.
722
+ try:
723
+ if get_status(spec.run_id).state == "cancelled":
724
+ raise _RunCancelled(f"run {spec.run_id} was cancelled")
725
+ except FileNotFoundError:
726
+ # Status file not yet written (early race): treat as not-cancelled, proceed.
727
+ pass
728
+ # Worker is done (DONE sentinel seen); GC every endpoint this seed used,
729
+ # including intermediate rN retries _gc_run_endpoints can't name.
730
+ _gc_seen_endpoints()
731
+ # Record the class actually allocated so _persist_metrics rates the right
732
+ # RunPod card when a policy GPU was re-allocated away from the provisional.
733
+ if chosen is not None and isinstance(res.metrics, dict):
734
+ res.metrics.setdefault("allocated_gpu", chosen.gpu)
735
+ return res.metrics
736
+ last_detail = f"{res.failure}: {res.detail}"
737
+ # Infra-shaped failures are retried on a FRESH endpoint/host; genuine worker
738
+ # code errors are not. Detail markers cover the observed flake classes:
739
+ # platform timeouts, worker pip-install network timeouts, and sick-GPU hosts.
740
+ _infra_markers = (
741
+ "TIMED_OUT",
742
+ "Failed to fetch",
743
+ "operation timed out",
744
+ "python_dependencies failed",
745
+ "Connection reset",
746
+ "cuda not available",
747
+ "GPU never became ready",
748
+ # Host vanished mid-run: the instance went "missing"/dead and NOTHING was captured
749
+ # (no marker error, no error_<phase>.txt, no console log) so _failure_detail falls back
750
+ # to this bare sentinel. A genuine worker code crash instead yields a RICHER detail
751
+ # (the captured traceback), so this exact phrase only ever marks a dead host -> retry it
752
+ # on a fresh one. Without this, a single ~1-in-200 host death killed the whole run.
753
+ "terminated without a DONE sentinel",
754
+ )
755
+ infra_shaped = res.failure in ("stalled", "poll_error") or any(
756
+ m in (res.detail or "") for m in _infra_markers
757
+ )
758
+ # A cancel deletes the endpoint, which the poller sees as an
759
+ # infra-shaped failure; retrying would resurrect the run and keep
760
+ # billing. The user's cancel wins over the retry budget.
761
+ try:
762
+ if get_status(spec.run_id).state == "cancelled":
763
+ raise _RunCancelled(f"run {spec.run_id} was cancelled")
764
+ except FileNotFoundError:
765
+ # Status file not yet written (early race): treat as not-cancelled and proceed.
766
+ pass
767
+ print(
768
+ f"seed={seed} attempt={attempt} failed ({res.failure}); "
769
+ f"{'retrying (resume from last checkpoint)' if infra_shaped and attempt < max_retries else 'not retrying'}"
770
+ f"\n--- failure detail ---\n{(res.detail or '')[:2000]}\n---",
771
+ file=log,
772
+ flush=True,
773
+ )
774
+ if not infra_shaped or attempt >= max_retries:
775
+ break
776
+ # Step to the next-cheapest class only when THIS attempt actually provisioned one
777
+ # and it failed infra-shaped. An allocation/pricing failure (chosen is None) never
778
+ # tried a card, so the next attempt must retry from the cheapest, not walk past it.
779
+ if chosen is not None:
780
+ gpu_walk_offset += 1
781
+ # Retry budget exhausted: GC every endpoint this seed registered (the final
782
+ # attempt's is in status.remote for _gc_run_endpoints, but intermediate rN ones
783
+ # are only known here).
784
+ _gc_seen_endpoints()
785
+ raise RuntimeError(f"seed {seed} failed after retries: {last_detail}")
786
+
787
+
788
+ def _run_job_inner(spec: JobSpec, log_path: str, upload_code) -> None:
789
+ try:
790
+ # Ship the slm package to the run's HF repo (the per-run [train] hf_repo) so the GPU
791
+ # worker — which fetches code/** from that same repo — can run it.
792
+ upload_code(spec.train.hf_repo)
793
+ with open(log_path, "a") as log:
794
+ _run_seed_loop(spec, log, start_index=0, prior_cost=0.0)
795
+ except _RunCancelled:
796
+ return # cancel_run already set the terminal state
797
+ except Exception as exc:
798
+ if get_status(spec.run_id).state != "cancelled":
799
+ _update(spec.run_id, "failed", error=str(exc))
800
+ raise
801
+
802
+
803
+ def _run_seed_loop(spec: JobSpec, log, *, start_index: int, prior_cost: float) -> None:
804
+ """Run spec.train.seeds[start_index:] under supervision; finalize the run.
805
+
806
+ Shared by a fresh submit (start_index=0) and post-restart recovery, which
807
+ resumes the remaining seeds after the in-flight one completes."""
808
+ total_cost = prior_cost
809
+ seeds = spec.train.seeds
810
+ for i in range(start_index, len(seeds)):
811
+ seed = seeds[i]
812
+ # An early cancel (before any remote handle existed) sets `cancelled`;
813
+ # do not overwrite it with `running` and submit the GPU job anyway.
814
+ if get_status(spec.run_id).state == "cancelled":
815
+ raise _RunCancelled(f"run {spec.run_id} was cancelled")
816
+ _update(spec.run_id, "running")
817
+ print(
818
+ f"starting seed={seed} phase={spec.phase} model={spec.model} gpu={spec.gpu.type}",
819
+ file=log,
820
+ flush=True,
821
+ )
822
+ metrics = _submit_seed_supervised(spec, seed, log)
823
+ total_cost += _persist_metrics(spec, seed, metrics)
824
+ # A cancel can land while this thread writes metrics — after the supervised
825
+ # late-cancel check. Re-read before the post-seed status writes so a late
826
+ # worker success doesn't resurrect a user-cancelled run via this "running"
827
+ # update (or the final "done" below).
828
+ with contextlib.suppress(FileNotFoundError):
829
+ if get_status(spec.run_id).state == "cancelled":
830
+ raise _RunCancelled(f"run {spec.run_id} was cancelled")
831
+ # If more seeds follow, this seed's endpoint/instance is already torn down, so
832
+ # clear the now-stale remote handle: a restart in the gap before the next
833
+ # seed's on_handle must not make recover_runs reattach to a deleted handle and
834
+ # fail the run. Record the next seed index so a restart in that handle-less gap
835
+ # RESUMES the remaining seeds (recover_runs) instead of discarding the completed
836
+ # ones. The last seed keeps its handle for post-run observability (the run is
837
+ # about to go terminal, which recover_runs never reattaches).
838
+ more_seeds = (i + 1) < len(seeds)
839
+ _update(
840
+ spec.run_id,
841
+ "running",
842
+ cost_usd=total_cost,
843
+ **({"remote": None, "resume_seed_index": i + 1} if more_seeds else {}),
844
+ )
845
+ print(
846
+ f"seed={seed} done: train_wall={metrics.get('wall_seconds')} cost_usd={total_cost:.4f}",
847
+ file=log,
848
+ flush=True,
849
+ )
850
+ # Final guard: a cancel landing after the last seed's check must not be overwritten
851
+ # by the terminal "done".
852
+ with contextlib.suppress(FileNotFoundError):
853
+ if get_status(spec.run_id).state == "cancelled":
854
+ raise _RunCancelled(f"run {spec.run_id} was cancelled")
855
+ _update(
856
+ spec.run_id,
857
+ "done",
858
+ cost_usd=total_cost,
859
+ artifacts_dir=artifacts_dir(spec),
860
+ resume_seed_index=None,
861
+ )
862
+
863
+
864
+ def _gc_run_endpoints(spec: JobSpec) -> None:
865
+ """Best-effort teardown of every endpoint a run may have registered.
866
+
867
+ Retried attempts run on rN-suffixed endpoints whose runpod_flash state is
868
+ isolated per-suffix, so the name-based terminate_endpoint cannot see them;
869
+ the persisted remote handle's endpoint id covers whichever attempt ran
870
+ last via the plain REST API."""
871
+ status = None
872
+ with contextlib.suppress(Exception):
873
+ status = get_status(spec.run_id)
874
+ if status is not None and status.remote:
875
+ try:
876
+ from autoslm.providers import get_provider
877
+ from autoslm.providers.base import JobHandle
878
+
879
+ handle = JobHandle.from_dict(status.remote)
880
+ get_provider(handle.provider).destroy(handle)
881
+ except Exception:
882
+ # Best-effort GC; the name-reconstructed RunPod gc below is the backstop.
883
+ pass
884
+ try:
885
+ # RunPod's gc reaps rN-suffixed endpoints the persisted handle can't name.
886
+ from autoslm.providers import get_provider
887
+
888
+ get_provider("runpod").gc(spec)
889
+ except Exception:
890
+ # Best-effort GC; an undeleted endpoint only holds worker quota, never blocks the run.
891
+ pass
892
+ # Vast instances bill until destroyed: the runner's per-attempt `finally` already
893
+ # destroys them, but a crashed supervisor thread can leave one behind. Reap any
894
+ # instance still labeled for this run via the provider's gc (best-effort).
895
+ from autoslm.providers import available_providers, get_provider
896
+
897
+ if "vast" in available_providers():
898
+ with contextlib.suppress(Exception):
899
+ get_provider("vast").gc(spec)
900
+
901
+
902
+ def _persist_metrics(spec: JobSpec, seed: int, metrics: dict) -> float:
903
+ """Write metrics to results/runpod/<phase>/<run_id>/seedN and return the cost.
904
+
905
+ The run id keeps concurrent/sequential runs of the same phase+seed from
906
+ overwriting each other's artifacts. Vast runs arrive with ``cost_usd`` already
907
+ stamped from the offer's real $/hr (plus provider notes) and short-circuit the
908
+ rate fallback below (the RunPod projection)."""
909
+ dest = os.path.join(artifacts_dir(spec), f"seed{seed}")
910
+ os.makedirs(dest, exist_ok=True)
911
+ # Rate the actually-allocated class, not the parse-time provisional spec.gpu.type:
912
+ # a policy GPU can be re-allocated to a different RunPod class at submit time, so
913
+ # the worker stamps "allocated_gpu" into metrics for the cost fallback below.
914
+ gpu_type = metrics.get("allocated_gpu") or spec.gpu.type
915
+ rate = _gpu_rate(gpu_type)
916
+ # A non-runpod provider (e.g. Vast) stamps the real cost_usd from its offer's $/hr
917
+ # AND tags notes["provider"] with its own name — and a near-zero-duration run can
918
+ # legitimately stamp cost_usd == 0.0. The RunPod arm, by contrast, never stamps a real
919
+ # cost: it arrives with cost_usd absent (or a 0.0 placeholder) and no provider note, so
920
+ # the wall-based projection below must run. A bare `cost or 0.0` would treat the Vast
921
+ # 0.0 as "absent" and re-rate it against RunPod pricing while overwriting the provider
922
+ # notes, mis-attributing the run to 'runpod'. So fall back only when the cost is
923
+ # missing/zero AND it has NOT already been attributed to a non-runpod provider.
924
+ _notes = metrics.get("notes")
925
+ _stamped_provider = _notes.get("provider") if isinstance(_notes, dict) else None
926
+ _non_runpod = bool(_stamped_provider) and _stamped_provider != "runpod"
927
+ cost = metrics.get("cost_usd")
928
+ if cost or _non_runpod:
929
+ cost = float(cost or 0.0)
930
+ else:
931
+ wall = float(metrics.get("wall_seconds") or 0.0)
932
+ cost = wall / 3600.0 * rate
933
+ metrics = {**metrics, "cost_usd": cost}
934
+ metrics.setdefault("notes", {})
935
+ if isinstance(metrics["notes"], dict):
936
+ metrics["notes"]["provider"] = "runpod"
937
+ metrics["notes"]["runpod_rate_usd_hr"] = rate
938
+ metrics["notes"]["runpod_gpu"] = gpu_type
939
+ with open(os.path.join(dest, "metrics.json"), "w") as f:
940
+ json.dump(metrics, f, indent=2)
941
+ return float(cost)
942
+
943
+
944
+ def _update(run_id: str, state: str, *, allow_from_terminal: bool = False, **updates) -> None:
945
+ # The read-check-write below must be atomic: a concurrent `slm cancel` (also via
946
+ # _update) landing between the get_status read and the _save_status write could
947
+ # otherwise be clobbered by this stale background update, resurrecting a cancelled
948
+ # run. The control plane is single-instance with per-run threads, so a process-wide
949
+ # lock serializes all status transitions into a compare-and-set.
950
+ with _STATUS_LOCK:
951
+ status = get_status(run_id)
952
+ # Terminal states are STICKY: once a run is done/failed/cancelled/dry_run, no
953
+ # other state may overwrite it. This closes the whole cancel-race class at the
954
+ # source — a cancel landing between a caller's check and a later write
955
+ # (provisioning/running, or even a late terminal done/failed from a worker that
956
+ # finished as the cancel arrived) can no longer resurrect the run. Same-state
957
+ # writes still pass so terminal field updates (cost_usd, error, artifacts_dir)
958
+ # are preserved.
959
+ #
960
+ # allow_from_terminal is the NARROW escape hatch used ONLY by cancel_run's final
961
+ # `cancelled` transition, and ONLY when the run was `deployed` at cancel entry (see
962
+ # cancel_run). In that case an explicit user cancel must WIN over a racing
963
+ # mark_undeployed() that flipped the `deployed` run to terminal `done` mid-teardown —
964
+ # that `done` is an undeploy artifact (restoring the pre-deploy completion marker while
965
+ # retiring serving), not a fresh result. Without the override the `cancelled` write
966
+ # no-ops against the freshly-written `done` and the run wrongly ends `done` despite the
967
+ # user asking to cancel. cancel_run passes allow_from_terminal=False for a non-deployed
968
+ # run, so a GENUINE training-completion `done` racing in from the run's own training
969
+ # thread is protected by the CAS below — cancel correctly loses to a real finish.
970
+ if status.state in TERMINAL_STATES and state != status.state and not allow_from_terminal:
971
+ return
972
+ status.state = state
973
+ status.updated_at = time.time()
974
+ for key, value in updates.items():
975
+ setattr(status, key, value)
976
+ _save_status(status)
977
+
978
+
979
+ def _save_status(status: RunStatus) -> None:
980
+ os.makedirs(RUNS_DIR, exist_ok=True)
981
+ # Write-then-rename: a concurrent reader (poll on /v1/runs or /logs) must
982
+ # never observe a half-written/truncated file and 500 on JSONDecodeError.
983
+ # The temp name is UNIQUE per write (mkstemp) so two threads updating the same
984
+ # run (e.g. a cancel racing the background seed update) can't clobber each
985
+ # other's temp file mid-dump — each os.replace is atomic and independent.
986
+ path = runs_file_path(status.run_id, ".json")
987
+ fd, tmp = tempfile.mkstemp(dir=RUNS_DIR, prefix=f"{status.run_id}.", suffix=".tmp")
988
+ try:
989
+ with os.fdopen(fd, "w") as f:
990
+ json.dump(status.to_dict(), f, indent=2, sort_keys=True)
991
+ os.replace(tmp, path)
992
+ finally:
993
+ with contextlib.suppress(FileNotFoundError):
994
+ os.unlink(tmp)
code/autoslm/schema.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parse AutoSLM TOML configs into worker JobSpecs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import tomllib
7
+ from typing import Any
8
+
9
+ from .catalog import normalize_algorithm, resolve_model
10
+ from .providers import PROVIDER_NAMES
11
+ from .providers.base import (
12
+ POLICY_NAMES,
13
+ SUPPORTED,
14
+ UnsupportedGpuError,
15
+ canonical_gpu,
16
+ is_validated,
17
+ providers_for,
18
+ resolve_gpu_policy,
19
+ unvalidated_allowed,
20
+ )
21
+ from .spec import EnvironmentSpec, GpuSpec, JobSpec, TrainSpec
22
+
23
+
24
+ def _train_int(train_raw: dict, key: str, *, minimum: int) -> int | None:
25
+ """Validate an optional integer [train] knob (>= minimum) -> ConfigError (HTTP 400).
26
+
27
+ None stays None (recipe default). Rejects bools, non-numbers, non-integers, and
28
+ out-of-range values at parse time instead of letting them reach a provisioned worker.
29
+ """
30
+ v = train_raw.get(key)
31
+ if v is None:
32
+ return None
33
+ if isinstance(v, bool) or not isinstance(v, (int, float)):
34
+ raise ConfigError(f"train.{key} must be an integer")
35
+ # Check finiteness BEFORE int(v): int(inf) raises OverflowError and int(nan) ValueError
36
+ # (the former would be a 500); reject both as a clean 400.
37
+ if not math.isfinite(v) or float(v) != int(v):
38
+ raise ConfigError(f"train.{key} must be a finite integer")
39
+ v = int(v)
40
+ if v < minimum:
41
+ raise ConfigError(f"train.{key} must be >= {minimum}")
42
+ return v
43
+
44
+
45
+ def _train_float(
46
+ train_raw: dict,
47
+ key: str,
48
+ *,
49
+ minimum: float,
50
+ exclusive: bool = False,
51
+ maximum: float | None = None,
52
+ ) -> float | None:
53
+ """Validate an optional float [train] knob -> ConfigError (HTTP 400). None stays None."""
54
+ v = train_raw.get(key)
55
+ if v is None:
56
+ return None
57
+ if isinstance(v, bool) or not isinstance(v, (int, float)):
58
+ raise ConfigError(f"train.{key} must be a number")
59
+ v = float(v)
60
+ # nan/inf slip past the range checks below (nan compares false, inf passes any minimum)
61
+ # and would reach TRL optimizer/sampling settings; reject them as a 400 here.
62
+ if not math.isfinite(v):
63
+ raise ConfigError(f"train.{key} must be a finite number")
64
+ if exclusive and v <= minimum:
65
+ raise ConfigError(f"train.{key} must be > {minimum}")
66
+ if not exclusive and v < minimum:
67
+ raise ConfigError(f"train.{key} must be >= {minimum}")
68
+ if maximum is not None and v > maximum:
69
+ raise ConfigError(f"train.{key} must be between {minimum} and {maximum}")
70
+ return v
71
+
72
+
73
+ def _train_stops(train_raw: dict) -> tuple[str, ...]:
74
+ """Validate stop_sequences -> ConfigError. A string is ONE stop (never char-split);
75
+ a list must hold strings; empties are dropped; anything else is rejected."""
76
+ v = train_raw.get("stop_sequences")
77
+ if v is None:
78
+ return ()
79
+ if isinstance(v, str):
80
+ return (v,) if v else ()
81
+ if not isinstance(v, (list, tuple)):
82
+ raise ConfigError("train.stop_sequences must be a string or a list of strings")
83
+ for s in v:
84
+ if not isinstance(s, str):
85
+ raise ConfigError("train.stop_sequences entries must be strings")
86
+ return tuple(s for s in v if s)
87
+
88
+
89
+ class ConfigError(ValueError):
90
+ pass
91
+
92
+
93
+ def _require_slug(value: str, message: str) -> None:
94
+ """Require a Prime Hub-style "owner/name" slug: exactly one slash, both parts
95
+ non-empty. Raises ConfigError(message) otherwise. Centralizes the rule used for
96
+ [environment] id, eval_env_id, and train.hf_repo so they cannot drift apart."""
97
+ parts = value.split("/")
98
+ if len(parts) != 2 or not all(parts):
99
+ raise ConfigError(message)
100
+
101
+
102
+ def load_toml(path: str) -> dict[str, Any]:
103
+ with open(path, "rb") as f:
104
+ return tomllib.load(f)
105
+
106
+
107
+ def spec_from_file(
108
+ path: str,
109
+ run_id: str | None = None,
110
+ overrides: list[str] | None = None,
111
+ extra_configs: list[str] | None = None,
112
+ ) -> JobSpec:
113
+ raw = load_toml(path)
114
+ # Composed configs: later files override earlier keys (deep merge).
115
+ for extra in extra_configs or []:
116
+ _deep_merge(raw, load_toml(extra))
117
+ # `--set key=value` dotted overrides (highest precedence).
118
+ for item in overrides or []:
119
+ _apply_override(raw, item)
120
+ return spec_from_dict(raw, run_id=run_id)
121
+
122
+
123
+ def _deep_merge(base: dict, extra: dict) -> dict:
124
+ for k, v in extra.items():
125
+ if isinstance(v, dict) and isinstance(base.get(k), dict):
126
+ _deep_merge(base[k], v)
127
+ else:
128
+ base[k] = v
129
+ return base
130
+
131
+
132
+ def _coerce_scalar(value: str):
133
+ low = value.strip().lower()
134
+ if low in ("true", "false"):
135
+ return low == "true"
136
+ try:
137
+ return int(value)
138
+ except ValueError:
139
+ pass
140
+ try:
141
+ return float(value)
142
+ except ValueError:
143
+ return value
144
+
145
+
146
+ def _apply_override(raw: dict, item: str) -> None:
147
+ if "=" not in item:
148
+ raise ConfigError(f"--set must be key=value, got {item!r}")
149
+ key, value = item.split("=", 1)
150
+ parts = key.strip().split(".")
151
+ node = raw
152
+ for p in parts[:-1]:
153
+ node = node.setdefault(p, {})
154
+ if not isinstance(node, dict):
155
+ raise ConfigError(f"--set path {key!r} traverses a non-table value")
156
+ leaf = parts[-1]
157
+ # support list values like seeds=[0,1]
158
+ val = value.strip()
159
+ if val.startswith("[") and val.endswith("]"):
160
+ inner = val[1:-1].strip()
161
+ node[leaf] = [_coerce_scalar(x.strip()) for x in inner.split(",") if x.strip()]
162
+ else:
163
+ node[leaf] = _coerce_scalar(val)
164
+
165
+
166
+ def spec_from_dict(raw: dict[str, Any], run_id: str | None = None) -> JobSpec:
167
+ try:
168
+ model = raw["model"]
169
+ except KeyError as exc:
170
+ raise ConfigError("config must set `model`") from exc
171
+
172
+ try:
173
+ algorithm = normalize_algorithm(raw.get("algorithm"))
174
+ except ValueError as exc:
175
+ raise ConfigError(str(exc)) from exc
176
+ model_policy = (raw.get("model_policy") or "catalog").lower()
177
+ if model_policy not in ("catalog", "allow"):
178
+ raise ConfigError('model_policy must be "catalog" or "allow"')
179
+ thinking = raw.get("thinking", False) # reasoning mode OFF by default (operator preference)
180
+ if not isinstance(thinking, bool):
181
+ raise ConfigError("thinking must be a boolean")
182
+
183
+ env_raw = raw.get("environment") or {}
184
+ if not isinstance(env_raw, dict):
185
+ raise ConfigError("[environment] must be a table")
186
+ # Local environment paths are gone: a run names a published Hub env by [environment] id.
187
+ # A stray `path` (alone or alongside `id`) is a stale config — reject it loudly instead of
188
+ # silently ignoring the key and training against the wrong/missing env.
189
+ if env_raw.get("path"):
190
+ raise ConfigError(
191
+ "local environment paths are no longer supported — remove `path` and reference a "
192
+ 'published Hub `id` ("owner/name")'
193
+ )
194
+ train_raw = raw.get("train") or {}
195
+ gpu_raw = raw.get("gpu") or {}
196
+
197
+ # Smart allocation is the default: an omitted gpu.type means "the cheapest GPU
198
+ # (across providers) that fits the model", re-resolved live at submit time. The
199
+ # original request survives in gpu.requested so the runner knows whether
200
+ # it may re-allocate (policy words) or must honor a concrete pin.
201
+ requested_gpu = str(gpu_raw.get("requested") or gpu_raw.get("type") or "auto")
202
+ provider = str(gpu_raw.get("provider") or "auto").strip().lower()
203
+ if provider not in ("auto", *PROVIDER_NAMES):
204
+ allowed = '", "'.join(("auto", *PROVIDER_NAMES))
205
+ raise ConfigError(f'gpu.provider must be "{allowed}"')
206
+ allow_unval = gpu_raw.get("allow_unvalidated")
207
+ if allow_unval is not None and not isinstance(allow_unval, bool):
208
+ raise ConfigError("gpu.allow_unvalidated must be a boolean")
209
+ try:
210
+ # Parse-time provisional: "cheapest"/"auto" resolve to the cheapest validated
211
+ # GPU class that fits (across providers, deterministic offline; open models
212
+ # sized from HF metadata); concrete names are canonicalized. The submit-time
213
+ # allocator re-resolves policy words live across providers.
214
+ gpu_type = resolve_gpu_policy(
215
+ requested_gpu,
216
+ model,
217
+ allow_unvalidated=allow_unval,
218
+ algorithm=algorithm,
219
+ train=train_raw,
220
+ thinking=thinking,
221
+ )
222
+ except UnsupportedGpuError as exc:
223
+ raise ConfigError(str(exc)) from exc
224
+ pinned = requested_gpu.strip().lower() not in POLICY_NAMES
225
+ if pinned and provider != "auto" and provider not in providers_for(gpu_type):
226
+ raise ConfigError(
227
+ f"gpu type {gpu_type!r} is not available on provider {provider!r} "
228
+ f"(providers: {', '.join(providers_for(gpu_type))})"
229
+ )
230
+ if (
231
+ pinned
232
+ and not is_validated(gpu_type, provider if provider != "auto" else None)
233
+ and not unvalidated_allowed(allow_unval)
234
+ ):
235
+ raise ConfigError(
236
+ f"gpu type {gpu_type!r} has not passed AutoSLM's live validation smoke"
237
+ f"{' on ' + provider if provider != 'auto' else ''} "
238
+ f"(validated: {', '.join(SUPPORTED)}). Set gpu.allow_unvalidated = true "
239
+ f"(or AUTOSLM_GPU_ALLOW_UNVALIDATED=1) to use it anyway."
240
+ )
241
+ try:
242
+ info = resolve_model(model, algorithm, policy=model_policy, gpu=gpu_type)
243
+ except ValueError as exc:
244
+ raise ConfigError(str(exc)) from exc
245
+ if thinking and info.thinking == "none":
246
+ raise ConfigError(
247
+ f"{model} does not support thinking mode (its chat template has no "
248
+ f"<think> support); pick a thinking-capable model — `slm models` lists "
249
+ f"each model's thinking capability"
250
+ )
251
+ if not thinking and info.thinking == "always":
252
+ raise ConfigError(
253
+ f"{model} always emits <think> reasoning and cannot run with thinking "
254
+ f"disabled; set thinking = true"
255
+ )
256
+ if thinking and info.thinking == "unknown":
257
+ print(
258
+ f"warning: open-model policy: cannot verify that {model}'s chat template "
259
+ f"supports thinking mode; the run proceeds with enable_thinking=true"
260
+ )
261
+
262
+ spec = JobSpec(
263
+ model=model,
264
+ algorithm=algorithm,
265
+ environment=EnvironmentSpec(
266
+ id=str(env_raw.get("id") or ""),
267
+ params=dict(env_raw.get("params") or {}),
268
+ pip=tuple(str(p) for p in env_raw.get("pip") or ()),
269
+ ),
270
+ train=TrainSpec(
271
+ steps=_train_int(train_raw, "steps", minimum=1),
272
+ epochs=_train_int(train_raw, "epochs", minimum=1),
273
+ lora_rank=_train_int(train_raw, "lora_rank", minimum=1) or 32,
274
+ lora_alpha=_train_int(train_raw, "lora_alpha", minimum=1) or 64,
275
+ seeds=tuple(int(s) for s in train_raw.get("seeds", (0,))),
276
+ init_from_adapter=str(train_raw.get("init_from_adapter") or ""),
277
+ hf_repo=str(train_raw.get("hf_repo") or ""),
278
+ learning_rate=_train_float(train_raw, "learning_rate", minimum=0.0, exclusive=True),
279
+ batch_size=_train_int(train_raw, "batch_size", minimum=1),
280
+ max_length=_train_int(train_raw, "max_length", minimum=1),
281
+ save_every=_train_int(train_raw, "save_every", minimum=1),
282
+ group_size=_train_int(train_raw, "group_size", minimum=1),
283
+ temperature=_train_float(train_raw, "temperature", minimum=0.0),
284
+ max_tokens=_train_int(train_raw, "max_tokens", minimum=1),
285
+ kl_penalty_coef=_train_float(train_raw, "kl_penalty_coef", minimum=0.0),
286
+ advantage_clip=_train_float(train_raw, "advantage_clip", minimum=0.0),
287
+ thinking_length_penalty_coef=_train_float(
288
+ train_raw, "thinking_length_penalty_coef", minimum=0.0, maximum=1.0
289
+ ),
290
+ stop_sequences=_train_stops(train_raw),
291
+ ),
292
+ gpu=GpuSpec(
293
+ type=gpu_type,
294
+ provider=provider,
295
+ requested=requested_gpu,
296
+ allow_unvalidated=allow_unval,
297
+ disk_gb=int(gpu_raw.get("disk_gb", 60)),
298
+ max_wall_seconds=int(gpu_raw.get("max_wall_seconds", 24 * 3600)),
299
+ max_retries=int(gpu_raw.get("max_retries", 2)),
300
+ network_volume=gpu_raw.get("network_volume"),
301
+ network_volume_gb=int(gpu_raw.get("network_volume_gb", 100)),
302
+ datacenter=gpu_raw.get("datacenter"),
303
+ ),
304
+ run_id=run_id or raw.get("run_id", "local"),
305
+ worker_env=_worker_env(raw.get("worker_env")),
306
+ model_policy=model_policy,
307
+ thinking=thinking,
308
+ )
309
+ _validate_spec(spec)
310
+ return spec
311
+
312
+
313
+ def _worker_env(raw: Any) -> dict[str, str]:
314
+ """Parse the optional [worker_env] table: per-run worker env overrides (string-valued)."""
315
+ if raw is None:
316
+ return {}
317
+ if not isinstance(raw, dict):
318
+ raise ConfigError("[worker_env] must be a table of string key/values")
319
+ env = {str(k): str(v) for k, v in raw.items()}
320
+ # [worker_env] is serialized into job_spec_json (persisted + logged), so it must NOT carry
321
+ # secrets — they would leak into run artifacts. Reject secret-looking keys; operators set
322
+ # those as real process environment variables (forwarded to the worker out-of-band) instead.
323
+ # Detect by `_`-delimited WORD components (not substring): flag a secret WORD, or `KEY`
324
+ # qualified by API/SECRET/PRIVATE/ACCESS/INTERNAL/AUTH. This catches HF_TOKEN, *_API_KEY,
325
+ # SECRET_KEY, INTERNAL_KEY, CREDENTIAL, AWS_SECRET_ACCESS_KEY while allowing legit knobs whose
326
+ # names merely contain a marker (RL_VLLM_MAX_BATCHED_TOKENS -> word TOKENS, not TOKEN; a bare
327
+ # SORT_KEY -> KEY without a secret qualifier).
328
+ _secret_words = {"TOKEN", "SECRET", "PASSWORD", "PASSWD", "CREDENTIAL", "CREDENTIALS", "APIKEY", "PRIVATEKEY"}
329
+ _key_qualifiers = {"API", "SECRET", "PRIVATE", "ACCESS", "INTERNAL", "AUTH", "SIGNING", "ENCRYPTION"}
330
+
331
+ def _is_secret_key(name: str) -> bool:
332
+ words = set(name.upper().split("_"))
333
+ return bool(words & _secret_words) or ("KEY" in words and bool(words & _key_qualifiers))
334
+
335
+ secrets = sorted(k for k in env if _is_secret_key(k))
336
+ if secrets:
337
+ raise ConfigError(
338
+ f"[worker_env] must not contain secret-bearing keys ({', '.join(secrets)}); these are "
339
+ "serialized into run artifacts — set them as real environment variables instead"
340
+ )
341
+ return env
342
+
343
+
344
+ def _validate_spec(spec: JobSpec) -> None:
345
+ if not spec.train.seeds:
346
+ raise ConfigError("train.seeds must contain at least one seed")
347
+ try:
348
+ canonical_gpu(spec.gpu.type)
349
+ except UnsupportedGpuError as exc:
350
+ raise ConfigError(str(exc)) from exc
351
+ # GRPO is step-driven; SFT is epoch-driven. Reject a non-positive explicit count
352
+ # for whichever the algorithm consumes, so an invalid config fails here instead of
353
+ # provisioning a worker that silently falls back to a default count.
354
+ if spec.algorithm == "grpo" and spec.train.steps is not None and spec.train.steps <= 0:
355
+ raise ConfigError("train.steps must be positive for GRPO")
356
+ if spec.algorithm == "sft" and spec.train.epochs is not None and spec.train.epochs <= 0:
357
+ raise ConfigError("train.epochs must be positive for SFT")
358
+ # Verifiers-only: every run must name an environment by its verifiers/Prime Hub slug
359
+ # via [environment] id. There is no default environment and no local path mode.
360
+ if not spec.environment.id:
361
+ raise ConfigError(
362
+ "config must set [environment] id (a verifiers/Prime Hub env slug, e.g. "
363
+ '"owner/name"); there is no local path mode'
364
+ )
365
+ # The id must be a full Prime Hub slug "owner/name": exactly one slash, both parts
366
+ # non-empty. A bare id like "gsm8k" passes the presence check but then the worker runs
367
+ # `prime env install gsm8k` (invalid — Prime needs owner/name) and fails after provisioning.
368
+ _require_slug(
369
+ spec.environment.id,
370
+ '[environment] id must be a published Prime Hub slug "owner/name"',
371
+ )
372
+ # A separate eval env ([environment.params] eval_env_id) is also prime-installed on the worker
373
+ # (worker_hub_env_ids), so it must be a full "owner/name" slug too — else a bare eval id passes
374
+ # --dry-run but fails `prime env install` after a GPU is provisioned.
375
+ if "eval_env" in spec.environment.params:
376
+ # Legacy alias: `eval_env` is no longer mapped (the worker installs only eval_env_id, and
377
+ # a stray `eval_env` would be forwarded into load_environment). Reject at parse rather than
378
+ # silently evaluating against the training env.
379
+ raise ConfigError(
380
+ "[environment.params] eval_env is no longer supported; use eval_env_id "
381
+ '(a published Prime Hub slug "owner/name")'
382
+ )
383
+ eval_ref = spec.environment.params.get("eval_env_id")
384
+ if eval_ref:
385
+ _require_slug(
386
+ str(eval_ref),
387
+ '[environment.params] eval_env_id must be a published Prime Hub slug "owner/name"',
388
+ )
389
+ if spec.train.lora_rank <= 0:
390
+ raise ConfigError("train.lora_rank must be positive")
391
+ # The per-run HF artifact repo (adapters/checkpoints/code + serving) is required: there
392
+ # is no operator-wide default anymore. It must look like "owner/name" (exactly one slash,
393
+ # both parts non-empty) — a malformed value would reach the worker/serve as an unusable id.
394
+ if not spec.train.hf_repo:
395
+ raise ConfigError(
396
+ "train.hf_repo is required: the HF dataset repo for this run's adapters/checkpoints, "
397
+ 'e.g. "owner/name"'
398
+ )
399
+ _require_slug(
400
+ spec.train.hf_repo,
401
+ 'train.hf_repo must be a HuggingFace repo of the form "owner/name"',
402
+ )
403
+ # GRPO recipe knobs (group_size/temperature/max_tokens/kl_penalty_coef/advantage_clip/
404
+ # thinking_length_penalty_coef) are range-validated at parse time by the _train_int/
405
+ # _train_float coercers above (including the thinking_length_penalty_coef <= 1.0 upper
406
+ # bound), so no re-check is needed here.
407
+ # lora_alpha scales the adapter contribution; 0 (or negative) trains a paid run
408
+ # that produces a no-op adapter (zero scaling at serve). Reject up front.
409
+ if spec.train.lora_alpha <= 0:
410
+ raise ConfigError("train.lora_alpha must be positive")
code/autoslm/serve/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Adapter serving helpers."""
code/autoslm/serve/deploy.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Serve a trained LoRA adapter for OpenAI-style chat via a managed RunPod Flash GPU.
2
+
3
+ Two deployment modes (the cost/latency trade-off is explicit and user-chosen):
4
+
5
+ - ``dev`` (default): scale-to-zero. ``workers=(0,1)`` with a configurable idle timeout
6
+ and FlashBoot — you accept a cold start after inactivity, and pay $0 while idle.
7
+ - ``always-on``: ``workers=(1,1)`` — one worker stays warm 24/7 (no cold starts,
8
+ continuous billing). ``slm deployments`` shows the projected $/day so the cost is
9
+ never a surprise.
10
+
11
+ Each run gets its OWN uniquely-named serve endpoint (``autoslm-serve-<gpu>-<run>``), so
12
+ deployments never fight over a shared endpoint config and ``slm undeploy <run_id>``
13
+ can tear down exactly one deployment (via the REST API, from any process).
14
+
15
+ The handler boots vLLM with the base model + the LoRA adapter (pulled from the HF
16
+ dataset repo the trainer streamed it to) and returns an OpenAI-shaped chat-completion.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import os
22
+ from dataclasses import asdict, dataclass
23
+
24
+ from autoslm._logging import get_logger
25
+ from autoslm.providers.base import canonical_gpu, gpu_short
26
+ from autoslm.providers.runpod.gpus import flash_gpu
27
+
28
+ logger = get_logger(__name__)
29
+
30
+
31
+ def _invoke_handler(handler, payload: dict) -> dict:
32
+ """Call a Flash serve handler, awaiting it if the live path returns a coroutine."""
33
+ import asyncio
34
+ import inspect
35
+
36
+ async def _call():
37
+ res = handler(payload)
38
+ if inspect.isawaitable(res):
39
+ res = await res
40
+ return res
41
+
42
+ return asyncio.run(_call())
43
+
44
+
45
+ # Serving deps mirror the worker stack minus the trainer bits.
46
+ SERVE_DEPS = [
47
+ "torch==2.10.0",
48
+ "vllm==0.19.1",
49
+ "transformers>=5.6,<5.11",
50
+ "huggingface_hub>=0.25",
51
+ "peft>=0.19",
52
+ "accelerate>=1.4",
53
+ ]
54
+ SERVE_SYSTEM_DEPS = ["build-essential"]
55
+
56
+ _ENDPOINT_CACHE: dict[str, object] = {}
57
+
58
+ # Serving cold start (image pull + vLLM/PEFT install + ~8 GB base model + adapter) can
59
+ # exceed 10 min on a fresh host; default the serve execution cap to 25 min
60
+ # (env-overridable) so the first `slm chat` on a cold worker doesn't fail with
61
+ # "executionTimeout exceeded".
62
+ _DEFAULT_SERVE_TIMEOUT_MS = 25 * 60 * 1000
63
+
64
+ MODES = ("dev", "always-on")
65
+ DEFAULT_IDLE_TIMEOUT_S = 300
66
+
67
+ # Projected always-on cost uses live RunPod rates (static fallback):
68
+ # providers/runpod/pricing.py (hourly_rate).
69
+
70
+
71
+ def serve_execution_timeout_ms() -> int:
72
+ return _DEFAULT_SERVE_TIMEOUT_MS
73
+
74
+
75
+ def resolve_serve_deps() -> list[str]:
76
+ explicit = os.environ.get("AUTOSLM_SERVE_DEPS")
77
+ if explicit:
78
+ # JSON list (use this for specs containing commas, e.g.
79
+ # "transformers>=5.6,<5.11") or a whitespace-separated string. NOT comma-split:
80
+ # a comma is part of a PEP 440 range and must not become two pip arguments
81
+ # (mirrors providers/runpod/train.resolve_worker_deps).
82
+ if explicit.strip().startswith("["):
83
+ import json as _json
84
+
85
+ deps = [str(d).strip() for d in _json.loads(explicit) if str(d).strip()]
86
+ else:
87
+ import shlex
88
+
89
+ deps = [d for d in shlex.split(explicit) if d.strip()]
90
+ if deps:
91
+ return deps
92
+ return SERVE_DEPS
93
+
94
+
95
+ @dataclass
96
+ class Deployment:
97
+ run_id: str
98
+ model: str
99
+ adapter_hf_prefix: str
100
+ gpu: str
101
+ openai_model: str
102
+ endpoint_name: str
103
+ mode: str = "dev"
104
+ idle_timeout_s: int = DEFAULT_IDLE_TIMEOUT_S
105
+ est_idle_cost_usd_per_day: float = 0.0
106
+ state: str = "ready"
107
+
108
+ def to_dict(self) -> dict:
109
+ return asdict(self)
110
+
111
+
112
+ def _language_model_only(model: str) -> bool:
113
+ """Natively-multimodal checkpoints are served text-only. Approximated here by
114
+ family name (the client can't load the HF config); the worker does the precise
115
+ config-based check (engine.worker.is_vl_checkpoint, which covers Qwen3.5/3.6).
116
+ Both families must match here or a Qwen3.6 checkpoint served via model_policy="allow"
117
+ loses the text-only guard and re-hits the vision-tower VRAM/flash-attn issues."""
118
+ return "Qwen3.5" in model or "Qwen3.6" in model
119
+
120
+
121
+ def serve_endpoint_name(friendly_gpu: str, run_id: str) -> str:
122
+ tail = (run_id or "").split("-")[-1][:24]
123
+ base = f"autoslm-serve-{gpu_short(canonical_gpu(friendly_gpu))}"
124
+ return f"{base}-{tail}" if tail else base
125
+
126
+
127
+ def servable_gpu(gpu_name: str, model: str) -> str:
128
+ """Serving runs on RunPod Flash only: a run trained on a class that is not
129
+ RunPod-validated (a Vast-only class like L40S/RTX Pro 4000, OR a class that has a
130
+ RunPod enum member but was validated only on Vast, e.g. RTX 3090) is served from the
131
+ cheapest RunPod-VALIDATED class with at least the trained class's VRAM — NOT directly
132
+ on the unvalidated RunPod substrate (which can fail on first chat) and NOT the
133
+ catalog default (32 GB for open models, too small for the >32 GB class the allocator
134
+ proved was needed)."""
135
+ from autoslm.providers.base import GPU_INFO, UnsupportedGpuError, cheapest_gpu
136
+
137
+ friendly = canonical_gpu(gpu_name)
138
+ info = GPU_INFO[friendly]
139
+ # Enum presence is not enough: serve directly only on a RunPod-VALIDATED class.
140
+ if "runpod" in info.validated_on:
141
+ return friendly
142
+ try:
143
+ # Prefer a RunPod-validated class big enough; only if none exists fall back
144
+ # to an unvalidated one (better than refusing to serve at all).
145
+ fallback = cheapest_gpu(info.vram_gb)
146
+ except UnsupportedGpuError:
147
+ fallback = cheapest_gpu(info.vram_gb, include_unvalidated=True)
148
+ logger.warning(
149
+ "%s is not RunPod-validated; serving %s on %s (>= %d GB)",
150
+ friendly,
151
+ model,
152
+ fallback,
153
+ info.vram_gb,
154
+ )
155
+ return fallback
156
+
157
+
158
+ def _serve_body(input_data: dict) -> dict:
159
+ """Runs ON the GPU worker: forward a chat request to a persistent local vLLM server.
160
+
161
+ vLLM runs as a LONG-LIVED SUBPROCESS (the OpenAI api_server on localhost), not in
162
+ the handler process: importing torch inside the Flash handler process crashes
163
+ (torch dynamo config-module assertion against the runpod runtime's module state -
164
+ observed live), and a subprocess keeps the engine warm across requests anyway.
165
+ The handler boots it on first request (the cold start) and proxies afterwards.
166
+
167
+ NOTE: Flash serializes this handler and runs it standalone - all imports live
168
+ inside the body, and state is cached in module globals while the worker is warm.
169
+ """
170
+ import json as _json
171
+ import os
172
+ import subprocess
173
+ import sys
174
+ import time
175
+ import urllib.error
176
+ import urllib.request
177
+
178
+ g = globals()
179
+ base = "http://127.0.0.1:8199"
180
+
181
+ def _tail_serve_log(limit: int = 3000) -> str:
182
+ # Defined IN the body: Flash serializes _serve_body and runs it standalone, so
183
+ # the module-level helper of the same name is out of scope on the worker — a
184
+ # bare reference would NameError on the boot-failure path and hide the vLLM log.
185
+ try:
186
+ with open("/tmp/vllm_serve.log") as f:
187
+ return f.read()[-limit:]
188
+ except OSError:
189
+ return "(no serve log)"
190
+
191
+ _thinking = input_data.get("thinking", False)
192
+ # Robust bool: input_data may arrive loosely typed (serialized handler payload), and
193
+ # bool("false") is True — treat the usual falsey strings as False.
194
+ thinking = (
195
+ _thinking.strip().lower() not in ("", "0", "false", "no", "off", "none")
196
+ if isinstance(_thinking, str)
197
+ else bool(_thinking)
198
+ )
199
+ # thinking is part of the engine key: it changes --max-model-len, and the vLLM
200
+ # subprocess must be rebooted to change that.
201
+ key = (input_data["model"], input_data["adapter_prefix"], thinking)
202
+
203
+ def server_alive() -> bool:
204
+ proc = g.get("_AUTOSLM_PROC")
205
+ if proc is None or proc.poll() is not None:
206
+ return False
207
+ try:
208
+ urllib.request.urlopen(f"{base}/health", timeout=3)
209
+ return True
210
+ except Exception:
211
+ return False
212
+
213
+ if g.get("_AUTOSLM_KEY") != key or not server_alive():
214
+ from huggingface_hub import snapshot_download
215
+
216
+ prefix = input_data["adapter_prefix"]
217
+ snapshot_download(
218
+ repo_id=input_data["hf_repo"],
219
+ repo_type="dataset",
220
+ allow_patterns=[f"{prefix}/adapter/*"],
221
+ local_dir="/adapter",
222
+ token=input_data.get("token"),
223
+ )
224
+ adapter_dir = f"/adapter/{prefix}/adapter"
225
+ old = g.get("_AUTOSLM_PROC")
226
+ if old is not None and old.poll() is None:
227
+ old.kill()
228
+ cmd = [
229
+ sys.executable,
230
+ "-m",
231
+ "vllm.entrypoints.openai.api_server",
232
+ "--host",
233
+ "127.0.0.1",
234
+ "--port",
235
+ "8199",
236
+ "--model",
237
+ input_data["model"],
238
+ "--served-model-name",
239
+ "base",
240
+ "--dtype",
241
+ "bfloat16",
242
+ "--max-model-len",
243
+ "4096" if thinking else "2048", # <think> blocks need completion headroom
244
+ "--gpu-memory-utilization",
245
+ "0.85",
246
+ "--enable-lora",
247
+ "--max-lora-rank",
248
+ str(int(input_data.get("max_lora_rank") or 64)),
249
+ "--lora-modules",
250
+ f"adapter={adapter_dir}",
251
+ "--trust-remote-code",
252
+ ]
253
+ if input_data.get("language_model_only"):
254
+ cmd.append("--language-model-only")
255
+ env = dict(os.environ)
256
+ env.setdefault("HF_TOKEN", input_data.get("token") or "")
257
+ # Popen dups the fd into the child, so the parent handle can close
258
+ # immediately while vLLM keeps writing to the log.
259
+ with open("/tmp/vllm_serve.log", "w") as log:
260
+ g["_AUTOSLM_PROC"] = subprocess.Popen(
261
+ cmd, stdout=log, stderr=subprocess.STDOUT, env=env
262
+ )
263
+ # Align the vLLM boot budget with the endpoint execution cap: a large model can take
264
+ # several minutes to load on a cold host, and a hard-coded 900 s would 502 a first chat /
265
+ # fail an always-on warmup while the RunPod request still has time budget. Leave ~60 s of
266
+ # the window for the first generation.
267
+ # Read the env DIRECTLY (with the same default as serve_execution_timeout_ms):
268
+ # Flash serializes _serve_body and runs it standalone, so the module-level
269
+ # helper is out of scope on the worker (see _tail_serve_log) and a bare call
270
+ # would NameError before vLLM gets a chance to boot.
271
+ serve_timeout_ms = 25 * 60 * 1000
272
+ default_boot = max(900, serve_timeout_ms // 1000 - 60)
273
+ deadline = time.time() + float(input_data.get("boot_timeout_s") or default_boot)
274
+ while time.time() < deadline:
275
+ if g["_AUTOSLM_PROC"].poll() is not None:
276
+ tail = _tail_serve_log()
277
+ raise RuntimeError(f"vLLM server exited during boot:\n{tail}")
278
+ try:
279
+ urllib.request.urlopen(f"{base}/health", timeout=3)
280
+ break
281
+ except Exception:
282
+ time.sleep(2)
283
+ else:
284
+ tail = _tail_serve_log()
285
+ raise RuntimeError(f"vLLM server did not become healthy in time:\n{tail}")
286
+ g["_AUTOSLM_KEY"] = key
287
+
288
+ # always-on warmup: pay the cold start (download + vLLM boot) at deploy time
289
+ # so the user's first real chat is warm, then return without a completion.
290
+ if input_data.get("warmup"):
291
+ return {"ok": True, "warmed": True}
292
+
293
+ body = {
294
+ "model": "adapter",
295
+ "messages": input_data.get("messages") or [],
296
+ "temperature": float(input_data.get("temperature", 0.0)),
297
+ "top_p": float(input_data.get("top_p", 1.0)),
298
+ "max_tokens": int(input_data.get("max_tokens", 512)),
299
+ # Serve with the run's training-time thinking flag (decoding parity). Thinking
300
+ # responses carry the raw <think>...</think> block in message.content.
301
+ "chat_template_kwargs": {"enable_thinking": thinking},
302
+ }
303
+
304
+ def post(payload: dict) -> dict:
305
+ req = urllib.request.Request(
306
+ f"{base}/v1/chat/completions",
307
+ data=_json.dumps(payload).encode(),
308
+ headers={"Content-Type": "application/json"},
309
+ )
310
+ with urllib.request.urlopen(req, timeout=600) as resp:
311
+ return _json.loads(resp.read())
312
+
313
+ try:
314
+ out = post(body)
315
+ except urllib.error.HTTPError as e:
316
+ if e.code == 400:
317
+ # A vLLM build that rejects the kwarg falls back to the chat template's own
318
+ # default (thinking ON for hybrid Qwen3 — correct for thinking runs, a logged
319
+ # degradation for non-thinking ones).
320
+ body.pop("chat_template_kwargs", None)
321
+ print("vLLM rejected chat_template_kwargs; retrying without enable_thinking")
322
+ out = post(body)
323
+ else:
324
+ raise
325
+ out["model"] = input_data.get("served_model", "autoslm-adapter")
326
+ return out
327
+
328
+
329
+ def _get_serve_endpoint(
330
+ friendly_gpu: str,
331
+ run_id: str,
332
+ mode: str = "dev",
333
+ idle_timeout_s: int = DEFAULT_IDLE_TIMEOUT_S,
334
+ ):
335
+ os.environ["FLASH_IS_LIVE_PROVISIONING"] = "true"
336
+ from runpod_flash import Endpoint
337
+
338
+ from autoslm.providers.runpod.auth import ensure_auth
339
+ from autoslm.providers.runpod.train import FLASH_SDK_LOCK, isolate_flash_state, min_cuda_for
340
+
341
+ ensure_auth()
342
+ friendly = canonical_gpu(friendly_gpu)
343
+ name = serve_endpoint_name(friendly, run_id)
344
+ cache_key = f"{name}:{mode}:{idle_timeout_s}"
345
+
346
+ # Serialize against training deploy/teardown on the same process: isolate_flash_state()
347
+ # swaps runpod_flash's process-wide registry globals and Endpoint() touches the SDK's
348
+ # asyncio singleton, so a concurrent terminate_endpoint()/always-on warmup on another
349
+ # thread could race the registry scope. Hold the same lock across isolation + construction.
350
+ with FLASH_SDK_LOCK:
351
+ isolate_flash_state(f"serve-{run_id.split('-')[-1]}")
352
+ if cache_key in _ENDPOINT_CACHE:
353
+ return _ENDPOINT_CACHE[cache_key]
354
+ kwargs = {
355
+ "name": name,
356
+ "gpu": flash_gpu(friendly),
357
+ "gpu_count": 1,
358
+ "min_cuda_version": min_cuda_for(friendly),
359
+ # dev: scale to zero after idle_timeout (cold start accepted, $0 idle).
360
+ # always-on: one permanently warm worker (no cold start, 24/7 billing).
361
+ "workers": (0, 1) if mode == "dev" else (1, 1),
362
+ "idle_timeout": int(idle_timeout_s),
363
+ "flashboot": True,
364
+ "execution_timeout_ms": serve_execution_timeout_ms(),
365
+ }
366
+ image = os.environ.get("AUTOSLM_WORKER_IMAGE")
367
+ if image:
368
+ kwargs["image"] = image
369
+ else:
370
+ kwargs["dependencies"] = resolve_serve_deps()
371
+ kwargs["system_dependencies"] = SERVE_SYSTEM_DEPS
372
+ ep = Endpoint(**kwargs)
373
+ handler = ep(_serve_body)
374
+ _ENDPOINT_CACHE[cache_key] = handler
375
+ return handler
376
+
377
+
378
+ def _reject_qlora_serving(model: str) -> None:
379
+ """vLLM serving boots the base in bf16; a 4-bit-QLoRA-only tier won't fit.
380
+
381
+ Eval/train use the 4-bit transformers path for those models, but there is
382
+ no quantized vLLM serving path, so reject up front instead of provisioning
383
+ an endpoint that fails on first chat."""
384
+ from autoslm.catalog import MODELS
385
+
386
+ info = MODELS.get(model)
387
+ if info is not None and info.quant == "4bit-qlora":
388
+ raise ValueError(
389
+ f"{model} is a 4-bit-QLoRA-only tier and cannot be served bf16 by vLLM; "
390
+ "merge the adapter into a full model (`build_hf_model`) and deploy that, "
391
+ "or use a smaller bf16 model."
392
+ )
393
+
394
+
395
+ def deploy_adapter(
396
+ run_id: str,
397
+ model: str,
398
+ hf_repo: str,
399
+ adapter_prefix: str,
400
+ gpu_name: str = "RTX 5090",
401
+ mode: str = "dev",
402
+ idle_timeout_s: int = DEFAULT_IDLE_TIMEOUT_S,
403
+ dry_run: bool = False,
404
+ lora_rank: int = 64,
405
+ thinking: bool = False,
406
+ ) -> Deployment:
407
+ """Provision a serving endpoint for a trained adapter (managed, no Docker)."""
408
+ if mode not in MODES:
409
+ raise ValueError(f"mode must be one of {MODES}, got {mode!r}")
410
+ _reject_qlora_serving(model)
411
+ friendly = servable_gpu(gpu_name, model)
412
+ from autoslm.runner import _gpu_rate
413
+
414
+ rate = _gpu_rate(friendly)
415
+ dep = Deployment(
416
+ run_id=run_id,
417
+ model=model,
418
+ adapter_hf_prefix=adapter_prefix,
419
+ gpu=friendly,
420
+ openai_model=f"autoslm-{run_id}",
421
+ endpoint_name=serve_endpoint_name(friendly, run_id),
422
+ mode=mode,
423
+ idle_timeout_s=idle_timeout_s,
424
+ est_idle_cost_usd_per_day=0.0 if mode == "dev" else round(rate * 24, 2),
425
+ state="dry_run" if dry_run else "ready",
426
+ )
427
+ if dry_run:
428
+ return dep
429
+ handler = _get_serve_endpoint(friendly, run_id, mode=mode, idle_timeout_s=idle_timeout_s)
430
+ # always-on promises no cold start: warm the worker now (download + vLLM boot)
431
+ # BEFORE returning ready, so the user's first chat is genuinely warm. dev mode
432
+ # is scale-to-zero by design, so it warms lazily on first chat.
433
+ if mode == "always-on":
434
+ warmup = {
435
+ "hf_repo": hf_repo,
436
+ "model": model,
437
+ "adapter_prefix": adapter_prefix,
438
+ "token": os.environ.get("HF_TOKEN", ""),
439
+ "max_lora_rank": max(64, int(lora_rank)),
440
+ "language_model_only": _language_model_only(model),
441
+ # warm the engine with the run's thinking flag so the first real chat (same
442
+ # flag) reuses the warmed subprocess instead of rebooting for --max-model-len.
443
+ "thinking": thinking,
444
+ "warmup": True,
445
+ }
446
+ try:
447
+ _invoke_handler(handler, warmup)
448
+ except Exception:
449
+ # The warmup invocation is what actually provisions the always-on worker;
450
+ # if adapter download / vLLM boot fails the endpoint is registered (and may
451
+ # bill) but no deployment is persisted. Tear it down before propagating.
452
+ import contextlib
453
+
454
+ with contextlib.suppress(Exception):
455
+ undeploy_adapter(run_id, gpu_name=friendly)
456
+ raise
457
+ return dep
458
+
459
+
460
+ def undeploy_adapter(run_id: str, gpu_name: str = "RTX 5090") -> list[str]:
461
+ """Tear down the run's serve endpoint via the REST API (works from any process)."""
462
+ from autoslm.providers.runpod import api as runpod_api
463
+
464
+ name = serve_endpoint_name(gpu_name, run_id)
465
+ # find_endpoints_by_name is a substring filter, so guard with an exact-name
466
+ # check (mirrors providers/runpod/train.py terminate_endpoint) — otherwise a
467
+ # name that is a substring of another run's endpoint would over-delete and
468
+ # mis-report the returned `deleted` list.
469
+ deleted = [
470
+ ep["name"]
471
+ for ep in runpod_api.find_endpoints_by_name(name)
472
+ if ep.get("name") == name and runpod_api.delete_endpoint(ep["id"])
473
+ ]
474
+ # Drop in-process handler cache entries for this endpoint (keyed name:mode:idle)
475
+ # so a later redeploy constructs a fresh endpoint instead of reusing a handler
476
+ # pointing at the just-deleted one.
477
+ for key in [k for k in _ENDPOINT_CACHE if k.startswith(f"{name}:")]:
478
+ _ENDPOINT_CACHE.pop(key, None)
479
+ return deleted
480
+
481
+
482
+ def chat(
483
+ run_id: str,
484
+ messages: list[dict],
485
+ model: str,
486
+ hf_repo: str,
487
+ adapter_prefix: str,
488
+ gpu_name: str = "RTX 5090",
489
+ temperature: float = 0.0,
490
+ max_tokens: int = 512,
491
+ mode: str = "dev",
492
+ idle_timeout_s: int = DEFAULT_IDLE_TIMEOUT_S,
493
+ lora_rank: int = 64,
494
+ thinking: bool = False,
495
+ ) -> dict:
496
+ """Send an OpenAI-style chat request to the adapter's managed Flash GPU."""
497
+ handler = _get_serve_endpoint(
498
+ servable_gpu(gpu_name, model), run_id, mode=mode, idle_timeout_s=idle_timeout_s
499
+ )
500
+ # Natively-multimodal checkpoints are served text-only (no transformers needed
501
+ # client-side; the family-name check mirrors the worker's config-based one).
502
+ language_model_only = _language_model_only(model)
503
+ payload = {
504
+ "hf_repo": hf_repo,
505
+ "model": model,
506
+ "adapter_prefix": adapter_prefix,
507
+ "token": os.environ.get("HF_TOKEN", ""),
508
+ "served_model": f"autoslm-{run_id}",
509
+ "messages": messages,
510
+ "temperature": temperature,
511
+ "max_tokens": max_tokens,
512
+ # vLLM rejects an adapter whose rank exceeds --max-lora-rank; cover the
513
+ # run's configured rank, not just the 64 default.
514
+ "max_lora_rank": max(64, int(lora_rank)),
515
+ "language_model_only": language_model_only,
516
+ "thinking": thinking,
517
+ }
518
+ return _invoke_handler(handler, payload)