DavidBShan commited on
Commit
2cf02da
·
verified ·
1 Parent(s): 55651df

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 +240 -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/disaggregated.py +434 -0
  13. code/autoslm/engine/multiturn_rollout.py +266 -0
  14. code/autoslm/engine/recipe.py +91 -0
  15. code/autoslm/engine/rollout_bench.py +125 -0
  16. code/autoslm/engine/verl_runner.py +695 -0
  17. code/autoslm/engine/vram.py +323 -0
  18. code/autoslm/engine/worker.py +0 -0
  19. code/autoslm/envs/__init__.py +10 -0
  20. code/autoslm/envs/adapter.py +706 -0
  21. code/autoslm/envs/base.py +49 -0
  22. code/autoslm/envs/registry.py +95 -0
  23. code/autoslm/mcp/__init__.py +1 -0
  24. code/autoslm/mcp/server.py +83 -0
  25. code/autoslm/providers/__init__.py +60 -0
  26. code/autoslm/providers/_http.py +100 -0
  27. code/autoslm/providers/_poll.py +87 -0
  28. code/autoslm/providers/allocator.py +336 -0
  29. code/autoslm/providers/base.py +549 -0
  30. code/autoslm/providers/preflight.py +80 -0
  31. code/autoslm/providers/runpod/__init__.py +108 -0
  32. code/autoslm/providers/runpod/api.py +117 -0
  33. code/autoslm/providers/runpod/auth.py +25 -0
  34. code/autoslm/providers/runpod/gpus.py +46 -0
  35. code/autoslm/providers/runpod/jobs.py +494 -0
  36. code/autoslm/providers/runpod/preflight.py +30 -0
  37. code/autoslm/providers/runpod/pricing.py +110 -0
  38. code/autoslm/providers/runpod/train.py +823 -0
  39. code/autoslm/providers/vast/__init__.py +124 -0
  40. code/autoslm/providers/vast/_bootstrap.py +274 -0
  41. code/autoslm/providers/vast/api.py +221 -0
  42. code/autoslm/providers/vast/auth.py +25 -0
  43. code/autoslm/providers/vast/gpus.py +21 -0
  44. code/autoslm/providers/vast/jobs.py +761 -0
  45. code/autoslm/providers/vast/preflight.py +26 -0
  46. code/autoslm/providers/vast/pricing.py +51 -0
  47. code/autoslm/providers/vast/train.py +27 -0
  48. code/autoslm/py.typed +0 -0
  49. code/autoslm/runner.py +1037 -0
  50. code/autoslm/schema.py +438 -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,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Requires the DISAGGREGATED (multi-GPU async) GRPO path: too large to colocate the trainer +
56
+ # vLLM rollout on one GPU. A GRPO request for such a model must set ``[train].inference_gpus>0``
57
+ # on a multi-GPU node (see engine.rollout_bench); colocate GRPO is rejected. SFT is unaffected.
58
+ requires_disaggregated: bool = False
59
+
60
+ def to_dict(self) -> dict[str, Any]:
61
+ return asdict(self)
62
+
63
+
64
+ # The default model AutoSLM trains when a config omits one. A current-gen dense 4B
65
+ # (text-only fine-tune) on the modern worker stack — the safe out-of-the-box choice for
66
+ # the average developer. It is thinking-"hybrid"; the thinking flag now defaults ON.
67
+ DEFAULT_MODEL = "Qwen/Qwen3.5-4B"
68
+
69
+ MODELS: dict[str, ModelInfo] = {
70
+ "openbmb/MiniCPM5-1B": ModelInfo(
71
+ id="openbmb/MiniCPM5-1B",
72
+ display_name="MiniCPM5 1B",
73
+ params="1.2B dense (Llama arch)",
74
+ algos=("sft", "grpo"),
75
+ min_vram_gb=12,
76
+ recommended_gpu="RTX 4090",
77
+ thinking="hybrid",
78
+ notes="On-device class SLM (131k ctx); standard Llama architecture.",
79
+ ),
80
+ # ---- Qwen3.5 dense family: validated on the modern worker stack ----
81
+ # (trl 1.x / vllm 0.19 / transformers 5.x). Trained + served TEXT-ONLY: the
82
+ # checkpoints are natively multimodal, so LoRA excludes the vision tower and vLLM
83
+ # loads language_model_only (see autoslm.engine.worker). Each entry passed a real
84
+ # train+eval smoke on its recommended GPU (bench/results/phase1/).
85
+ "Qwen/Qwen3.5-0.8B": ModelInfo(
86
+ id="Qwen/Qwen3.5-0.8B",
87
+ display_name="Qwen3.5 0.8B",
88
+ params="0.9B (text-only fine-tune)",
89
+ algos=("sft", "grpo"),
90
+ min_vram_gb=12,
91
+ recommended_gpu="RTX 4090",
92
+ thinking="hybrid",
93
+ notes="Smallest Qwen3.5; cheap smoke/dev runs with the modern arch.",
94
+ ),
95
+ "Qwen/Qwen3.5-2B": ModelInfo(
96
+ id="Qwen/Qwen3.5-2B",
97
+ display_name="Qwen3.5 2B",
98
+ params="2.3B (text-only fine-tune)",
99
+ algos=("sft", "grpo"),
100
+ min_vram_gb=16,
101
+ recommended_gpu="RTX 4090",
102
+ thinking="hybrid",
103
+ ),
104
+ "Qwen/Qwen3.5-4B": ModelInfo(
105
+ id="Qwen/Qwen3.5-4B",
106
+ display_name="Qwen3.5 4B",
107
+ params="4.7B (text-only fine-tune)",
108
+ algos=("sft", "grpo"),
109
+ min_vram_gb=32,
110
+ recommended_gpu="RTX 5090",
111
+ thinking="hybrid",
112
+ notes="Current-gen 4B. GRPO uses the sleep-mode memory recipe (hybrid arch needs "
113
+ "extra engine state-cache); fused DeltaNet kernels ship in the default stack.",
114
+ ),
115
+ "Qwen/Qwen3.5-9B": ModelInfo(
116
+ id="Qwen/Qwen3.5-9B",
117
+ display_name="Qwen3.5 9B",
118
+ params="9.7B (text-only fine-tune)",
119
+ algos=("sft", "grpo"),
120
+ min_vram_gb=16,
121
+ # MEMORY-OPTIMIZED: 4-bit NF4 frozen base + bf16 LoRA adapter (QLoRA). The base
122
+ # drops from ~19 GB bf16 to ~5.3 GB, so colocated GRPO holds two 4-bit copies
123
+ # (trainer + bnb-quantized vLLM rollout) instead of two bf16 copies -> it fits a
124
+ # ~24-32 GB card instead of an 80 GB A100. NF4 is near-lossless for adapter training
125
+ # (QLoRA paper + follow-ups), a small quality trade for a ~3x cheaper GPU. No GRPO
126
+ # floor: the matrix sizes the (much smaller) 4-bit footprint directly.
127
+ grpo_min_vram_gb=0,
128
+ quant="4bit-qlora",
129
+ recommended_gpu="RTX 5090",
130
+ thinking="hybrid",
131
+ notes="QLoRA (4-bit NF4 base + bf16 LoRA). GRPO's colocated vLLM rollout loads the "
132
+ "base 4-bit via bitsandbytes too, so both copies are 4-bit -> fits ~24-32 GB "
133
+ "instead of 80 GB bf16. ~near-lossless vs bf16 LoRA.",
134
+ ),
135
+ "Qwen/Qwen3.6-35B-A3B": ModelInfo(
136
+ id="Qwen/Qwen3.6-35B-A3B",
137
+ display_name="Qwen3.6 35B-A3B (MoE)",
138
+ params="35B total / ~3B active (MoE)",
139
+ algos=("sft", "grpo"),
140
+ min_vram_gb=48,
141
+ grpo_min_vram_gb=80,
142
+ quant="4bit-qlora",
143
+ recommended_gpu="A100 PCIe",
144
+ thinking="hybrid",
145
+ # Re-added for the DISAGGREGATED (multi-GPU async) GRPO path only: it OOMs when the trainer
146
+ # and the vLLM rollout are colocated on one card. With a dedicated inference GPU (35B served
147
+ # 4-bit) + a sharded trainer on the rest, it fits. GRPO colocate for it is rejected.
148
+ requires_disaggregated=True,
149
+ notes="MoE; GRPO requires the disaggregated multi-GPU node ([train].inference_gpus>0). "
150
+ "The 35B is served 4-bit on the inference GPU while a sharded trainer runs on the rest.",
151
+ ),
152
+ }
153
+
154
+
155
+ def list_models() -> list[ModelInfo]:
156
+ return sorted(MODELS.values(), key=lambda m: (m.min_vram_gb, m.id))
157
+
158
+
159
+ def get_model(model_id: str) -> ModelInfo:
160
+ try:
161
+ return MODELS[model_id]
162
+ except KeyError as exc:
163
+ allowed = ", ".join(MODELS)
164
+ raise ValueError(
165
+ f"unsupported model {model_id!r}; choose one of: {allowed} — or set "
166
+ f'model_policy = "allow" in the config to run any HF model that fits the GPU '
167
+ f"(open-model policy)"
168
+ ) from exc
169
+
170
+
171
+ def resolve_model(
172
+ model_id: str,
173
+ algorithm: str,
174
+ policy: str = "catalog",
175
+ gpu: str | None = None,
176
+ ) -> ModelInfo:
177
+ """Resolve a model under the configured policy.
178
+
179
+ ``catalog`` (default): the model must be a curated catalog entry.
180
+ ``allow``: any HF model is accepted; a coarse VRAM-fit estimate (HF safetensors
181
+ metadata, no download) blocks only provably-impossible fits and warns on tight ones.
182
+ """
183
+ algo = normalize_algorithm(algorithm)
184
+ if model_id in MODELS:
185
+ return validate_model_for_algorithm(model_id, algo)
186
+ if policy != "allow":
187
+ # Reuse get_model's error (includes the open-model hint).
188
+ return get_model(model_id)
189
+ return _resolve_open_model(model_id, algo, gpu)
190
+
191
+
192
+ def _resolve_open_model(model_id: str, algo: str, gpu: str | None) -> ModelInfo:
193
+ """Synthesize a ModelInfo for the open-model "allow" policy from a coarse VRAM-fit
194
+ estimate (HF safetensors metadata, no download). Blocks provably-impossible fits and
195
+ warns on tight ones. Isolates the engine.vram dependency + disk-floor heuristic from
196
+ the curated-catalog path in resolve_model."""
197
+ from autoslm.engine.vram import check_fit
198
+
199
+ est = check_fit(model_id, algo, gpu or DEFAULT_GPU)
200
+ if est.verdict == "too_big":
201
+ raise ValueError(
202
+ f"{model_id} does not fit the requested GPU: {est.describe()}. "
203
+ f"Pick a smaller model or a larger supported GPU."
204
+ )
205
+ if est.verdict in ("tight", "unknown"):
206
+ print(f"warning: open-model policy: {est.describe()}")
207
+ params = f"{est.params_b:.1f}B" if est.params_b else "unknown size"
208
+ # Disk floor for the open model: a bf16 checkpoint is ~2 GB per billion params;
209
+ # add worker-stack headroom so a large model that passes the VRAM check can't
210
+ # provision a paid worker and then fail in prefetch_model when the checkpoint
211
+ # overflows the 64 GB container default. 0 (unknown size) leaves the default
212
+ # (the user can still raise it with gpu.disk_gb).
213
+ min_disk = int(est.params_b * 2) + 64 if est.params_b else 0
214
+ return ModelInfo(
215
+ id=model_id,
216
+ display_name=model_id,
217
+ params=params,
218
+ algos=ALGORITHMS,
219
+ min_vram_gb=math.ceil(est.est_gb) if est.est_gb else 24,
220
+ min_disk_gb=min_disk,
221
+ recommended_gpu=gpu or DEFAULT_GPU,
222
+ thinking="unknown",
223
+ notes="unlisted model accepted via the open-model policy (not curated/validated)",
224
+ )
225
+
226
+
227
+ def validate_model_for_algorithm(model_id: str, algorithm: str) -> ModelInfo:
228
+ info = get_model(model_id)
229
+ algo = normalize_algorithm(algorithm)
230
+ # Catalog entries advertise the capability classes "sft" and "grpo": grpo needs the
231
+ # colocated rollout engine, sft is trainer-only.
232
+ required = "grpo" if algo == "grpo" else "sft"
233
+ if required not in info.algos:
234
+ allowed = ", ".join(info.algos)
235
+ raise ValueError(f"{model_id} supports {allowed}, not {algo}")
236
+ return info
237
+
238
+
239
+ def public_model_rows() -> list[dict[str, Any]]:
240
+ 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/disaggregated.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Disaggregated (multi-GPU async) GRPO rollout: launch a ``trl vllm-serve`` rollout server on
2
+ the inference GPUs and point the GRPO trainer at it (``vllm_mode="server"``), so generation for
3
+ the next batch overlaps the current optimizer step instead of time-sharing one GPU.
4
+
5
+ verl ref (3D-HybridEngine / flexible device mapping + async rollout):
6
+ https://github.com/verl-project/verl
7
+
8
+ The command/env builders here are PURE (no torch, no subprocess) so the launch contract is
9
+ unit-testable on CPU; only :func:`launch_vllm_server` / :func:`wait_for_server_health` /
10
+ :func:`detect_total_gpus` touch the system. The device split itself lives in
11
+ :mod:`autoslm.engine.rollout_bench` (``select_rollout_split``).
12
+
13
+ TRL 1.6 server-mode contract (verified against trl/scripts/vllm_serve.py + trl/generation/
14
+ vllm_client.py): the trainer's ``VLLMClient`` waits for the server (``vllm_server_timeout``),
15
+ opens a NCCL weight-sync group on ``vllm_group_port`` (default 51216), and on every generation
16
+ batch ``sync_weights()`` POSTs ``/update_named_param/`` then broadcasts the (PEFT-merged) weights
17
+ over NCCL — so weight sync is automatic; we only have to bring the server up first.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import contextlib
23
+ import os
24
+ import subprocess
25
+ import time
26
+ import urllib.error
27
+ import urllib.request
28
+
29
+ from autoslm.engine.rollout_bench import RolloutSplit
30
+
31
+ # Loopback HTTP port the rollout server binds (trainer connects via vllm_server_base_url) and the
32
+ # NCCL weight-sync group port. Single-node (all GPUs on one rented instance) -> loopback, so no
33
+ # firewall concerns. Both overridable for the rare port clash.
34
+ DEFAULT_SERVER_PORT = 8000
35
+ DEFAULT_GROUP_PORT = 51216
36
+ # vLLM rollout server gets the whole inference card (no trainer sharing it, unlike colocate's ~0.45).
37
+ DEFAULT_SERVER_GPU_UTIL = 0.90
38
+
39
+
40
+ def server_port() -> int:
41
+ return int(os.environ.get("AUTOSLM_VLLM_SERVER_PORT", DEFAULT_SERVER_PORT))
42
+
43
+
44
+ def group_port() -> int:
45
+ return int(os.environ.get("AUTOSLM_VLLM_GROUP_PORT", DEFAULT_GROUP_PORT))
46
+
47
+
48
+ def server_base_url(port: int | None = None) -> str:
49
+ return f"http://127.0.0.1:{port or server_port()}"
50
+
51
+
52
+ def detect_total_gpus(env: dict | None = None) -> int:
53
+ """Number of GPUs physically on this node, WITHOUT initializing a torch CUDA context.
54
+
55
+ ``torch.cuda.device_count()`` is avoided on the hot path because the disaggregated split must
56
+ set ``CUDA_VISIBLE_DEVICES`` on the trainer process *before* any CUDA context is created;
57
+ querying torch here could bind the context to all visible devices first. Prefer the explicit
58
+ ``AUTOSLM_GPU_COUNT`` the provisioner sets (= ``[gpu] count``), else count ``nvidia-smi -L``.
59
+ """
60
+ env = env if env is not None else os.environ
61
+ # GROUND TRUTH = the GPUs actually visible to THIS container (`nvidia-smi -L`, CUDA-free, honors
62
+ # the container's NVIDIA_VISIBLE_DEVICES). The provisioner's AUTOSLM_GPU_COUNT (= [gpu] count)
63
+ # is only the REQUESTED count — a provider can rent a 2-GPU offer yet expose 1 GPU to the
64
+ # container (observed on Vast), so trusting it would make the split assign a nonexistent device.
65
+ # We take the real count and only fall back to the hint when nvidia-smi is unavailable.
66
+ try:
67
+ out = subprocess.run(["nvidia-smi", "-L"], capture_output=True, text=True, timeout=20)
68
+ # Raw container GPU/visibility diagnostic — definitively shows what the container sees and
69
+ # whether an env var (CUDA_VISIBLE_DEVICES / NVIDIA_VISIBLE_DEVICES) is hiding GPUs vs the
70
+ # provider genuinely exposing fewer. Printed once at split time.
71
+ print(
72
+ f"[rl][disagg][diag] nvidia-smi -L:\n{out.stdout.strip()}\n"
73
+ f"[rl][disagg][diag] CUDA_VISIBLE_DEVICES={env.get('CUDA_VISIBLE_DEVICES')!r} "
74
+ f"NVIDIA_VISIBLE_DEVICES={env.get('NVIDIA_VISIBLE_DEVICES')!r} "
75
+ f"AUTOSLM_GPU_COUNT={env.get('AUTOSLM_GPU_COUNT')!r}"
76
+ )
77
+ lines = [ln for ln in out.stdout.splitlines() if ln.strip().startswith("GPU ")]
78
+ if lines:
79
+ real = len(lines)
80
+ hint = env.get("AUTOSLM_GPU_COUNT")
81
+ if hint and hint.isdigit() and int(hint) != real:
82
+ _note = (
83
+ "The provider under-provisioned the node."
84
+ if real < int(hint)
85
+ else "The node exposes more GPUs than requested."
86
+ )
87
+ print(
88
+ f"[rl][disagg] WARNING: [gpu] count requested {hint} but the container exposes "
89
+ f"{real} GPU(s) (nvidia-smi) — using {real}. {_note}"
90
+ )
91
+ return real
92
+ except Exception:
93
+ pass
94
+ explicit = env.get("AUTOSLM_GPU_COUNT")
95
+ if explicit and explicit.isdigit() and int(explicit) >= 1:
96
+ return int(explicit)
97
+ try:
98
+ import torch
99
+
100
+ return int(torch.cuda.device_count())
101
+ except Exception:
102
+ return 1
103
+
104
+
105
+ def _cvd(devices: tuple[int, ...]) -> str:
106
+ """CUDA_VISIBLE_DEVICES string from GLOBAL physical device indices."""
107
+ return ",".join(str(d) for d in devices)
108
+
109
+
110
+ def trainer_cuda_visible_devices(split: RolloutSplit) -> str:
111
+ """The CUDA_VISIBLE_DEVICES the trainer process must use (its train devices, global indices)."""
112
+ return _cvd(split.train_devices)
113
+
114
+
115
+ def build_vllm_serve_cmd(
116
+ model_id: str,
117
+ split: RolloutSplit,
118
+ *,
119
+ max_model_len: int,
120
+ port: int,
121
+ gpu_memory_util: float = DEFAULT_SERVER_GPU_UTIL,
122
+ quant: str = "bf16",
123
+ trl_bin: str | None = None,
124
+ trust_remote_code: bool = True,
125
+ enable_prefix_caching: bool = True,
126
+ kv_cache_dtype: str | None = None,
127
+ parallel: str = "tp",
128
+ extra: list[str] | None = None,
129
+ ) -> list[str]:
130
+ """The ``trl vllm-serve`` argv for the rollout server.
131
+
132
+ PARALLELISM across the inference GPUs (after CUDA_VISIBLE_DEVICES pins the server to
133
+ ``split.infer_devices``, those cards re-index to 0..infer_gpus-1):
134
+
135
+ * ``parallel="tp"`` (DEFAULT) -> ``--tensor_parallel_size infer_gpus``: shard ONE model across
136
+ the inference GPUs. For a generation-bound GRPO step the decode phase is memory-bandwidth
137
+ bound, so TP gives ~the aggregate HBM bandwidth of all inference cards (weights + KV split
138
+ across them) -> larger concurrent batches + faster decode, which is how higher inference
139
+ ratios (1:2, 1:3) clear the rollout bottleneck. Works for DENSE and MoE alike.
140
+ * ``parallel="dp"`` -> ``--data_parallel_size infer_gpus --tensor_parallel_size 1``: each
141
+ inference GPU is a FULL replica and the server load-balances across them. **vLLM REJECTS
142
+ offline data-parallel for DENSE models** ("Offline data parallel mode is not supported/useful
143
+ for dense models" — ParallelConfig validation), so this is ONLY usable for the MoE model
144
+ (Qwen3.6-35B-A3B), where DP shards experts. Do NOT default to it: every dense model in the
145
+ catalog (MiniCPM, the Qwen3.5 dense line) must use TP.
146
+
147
+ ``max_model_len`` bounds the KV cache to the GRPO need (prompt+completion) so the server starts
148
+ on a consumer card instead of sizing for the model's full context.
149
+
150
+ Only flags that ``trl vllm-serve``'s ScriptArguments actually defines are emitted (verified
151
+ against trl/scripts/vllm_serve.py): model, tensor_parallel_size, data_parallel_size, host, port,
152
+ gpu_memory_utilization, max_model_len, enable_prefix_caching, trust_remote_code. The CLI has NO
153
+ quantization/load_format option, so a ``4bit-qlora`` model is served bf16/auto on its OWN
154
+ inference card (in disaggregated mode the inference GPU holds ONLY the rollout, not a colocated
155
+ trainer, so the full-precision weights fit a big enough card). The trainer still loads the base
156
+ 4-bit (its model_init_kwargs are independent); TRL merges the LoRA into bf16 before each weight
157
+ sync, so trainer-4-bit + server-bf16 stays consistent. ``quant`` is accepted for signature
158
+ stability / sizing notes but does not change the server command.
159
+ """
160
+ bin_ = trl_bin or os.environ.get("AUTOSLM_TRL_BIN", "trl")
161
+ if parallel == "dp":
162
+ # DP replicas: server load-balances generation across infer_gpus full copies. vLLM ONLY
163
+ # allows offline DP for MoE models -> reserve this for the 35B-A3B; dense models must use TP.
164
+ par_flags = [
165
+ "--data_parallel_size",
166
+ str(split.infer_gpus),
167
+ "--tensor_parallel_size",
168
+ "1",
169
+ ]
170
+ else:
171
+ # TP (DEFAULT): shard one model across the inference GPUs -> aggregate HBM bandwidth for a
172
+ # faster, larger-batch decode (the win for higher ratios on a generation-bound step).
173
+ par_flags = ["--tensor_parallel_size", str(split.infer_gpus)]
174
+ cmd = [
175
+ bin_,
176
+ "vllm-serve",
177
+ "--model",
178
+ model_id,
179
+ *par_flags,
180
+ "--host",
181
+ "127.0.0.1",
182
+ "--port",
183
+ str(port),
184
+ "--gpu_memory_utilization",
185
+ str(gpu_memory_util),
186
+ "--max_model_len",
187
+ str(max_model_len),
188
+ ]
189
+ if trust_remote_code:
190
+ cmd += ["--trust_remote_code", "true"]
191
+ # verl-validated rollout-engine levers (mirror the colocate path): PREFIX CACHING reuses the
192
+ # shared GRPO prompt-prefix KV across a group's completions (the dominant rollout win); fp8 KV
193
+ # CACHE (Ada/Hopper/Blackwell, compute capability >= 8.9) ~halves the KV pool so a bigger
194
+ # generation batch fits the inference card. CUDA graphs are on by default (enforce_eager unset).
195
+ if enable_prefix_caching:
196
+ cmd += ["--enable_prefix_caching", "true"]
197
+ if kv_cache_dtype:
198
+ cmd += ["--kv_cache_dtype", kv_cache_dtype]
199
+ if extra:
200
+ cmd += list(extra)
201
+ return cmd
202
+
203
+
204
+ # The flags `trl vllm-serve` (TRL 1.6 ScriptArguments) actually accepts. HfArgumentParser REJECTS
205
+ # any unknown --flag, failing server launch — so build_vllm_serve_cmd must only emit these (see the
206
+ # allowlist test). Mirrors trl/scripts/vllm_serve.py:ScriptArguments.
207
+ TRL_VLLM_SERVE_FLAGS = frozenset(
208
+ {
209
+ "--model",
210
+ "--revision",
211
+ "--tensor_parallel_size",
212
+ "--data_parallel_size",
213
+ "--host",
214
+ "--port",
215
+ "--gpu_memory_utilization",
216
+ "--dtype",
217
+ "--max_model_len",
218
+ "--enable_prefix_caching",
219
+ "--enforce_eager",
220
+ "--kv_cache_dtype",
221
+ "--trust_remote_code",
222
+ "--log_level",
223
+ "--vllm_model_impl",
224
+ "--distributed_executor_backend",
225
+ "--speculative_config",
226
+ }
227
+ )
228
+
229
+
230
+ def build_accelerate_launch_cmd(
231
+ split: RolloutSplit,
232
+ *,
233
+ worker_module: str = "autoslm.engine.worker",
234
+ mixed_precision: str = "bf16",
235
+ use_fsdp: bool = True,
236
+ python_bin: str | None = None,
237
+ ) -> list[str]:
238
+ """``accelerate launch`` argv that runs the GRPO trainer across the TRAIN devices (FSDP).
239
+
240
+ For a train_gpus>1 ratio (2:1, 3:1, 2:2) the trainer must be a *distributed* process group, not
241
+ a single process spanning many GPUs (that silently becomes nn.DataParallel, which TRL's
242
+ weight-sync gather does not support). The disaggregated launcher brings the vLLM rollout server
243
+ up on the inference GPUs first, then re-execs the worker's RL phase under this command so
244
+ ``accelerate`` shards the trainer across ``split.train_gpus`` with FSDP and the trainer connects
245
+ to the already-running server (``AUTOSLM_RL_TRAINER_ONLY=1`` in the child env).
246
+
247
+ ``--gpu_ids`` pins the child group to the GLOBAL train device indices (so it never touches the
248
+ inference card), and ``--num_processes`` == train_gpus (one rank per train GPU). FSDP (vs DDP)
249
+ is the default because it shards the base weights — required for the 35B-A3B whose base does not
250
+ fit one card replicated; for small models it is still correct, just less memory-critical.
251
+ """
252
+ cmd = [
253
+ "accelerate",
254
+ "launch",
255
+ "--num_machines",
256
+ "1",
257
+ "--num_processes",
258
+ str(split.train_gpus),
259
+ "--gpu_ids",
260
+ _cvd(split.train_devices),
261
+ "--mixed_precision",
262
+ mixed_precision,
263
+ "--dynamo_backend",
264
+ "no",
265
+ ]
266
+ if use_fsdp:
267
+ # FSDP full-shard with transformer auto-wrap: shards params+grads+optimizer across ranks so
268
+ # the trainer scales past one card. CPU-offload off (the train GPUs have room; offload would
269
+ # tank throughput). NB: `--use_fsdp` already implies multi-GPU — accelerate REJECTS
270
+ # `--multi_gpu` alongside it ("You can only use one of --cpu/--multi_gpu/--use_fsdp ..."), so
271
+ # we must NOT pass --multi_gpu here. These are accelerate-launch FSDP flags (accelerate>=1.4).
272
+ cmd += [
273
+ "--use_fsdp",
274
+ # SHARD_GRAD_OP (ZeRO-2: shard gradients+optimizer, REPLICATE parameters) — NOT FULL_SHARD.
275
+ # TRL's per-step weight sync calls peft merge_adapter() -> get_delta_weight() ->
276
+ # weight_B @ weight_A; under FULL_SHARD the LoRA weights are param-sharded so each rank
277
+ # holds a slice and the matmul fails ("inconsistent tensor size [32768] vs [24576]").
278
+ # SHARD_GRAD_OP keeps params whole on every rank so the merge sees full LoRA weights, while
279
+ # still sharding the optimizer/grads. Fine for the dense 1-9B bases (replicated base fits);
280
+ # a base too big to replicate (35B) would need FULL_SHARD + a TRL patch that gathers LoRA
281
+ # before merge — out of scope here.
282
+ "--fsdp_sharding_strategy",
283
+ "SHARD_GRAD_OP",
284
+ "--fsdp_auto_wrap_policy",
285
+ "TRANSFORMER_BASED_WRAP",
286
+ # use_orig_params keeps the original (un-flattened) parameter tensors so peft can read
287
+ # weight_A/weight_B with their real shapes during the merge.
288
+ "--fsdp_use_orig_params",
289
+ "true",
290
+ # FULL_STATE_DICT: transformers' Trainer rejects save_only_model (set by GRPOConfig)
291
+ # alongside SHARDED_STATE_DICT; FULL gathers the small LoRA adapter on rank 0 at save time.
292
+ "--fsdp_state_dict_type",
293
+ "FULL_STATE_DICT",
294
+ ]
295
+ else:
296
+ # Plain DDP across the train GPUs (replicate, no sharding) — needs the explicit --multi_gpu.
297
+ cmd.insert(2, "--multi_gpu")
298
+ cmd += ["-m", worker_module]
299
+ return cmd
300
+
301
+
302
+ def is_main_rank(env: dict | None = None) -> bool:
303
+ """True on the rank that must write artifacts (adapter/metrics/DONE/upload).
304
+
305
+ Single-process paths (colocate, train_gpus==1) set no RANK -> "0" -> main, so existing behavior
306
+ is unchanged; under ``accelerate launch`` only RANK 0 writes, avoiding N concurrent HF uploads.
307
+ """
308
+ env = env if env is not None else os.environ
309
+ return str(env.get("RANK", "0")) == "0"
310
+
311
+
312
+ def trainer_only_mode(env: dict | None = None) -> bool:
313
+ """True inside the accelerate-launched trainer child (server already up; skip the launcher)."""
314
+ env = env if env is not None else os.environ
315
+ return str(env.get("AUTOSLM_RL_TRAINER_ONLY", "")) in ("1", "true", "True")
316
+
317
+
318
+ def server_subprocess_env(base_env: dict, split: RolloutSplit) -> dict:
319
+ """Env for the vllm-serve subprocess: pin it to the GLOBAL inference device indices.
320
+
321
+ Built from a COPY so the parent (trainer) can independently set its own CUDA_VISIBLE_DEVICES to
322
+ the train devices without affecting the already-launched server. The group port is exported so
323
+ the server's weight-sync extension and the trainer's client agree on the NCCL rendezvous.
324
+ """
325
+ env = dict(base_env)
326
+ env["CUDA_VISIBLE_DEVICES"] = _cvd(split.infer_devices)
327
+ env.setdefault("AUTOSLM_VLLM_GROUP_PORT", str(group_port()))
328
+ # Force vLLM's worker/inspection subprocesses to SPAWN (not fork). `trl vllm-serve` runs its
329
+ # llm_worker as a multiprocessing.Process and vLLM forks a further subprocess to inspect the
330
+ # model architecture; a fork after the parent has touched CUDA/NVML corrupts the NVML handle in
331
+ # the child -> `NVMLError_InvalidArgument` during ModelConfig inspection ("architectures failed
332
+ # to be inspected"). Spawn gives each child a clean CUDA/NVML state. (The colocate path is
333
+ # in-process so it never hit this.)
334
+ env.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
335
+ return env
336
+
337
+
338
+ def _server_log_tail(log_path: str | None, n: int = 60) -> str:
339
+ """Last ``n`` lines of the rollout server's log (its model-load crash lives here). The TRL
340
+ server only binds its HTTP port AFTER its llm_worker child loads the model + reports ready
341
+ (trl/scripts/vllm_serve.py lifespan), so a load crash shows as 'connection refused' on the
342
+ port while the real error is ONLY in this log — surface it so error_rl.txt is diagnosable."""
343
+ if not log_path:
344
+ return ""
345
+ try:
346
+ with open(log_path, errors="replace") as f:
347
+ lines = f.read().splitlines()
348
+ return "\n".join(lines[-n:])
349
+ except Exception as e:
350
+ return f"(server log unreadable: {e})"
351
+
352
+
353
+ def wait_for_server_health(
354
+ port: int,
355
+ *,
356
+ timeout: float,
357
+ proc: subprocess.Popen | None = None,
358
+ log_path: str | None = None,
359
+ interval: float = 3.0,
360
+ on_wait=None,
361
+ on_wait_every: float = 60.0,
362
+ ) -> None:
363
+ """Block until the rollout server answers ``/health/`` 200, the timeout elapses, or the
364
+ subprocess dies (fail fast — a dead server would otherwise hang the trainer at first generation).
365
+ On any failure the server log tail is appended (the HTTP port stays unbound until the worker
366
+ finishes loading the model, so a load/OOM crash surfaces only as 'connection refused').
367
+
368
+ ``on_wait`` (called every ``on_wait_every`` s while waiting) lets the caller emit a liveness
369
+ heartbeat during a long boot: a BIG model (35B bf16 ~70 GB + tilelang/CUDA-graph JIT) can take
370
+ >20 min to bind the port, and the control plane's no-heartbeat STALL detector (~25 min) would
371
+ otherwise kill the run mid-boot even though it is healthy-progressing."""
372
+ url = f"http://127.0.0.1:{port}/health/"
373
+ deadline = time.time() + timeout
374
+ last = None
375
+ # Fire the FIRST boot heartbeat promptly at loop entry, not one full ``on_wait_every`` in:
376
+ # the poller's stall clock may already be near its limit after the work between rl_start and
377
+ # server launch, so a 60s-late first ping could let it kill the run before any rl_server_boot.
378
+ _next_ping = time.time()
379
+ while time.time() < deadline:
380
+ if on_wait is not None and time.time() >= _next_ping:
381
+ with contextlib.suppress(Exception):
382
+ on_wait()
383
+ _next_ping = time.time() + on_wait_every
384
+ # ``on_wait`` (the worker's heartbeat) can BLOCK on a slow Hugging Face upload, so re-check
385
+ # liveness AND the deadline AFTER it returns: otherwise a blocking heartbeat would both mask
386
+ # a dead vllm-serve process and let the loop overrun ``timeout`` (the while-condition only
387
+ # re-checks at the top of the NEXT iteration).
388
+ if proc is not None and proc.poll() is not None:
389
+ raise RuntimeError(
390
+ f"vllm-serve exited (code {proc.returncode}) before becoming healthy.\n"
391
+ f"--- vllm-serve log tail ---\n{_server_log_tail(log_path)}"
392
+ )
393
+ if time.time() >= deadline:
394
+ break
395
+ try:
396
+ with urllib.request.urlopen(url, timeout=interval) as r:
397
+ if 200 <= r.status < 300:
398
+ return
399
+ except urllib.error.HTTPError as e:
400
+ # Only a 2xx on /health/ means ready. vLLM routes (and returns 4xx on) endpoints while
401
+ # the engine is still loading, so a 4xx is NOT healthy — keep polling until a real 200
402
+ # (or the timeout / a dead subprocess), rather than handing the trainer a server that
403
+ # then fails at the first generation.
404
+ last = f"HTTP {e.code}"
405
+ except Exception as e: # connection refused while still loading
406
+ last = str(e)[:80]
407
+ time.sleep(interval)
408
+ raise TimeoutError(
409
+ f"vllm-serve not healthy after {timeout:.0f}s (last: {last}).\n"
410
+ f"--- vllm-serve log tail ---\n{_server_log_tail(log_path)}"
411
+ )
412
+
413
+
414
+ def launch_vllm_server(
415
+ cmd: list[str], env: dict, *, log_path: str = "/tmp/vllm_serve.log"
416
+ ) -> subprocess.Popen:
417
+ """Start the rollout server subprocess, streaming its stdout/stderr to ``log_path`` (so a
418
+ server-side load/OOM is recoverable from the run log on a rented node)."""
419
+ log = open(log_path, "wb") # noqa: SIM115 — handle lives with the long-running subprocess
420
+ print(f"[rl][disagg] launching rollout server: {' '.join(cmd)}")
421
+ print(f"[rl][disagg] server CUDA_VISIBLE_DEVICES={env.get('CUDA_VISIBLE_DEVICES')} log={log_path}")
422
+ return subprocess.Popen(cmd, env=env, stdout=log, stderr=subprocess.STDOUT)
423
+
424
+
425
+ def terminate_server(proc: subprocess.Popen | None, *, timeout: float = 15.0) -> None:
426
+ """Best-effort shutdown of the rollout server after training (free its GPU + port)."""
427
+ if proc is None or proc.poll() is not None:
428
+ return
429
+ try:
430
+ proc.terminate()
431
+ proc.wait(timeout=timeout)
432
+ except Exception:
433
+ with contextlib.suppress(Exception):
434
+ proc.kill()
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/rollout_bench.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trainer:inference GPU-split selection + the ratio-benchmark grid for disaggregated GRPO.
2
+
3
+ Pure logic (no torch / no provisioning): given a node's GPU ``count`` and the number of
4
+ ``inference_gpus`` to dedicate to the vLLM rollout server, decide the rollout MODE and the
5
+ ``CUDA_VISIBLE_DEVICES`` split for trainer vs inference. ``ratio_grid`` enumerates the *reasonable*
6
+ trainer:inference splits within a node for the benchmark sweep (colocate, 1:1, 1:2, 2:1, ...) —
7
+ deliberately excluding absurd splits (e.g. 7 train : 1 infer).
8
+
9
+ The live worker (``engine.worker.run_rl``) consumes :func:`select_rollout_split` to launch
10
+ ``trl vllm-serve`` on the inference devices and the FSDP trainer on the rest; this module stays
11
+ GPU-free so the split math + grid are unit-testable on CPU.
12
+
13
+ verl ref (3D-HybridEngine / flexible device mapping): https://github.com/verl-project/verl
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass
19
+
20
+ # Don't dedicate more than this fraction of a node to one side — keeps the sweep to "reasonable"
21
+ # splits. A 3:1 (or 1:3) imbalance is the practical ceiling; beyond that the small side starves.
22
+ _MAX_RATIO = 3
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class RolloutSplit:
27
+ """How a node's GPUs are partitioned for one GRPO config."""
28
+
29
+ mode: str # "colocate" (vLLM shares the trainer GPU) | "disaggregated" (separate infer GPUs)
30
+ total_gpus: int
31
+ train_gpus: int
32
+ infer_gpus: int
33
+ train_devices: tuple[int, ...]
34
+ infer_devices: tuple[int, ...]
35
+
36
+ @property
37
+ def label(self) -> str:
38
+ if self.mode == "colocate":
39
+ return "colocate"
40
+ return f"{self.train_gpus}:{self.infer_gpus}"
41
+
42
+
43
+ def select_rollout_split(total_gpus: int, inference_gpus: int) -> RolloutSplit:
44
+ """Partition ``total_gpus`` into a trainer set + an inference (vLLM-server) set.
45
+
46
+ ``inference_gpus == 0`` → colocate (the current single-process TRL path; vLLM shares device 0).
47
+ ``inference_gpus > 0`` → disaggregated: the FIRST ``inference_gpus`` devices serve vLLM, the
48
+ rest train. The vLLM server is pinned to device 0 deliberately: vLLM's model-inspection probe
49
+ queries NVML by the *physical* device id of its first visible card, and NVML (which respects
50
+ CUDA_VISIBLE_DEVICES) only exposes the restricted set — so a server pinned to a non-zero device
51
+ (e.g. CVD="1") makes vLLM query NVML index 1 in a 1-device view → NVMLError_InvalidArgument
52
+ ("architectures failed to be inspected"). Putting inference on device 0 keeps that query at the
53
+ always-valid index 0. The trainer (in-process torch, no vLLM inspection) handles a non-zero CVD
54
+ fine. Raises on an impossible split so a bad config fails fast at setup rather than mid-run.
55
+ """
56
+ if total_gpus < 1:
57
+ raise ValueError(f"total_gpus must be >= 1, got {total_gpus}")
58
+ if inference_gpus < 0:
59
+ raise ValueError(f"inference_gpus must be >= 0, got {inference_gpus}")
60
+ if inference_gpus == 0:
61
+ return RolloutSplit(
62
+ mode="colocate",
63
+ total_gpus=total_gpus,
64
+ train_gpus=total_gpus,
65
+ infer_gpus=0,
66
+ train_devices=tuple(range(total_gpus)),
67
+ infer_devices=(),
68
+ )
69
+ if inference_gpus >= total_gpus:
70
+ raise ValueError(
71
+ f"inference_gpus ({inference_gpus}) must be < total_gpus ({total_gpus}); "
72
+ "at least one GPU must train"
73
+ )
74
+ train_gpus = total_gpus - inference_gpus
75
+ return RolloutSplit(
76
+ mode="disaggregated",
77
+ total_gpus=total_gpus,
78
+ train_gpus=train_gpus,
79
+ infer_gpus=inference_gpus,
80
+ # Inference on the FIRST devices (server gets device 0 → NVML index 0, always valid);
81
+ # trainer on the rest.
82
+ train_devices=tuple(range(inference_gpus, total_gpus)),
83
+ infer_devices=tuple(range(inference_gpus)),
84
+ )
85
+
86
+
87
+ def validate_disaggregated_requirement(
88
+ *, requires_disaggregated: bool, algorithm: str, inference_gpus: int
89
+ ) -> None:
90
+ """Reject colocated GRPO for a model that needs the disaggregated path.
91
+
92
+ A ``requires_disaggregated`` model (e.g. Qwen3.6-35B-A3B) OOMs when the trainer and the vLLM
93
+ rollout share one GPU, so its GRPO runs must dedicate inference GPUs (``inference_gpus>0`` on a
94
+ multi-GPU node). SFT has no rollout engine and is unaffected. Raising here fails a bad config at
95
+ submit instead of mid-run on a paid GPU.
96
+ """
97
+ if requires_disaggregated and (algorithm or "").lower() == "grpo" and inference_gpus <= 0:
98
+ raise ValueError(
99
+ "this model requires the disaggregated GRPO path: set [train].inference_gpus>0 on a "
100
+ "multi-GPU node ([gpu] count = train_gpus + inference_gpus). Colocated GRPO OOMs for it."
101
+ )
102
+
103
+
104
+ def ratio_grid(max_gpus: int = 4) -> list[RolloutSplit]:
105
+ """The reasonable (train:infer) configs to benchmark, in a sensible order.
106
+
107
+ Always starts with ``colocate`` (1 GPU, the baseline), then the 2..``max_gpus`` node splits with
108
+ both sides >= 1 and the imbalance bounded by ``_MAX_RATIO`` (so no 7:1). Ordered by total GPUs,
109
+ then by infer count, so the table reads colocate → 1:1 → 1:2 → 2:1 → 3:1 → ...
110
+ """
111
+ grid = [select_rollout_split(1, 0)] # colocate baseline
112
+ seen = {grid[0].label}
113
+ for total in range(2, max_gpus + 1):
114
+ for infer in range(1, total):
115
+ train = total - infer
116
+ if max(train, infer) / min(train, infer) > _MAX_RATIO:
117
+ continue
118
+ split = select_rollout_split(total, infer)
119
+ if split.label not in seen:
120
+ seen.add(split.label)
121
+ grid.append(split)
122
+ # colocate first, then by (total gpus, infer gpus) for a readable sweep
123
+ head, tail = grid[0], grid[1:]
124
+ tail.sort(key=lambda s: (s.total_gpus, s.infer_gpus))
125
+ return [head, *tail]
code/autoslm/engine/verl_runner.py ADDED
@@ -0,0 +1,695 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """verl GRPO + LoRA runner (AUTOSLM_FRAMEWORK=verl).
2
+
3
+ Runs verl in a SIDECAR venv on the provisioned box, isolated from the baked TRL/vLLM
4
+ stack (baked = torch 2.10 + vllm 0.19.1 + transformers 5; verl needs vllm<=0.12 +
5
+ transformers<5 — hard conflict, so a clean venv). Benchmarks verl's one-step-off async
6
+ overlap WITH LoRA (the path TRL's AsyncGRPOTrainer can't do — it's full-FT-only).
7
+
8
+ Single GPU (inference_gpus=0): verl.trainer.main_ppo colocate (hybrid_engine, no overlap)
9
+ -> apples-to-apples vs our TRL colocate s/step.
10
+ >=2 GPU (inference_gpus>0): verl.experimental.one_step_off_policy.main_ppo, hybrid_engine=False
11
+ -> the real generation<->training OVERLAP (gen(t+1) overlaps train(t)).
12
+
13
+ Writes /tmp/metrics.json in the shape the autoslm pipeline reads
14
+ ({wall_seconds, notes:{steps,...}, reward_history}).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import re
22
+ import subprocess
23
+ import sys
24
+ import threading
25
+ import time
26
+
27
+ VENV = "/opt/verl-venv"
28
+ VPY = f"{VENV}/bin/python"
29
+ VPIP = f"{VENV}/bin/pip"
30
+ VERL_DIR = "/opt/verl"
31
+ WORKDIR = "/tmp/verl"
32
+ # The python verl actually runs with. OLD stack -> the sidecar venv (VPY). BAKED stack -> the SYSTEM
33
+ # python (sys.executable), reusing the baked torch/vllm/transformers/torchvision (all matching), since
34
+ # a --system-site-packages venv + uv reinstalls torch and breaks the baked torchvision. Set by _install.
35
+ RUN_PY = VPY
36
+
37
+
38
+ def _hb(stage: str, **kw):
39
+ try:
40
+ from autoslm.engine.worker import heartbeat
41
+
42
+ heartbeat(stage, **kw)
43
+ except Exception:
44
+ print(f"[verl][hb] {stage} {kw}", flush=True)
45
+
46
+
47
+ def _spec():
48
+ from autoslm.engine import worker as W
49
+
50
+ return W.JOB_SPEC
51
+
52
+
53
+ def _run(cmd, cwd=None, env=None, check=True, capture=False):
54
+ print(f"[verl] $ {cmd if isinstance(cmd, str) else ' '.join(map(str, cmd))}", flush=True)
55
+ r = subprocess.run(
56
+ cmd, cwd=cwd, env=env, shell=isinstance(cmd, str),
57
+ text=True, capture_output=capture,
58
+ )
59
+ if capture:
60
+ if r.stdout:
61
+ print(r.stdout[-4000:], flush=True)
62
+ if r.stderr:
63
+ print(r.stderr[-4000:], flush=True)
64
+ if check and r.returncode != 0:
65
+ raise RuntimeError(f"command failed (rc={r.returncode}): {cmd if isinstance(cmd,str) else ' '.join(map(str,cmd))}")
66
+ return r
67
+
68
+
69
+ def _ensure_uv() -> str:
70
+ """Return a path to `uv` (creates venvs without python3-venv/ensurepip, installs fast).
71
+ Prefer one already on the image; else bootstrap via system pip, else the standalone installer."""
72
+ import shutil
73
+
74
+ def _find():
75
+ cands = ["uv", os.path.expanduser("~/.local/bin/uv"), "/root/.local/bin/uv",
76
+ "/usr/local/bin/uv", "/opt/uv/uv"]
77
+ for c in cands:
78
+ p = shutil.which(c) if "/" not in c else (c if os.path.exists(c) else None)
79
+ if p:
80
+ return p
81
+ return None
82
+
83
+ p = _find()
84
+ if p:
85
+ return p
86
+ for pipcmd in ([sys.executable, "-m", "pip", "install", "-q", "uv"], ["pip", "install", "-q", "uv"]):
87
+ if subprocess.run(pipcmd, capture_output=True, text=True).returncode == 0:
88
+ break
89
+ p = _find()
90
+ if p:
91
+ return p
92
+ subprocess.run("curl -LsSf https://astral.sh/uv/install.sh | sh", shell=True)
93
+ p = _find()
94
+ if p:
95
+ return p
96
+ raise RuntimeError("could not obtain uv for the verl sidecar venv")
97
+
98
+
99
+ def _install():
100
+ """Install the verl stack and return the python executable verl should run with.
101
+
102
+ OLD stack (default): a fresh uv venv with PUBLIC-PyPI vllm 0.11 + transformers 4.57 + a MATCHING
103
+ torchvision -> MiniCPM/Qwen2.5/Qwen3-dense. Cannot load the qwen3_5 arch.
104
+ BAKED stack (AUTOSLM_VERL_USE_BAKED_STACK=1): for Qwen3.5/3.6. The baked image's vllm 0.19.1 +
105
+ transformers 5 + torch + torchvision are INTERNAL builds (not on PyPI) and MUTUALLY MATCHED.
106
+ Install verl + its non-baked deps straight into the SYSTEM python (no venv) so all of them are
107
+ reused as-is. (A --system-site-packages venv + uv reinstalls torch and breaks the baked
108
+ torchvision -> `operator torchvision::nms does not exist`.)
109
+ """
110
+ global RUN_PY
111
+ # BAKED is the DEFAULT: the host-matched vllm0.19.1/tf5 boots reliably and loads every model we
112
+ # benchmark (MiniCPM/Qwen2.5/Qwen3-dense AND Qwen3.5/3.6). The OLD uv-venv stack (set
113
+ # AUTOSLM_VERL_USE_BAKED_STACK=0) installs fresh vllm0.11 wheels -> fragile torch/CUDA resolution
114
+ # (vllm==0.11.0 install now fails outright) -> retired as the default.
115
+ use_baked = os.environ.get("AUTOSLM_VERL_USE_BAKED_STACK", "1").strip().lower() in ("1", "true", "yes")
116
+ py = sys.executable if use_baked else VPY
117
+ RUN_PY = py
118
+ # Idempotency: if verl already imports under `py`, skip. Guard on the interpreter existing — the
119
+ # OLD-stack venv python won't exist on a fresh box (FileNotFoundError otherwise).
120
+ if os.path.exists(py):
121
+ chk = subprocess.run(
122
+ [py, "-c", "import verl, vllm, torch, transformers; print(vllm.__version__, torch.__version__, transformers.__version__)"],
123
+ text=True, capture_output=True,
124
+ )
125
+ if chk.returncode == 0:
126
+ print(f"[verl] stack ready ({py}): vllm/torch/transformers = {chk.stdout.strip()}", flush=True)
127
+ return py
128
+
129
+ verl_ref = os.environ.get("AUTOSLM_VERL_REF", "").strip()
130
+ vllm_pin = os.environ.get("AUTOSLM_VERL_VLLM", "vllm==0.11.0").strip()
131
+ tf_pin = os.environ.get("AUTOSLM_VERL_TRANSFORMERS", "transformers==4.57.0").strip()
132
+ fa_pin = os.environ.get("AUTOSLM_VERL_FLASHATTN", "flash-attn==2.8.1").strip()
133
+ tv_pin = os.environ.get("AUTOSLM_VERL_TORCHVISION", "torchvision==0.23.0").strip() # matches torch 2.8 (vllm 0.11)
134
+ uv = _ensure_uv()
135
+
136
+ # The baked system python is PEP-668 "externally managed" -> uv/pip refuse it without this flag.
137
+ bsp = ["--break-system-packages"] if use_baked else []
138
+
139
+ def upip(*pkgs, check=True):
140
+ return _run([uv, "pip", "install", "-p", py, *bsp, *pkgs], check=check, capture=True)
141
+
142
+ _hb("verl_install", step="venv", baked=use_baked)
143
+ if not use_baked:
144
+ # uv venv: no python3-venv/ensurepip needed (baked image lacks it).
145
+ _run([uv, "venv", VENV, "--python", sys.executable])
146
+ upip("pip", "setuptools", "wheel")
147
+ if not os.path.exists(os.path.join(VERL_DIR, "setup.py")) and not os.path.exists(os.path.join(VERL_DIR, "pyproject.toml")):
148
+ _hb("verl_install", step="clone")
149
+ clone = ["git", "clone", "--depth", "1"]
150
+ if verl_ref:
151
+ clone += ["--branch", verl_ref]
152
+ clone += ["https://github.com/verl-project/verl", VERL_DIR]
153
+ _run(clone, check=not verl_ref)
154
+ if not os.path.exists(os.path.join(VERL_DIR, "pyproject.toml")):
155
+ _run(["rm", "-rf", VERL_DIR], check=False)
156
+ _run(["git", "clone", "https://github.com/verl-project/verl", VERL_DIR])
157
+ if verl_ref:
158
+ _run(["git", "checkout", verl_ref], cwd=VERL_DIR)
159
+ if not use_baked:
160
+ _hb("verl_install", step="vllm_transformers", vllm=vllm_pin, transformers=tf_pin)
161
+ upip(vllm_pin, tf_pin) # vllm pins torch; resolve it first
162
+ # torchvision UNPINNED in a second pass so uv matches it to whatever torch vllm resolved
163
+ # (a hard pin like ==0.23.0 conflicts/flakes host-to-host); tv must match torch or nms op missing.
164
+ _tvr = upip("torchvision", check=False)
165
+ if _tvr.returncode != 0:
166
+ upip(tv_pin, check=False)
167
+ _hb("verl_install", step="flash_attn")
168
+ upip(fa_pin, "--no-build-isolation", check=False) # wheel; tolerate fail
169
+ else:
170
+ _hb("verl_install", step="baked_stack_reused", note="vllm/transformers/torch/torchvision from baked system python")
171
+ _hb("verl_install", step="deps")
172
+ # --no-deps on the ones likely to drag torch so the BAKED torch/torchvision are never disturbed;
173
+ # install their needed extras explicitly. On the OLD venv this is harmless (torch already pinned).
174
+ upip("ray[default]>=2.41.0", "tensordict>=0.8.0,<=0.10.0", "hydra-core", "omegaconf",
175
+ "datasets", "pyarrow", "pandas", "codetiming", "dill", "pylatexenc", "wandb",
176
+ "math_verify", "accelerate", "peft>=0.19", "torchdata", "torchmetrics")
177
+ # one_step_off async overlap transfers weights trainer->rollout via the NCCL checkpoint engine,
178
+ # which only REGISTERS if cupy + pyzmq import (else verl dies "Checkpoint engine nccl not
179
+ # registered"). Install them for the overlap path (heavy cupy wheel -> skip for plain colocate).
180
+ if os.environ.get("AUTOSLM_VERL_OVERLAP", "").strip().lower() in ("1", "true", "yes"):
181
+ _hb("verl_install", step="nccl_ckpt_engine_deps")
182
+ upip("cupy-cuda12x", "pyzmq", check=False)
183
+ _hb("verl_install", step="verl")
184
+ _run([uv, "pip", "install", "-p", py, *bsp, "--no-deps", "-e", "."], cwd=VERL_DIR)
185
+ _install_chalk(uv, py)
186
+ chk = _run([py, "-c", "import verl, vllm, torch, torchvision, transformers; print('verl-ok', vllm.__version__, torch.__version__, torchvision.__version__, transformers.__version__)"], capture=True, check=False)
187
+ print(f"[verl] install verified ({py}): {chk.stdout.strip()}", flush=True)
188
+ return py
189
+
190
+
191
+ # FLASH_* flags -> the freesolo-chalk class-level installer to call (install-on-call, no model needed).
192
+ # These patch the transformers Qwen3.5 model CLASS, so verl's actor model picks up the kernels.
193
+ _CHALK_CLASS_INSTALLERS = {
194
+ "FLASH_MLP_KERNEL": "install_qwen35_mlp",
195
+ "FLASH_QKV_KERNEL": "install_qwen35_qkv",
196
+ "FLASH_TRITON_LORA": "install_lora",
197
+ "FLASH_ROPE_KERNEL": "install_qwen35_rope",
198
+ }
199
+
200
+
201
+ def _install_chalk(uv, py):
202
+ """Keep our kernel optimizations (chalk) active in the verl path. chalk = the freesolo-chalk
203
+ package (hand-written Triton/CUDA Qwen3.5 kernels), install-on-call. We (a) install it via
204
+ FLASH_CHALK_SPEC, and (b) drop a sitecustomize.py in `py`'s site-packages that calls the selected
205
+ class-level installers at interpreter startup, so verl's actor model gets the kernels before build.
206
+ Best-effort + gated: no FLASH_* flag / no spec -> no-op. Only meaningful for Qwen3.5 (baked stack)."""
207
+ selected = [v for k, v in _CHALK_CLASS_INSTALLERS.items()
208
+ if os.environ.get(k, "").strip().lower() in ("1", "true", "yes")]
209
+ spec = os.environ.get("FLASH_CHALK_SPEC", "").strip()
210
+ if not selected and not spec:
211
+ return
212
+ _hb("verl_install", step="chalk", installers=selected)
213
+ if spec:
214
+ _run([uv, "pip", "install", "-p", py, spec], check=False, capture=True)
215
+ # sitecustomize runs at EVERY interpreter start (incl. verl + its ray workers), before the model is
216
+ # constructed -> the class-level kernel patches apply to verl's model.
217
+ r = subprocess.run([py, "-c", "import site;print(site.getsitepackages()[0])"], text=True, capture_output=True)
218
+ site_dir = r.stdout.strip() if r.returncode == 0 and r.stdout.strip() else None
219
+ if not site_dir or not os.path.isdir(site_dir):
220
+ print("[verl][chalk] no site-packages dir found; skipping sitecustomize", flush=True)
221
+ return
222
+ site_dirs = [site_dir]
223
+ calls = "\n".join(f" _c.{fn}()" for fn in selected)
224
+ sc = (
225
+ "import os\n"
226
+ "try:\n"
227
+ " import freesolo_chalk as _c\n"
228
+ f"{calls if calls else ' pass'}\n"
229
+ " print('[chalk] class-level kernels installed: ' + ','.join(%r))\n" % selected
230
+ + "except Exception as _e:\n"
231
+ " print('[chalk] sitecustomize skipped: ' + repr(_e))\n"
232
+ )
233
+ with open(os.path.join(site_dirs[0], "sitecustomize.py"), "w") as f:
234
+ f.write(sc)
235
+ print(f"[verl][chalk] wrote sitecustomize calling {selected}", flush=True)
236
+
237
+
238
+ def _build_dataset(model_path: str, n_rows: int, prompt_tokens: int):
239
+ """Synthetic GRPO dataset: ~prompt_tokens-long chat prompts + a simple rule reward.
240
+ Throughput (gen n*resp + train) dominates s/step, so a simple reward is fine for the bench."""
241
+ os.makedirs(WORKDIR, exist_ok=True)
242
+ import pandas as pd # baked image has pandas; if not, the sidecar does
243
+
244
+ # Build prompts COMFORTABLY UNDER max_prompt_length (~prompt_tokens). English ≈ 1.3 tok/word, so
245
+ # target ~0.55*prompt_tokens/1.3 words to stay well within the limit (avoids all-rows-filtered ->
246
+ # num_samples=0). truncation=right + filter_overlong_prompts=False in the config also protect this.
247
+ filler = ("Reason step by step about the following problem and give the final answer. " * 60)
248
+ words = filler.split()
249
+ approx = max(8, int(prompt_tokens * 0.55 / 1.3))
250
+ content = " ".join((words * (approx // len(words) + 1))[:approx])
251
+ rows = []
252
+ for i in range(n_rows):
253
+ rows.append({
254
+ "data_source": "autoslm_bench",
255
+ "prompt": [{"role": "user", "content": f"[{i}] {content}"}],
256
+ "ability": "bench",
257
+ "reward_model": {"style": "rule", "ground_truth": "x"},
258
+ "extra_info": {"index": i, "split": "train"},
259
+ })
260
+ df = pd.DataFrame(rows)
261
+ df.to_parquet(f"{WORKDIR}/train.parquet")
262
+ df.head(max(8, n_rows // 8)).to_parquet(f"{WORKDIR}/val.parquet")
263
+ print(f"[verl] dataset: {n_rows} rows, ~{prompt_tokens} prompt tok -> {WORKDIR}/train.parquet", flush=True)
264
+
265
+
266
+ def _write_reward():
267
+ """A trivial length-aware reward (verl custom_reward_function contract). Throughput bench
268
+ doesn't depend on the reward signal; this just exercises the scoring path."""
269
+ src = (
270
+ "def compute_score(data_source, solution_str, ground_truth, extra_info=None):\n"
271
+ " n = len(solution_str or '')\n"
272
+ " return 1.0 if n > 0 else 0.0\n"
273
+ )
274
+ with open(f"{WORKDIR}/verl_reward.py", "w") as f:
275
+ f.write(src)
276
+
277
+
278
+ def _build_cmd(model_path, split, *, group_size, prompt_len, resp_len, lora_rank, lora_alpha, steps, train_bs):
279
+ overlap = split.infer_gpus > 0
280
+ if overlap:
281
+ entry = ["-m", "verl.experimental.one_step_off_policy.main_ppo",
282
+ "--config-path=config", "--config-name=one_step_off_ppo_trainer"]
283
+ else:
284
+ entry = ["-m", "verl.trainer.main_ppo"]
285
+ ov = [
286
+ "algorithm.adv_estimator=grpo",
287
+ "algorithm.use_kl_in_reward=False",
288
+ f"data.train_files={WORKDIR}/train.parquet",
289
+ f"data.val_files={WORKDIR}/val.parquet",
290
+ f"data.train_batch_size={train_bs}",
291
+ f"data.max_prompt_length={prompt_len}",
292
+ f"data.max_response_length={resp_len}",
293
+ "data.filter_overlong_prompts=False", # never drop rows (would zero the dataset -> num_samples=0)
294
+ "data.truncation=right", # truncate instead of erroring on length
295
+ "data.dataloader_num_workers=0", # no dataloader worker threads (Vast pids cap is tight)
296
+ f"actor_rollout_ref.model.path={model_path}",
297
+ # MiniCPM / custom-arch models load via remote code -> without this the vLLM EngineCore dies
298
+ # at startup ("Failed core proc(s): {}"). Harmless for natively-supported archs.
299
+ "actor_rollout_ref.model.trust_remote_code=True",
300
+ "actor_rollout_ref.model.use_remove_padding=True",
301
+ "actor_rollout_ref.model.enable_gradient_checkpointing=True",
302
+ f"actor_rollout_ref.model.lora_rank={lora_rank}",
303
+ f"actor_rollout_ref.model.lora_alpha={lora_alpha}",
304
+ # all-linear LoRA-wraps EVERY nn.Linear incl. Qwen3.5's VISION tower -> the one_step_off
305
+ # bucketed weight-transfer then sends vision 'qkv.base_layer.weight' which vLLM's qwen3_vl
306
+ # load_weights rejects (KeyError). Set AUTOSLM_VERL_TARGET_MODULES to a language-only list
307
+ # (e.g. "[q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj]") for Qwen3.5 async.
308
+ f"actor_rollout_ref.model.target_modules={os.environ.get('AUTOSLM_VERL_TARGET_MODULES', 'all-linear').strip()}",
309
+ "actor_rollout_ref.actor.optim.lr=1e-5",
310
+ f"actor_rollout_ref.actor.ppo_mini_batch_size={max(8, train_bs // 2)}",
311
+ "actor_rollout_ref.actor.use_kl_loss=True",
312
+ "actor_rollout_ref.actor.kl_loss_coef=0.001",
313
+ "actor_rollout_ref.actor.kl_loss_type=low_var_kl",
314
+ "actor_rollout_ref.actor.entropy_coeff=0",
315
+ # FSDP2 (DTensor) — the strategy selector is actor.strategy, NOT fsdp_config.strategy.
316
+ # FSDP1 (the default) on a SINGLE GPU is NO_SHARD, and verl's vLLM weight-sync summons
317
+ # full params with offload_to_cpu=True -> "offload_to_cpu=True and NO_SHARD is not supported".
318
+ # FSDP2 syncs via DTensor.full_tensor and avoids that codepath entirely.
319
+ "actor_rollout_ref.actor.strategy=fsdp2",
320
+ "actor_rollout_ref.ref.strategy=fsdp2",
321
+ # verl requires explicit micro-batch sizes (or use_dynamic_bsz). Set small per-GPU micro-batches.
322
+ "actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=4",
323
+ "actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=8",
324
+ "actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=8",
325
+ "actor_rollout_ref.rollout.name=vllm",
326
+ f"actor_rollout_ref.rollout.n={group_size}",
327
+ "actor_rollout_ref.rollout.temperature=1.0",
328
+ f"actor_rollout_ref.rollout.response_length={resp_len}",
329
+ # CAP vLLM's max_model_len to the ACTUAL prompt+response budget. Without this the rollout
330
+ # vLLM defaults to the model's full context (Qwen3.5 = 262144) and sizes its KV cache for a
331
+ # 256K-token request -> "KV cache needed (3.04 GiB) > available" -> EngineCore dies before
332
+ # step 0. This was THE async-rollout blocker (host-independent; verified across 4 GPU classes).
333
+ f"actor_rollout_ref.rollout.max_model_len={prompt_len + resp_len}",
334
+ "actor_rollout_ref.rollout.gpu_memory_utilization=0.4",
335
+ "actor_rollout_ref.rollout.enforce_eager=True", # skip CUDA-graph capture (lighter/faster vLLM init)
336
+ "actor_rollout_ref.rollout.load_format=safetensors",
337
+ "actor_rollout_ref.rollout.layered_summon=True",
338
+ # Rollout parallelism: DEFAULT TP=1 so verl auto-runs dp=infer_gpus INDEPENDENT vLLM replicas
339
+ # (data-parallel), NOT a tensor-sharded engine. TP=infer_gpus all-reduces every layer/token —
340
+ # pure comm waste on small models (TP=2 on 0.8B made 4-GPU SLOWER than 2-GPU). DP scales
341
+ # rollout throughput with zero per-token cross-GPU comm. Big models that don't fit one card
342
+ # set AUTOSLM_VERL_ROLLOUT_TP=2+ to shard. (dense DP is fully supported by verl/modern vLLM.)
343
+ f"actor_rollout_ref.rollout.tensor_model_parallel_size={int(os.environ.get('AUTOSLM_VERL_ROLLOUT_TP', '1'))}",
344
+ # Two reward paths exist. The STANDARD reward manager reads top-level custom_reward_function.*;
345
+ # the async-server AgentLoop/RewardLoop (what colocate uses, since rollout boots a vLLMHttpServer)
346
+ # reads reward.custom_reward_function.* and otherwise routes by data_source -> "Reward function
347
+ # is not implemented for data_source='autoslm_bench'". Set BOTH so whichever path runs is wired.
348
+ f"custom_reward_function.path={WORKDIR}/verl_reward.py",
349
+ "custom_reward_function.name=compute_score",
350
+ f"reward.custom_reward_function.path={WORKDIR}/verl_reward.py",
351
+ "reward.custom_reward_function.name=compute_score",
352
+ "trainer.logger=[console]",
353
+ "trainer.val_before_train=False",
354
+ "trainer.nnodes=1",
355
+ f"trainer.total_training_steps={steps}",
356
+ "trainer.save_freq=-1",
357
+ "trainer.test_freq=-1",
358
+ "trainer.project_name=autoslm_verl",
359
+ ]
360
+ if overlap:
361
+ ov += [
362
+ "actor_rollout_ref.hybrid_engine=False",
363
+ "critic.strategy=fsdp2",
364
+ # verl FSDP2 loads the base model fp32 by default (FSDPEngineConfig.model_dtype="fp32") ->
365
+ # LoRA trainable params stay fp32 (grad_dtype=fp32) but the bf16 autocast backward emits
366
+ # bf16 grads -> "assign a gradient with dtype BFloat16 to a tensor with grad_dtype Float"
367
+ # (verl #3470/#2969). Load base+LoRA in bf16 so grad_dtype==grad dtype==bf16. (colocate's
368
+ # known-good LoRA path sets this; one_step_off's config never exercised LoRA -> inherits fp32.)
369
+ "actor_rollout_ref.actor.fsdp_config.model_dtype=bf16",
370
+ f"trainer.n_gpus_per_node={split.train_gpus}",
371
+ "rollout.nnodes=1",
372
+ f"rollout.n_gpus_per_node={split.infer_gpus}",
373
+ # Rollout vLLM executor. DEFAULT = mp (MultiprocExecutor) — the SAME path colocate uses,
374
+ # which WORKS on Vast hosts that allow the pidfd_getfd syscall (CUDA IPC); pidfd is
375
+ # HOST-dependent seccomp, so retry async across hosts to land on a permissive one. The
376
+ # Ray executor (AUTOSLM_VERL_ROLLOUT_EXECUTOR=ray) dodges pidfd but CONFLICTS with verl's
377
+ # one_step_off placement groups ("Current node has no GPU available"), so it's opt-in only.
378
+ ]
379
+ if os.environ.get("AUTOSLM_VERL_ROLLOUT_EXECUTOR", "mp").strip().lower() == "ray":
380
+ ov += [
381
+ "+actor_rollout_ref.rollout.engine_kwargs.vllm.distributed_executor_backend=ray",
382
+ ]
383
+ else:
384
+ ov += [f"trainer.n_gpus_per_node={split.train_gpus or 1}"]
385
+ # Escape hatch: space-separated extra hydra overrides via env (test verl config fixes without a
386
+ # code change), e.g. AUTOSLM_VERL_EXTRA_OVERRIDES="actor_rollout_ref.actor.fsdp_config.mixed_precision.param_dtype=bf16".
387
+ _extra = os.environ.get("AUTOSLM_VERL_EXTRA_OVERRIDES", "").strip()
388
+ if _extra:
389
+ ov += _extra.split()
390
+ return [RUN_PY] + entry + ov
391
+
392
+
393
+ def run():
394
+ from autoslm.engine import worker as W
395
+ from autoslm.engine.disaggregated import detect_total_gpus
396
+ from autoslm.engine.rollout_bench import select_rollout_split
397
+
398
+ t0 = time.time()
399
+ _hb("rl_start")
400
+ spec = _spec()
401
+ tr = spec.train
402
+ model_id = spec.model
403
+ group_size = int(getattr(tr, "group_size", 8) or 8)
404
+ max_len = int(getattr(tr, "max_length", 2048) or 2048)
405
+ resp_len = int(getattr(tr, "max_tokens", 1024) or 1024)
406
+ prompt_len = max(256, max_len - resp_len)
407
+ steps = int(getattr(tr, "steps", 12) or 12)
408
+ lora_rank = int(getattr(tr, "lora_rank", 0) or 32)
409
+ lora_alpha = int(getattr(tr, "lora_alpha", 0) or (2 * lora_rank))
410
+ inf = int(getattr(tr, "inference_gpus", 0) or 0)
411
+ inf = int(os.environ.get("AUTOSLM_INFERENCE_GPUS", inf))
412
+ train_bs = 32
413
+
414
+ # Tell _install whether to pull the NCCL-checkpoint-engine deps (cupy/pyzmq) for the overlap path.
415
+ os.environ["AUTOSLM_VERL_OVERLAP"] = "1" if inf > 0 else "0"
416
+ _hb("verl_install", note="sidecar venv + verl stack (slow cold start)")
417
+ _install()
418
+
419
+ _hb("verl_prefetch")
420
+ W.prefetch_model(model_id)
421
+ # local HF snapshot dir
422
+ model_path = model_id
423
+ try:
424
+ from huggingface_hub import snapshot_download
425
+
426
+ model_path = snapshot_download(model_id)
427
+ except Exception as e:
428
+ print(f"[verl] snapshot_download fallback to id ({e})", flush=True)
429
+
430
+ total = detect_total_gpus()
431
+ split = select_rollout_split(total, inf) if inf > 0 else type("S", (), {"train_gpus": total or 1, "infer_gpus": 0})()
432
+ print(f"[verl] total_gpus={total} inference_gpus={inf} -> train={getattr(split,'train_gpus','?')} infer={getattr(split,'infer_gpus','?')} "
433
+ f"({'one-step-off OVERLAP' if inf>0 else 'colocate (no overlap)'})", flush=True)
434
+
435
+ _build_dataset(model_path, n_rows=max(64, train_bs * 4), prompt_tokens=prompt_len)
436
+ _write_reward()
437
+
438
+ cmd = _build_cmd(model_path, split, group_size=group_size, prompt_len=prompt_len,
439
+ resp_len=resp_len, lora_rank=lora_rank, lora_alpha=lora_alpha,
440
+ steps=steps, train_bs=train_bs)
441
+ env = dict(os.environ)
442
+ env["VLLM_USE_V1"] = env.get("VLLM_USE_V1", "1")
443
+ env["HF_HUB_DISABLE_XET"] = "1"
444
+ env["HYDRA_FULL_ERROR"] = "1" # full trace incl. the vLLM EngineCore root cause
445
+ env["VLLM_ENGINE_ITERATION_TIMEOUT_S"] = env.get("VLLM_ENGINE_ITERATION_TIMEOUT_S", "1800")
446
+ # verl/ray must SEE ALL GPUs (one_step_off splits them into trainer+rollout pools itself). The
447
+ # worker may have pre-pinned CUDA_VISIBLE_DEVICES to a subset (the TRL disaggregated split) ->
448
+ # ray then reports "Total available GPUs 0". Expose every GPU to verl.
449
+ if total and total > 0:
450
+ env["CUDA_VISIBLE_DEVICES"] = ",".join(str(i) for i in range(total))
451
+ # vLLM's CuMemAllocator (sleep-mode memory pool — verl colocate uses it to offload base weights
452
+ # while the actor steps) HARD-ASSERTS expandable_segments is OFF. The baked image ships
453
+ # PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True -> the vLLM rollout EngineCore dies at startup
454
+ # with "Expandable segments are not compatible with memory pool" (Failed core proc(s): {}).
455
+ # Strip ONLY the expandable_segments token (keep any other alloc knobs) for the verl subprocess.
456
+ _alloc = env.get("PYTORCH_CUDA_ALLOC_CONF", "")
457
+ _kept = [p for p in _alloc.split(",") if p.strip() and "expandable_segments" not in p]
458
+ if _kept:
459
+ env["PYTORCH_CUDA_ALLOC_CONF"] = ",".join(_kept)
460
+ else:
461
+ env.pop("PYTORCH_CUDA_ALLOC_CONF", None)
462
+ env.pop("PYTHONPATH", None) # keep the sidecar clean of the baked stack
463
+ # Cheap/shared Vast containers ship a LOW soft process+fd limit. Ray's CoreWorker spawns a
464
+ # thread pool at init; when pthread_create hits RLIMIT_NPROC it THROWS -> C++ std::terminate ->
465
+ # SIGABRT ("Fatal Python error: Aborted", init_once.cold) that retries can't clear. Raise the
466
+ # soft limits to the hard cap (inherited by the verl child) so Ray/vLLM can spawn their threads.
467
+ try:
468
+ import resource
469
+
470
+ for _lim, _name in ((resource.RLIMIT_NPROC, "NPROC"), (resource.RLIMIT_NOFILE, "NOFILE")):
471
+ _soft, _hard = resource.getrlimit(_lim)
472
+ if _hard == resource.RLIM_INFINITY or _soft < _hard:
473
+ resource.setrlimit(_lim, (_hard, _hard))
474
+ print(f"[verl] raised RLIMIT_{_name} {_soft}->{_hard}", flush=True)
475
+ except Exception as _e:
476
+ print(f"[verl] rlimit bump skipped: {_e}", flush=True)
477
+ # Cap math-lib thread pools so the process doesn't fan out hundreds of threads on a Vast
478
+ # container with a low pids cap ("RuntimeError: can't start new thread" hit even on an A100 at
479
+ # the heavier matched config); verl/vLLM still parallelize on the GPU.
480
+ for _tv in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS"):
481
+ env.setdefault(_tv, "4")
482
+ # glibc spawns one heap arena PER thread by default (each reserves virtual memory) -> compounds
483
+ # the thread/memory pressure on a constrained container. Cap arenas to shrink the footprint.
484
+ env.setdefault("MALLOC_ARENA_MAX", "2")
485
+ # Multi-GPU (one_step_off async) NCCL: many Vast nodes are plain-PCIe with NO CUDA P2P between
486
+ # cards -> "peer access is not supported between these two devices" / NCCL_ERROR_UNHANDLED.
487
+ # Force NCCL onto the SHM/host path so cross-GPU weight transfer works without P2P.
488
+ if total and total > 1:
489
+ # Vast containers block CUDA peer access (cudaDeviceEnablePeerAccess -> "peer access is not
490
+ # supported between these two devices"), even on NVLink cards — it's the container sandbox,
491
+ # not the hardware. The cupy/ray-collective nccl checkpoint engine (trainer<->rollout weight
492
+ # transfer) hits this in NCCL's P2P AND SHM transports. Force NCCL onto the NET (socket)
493
+ # transport, which needs no peer access. (Set here AND best to also pass via [worker_env] so
494
+ # it reaches every Ray actor's env.)
495
+ # Container blocks CUDA peer access, BUT disabling SHM forces the slow TCP NET/socket transport
496
+ # -> the trainer DDP all-reduce crawls (2:2 update_actor 32s->138s = 4.3x, made 4-GPU SLOWER
497
+ # than 2-GPU). Keep SHM but force the LEGACY host-staged mmap path (NCCL_CUMEM_HOST_ENABLE=0):
498
+ # host-bounce SHM needs NO peer access yet is far faster than sockets. Only P2P stays disabled.
499
+ env.setdefault("NCCL_P2P_DISABLE", "1")
500
+ env.setdefault("NCCL_SHM_DISABLE", "0")
501
+ env.setdefault("NCCL_CUMEM_ENABLE", "0")
502
+ env.setdefault("NCCL_CUMEM_HOST_ENABLE", "0")
503
+ # vLLM's Ray executor (rollout) places a worker bundle that requests CPU:10 each; verl's own
504
+ # Ray actors already hold most of the box's CPUs -> "No available node types can fulfill
505
+ # resource request {'CPU': 10.0}". Tell Ray the node has plenty of CPUs (scheduling bookkeeping
506
+ # only; the box isn't actually CPU-bound) so the placement group is satisfiable.
507
+ env.setdefault("RAY_OVERRIDE_RESOURCES", json.dumps({"CPU": 64}))
508
+ # one_step_off async init (Ray placement groups + Ray-executor vLLM workers + weight transfer)
509
+ # is much slower than colocate -> give the first step a longer watchdog budget.
510
+ os.environ.setdefault("AUTOSLM_VERL_FIRST_STEP_TIMEOUT", "2400")
511
+
512
+ _hb("rl_train_start", setup_seconds=time.time() - t0)
513
+ log_path = "/tmp/verl_console.txt"
514
+ print(f"[verl] launching: {' '.join(map(str, cmd))}", flush=True)
515
+ # verl's console logger (trainer.logger=[console]) prints ONE line per training step via
516
+ # concat_dict_to_str: "step:N - perf/time_per_step:12.3 - actor/.. - .." (numeric keys only).
517
+ step_line_re = re.compile(r"\bstep:(\d+)\b")
518
+ tps_re = re.compile(r"(?:perf/time_per_step|timing_s/step|time_per_step)\s*[:=]\s*([0-9.eE+-]+)")
519
+ step_times: list[float] = [] # per-step wall times (s) when verl logs the perf key
520
+ seen_steps: set[int] = set() # step numbers seen — robust counter even if the timing key differs
521
+ train_t0 = [time.time()] # reset at each launch attempt; for the wall/steps fallback
522
+ stop = threading.Event()
523
+
524
+ def _beat():
525
+ while not stop.is_set():
526
+ _hb("verl_running", steps_seen=len(seen_steps), timed=len(step_times))
527
+ stop.wait(60)
528
+
529
+ th = threading.Thread(target=_beat, daemon=True)
530
+ th.start()
531
+
532
+ def _launch_once():
533
+ """Run verl once, streaming combined output to log_path. Returns (rc, aborted); appends
534
+ any timed steps to step_times. A watchdog kills a STALLED run (no first step within
535
+ FIRST_STEP_TIMEOUT, or no new step within STALL_TIMEOUT) so a hang (seen on the async
536
+ one_step_off path: stuck at step1 for 60-90 min) is terminated and its console is still
537
+ uploaded for diagnosis instead of burning GPU forever."""
538
+ aborted = False
539
+ with open(log_path, "w") as lf:
540
+ proc = subprocess.Popen(cmd, cwd=VERL_DIR, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
541
+ first_to = float(os.environ.get("AUTOSLM_VERL_FIRST_STEP_TIMEOUT", "1500")) # 25 min cold budget
542
+ stall_to = float(os.environ.get("AUTOSLM_VERL_STALL_TIMEOUT", "900")) # 15 min between steps
543
+ progress = [time.time(), 0] # [last-progress wallclock, step count at that time]
544
+ wd_stop = threading.Event()
545
+
546
+ def _watchdog():
547
+ while not wd_stop.wait(30):
548
+ n = len(seen_steps)
549
+ now = time.time()
550
+ if n > progress[1]:
551
+ progress[0], progress[1] = now, n
552
+ budget = first_to if n == 0 else stall_to
553
+ if now - progress[0] > budget:
554
+ print(f"[verl] WATCHDOG: no step progress in {int(budget)}s (steps_seen={n}) "
555
+ f"-> killing verl (hang)", flush=True)
556
+ _hb("verl_watchdog_kill", steps_seen=n)
557
+ try:
558
+ proc.kill()
559
+ except Exception:
560
+ pass
561
+ return
562
+
563
+ wt = threading.Thread(target=_watchdog, daemon=True)
564
+ wt.start()
565
+ for line in proc.stdout:
566
+ lf.write(line)
567
+ lf.flush()
568
+ print(line, end="", flush=True)
569
+ if "SIGABRT" in line or "Fatal Python error: Aborted" in line:
570
+ aborted = True
571
+ sm = step_line_re.search(line)
572
+ if sm:
573
+ snum = int(sm.group(1))
574
+ if snum not in seen_steps:
575
+ seen_steps.add(snum)
576
+ tm = tps_re.search(line)
577
+ if tm:
578
+ try:
579
+ step_times.append(float(tm.group(1)))
580
+ except ValueError:
581
+ pass
582
+ _hb("rl_step", step=snum, timed=len(step_times))
583
+ rc = proc.wait()
584
+ wd_stop.set()
585
+ return rc, aborted
586
+
587
+ # The vLLM async server intermittently SIGABRTs at startup (init_once.cold, "Fatal Python error:
588
+ # Aborted") BEFORE any step — a transient native-init race. Retry the whole verl launch a couple
589
+ # times when that happens; never re-run once we've already timed real steps.
590
+ max_attempts = 3
591
+ rc = 1
592
+ for attempt in range(max_attempts):
593
+ step_times.clear()
594
+ seen_steps.clear()
595
+ train_t0[0] = time.time()
596
+ rc, aborted = _launch_once()
597
+ if rc == 0 or seen_steps:
598
+ break
599
+ if aborted and attempt < max_attempts - 1:
600
+ print(f"[verl] vLLM SIGABRT at startup (attempt {attempt + 1}/{max_attempts}) -> retrying", flush=True)
601
+ _hb("verl_retry_abort", attempt=attempt + 1)
602
+ continue
603
+ break
604
+ stop.set()
605
+ train_wall = time.time() - train_t0[0]
606
+
607
+ # s/step preference: (1) verl's logged per-step times (drop step 0 warmup, average the rest);
608
+ # (2) fallback to train-phase wall / #steps when the perf key wasn't logged but steps DID run
609
+ # (excludes install/model-load/vLLM-boot since train_t0 is set right before the launch).
610
+ useful = step_times[1:] if len(step_times) > 1 else step_times
611
+ s_per_step = (sum(useful) / len(useful)) if useful else None
612
+ s_per_step_source = "verl_perf_key" if s_per_step is not None else None
613
+ if s_per_step is None and len(seen_steps) >= 2:
614
+ # avg over steps after the first (warmup) — approximate but real (timed steps actually ran)
615
+ s_per_step = train_wall / len(seen_steps)
616
+ s_per_step_source = "train_wall_div_steps"
617
+ wall = time.time() - t0
618
+ print(f"[verl] DONE rc={rc} steps_seen={len(seen_steps)} steps_timed={len(step_times)} "
619
+ f"s/step={s_per_step} ({s_per_step_source})", flush=True)
620
+ if rc != 0 and not seen_steps:
621
+ tail = ""
622
+ root = ""
623
+ try:
624
+ with open(log_path) as f:
625
+ lines = f.readlines()
626
+ tail = "".join(lines[-60:])
627
+ # The vLLM EngineCore dies in a SUBPROCESS whose error is printed BEFORE the outer
628
+ # "Engine core initialization failed" wrapper -> it gets pushed out of the tail. Hunt
629
+ # for the real root cause (OOM / CUDA / import / KV-cache) anywhere in the console.
630
+ markers = ("EngineCore failed", "EngineCore hit an exception", "Process EngineCore",
631
+ "(EngineCore", "EngineCore_", "failed to start", "Worker proc",
632
+ "CUDA error", "out of memory", "OutOfMemory", "No available memory",
633
+ "free memory", "KV cache", "GPU blocks", "No kernel image",
634
+ "ImportError", "ModuleNotFoundError", "ABI", "undefined symbol",
635
+ "does not exist", "not a supported", "Unrecognized", "trust_remote_code",
636
+ "RuntimeError:", "ValueError:", "AssertionError:", "KeyError:", "Cannot")
637
+ hits = [i for i, l in enumerate(lines) if any(m in l for m in markers)]
638
+ # exclude the generic outer wrapper lines so we land on the inner cause
639
+ hits = [i for i in hits if "Engine core initialization failed" not in lines[i]]
640
+ if hits:
641
+ lo = max(0, hits[0] - 4)
642
+ hi = min(len(lines), hits[0] + 25)
643
+ root = "".join(lines[lo:hi])
644
+ except Exception:
645
+ pass
646
+ # Surface verl's actual stderr in the raised error so it reaches the plane failure detail
647
+ # (the HF console upload may not happen on an early crash).
648
+ msg = f"verl run failed (rc={rc})."
649
+ if root:
650
+ msg += f"\n--- ROOT CAUSE region ---\n{root[-2500:]}"
651
+ msg += f"\n--- Last verl output ---\n{tail[-2500:]}"
652
+ raise RuntimeError(msg)
653
+
654
+ metrics = {
655
+ "wall_seconds": (s_per_step * steps) if s_per_step else wall,
656
+ "verl_s_per_step": s_per_step,
657
+ "verl_step_times": step_times,
658
+ "verl_s_per_step_source": s_per_step_source,
659
+ "verl_steps_seen": sorted(seen_steps),
660
+ "verl_train_wall": train_wall,
661
+ "notes": {"steps": steps, "framework": "verl",
662
+ "mode": "one_step_off_overlap" if inf > 0 else "colocate",
663
+ "model": model_id, "group_size": group_size, "lora_rank": lora_rank,
664
+ "inference_gpus": inf, "total_gpus": total},
665
+ "reward_history": [1.0] * max(len(step_times), len(seen_steps)),
666
+ }
667
+ with open("/tmp/metrics.json", "w") as f:
668
+ json.dump(metrics, f)
669
+ print(f"[verl] wrote /tmp/metrics.json: s/step={s_per_step}", flush=True)
670
+
671
+ # CRITICAL: the verl path returns early in worker.run_rl and bypasses the TRL _finalize, so
672
+ # nothing uploads the completion artifacts -> the control plane never sees the DONE sentinel and
673
+ # RESTARTS the run as an orphan (infinite re-run loop). Upload metrics.json + DONE here so the run
674
+ # is marked finished. ALWAYS upload the console too (the Vast bootstrap only uploads it on
675
+ # FAILURE, so a SUCCESSFUL run's step output — needed to verify the per-step timings — is
676
+ # otherwise lost).
677
+ try:
678
+ from autoslm.engine.worker import hf_upload_file
679
+
680
+ try:
681
+ hf_upload_file(log_path, "verl_console.txt")
682
+ except Exception as _e:
683
+ print(f"[verl] console upload warn: {_e}", flush=True)
684
+ hf_upload_file("/tmp/metrics.json", "metrics.json", required=True)
685
+ with open("/tmp/DONE", "w") as f:
686
+ f.write(str(time.time()))
687
+ hf_upload_file("/tmp/DONE", "DONE", required=True)
688
+ _hb("done")
689
+ print("[verl] uploaded metrics.json + DONE (run finalized)", flush=True)
690
+ except Exception as _e:
691
+ print(f"[verl] finalize upload FAILED ({_e}) -> plane may orphan-restart", flush=True)
692
+
693
+ return metrics
694
+ _hb("done", verl_s_per_step=s_per_step or 0.0)
695
+ return metrics
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,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ gpu_count: int = 1,
56
+ ) -> int:
57
+ """VRAM the full run needs, sized to the run's actual knobs (context length, LoRA
58
+ rank, batch / group size, thinking) via the shared ``model_required_vram_gb`` matrix.
59
+
60
+ Catalog GRPO floors stay hard floors (never under-provision a validated model); the
61
+ matrix sizes up from there for big contexts/groups and down to a cheaper card for
62
+ small runs. Unlisted open models size from HF metadata, falling back to the 24 GB tier
63
+ when unreadable (handled inside model_required_vram_gb)."""
64
+ from autoslm.engine.vram import model_required_vram_gb
65
+
66
+ colocate = model_required_vram_gb(
67
+ model_id,
68
+ algorithm,
69
+ train=train,
70
+ thinking=thinking,
71
+ headroom=vram_headroom(),
72
+ )
73
+ # Disaggregated GRPO ([train].inference_gpus>0) splits memory across the node's GPUs: the
74
+ # inference server (full bf16 weights + KV) and the trainer (quant weights + LoRA optimizer +
75
+ # activations) live on SEPARATE cards, so no single GPU needs the colocate total. The binding
76
+ # per-GPU need is max(server bf16 weights + KV/overhead, the trainer's share ~= colocate minus
77
+ # the vLLM engine/KV). Sizing to that lets a big model fit a per-role card (e.g. Qwen3.6-35B-A3B
78
+ # served bf16 on a 94GB H100 NVL, 4-bit trainer on the other) instead of demanding the colocate
79
+ # floor (~96GB) — which no available 2-GPU node meets — while staying FLOORED by the bf16 weights
80
+ # so the server can never be under-provisioned into an OOM. Also unblocks 4B 1:2 on a 5090 (the
81
+ # disaggregated server/trainer each fit 32GB though colocate 4B needs ~35GB).
82
+ if train is not None and int(getattr(train, "inference_gpus", 0) or 0) > 0:
83
+ pb = _params_b_for_vram(model_id)
84
+ if pb:
85
+ infer = max(1, int(getattr(train, "inference_gpus", 1) or 1))
86
+ # Total GPUs on the node (rollout + trainer). The trainer pool is everything that
87
+ # isn't a rollout GPU; default to a single trainer when the caller didn't pass a count
88
+ # (the colocate cap below still protects that degenerate case).
89
+ total = max(infer + 1, int(gpu_count or (infer + 1)))
90
+ n_trainer = max(1, total - infer)
91
+ base = 2.0 * pb # frozen base model, bf16, ALL params resident (MoE: every expert loaded)
92
+
93
+ # ROLLOUT card. The baked verl default is DATA-PARALLEL (TP=1) — each replica holds the
94
+ # FULL base + KV. A base too large to fit one 80GB card as a DP replica is served
95
+ # TENSOR-PARALLEL across the inference GPUs instead (verl_runner auto-bumps
96
+ # AUTOSLM_VERL_ROLLOUT_TP to match), so size per shard. Floors the per-card need so the
97
+ # inference GPU is never under-provisioned into a KV/weights OOM.
98
+ rollout_tp = infer if (base * 1.35 + 4) > 78 else 1
99
+ rollout_need = int(base * 1.35 / rollout_tp) + 4 # weights/shard + KV / CUDA-graph / overhead
100
+
101
+ # TRAINER card. FSDP2 shards the frozen base (+ tiny LoRA grads/optim) across the
102
+ # n_trainer trainer GPUs; activations and the one_step_off *bucketed* weight-transfer
103
+ # staging do NOT shard, so floor each card at base/n_trainer + a bounded transfer buffer +
104
+ # fixed overhead. n_trainer==1 keeps the whole base on one card (matches the observed 4B
105
+ # one-trainer OOM on a 24GB card — needed ~26GB, fits 40GB — while 4B sharded across two
106
+ # trainers fits 24GB). The bucketed sync stages only a few layers, NOT a full second copy,
107
+ # so 35B-A3B (70GB base) trains across 2 trainers at ~58GB/card and fits an 80GB H100/A100.
108
+ transfer_buf = min(0.5 * base, 10.0)
109
+ trainer_need = int(base / n_trainer + transfer_buf + 13)
110
+
111
+ # Per-card requirement is the heavier role on a homogeneous node. This is already a true
112
+ # per-card figure (both roles divided by their parallel degree), so no colocate cap — a
113
+ # multi-GPU FSDP/TP split legitimately needs LESS per card than the whole colocated total.
114
+ return max(rollout_need, trainer_need)
115
+ return colocate
116
+
117
+
118
+ def _params_b_for_vram(model_id: str) -> float | None:
119
+ """Param count (billions) for disaggregated VRAM sizing: catalog first, then HF metadata."""
120
+ from autoslm.engine.vram import fetch_hf_params_b, params_b_from_str
121
+
122
+ try:
123
+ from autoslm.catalog import get_model
124
+
125
+ pb = params_b_from_str(getattr(get_model(model_id), "params", None))
126
+ if pb:
127
+ return pb
128
+ except Exception:
129
+ pass
130
+ try:
131
+ return fetch_hf_params_b(model_id)
132
+ except Exception:
133
+ return None
134
+
135
+
136
+ def _runpod_candidates(need: int, pinned_gpu: str | None, allow_unval: bool) -> list[Candidate]:
137
+ """RunPod's fitting classes priced live (static fallback)."""
138
+ provider = get_provider("runpod")
139
+ out: list[Candidate] = []
140
+ for g in provider.gpu_classes():
141
+ if g.vram_gb < need:
142
+ continue
143
+ if pinned_gpu and g.name != pinned_gpu:
144
+ continue
145
+ if "runpod" not in g.validated_on and not allow_unval:
146
+ continue
147
+ out.append(
148
+ Candidate(
149
+ "runpod",
150
+ g.name,
151
+ provider.hourly_rate(g.name),
152
+ g.vram_gb,
153
+ "runpod" in g.validated_on,
154
+ )
155
+ )
156
+ return out
157
+
158
+
159
+ def _vast_candidates(
160
+ need: int,
161
+ pinned_gpu: str | None,
162
+ allow_unval: bool,
163
+ disk_gb: int,
164
+ exclude_machine_ids,
165
+ *,
166
+ required: bool,
167
+ num_gpus: int = 1,
168
+ ) -> tuple[list[Candidate], tuple]:
169
+ """Vast's fitting classes from the live offer book (cheapest per class).
170
+
171
+ Returns (candidates, full_offer_book). ``required`` (a hard ``provider="vast"``
172
+ pin) re-raises a search failure; otherwise it degrades to RunPod-only.
173
+ """
174
+ from autoslm.providers.base import GPU_INFO
175
+ from autoslm.providers.vast.jobs import MIN_DISK_GB, usable_offers
176
+
177
+ # When a larger class is pinned for a small model, search at the PINNED class's VRAM,
178
+ # not the (smaller) model requirement: the offer search returns the cheapest ``limit``
179
+ # offers from a VRAM floor, so a search at ``need`` can fill that window entirely with
180
+ # small cheap cards and never surface the pinned larger class. ``need`` is still the
181
+ # validity floor (allocate() rejects an undersized pin before we get here).
182
+ search_vram = max(need, GPU_INFO[pinned_gpu].vram_gb) if pinned_gpu else need
183
+ book: list = []
184
+ try:
185
+ # The offer search must use the SAME disk floor instances are actually
186
+ # provisioned with (``create_instance``/``_effective_disk_gb``); searching at a
187
+ # smaller requested ``disk_gb`` would surface offers that then fail to rent.
188
+ book = usable_offers(
189
+ search_vram, max(float(disk_gb), MIN_DISK_GB),
190
+ exclude_machine_ids=exclude_machine_ids, num_gpus=num_gpus,
191
+ )
192
+ except Exception as exc:
193
+ if required:
194
+ raise UnsupportedGpuError(f"vast offer search failed: {exc}") from exc
195
+ logger.warning("vast offer search failed (%s); allocating on runpod only", exc)
196
+ out: list[Candidate] = []
197
+ seen: set[str] = set()
198
+ for o in book:
199
+ if pinned_gpu and o.gpu != pinned_gpu:
200
+ continue
201
+ info = GPU_INFO[o.gpu]
202
+ if "vast" not in info.validated_on and not allow_unval:
203
+ continue
204
+ if o.gpu in seen: # offers are price-sorted; keep the cheapest per class
205
+ continue
206
+ seen.add(o.gpu)
207
+ out.append(
208
+ Candidate(
209
+ "vast", o.gpu, o.dph_total, info.vram_gb, "vast" in info.validated_on, offer=o
210
+ )
211
+ )
212
+ return out, tuple(book)
213
+
214
+
215
+ def allocate(
216
+ model_id: str,
217
+ algorithm: str,
218
+ *,
219
+ gpu: str | None = None,
220
+ provider: str = "auto",
221
+ disk_gb: int = 60,
222
+ allow_unvalidated: bool | None = None,
223
+ exclude_machine_ids: set[int] | frozenset[int] = frozenset(),
224
+ exclude_gpu_classes: set[str] | frozenset[str] = frozenset(),
225
+ gpu_count: int = 1,
226
+ train=None,
227
+ thinking: bool = False,
228
+ ) -> Allocation:
229
+ """Pick the cheapest (provider, GPU class) able to run the job across providers.
230
+
231
+ ``gpu`` pins the class (the allocator then only picks the provider); ``provider``
232
+ pins the substrate ("auto"/"runpod"/"vast"). Both default to fully automatic.
233
+ ``train``/``thinking`` size the requirement to the run's actual knobs (context, group,
234
+ rank, batch) via the matrix — long context / large group route up, small runs down.
235
+ ``exclude_gpu_classes`` drops whole GPU classes (any provider) from the candidate pool —
236
+ the orchestrator adds a class here after it failed ``no_capacity`` (capacity-starved /
237
+ throttled) so re-allocation walks to the next-cheapest AVAILABLE class instead of retrying
238
+ the same starved one on another provider.
239
+ """
240
+ _excluded_classes = {canonical_gpu(c) for c in exclude_gpu_classes}
241
+ if provider not in ("auto", *PROVIDER_NAMES):
242
+ raise UnsupportedGpuError(
243
+ f"unknown provider {provider!r} (auto, {', '.join(PROVIDER_NAMES)})"
244
+ )
245
+ pinned_gpu = canonical_gpu(gpu) if gpu else None
246
+ # The model's requirement is the floor regardless of a pin: an undersized concrete
247
+ # pin (e.g. Qwen3-8B on a 24 GB card) must drop out of the candidate filter and
248
+ # raise here, not provision a paid worker that OOMs. The pin only narrows WHICH
249
+ # fitting class is chosen, never lowers the VRAM bar.
250
+ need = required_vram_gb(model_id, algorithm, train=train, thinking=thinking, gpu_count=gpu_count)
251
+ allow_unval = unvalidated_allowed(allow_unvalidated)
252
+ live = available_providers()
253
+ if provider != "auto" and provider not in live:
254
+ raise UnsupportedGpuError(
255
+ f"provider {provider!r} requested but not available on this control plane "
256
+ f"(available: {', '.join(live) or '(none)'}; vast needs VAST_API_KEY)"
257
+ )
258
+
259
+ def _gather(pin: str | None) -> tuple[list[Candidate], tuple]:
260
+ cands: list[Candidate] = []
261
+ book: tuple = ()
262
+ if provider in ("auto", "runpod") and "runpod" in live:
263
+ cands += _runpod_candidates(need, pin, allow_unval)
264
+ if provider in ("auto", "vast") and "vast" in live:
265
+ vcands, book = _vast_candidates(
266
+ need, pin, allow_unval, disk_gb, exclude_machine_ids,
267
+ required=(provider == "vast"), num_gpus=gpu_count,
268
+ )
269
+ cands += vcands
270
+ if _excluded_classes:
271
+ cands = [c for c in cands if c.gpu not in _excluded_classes]
272
+ return cands, book
273
+
274
+ candidates, offer_book = _gather(pinned_gpu)
275
+ # NEVER hard-fail on availability: a pin that no live provider can serve (the class isn't
276
+ # offered right now, or is below ``need`` so it's filtered out) escalates to the cheapest
277
+ # FITTING class across providers instead of raising -- "one spot larger, and so on". The
278
+ # ``need`` floor is still absolute (we never drop below it -> no OOM), and the pin is only a
279
+ # preference. We only raise when NOTHING >= need is available anywhere (truly unsatisfiable).
280
+ escalated_from = None
281
+ if not candidates and pinned_gpu is not None:
282
+ escalated_from = pinned_gpu
283
+ candidates, offer_book = _gather(None)
284
+ if not candidates:
285
+ raise UnsupportedGpuError(
286
+ f"no allocatable GPU (>= {need} GB VRAM for {model_id}, provider={provider}, "
287
+ f"validated_only={not allow_unval}); widen with gpu.allow_unvalidated = true, add a "
288
+ f"provider (VAST_API_KEY), or the run genuinely exceeds every available GPU class"
289
+ )
290
+ if escalated_from is not None:
291
+ order0 = {n: i for i, n in enumerate(PROVIDER_NAMES)}
292
+ _cheapest = sorted(candidates, key=lambda c: (c.hourly_usd, c.vram_gb, order0.get(c.provider, 99)))[0]
293
+ # WARNING level so it surfaces at default `slm train` verbosity (configure_logging is
294
+ # WARNING) — a silently-escalated pin changes cost/hardware and operators must see it;
295
+ # still routed through the logger (stderr), so machine-readable stdout stays clean.
296
+ logger.warning(
297
+ "pinned GPU %r unavailable or below need (%s GB) on provider=%s; "
298
+ "escalated to cheapest fitting class %s (%s GB, %s)",
299
+ escalated_from,
300
+ need,
301
+ provider,
302
+ _cheapest.gpu,
303
+ _cheapest.vram_gb,
304
+ _cheapest.provider,
305
+ )
306
+ # Cheapest first; equal rates prefer less VRAM (don't burn a big card on a small
307
+ # job), then registry order (runpod is the longest-validated substrate).
308
+ order = {n: i for i, n in enumerate(PROVIDER_NAMES)}
309
+ ranked = sorted(candidates, key=lambda c: (c.hourly_usd, c.vram_gb, order.get(c.provider, 99)))
310
+ best = ranked[0]
311
+ return Allocation(
312
+ provider=best.provider,
313
+ gpu=best.gpu,
314
+ hourly_usd=best.hourly_usd,
315
+ min_vram_gb=need,
316
+ candidates=tuple(ranked),
317
+ offer=best.offer,
318
+ provider_offers=offer_book,
319
+ )
320
+
321
+
322
+ def allocation_summary(a: Allocation) -> str:
323
+ head = (
324
+ f"allocated {a.gpu} on {a.provider} at ${a.hourly_usd:.2f}/hr "
325
+ f"(need >= {a.min_vram_gb} GB VRAM"
326
+ )
327
+ # ``a.offer`` is an OPAQUE per-provider provisioning hint, not necessarily a Vast
328
+ # offer — only format Vast specifics when the chosen provider is vast, so a future
329
+ # provider's hint never misformats or raises on a missing attribute.
330
+ if a.provider == "vast" and a.offer is not None:
331
+ head += f", vast offer {a.offer.offer_id} in {a.offer.geolocation}"
332
+ head += ")"
333
+ if len(a.candidates) > 1:
334
+ nxt = a.candidates[1]
335
+ head += f"; next-best: {nxt.gpu}@{nxt.provider} ${nxt.hourly_usd:.2f}/hr"
336
+ 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,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # ``rl_server_boot`` is the disaggregated (multi-GPU) rollout server's boot heartbeat, emitted
66
+ # every ~60s while vLLM loads the model and binds its port — still pre-training, so it likewise
67
+ # stays under setup_grace_s (otherwise the FIRST boot ping would prematurely flip to the tight
68
+ # training window while the server is still booting).
69
+ # Receiving one proves the worker is alive but NOT that the slow setup (model download +
70
+ # vLLM init) finished, so they must not flip stall detection to the tight training window.
71
+ _SETUP_HEARTBEAT_STAGES = frozenset(
72
+ {"boot", "sft_start", "rl_start", "sft_model_load", "rl_train_start", "rl_server_boot"}
73
+ )
74
+
75
+
76
+ def stall_kwargs() -> dict:
77
+ """``poll_job`` stall-window kwargs, shared by the submit and reattach paths so a recovered
78
+ run uses the same tuning as the original submit. ``stall_after_s`` = post-training-heartbeat
79
+ window; ``setup_grace_s`` = the larger cold-start window before the first training heartbeat;
80
+ ``queue_grace_s`` = how long a job may sit IN_QUEUE (no worker assigned) before it's judged
81
+ capacity-starved and fails ``no_capacity`` so the orchestrator advances to the next class.
82
+ """
83
+ return {"stall_after_s": 1500.0, "setup_grace_s": 3000.0, "queue_grace_s": 720.0}
84
+
85
+
86
+ def volume_endpoint_kwargs(spec) -> dict:
87
+ """Endpoint kwargs for the OPT-IN persistent network volume (cross-run HF cache).
88
+
89
+ Returns {} unless ``gpu.network_volume`` is set. The volume pins the endpoint to
90
+ one datacenter (``gpu.datacenter``, default EU-RO-1 — the SDK's storage default),
91
+ which shrinks the available GPU pool; that trade-off is why this is opt-in.
92
+ """
93
+ nv = getattr(spec.gpu, "network_volume", None) if spec is not None else None
94
+ if not nv:
95
+ return {}
96
+ from runpod_flash import NetworkVolume
97
+ from runpod_flash.core.resources.datacenter import DataCenter
98
+
99
+ dc = DataCenter.from_string(spec.gpu.datacenter) if spec.gpu.datacenter else None
100
+ volume = NetworkVolume(
101
+ name=str(nv),
102
+ size=int(getattr(spec.gpu, "network_volume_gb", 100) or 100),
103
+ **({"datacenter": dc} if dc else {}),
104
+ )
105
+ kwargs: dict = {"volume": volume}
106
+ if dc:
107
+ kwargs["datacenter"] = dc
108
+ return kwargs
109
+
110
+
111
+ def apply_disk_gb(config, disk_gb: int | None) -> None:
112
+ """Raise the worker's container disk on a built endpoint config.
113
+
114
+ The Flash SDK's ``PodTemplate.containerDiskInGb`` defaults to 64 GB and the
115
+ ``Endpoint`` wrapper exposes no disk knob, which is what blocked models whose
116
+ checkpoint alone exceeds 64 GB. The template
117
+ is already populated by the SDK's validators when the resource config is built, so
118
+ raising the field here is the supported injection point. Raise-only: shrinking
119
+ below the SDK default buys nothing (serverless disk isn't billed separately) and
120
+ would regress runs whose configs carry the historical ``disk_gb = 60`` default.
121
+ """
122
+ if not disk_gb:
123
+ return
124
+ template = getattr(config, "template", None)
125
+ if template is None:
126
+ logger.warning("disk_gb=%s requested but endpoint config has no template", disk_gb)
127
+ return
128
+ template.containerDiskInGb = max(int(disk_gb), int(template.containerDiskInGb or 0))
129
+
130
+
131
+ @dataclass
132
+ class JobHandle:
133
+ endpoint_id: str
134
+ endpoint_name: str
135
+ job_id: str
136
+
137
+ def to_dict(self) -> dict:
138
+ return {
139
+ "provider": "runpod",
140
+ "endpoint_id": self.endpoint_id,
141
+ "endpoint_name": self.endpoint_name,
142
+ "job_id": self.job_id,
143
+ }
144
+
145
+ @classmethod
146
+ def from_dict(cls, d: dict) -> JobHandle:
147
+ # `provider` is routing metadata consumed upstream (runner); handles
148
+ # persisted before it existed default to runpod there.
149
+ return cls(d["endpoint_id"], d.get("endpoint_name", ""), d["job_id"])
150
+
151
+
152
+ def deploy_train_endpoint(
153
+ friendly_gpu: str,
154
+ execution_timeout_ms: int | None = None,
155
+ name_suffix: str | None = None,
156
+ disk_gb: int | None = None,
157
+ spec=None,
158
+ ) -> tuple[str, str]:
159
+ """Deploy (or reuse) the run's uniquely-named worker endpoint; return (id, name)."""
160
+ os.environ["FLASH_IS_LIVE_PROVISIONING"] = "true"
161
+ from runpod_flash import Endpoint
162
+
163
+ from autoslm.providers.runpod.auth import ensure_auth
164
+
165
+ ensure_auth()
166
+ _patch_runpod_backoff()
167
+ friendly = canonical_gpu(friendly_gpu)
168
+ name = endpoint_name(friendly, name_suffix)
169
+ image = WORKER_IMAGE
170
+ from runpod_flash.core.resources.resource_manager import ResourceManager
171
+
172
+ # isolate_flash_state mutates runpod_flash's process-wide registry globals for this run's
173
+ # suffix, and ResourceManager + the deploy share the SDK's asyncio singleton. Hold the
174
+ # lock across the whole critical section so a concurrent run can't swap the registry
175
+ # scope or race the event loop mid-deploy.
176
+ with FLASH_SDK_LOCK:
177
+ isolate_flash_state(name_suffix)
178
+ kwargs = dict(
179
+ name=name,
180
+ gpu=flash_gpu(friendly),
181
+ # GPUs per worker on the endpoint (= trainer + inference_gpus). >1 for the
182
+ # disaggregated async GRPO path; default 1 (single-GPU colocate).
183
+ gpu_count=max(1, int(getattr(getattr(spec, "gpu", None), "count", 1))),
184
+ min_cuda_version=min_cuda_for(friendly),
185
+ execution_timeout_ms=execution_timeout_ms or DEFAULT_EXECUTION_TIMEOUT_MS,
186
+ workers=(0, 1),
187
+ **volume_endpoint_kwargs(spec),
188
+ )
189
+ if image:
190
+ kwargs["image"] = image
191
+ else:
192
+ # Pass the resolved GPU so Hopper (sm90) gets its fla-drop treatment (resolve_worker_deps
193
+ # is GPU-scoped); a bare call would ship the generic deps and run fla's #640-buggy GDN
194
+ # Triton kernel on an H100 instead of the correct pure-PyTorch delta rule.
195
+ kwargs["dependencies"] = resolve_worker_deps(friendly)
196
+ kwargs["system_dependencies"] = WORKER_SYSTEM_DEPS
197
+ ep = Endpoint(**kwargs)
198
+ ep._qb_target = _train_body
199
+ config = ep._build_resource_config()
200
+ apply_disk_gb(config, disk_gb)
201
+ # Worker image is PUBLIC, so no container-registry credential is needed to pull it.
202
+ rm = ResourceManager()
203
+ resource = asyncio.run(rm.get_or_deploy_resource(config))
204
+ endpoint_id = getattr(resource, "id", None)
205
+ if not endpoint_id:
206
+ raise RuntimeError(f"deploy_train_endpoint: no endpoint id on resource {resource!r}")
207
+ return endpoint_id, name
208
+
209
+
210
+ def build_function_input(payload: dict, friendly_gpu: str | None = None) -> dict:
211
+ """The FunctionRequest dict a Flash queue worker expects for `_train_body(payload)`.
212
+
213
+ ``friendly_gpu`` is threaded into ``resolve_worker_deps`` so the request-level dependency
214
+ list is GPU-scoped exactly like the endpoint config (deploy_train_endpoint): on Hopper (sm90)
215
+ it must drop ``flash-linear-attention`` so the worker uses the pure-PyTorch delta rule instead
216
+ of fla's #640-buggy GDN Triton kernel. A bare call would reinstall the generic deps and
217
+ reintroduce that sm90 correctness issue even when the endpoint was configured correctly.
218
+ """
219
+ from runpod_flash.runtime.serialization import serialize_args
220
+ from runpod_flash.stubs.live_serverless import get_function_source
221
+
222
+ source, _src_hash = get_function_source(_train_body)
223
+ req: dict = {
224
+ "function_name": "_train_body",
225
+ "function_code": source,
226
+ "args": serialize_args((payload,)),
227
+ "accelerate_downloads": True,
228
+ }
229
+ if not WORKER_IMAGE:
230
+ req["dependencies"] = resolve_worker_deps(canonical_gpu(friendly_gpu) if friendly_gpu else None)
231
+ req["system_dependencies"] = WORKER_SYSTEM_DEPS
232
+ return req
233
+
234
+
235
+ def decode_output(output) -> dict:
236
+ """Decode a Flash FunctionResponse job output into the worker's metrics dict."""
237
+ if isinstance(output, str):
238
+ try:
239
+ output = json.loads(output)
240
+ except json.JSONDecodeError as exc:
241
+ raise RuntimeError(f"unexpected job output: {output[:200]}") from exc
242
+ if not isinstance(output, dict):
243
+ raise RuntimeError(f"unexpected job output type: {type(output)}")
244
+ if output.get("success") and output.get("result") is not None:
245
+ import cloudpickle
246
+
247
+ result = cloudpickle.loads(base64.b64decode(output["result"]))
248
+ if not isinstance(result, dict):
249
+ raise RuntimeError(f"flash job returned no metrics: {result!r}")
250
+ return result
251
+ err = output.get("error") or "unknown worker error"
252
+ stdout_tail = (output.get("stdout") or "")[-1500:]
253
+ raise RuntimeError(f"Remote execution failed: {err}\n--- worker stdout tail ---\n{stdout_tail}")
254
+
255
+
256
+ def poll_job(
257
+ handle: JobHandle,
258
+ log=None,
259
+ interval_s: float = 10.0,
260
+ heartbeat_reader=None,
261
+ stall_after_s: float = 1200.0,
262
+ setup_grace_s: float = 3000.0,
263
+ queue_grace_s: float = 720.0,
264
+ deadline_s: float | None = None,
265
+ ) -> PollResult:
266
+ """Poll a queue job to completion; resilient to transient API errors.
267
+
268
+ Two stall windows: the cold-start phase (dep install, per-run env pip, model download,
269
+ vLLM init) is slow and only emits *setup* heartbeats (``_SETUP_HEARTBEAT_STAGES``).
270
+ Until a *training* heartbeat arrives we apply the larger ``setup_grace_s`` budget so a
271
+ slow cold start isn't misread as a stall; after it we use the tight ``stall_after_s``.
272
+ Needs a ``heartbeat_reader`` to tell the phases apart — without one we keep
273
+ ``stall_after_s`` throughout (no regression).
274
+ """
275
+
276
+ say = make_say(log)
277
+ poll_errors = PollErrorTracker(say, interval_s)
278
+
279
+ start = time.time()
280
+ last_status = None
281
+ last_hb_key = None
282
+ last_progress = time.time()
283
+ seen_heartbeat = False
284
+ last_health_probe = 0.0
285
+ while True:
286
+ if deadline_s is not None and time.time() - start > deadline_s:
287
+ return PollResult(False, failure="stalled", detail="client-side deadline exceeded")
288
+ try:
289
+ st = runpod_api.job_status(handle.endpoint_id, handle.job_id)
290
+ poll_errors.reset()
291
+ except runpod_api.RunpodApiError as e:
292
+ if poll_errors.record(e):
293
+ return PollResult(False, failure="poll_error", detail=str(e))
294
+ continue
295
+ status = st.get("status")
296
+ if status != last_status:
297
+ say(f"job {handle.job_id}: {status}")
298
+ last_status = status
299
+ last_progress = time.time()
300
+ if status in TERMINAL_OK:
301
+ try:
302
+ return PollResult(True, metrics=decode_output(st.get("output")))
303
+ except RuntimeError as e:
304
+ return PollResult(False, failure="job_failed", detail=str(e))
305
+ if status in TERMINAL_FAIL:
306
+ detail = str(st.get("error") or "")[:1500]
307
+ out = st.get("output")
308
+ if isinstance(out, dict) and out.get("stdout"):
309
+ # Worker stdout tail is the only place the REAL root cause lives for
310
+ # crashes inside subprocesses (e.g. vLLM EngineCore deaths).
311
+ detail += "\n--- worker stdout tail ---\n" + str(out["stdout"])[-2000:]
312
+ elif not detail:
313
+ detail = str(out)[:1500]
314
+ # Prefix the terminal status so the runner's infra-retry markers
315
+ # (e.g. TIMED_OUT) match even when RunPod sets no error/output text.
316
+ return PollResult(False, failure="job_failed", detail=f"[{status}] {detail}")
317
+ # While queued, surface worker availability (throttled hosts are the common
318
+ # cause of silent multi-minute waits — make them visible in the run log).
319
+ if status == "IN_QUEUE" and time.time() - last_health_probe > 90:
320
+ last_health_probe = time.time()
321
+ try:
322
+ h = runpod_api.endpoint_health(handle.endpoint_id)
323
+ workers = h.get("workers") or {}
324
+ if any(workers.get(k) for k in ("throttled", "unhealthy", "initializing")) or not (
325
+ workers.get("running") or workers.get("ready") or workers.get("idle")
326
+ ):
327
+ say(f"queued; workers: {workers}")
328
+ except Exception:
329
+ # Health surfacing is diagnostic only; a probe failure must not stop polling.
330
+ pass
331
+ # CAPACITY FAST-PATH: a job that can't even LEAVE the queue (no worker ever assigned)
332
+ # is on a capacity-starved GPU class — RunPod keeps the worker `throttled` and the job
333
+ # IN_QUEUE indefinitely. Fail FAST with ``no_capacity`` (well before the multi-minute
334
+ # setup grace) so the orchestrator advances to the next-cheapest AVAILABLE class instead
335
+ # of burning the whole retry budget on a class with zero free workers. Only fires while
336
+ # still IN_QUEUE: once a worker picks the job up (status RUNNING) the slow-but-legit
337
+ # cold start (image pull / dep install / model download) gets the full setup grace below.
338
+ if status == "IN_QUEUE" and time.time() - last_progress > queue_grace_s:
339
+ return PollResult(
340
+ False,
341
+ failure="no_capacity",
342
+ detail=(
343
+ f"no worker assigned for {int(time.time() - last_progress)}s while IN_QUEUE "
344
+ f"(GPU class capacity-starved / throttled; limit {int(queue_grace_s)}s) — "
345
+ "advancing to the next-cheapest available class"
346
+ ),
347
+ )
348
+ # heartbeat progress surfacing + stall detection
349
+ new_key, stage = surface_heartbeat(heartbeat_reader, last_hb_key, say)
350
+ if new_key != last_hb_key:
351
+ last_hb_key = new_key
352
+ last_progress = time.time()
353
+ # Only a training-phase heartbeat means cold-start setup is done and we
354
+ # can switch to the tight window; setup heartbeats keep the grace budget.
355
+ if stage not in _SETUP_HEARTBEAT_STAGES:
356
+ seen_heartbeat = True
357
+ # Cold start (before any training-phase heartbeat) gets the larger setup_grace_s,
358
+ # but only when a heartbeat_reader lets us tell setup from training; without one we
359
+ # can't, so stay on stall_after_s (no regression).
360
+ in_setup = heartbeat_reader is not None and not seen_heartbeat
361
+ stall_limit = setup_grace_s if in_setup else stall_after_s
362
+ if time.time() - last_progress > stall_limit:
363
+ phase = "setup (pre-training)" if in_setup else "training"
364
+ return PollResult(
365
+ False,
366
+ failure="stalled",
367
+ detail=f"no worker progress for {int(time.time() - last_progress)}s "
368
+ f"during {phase} (job status {status}, limit {int(stall_limit)}s)",
369
+ )
370
+ time.sleep(interval_s)
371
+
372
+
373
+ def submit_run(spec, seed: int, log=None, on_handle=None, attempt: int = 0) -> PollResult:
374
+ """Durable equivalent of ``submit_train``: deploy, submit, persist handle, poll.
375
+
376
+ ``on_handle(handle_dict)`` is invoked as soon as the job is queued so the
377
+ runner can persist {endpoint_id, job_id} for cross-process reattach.
378
+ """
379
+ from autoslm.envs.registry import worker_hub_env_ids, worker_pip_for_env
380
+ from autoslm.providers.runpod.train import _run_suffix, build_worker_env
381
+
382
+ timeout_s = max(60, int(spec.gpu.max_wall_seconds))
383
+ # Per-attempt endpoint name: a retry must land on a genuinely fresh endpoint —
384
+ # reusing the name lets the SDK/platform pin the job back onto the same
385
+ # (possibly throttled/sick) host.
386
+ suffix = _run_suffix(spec.run_id)
387
+ if attempt:
388
+ suffix = f"{suffix}r{attempt}"
389
+ # Resolve the worker env BEFORE provisioning: an unrecorded Hub env raises here, and
390
+ # doing it after deploy_train_endpoint() would leak the just-created endpoint (its
391
+ # rN-suffixed name can't be reconstructed from the run id later) against the account
392
+ # quota — the runner would also treat the raise as a retryable poll_error.
393
+ extra_pip = list(spec.environment.pip) or worker_pip_for_env(spec.environment.id)
394
+ worker_env = build_worker_env(spec, seed)
395
+ endpoint_id, name = deploy_train_endpoint(
396
+ spec.gpu.type,
397
+ execution_timeout_ms=timeout_s * 1000,
398
+ name_suffix=suffix,
399
+ disk_gb=spec.gpu.disk_gb,
400
+ spec=spec,
401
+ )
402
+ payload = {
403
+ "hf_repo": spec.train.hf_repo,
404
+ "job_spec_json": spec.to_json(),
405
+ "phase": spec.phase,
406
+ "seed": int(seed),
407
+ "env": worker_env,
408
+ "extra_pip": extra_pip,
409
+ "hub_env_ids": worker_hub_env_ids(spec.environment.id, spec.environment.params),
410
+ }
411
+ # The BAKED worker image ships a custom /rp_handler.py whose handler calls
412
+ # ``_train_body(job["input"])`` directly, so the job input must be the RAW payload. The
413
+ # ``build_function_input`` FunctionRequest envelope ({function_name, function_code, args}) is
414
+ # ONLY for the live runpod_flash runtime (no image), which deserializes ``args`` before calling
415
+ # ``_train_body``. Sending the envelope to the baked handler made it read the envelope as
416
+ # ``input_data`` -> ``input_data["hf_repo"]`` KeyError. Pick the shape that matches the runtime.
417
+ job_input = payload if WORKER_IMAGE else build_function_input(payload, spec.gpu.type)
418
+ try:
419
+ job_id = runpod_api.submit_job(endpoint_id, job_input)
420
+ except Exception:
421
+ # The endpoint is registered but no run handle exists yet, and a
422
+ # retry endpoint's rN-suffixed name can't be reconstructed from the run
423
+ # id later — delete it now so a transient submit failure doesn't leak a
424
+ # serverless endpoint against the account quota.
425
+ with contextlib.suppress(Exception):
426
+ runpod_api.delete_endpoint(endpoint_id)
427
+ raise
428
+ handle = JobHandle(endpoint_id, name, job_id)
429
+ if log is not None:
430
+ print(
431
+ f"submitted job: endpoint={name} ({endpoint_id}) job={job_id} "
432
+ f"attempt={attempt} gpu={spec.gpu.type} phase={spec.phase} seed={seed}",
433
+ file=log,
434
+ flush=True,
435
+ )
436
+ if on_handle is not None:
437
+ on_handle(handle.to_dict())
438
+ hf_repo = spec.train.hf_repo
439
+ prefix = f"{spec.phase}/{spec.run_id}/seed{seed}"
440
+ reader = make_hf_heartbeat_reader(hf_repo, prefix) if hf_repo else None
441
+ return poll_job(handle, log=log, heartbeat_reader=reader, **stall_kwargs())
442
+
443
+
444
+ def make_hf_text_reader(hf_repo: str, path_in_repo: str, min_interval_s: float = 45.0):
445
+ """Rate-limited reader for one HF artifact's text content (None until it exists).
446
+
447
+ Generic helper shared by both providers' pollers (runpod heartbeats + vast's
448
+ DONE/metrics/error artifacts). ``read(force=False)`` re-downloads at most once per
449
+ ``min_interval_s`` (``force=True`` bypasses the gate); it never raises — any HF error
450
+ (artifact absent, network) returns None.
451
+ """
452
+ state = {"last": 0.0}
453
+
454
+ def read(force: bool = False) -> str | None:
455
+ if not hf_repo:
456
+ return None
457
+ if not force and time.time() - state["last"] < min_interval_s:
458
+ return None
459
+ state["last"] = time.time()
460
+ try:
461
+ from huggingface_hub import hf_hub_download
462
+
463
+ p = hf_hub_download(
464
+ hf_repo,
465
+ path_in_repo,
466
+ repo_type="dataset",
467
+ token=os.environ.get("HF_TOKEN"),
468
+ force_download=True,
469
+ )
470
+ with open(p) as f:
471
+ return f.read()
472
+ except Exception:
473
+ return None
474
+
475
+ return read
476
+
477
+
478
+ def make_hf_heartbeat_reader(hf_repo: str, prefix: str, min_interval_s: float = 30.0):
479
+ """Reader for the worker's heartbeat.json on HF (rate-limited, never raises).
480
+
481
+ Thin JSON-parsing wrapper over :func:`make_hf_text_reader` bound to ``{prefix}/heartbeat.json``.
482
+ """
483
+ text_reader = make_hf_text_reader(hf_repo, f"{prefix}/heartbeat.json", min_interval_s)
484
+
485
+ def read() -> dict | None:
486
+ raw = text_reader()
487
+ if raw is None:
488
+ return None
489
+ try:
490
+ return json.loads(raw)
491
+ except (ValueError, TypeError):
492
+ return None
493
+
494
+ 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,823 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_TRAIN_WORKER_IMAGE overrides the tag (e.g. to
93
+ # validate a candidate image like :cu128-mgpu without overwriting the production :cu128) — read at
94
+ # import, so set it in the control-plane env. Must be published to GHCR + public before runs pull it.
95
+ # .strip() so a whitespace-only AUTOSLM_TRAIN_WORKER_IMAGE falls back to the default tag instead of
96
+ # becoming an invalid Docker ref that RunPod Flash / Vast would try (and fail) to provision with.
97
+ WORKER_IMAGE = (
98
+ os.environ.get("AUTOSLM_TRAIN_WORKER_IMAGE") or ""
99
+ ).strip() or "ghcr.io/freesolo-co/autoslm-worker:cu128"
100
+
101
+
102
+ def resolve_worker_deps(friendly_gpu: str | None = None) -> list[str]:
103
+ """The dependency list Flash installs on the GPU worker for this run.
104
+
105
+ Precedence: AUTOSLM_WORKER_DEPS (explicit list) > the pinned ``WORKER_DEPS``.
106
+
107
+ GPU-specific: on HOPPER (sm90, H100), DROP flash-linear-attention — its gated
108
+ chunk_bwd Triton kernel is miscomputed there (Triton>=3.4, fla #640). Without fla,
109
+ transformers uses the correct pure-PyTorch delta rule (slower but correct).
110
+ Ampere/Ada/Blackwell keep fla for the speedup.
111
+ """
112
+ explicit = os.environ.get("AUTOSLM_WORKER_DEPS")
113
+ if explicit:
114
+ # JSON list (use this for specs containing commas, e.g.
115
+ # "transformers>=5.6,<5.13") or a whitespace-separated string.
116
+ if explicit.strip().startswith("["):
117
+ import json as _json
118
+
119
+ deps = [str(d).strip() for d in _json.loads(explicit) if str(d).strip()]
120
+ else:
121
+ # shlex (whitespace) splitting, NOT comma: a comma is part of a PEP 440
122
+ # range like `transformers>=5.6,<5.11` and must not be split.
123
+ import shlex
124
+
125
+ deps = [d for d in shlex.split(explicit) if d.strip()]
126
+ if deps:
127
+ return deps
128
+ deps = list(WORKER_DEPS)
129
+ # Hopper (sm90) fla strategy: DROP flash-linear-attention -> the correct pure-PyTorch delta
130
+ # rule. fla's gated chunk_bwd Triton kernel is miscomputed on Hopper (Triton>=3.4, fla #640),
131
+ # so on H100 we run without it (the dense Qwen3.5 GDN models route to consumer cards by
132
+ # default, where fla stays). Ampere/Ada/Blackwell keep fla for the speedup.
133
+ if friendly_gpu:
134
+ try:
135
+ from autoslm.providers.base import get_gpu_info
136
+
137
+ if get_gpu_info(friendly_gpu).sm == "sm90":
138
+ deps = [d for d in deps if not d.startswith("flash-linear-attention")]
139
+ except Exception:
140
+ pass
141
+ # Additive per-run extras (e.g. an extra pinned wheel for an A/B) without
142
+ # restating the whole pinned stack the way AUTOSLM_WORKER_DEPS requires.
143
+ extra = os.environ.get("AUTOSLM_WORKER_EXTRA_DEPS")
144
+ if extra:
145
+ import shlex
146
+
147
+ deps = deps + [d for d in shlex.split(extra) if d.strip()]
148
+ return deps
149
+
150
+
151
+ DEFAULT_EXECUTION_TIMEOUT_MS = 6 * 3600 * 1000 # 6h RunPod worker execution cap
152
+
153
+ _ENDPOINT_CACHE: dict[str, Any] = {}
154
+
155
+
156
+ def upload_code(repo: str | None = None) -> str:
157
+ """Upload the ``autoslm`` package to the run's HF artifact repo.
158
+
159
+ ``repo`` is the per-run artifact repo (``spec.train.hf_repo``); the worker fetches
160
+ ``code/**`` from the same repo it is given in the submit payload, so the code must land in
161
+ that per-run repo.
162
+
163
+ The worker downloads ``code/**`` to ``/runcode``. Verifiers-only: there are no built-in
164
+ example environments to ship — Hub/installed envs are pip-installed on the worker (see
165
+ ``registry.worker_pip_for_env``).
166
+
167
+ Only the ``autoslm`` package is uploaded, NOT the client's project tree. Managed runs must
168
+ reference a published Hub env by ``id`` (``slm env push`` to publish a local env first); the
169
+ worker pip-installs the env wheel.
170
+ """
171
+ from huggingface_hub import HfApi
172
+
173
+ import autoslm
174
+
175
+ if not repo:
176
+ raise RuntimeError(
177
+ "hf_repo must be set (the run's [train] hf_repo: HF dataset repo for code + artifacts)"
178
+ )
179
+ token = os.environ.get("HF_TOKEN")
180
+ pkg_dir = os.path.dirname(os.path.abspath(autoslm.__file__))
181
+ api = HfApi(token=token)
182
+ # Worker pulls code/** by HTTP; HF FREE-TIER accounts cannot serve PRIVATE dataset
183
+ # downloads (worker gets 403), so operators on a free tier must publish artifact repos
184
+ # public. Default private (paid-tier safe); set AUTOSLM_HF_REPO_PRIVATE=0 to create public.
185
+ private = os.environ.get("AUTOSLM_HF_REPO_PRIVATE", "1") not in ("0", "false", "False")
186
+ api.create_repo(repo, repo_type="dataset", exist_ok=True, private=private)
187
+ # create_repo(exist_ok=True) is a no-op on an EXISTING repo, so it never flips a repo that
188
+ # already exists private back to public. When the operator wants public (free-tier: workers
189
+ # 403 on private downloads), force visibility explicitly so a reused private repo is fixed.
190
+ if not private:
191
+ try:
192
+ api.update_repo_settings(repo_id=repo, repo_type="dataset", private=False)
193
+ except Exception as e:
194
+ logger.warning("could not ensure %s is public (free-tier worker may 403): %s", repo, e)
195
+ api.upload_folder(
196
+ folder_path=pkg_dir,
197
+ path_in_repo="code/autoslm",
198
+ repo_id=repo,
199
+ repo_type="dataset",
200
+ ignore_patterns=["__pycache__/*", "*.pyc"],
201
+ )
202
+ return repo
203
+
204
+
205
+ def _train_body(input_data: dict) -> dict:
206
+ """Runs ON the RunPod GPU worker: fetch code, train (phase), return metrics.
207
+
208
+ NOTE: Flash serializes this handler and runs it standalone, so every name it uses
209
+ must be imported INSIDE the function body (module-level imports are not in scope).
210
+ """
211
+ import contextlib
212
+ import json
213
+ import os
214
+ import shutil
215
+ import subprocess
216
+ import sys
217
+
218
+ from huggingface_hub import snapshot_download
219
+
220
+ # NB: the Hopper fla guard lives in engine.worker._drop_fla_on_hopper (runs in the worker
221
+ # process AFTER all installs, before any model import) — doing it here would be undone by a
222
+ # later extra_pip / `prime env install` that pulls fla back, and depends on a handler redeploy.
223
+
224
+ # Extra pip deps for verifiers / Prime Hub environments (installed per-run).
225
+ extra_pip = input_data.get("extra_pip") or []
226
+ if extra_pip:
227
+ # check=True: a deterministic dependency failure should fail fast here,
228
+ # not after model download + worker startup with a less actionable error.
229
+ subprocess.run([sys.executable, "-m", "pip", "install", *extra_pip], check=True)
230
+
231
+ # NB: fla is dropped on Hopper (sm90) automatically — resolve_worker_deps omits it from the
232
+ # install list, and engine.worker._drop_fla_on_hopper removes any baked-in copy at worker
233
+ # startup (fla's GDN backward is miscomputed on sm90, #640). No env toggle: fla only ever runs
234
+ # on the consumer archs where its Triton kernel is correct.
235
+
236
+ # Install the run's verifiers environment(s) from the Prime Hub via the authenticated
237
+ # `prime` CLI. The public pip index does not serve PRIVATE env wheels, so a plain pip
238
+ # install can't fetch them; `prime env install` pulls/builds/installs public + private
239
+ # alike, authenticated by PRIME_API_KEY forwarded from the control plane.
240
+ hub_env_ids = input_data.get("hub_env_ids") or []
241
+ if hub_env_ids:
242
+ worker_env = {k: str(v) for k, v in (input_data.get("env") or {}).items()}
243
+ prime_key = worker_env.get("PRIME_API_KEY") or os.environ.get("PRIME_API_KEY")
244
+ if not prime_key:
245
+ raise RuntimeError(
246
+ "PRIME_API_KEY is required to install the Prime Hub environment on the worker"
247
+ )
248
+ # Only install `prime` when it isn't already on the worker (it's often baked into
249
+ # the worker image) — an unconditional install adds latency and a per-run PyPI
250
+ # failure point every run.
251
+ if shutil.which("prime") is None:
252
+ subprocess.run([sys.executable, "-m", "pip", "install", "prime"], check=True)
253
+ # --with pip: install the env into THIS (the trainer's) python via pip. The default
254
+ # (`--with uv`) installs into prime's own isolated uv env, so the trainer then can't
255
+ # import the env module (ModuleNotFoundError at load_environment). PIP_BREAK_SYSTEM_PACKAGES
256
+ # lets pip write to a PEP-668 "externally-managed" base python (the worker image's).
257
+ install_env = {
258
+ **os.environ,
259
+ "PRIME_API_KEY": prime_key,
260
+ "PRIME_DISABLE_VERSION_CHECK": "1",
261
+ "PIP_BREAK_SYSTEM_PACKAGES": "1",
262
+ }
263
+ for env_id in hub_env_ids:
264
+ subprocess.run(
265
+ ["prime", "env", "install", env_id, "--with", "pip"], check=True, env=install_env
266
+ )
267
+
268
+ overrides = {k: str(v) for k, v in (input_data.get("env") or {}).items()}
269
+ snapshot_download(
270
+ repo_id=input_data["hf_repo"],
271
+ repo_type="dataset",
272
+ allow_patterns=["code/**"],
273
+ local_dir="/runcode",
274
+ token=overrides.get("HF_TOKEN"),
275
+ )
276
+ code_dir = "/runcode/code"
277
+
278
+ env = dict(os.environ)
279
+ env.update(overrides)
280
+ # A large job_spec_json (e.g. many inline params/dataset refs) can blow past the
281
+ # ~128 KiB per-env-string exec limit ("Argument list too long"). Pass a large spec
282
+ # via a file (AUTOSLM_JOB_SPEC_PATH); keep the inline env var for small specs.
283
+ # load_job_spec_from_env reads either.
284
+ spec_json = input_data["job_spec_json"]
285
+ if len(spec_json) > 96_000:
286
+ spec_path = "/tmp/job_spec.json"
287
+ with open(spec_path, "w") as sf:
288
+ sf.write(spec_json)
289
+ env["AUTOSLM_JOB_SPEC_PATH"] = spec_path
290
+ env.pop("AUTOSLM_JOB_SPEC_JSON", None)
291
+ else:
292
+ env["AUTOSLM_JOB_SPEC_JSON"] = spec_json
293
+ env["PHASE"] = input_data["phase"]
294
+ env["SEED"] = str(input_data["seed"])
295
+ env["PYTHONPATH"] = code_dir + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
296
+
297
+ def run_mode(mode: str, check: bool) -> int:
298
+ """Run one worker process, tee its console to a file, and on failure upload the
299
+ tail to HF as console_<mode>.txt — the engine-core root cause of crashes like
300
+ vLLM EngineDeadError only ever appears on the subprocess console, never in the
301
+ Python traceback."""
302
+ console = f"/tmp/console_{mode}.txt"
303
+ with open(console, "w") as cf:
304
+ proc = subprocess.Popen(
305
+ [sys.executable, "-m", "autoslm.engine.worker"],
306
+ cwd=code_dir,
307
+ env={**env, "RUN_MODE": mode},
308
+ stdout=subprocess.PIPE,
309
+ stderr=subprocess.STDOUT,
310
+ text=True,
311
+ )
312
+ for line in proc.stdout:
313
+ print(line, end="") # keep streaming to the platform console
314
+ cf.write(line)
315
+ proc.wait()
316
+ if proc.returncode != 0:
317
+ try:
318
+ from huggingface_hub import HfApi
319
+
320
+ spec = json.loads(input_data["job_spec_json"])
321
+ phase_ns = "rl" if spec.get("algorithm") == "grpo" else spec["algorithm"]
322
+ prefix = f"{phase_ns}/{spec['run_id']}/seed{input_data['seed']}"
323
+ with open(console) as f:
324
+ tail = f.read()[-64_000:]
325
+ with open(console + ".tail", "w") as f:
326
+ f.write(tail)
327
+ HfApi(token=env.get("HF_TOKEN")).upload_file(
328
+ path_or_fileobj=console + ".tail",
329
+ path_in_repo=f"{prefix}/console_{mode}.txt",
330
+ repo_id=input_data["hf_repo"],
331
+ repo_type="dataset",
332
+ )
333
+ except Exception as up_err:
334
+ print("console upload warn:", up_err)
335
+ if check:
336
+ raise RuntimeError(
337
+ f"worker mode '{mode}' exited {proc.returncode}; see console_{mode}.txt "
338
+ f"and error_{mode}.txt in the HF dataset repo"
339
+ )
340
+ return proc.returncode
341
+
342
+ # A warm worker can carry a previous seed's metrics files; a stale metrics.json
343
+ # would let a crashed train phase report the previous run's numbers. Clear before
344
+ # training.
345
+ for stale in ("/tmp/train_meta.json", "/tmp/metrics.json"):
346
+ with contextlib.suppress(FileNotFoundError):
347
+ os.remove(stale)
348
+ # Train. check=False — RL's colocated vLLM can segfault at interpreter exit AFTER
349
+ # the adapter + metrics.json + DONE are saved; don't treat that as a failure.
350
+ run_mode(input_data["phase"], check=False)
351
+ # The train phase writes metrics.json + the DONE sentinel itself (RunPod can also
352
+ # redeliver a completed job, whose worker restores metrics.json from DONE). If it
353
+ # is missing, the train phase crashed before finishing — fail fast with the real
354
+ # cause (full traceback in error_<phase>.txt / console_<phase>.txt in the HF repo).
355
+ if not os.path.exists("/tmp/metrics.json"):
356
+ phase = input_data["phase"]
357
+ raise RuntimeError(
358
+ f"train phase '{phase}' produced no /tmp/metrics.json (it crashed before "
359
+ f"finishing); see error_{phase}.txt and console_{phase}.txt in the HF "
360
+ f"dataset repo for the full traceback"
361
+ )
362
+ with open("/tmp/metrics.json") as f:
363
+ return json.load(f)
364
+
365
+
366
+ def isolate_flash_state(scope: str | None = None) -> None:
367
+ """Point the Flash SDK's resource registry at a per-process/private directory.
368
+
369
+ The SDK persists its registry to ``./.flash/resources.pkl`` — shared, whole-dict,
370
+ last-writer-wins across every process in the CWD. Observed failure modes: stale
371
+ entries resurrecting long-dead endpoints on later syncs, and concurrent processes
372
+ clobbering each other's bookkeeping. Each AutoSLM process gets its own registry
373
+ under ``~/.autoslm/flash-state/<scope>``; remote cleanup never relies on the
374
+ registry anyway (REST by id/name — see api.py).
375
+ """
376
+ try:
377
+ from pathlib import Path
378
+
379
+ import runpod_flash.core.resources.resource_manager as rm
380
+
381
+ scope = scope or f"pid{os.getpid()}"
382
+ state_dir = Path.home() / ".autoslm" / "flash-state" / scope
383
+ state_dir.mkdir(parents=True, exist_ok=True)
384
+ rm.FLASH_STATE_DIR = state_dir
385
+ rm.RESOURCE_STATE_FILE = state_dir / "resources.pkl"
386
+ except Exception as exc: # never block a run on this
387
+ logger.warning("flash state isolation skipped: %s", exc)
388
+
389
+
390
+ def _patch_runpod_backoff() -> None:
391
+ """Work around a runpod_flash bug that aborts long-running jobs.
392
+
393
+ The SDK polls a synchronous job with exponential backoff computed as
394
+ ``base * (2 ** attempt)`` and only clamps to ``max_seconds`` afterwards. On a long
395
+ run the poll ``attempt`` grows without bound, so ``2 ** attempt`` becomes a huge int
396
+ and the float multiply raises ``OverflowError: int too large to convert to float``
397
+ (observed ~80 min in), killing an otherwise-healthy job mid-run. We patch the symbol
398
+ to cap the exponent before the power so the delay still saturates at ``max_seconds``.
399
+ """
400
+ try:
401
+ import math
402
+ import random
403
+
404
+ from runpod_flash.core.utils import backoff as _bo
405
+
406
+ if getattr(_bo, "_autoslm_backoff_patched", False):
407
+ return
408
+
409
+ def _safe_get_backoff_delay(
410
+ attempt,
411
+ base=0.1,
412
+ max_seconds=10.0,
413
+ jitter=0.2,
414
+ strategy=_bo.BackoffStrategy.EXPONENTIAL,
415
+ ):
416
+ a = min(int(attempt), 30) # cap exponent: 2**30 is plenty; delay saturates anyway
417
+ if strategy == _bo.BackoffStrategy.EXPONENTIAL:
418
+ delay = base * (2**a)
419
+ elif strategy == _bo.BackoffStrategy.LINEAR:
420
+ delay = base + (attempt * base)
421
+ elif strategy == _bo.BackoffStrategy.LOGARITHMIC:
422
+ delay = base * math.log2(attempt + 2)
423
+ else:
424
+ raise ValueError(f"Unsupported backoff strategy: {strategy}")
425
+ delay = min(delay, max_seconds)
426
+ return delay * random.uniform(1 - jitter, 1 + jitter)
427
+
428
+ _bo.get_backoff_delay = _safe_get_backoff_delay
429
+ _bo._autoslm_backoff_patched = True
430
+ # serverless.py did `from ..utils.backoff import get_backoff_delay`, so patch its ref too.
431
+ try:
432
+ from runpod_flash.core.resources import serverless as _sl
433
+
434
+ _sl.get_backoff_delay = _safe_get_backoff_delay
435
+ except Exception:
436
+ # serverless.py may not import the symbol in this SDK version; the primary
437
+ # patch above still applies, so a missing alias is fine to ignore.
438
+ pass
439
+ except Exception as exc: # never let the patch break submission
440
+ logger.warning("runpod backoff patch skipped: %s", exc)
441
+
442
+
443
+ def min_cuda_for(friendly_gpu: str) -> str:
444
+ """Minimum host CUDA (driver) version for this GPU class on the active stack.
445
+
446
+ Blackwell classes (sm_120 — RTX 5090, RTX Pro 6000): pypi wheels for
447
+ the modern stack (vllm 0.19) ship no Blackwell SASS, so every custom CUDA kernel
448
+ is PTX-JIT'd by the driver — and their PTX is built with a newer toolchain than
449
+ CUDA-12.8-era drivers can JIT (observed: "the provided PTX was compiled with an
450
+ unsupported toolchain" on driver 570.x). CUDA-13 drivers JIT it fine, so those
451
+ classes are pinned to >=13.0 on the modern stack (per-GPU ``min_cuda_modern`` in
452
+ providers.base.GPU_INFO). Ampere/Ada/Hopper have SASS in the wheels and run on 12.8.
453
+ Override with AUTOSLM_MIN_CUDA.
454
+ """
455
+ explicit = os.environ.get("AUTOSLM_MIN_CUDA")
456
+ if explicit:
457
+ return explicit
458
+ from autoslm.providers.base import min_cuda_modern
459
+
460
+ return min_cuda_modern(friendly_gpu)
461
+
462
+
463
+ def endpoint_name(friendly_gpu: str, suffix: str | None = None) -> str:
464
+ """Flash endpoint/template name for a GPU class, optionally made unique per run.
465
+
466
+ A fixed name (``autoslm-train-5090``) collides across back-to-back runs: runpod_flash's
467
+ ``get_or_deploy_resource`` finds the prior run's still-registered resource and tries to
468
+ *update* it, which fails with ``GraphQL errors: Template name must be unique`` (there is
469
+ no endpoint GC/reuse). A per-run ``suffix`` (the run id tail) gives each run its own
470
+ endpoint so it deploys fresh instead of colliding. RunPod scales each to zero when idle.
471
+ """
472
+ base = f"autoslm-train-{gpu_short(friendly_gpu)}"
473
+ if not suffix:
474
+ return base
475
+ safe = "".join(c for c in str(suffix) if c.isalnum() or c == "-").strip("-")[:24]
476
+ return f"{base}-{safe}" if safe else base
477
+
478
+
479
+ def get_train_endpoint(
480
+ friendly_gpu: str,
481
+ execution_timeout_ms: int | None = None,
482
+ name_suffix: str | None = None,
483
+ disk_gb: int | None = None,
484
+ spec=None,
485
+ ):
486
+ """Build (and cache) the live Flash endpoint handler for a GPU class."""
487
+ # Live ("ad-hoc") provisioning: provision on call, no separate `flash deploy`.
488
+ os.environ["FLASH_IS_LIVE_PROVISIONING"] = "true"
489
+ from runpod_flash import Endpoint
490
+
491
+ from autoslm.providers.runpod.auth import ensure_auth
492
+ from autoslm.providers.runpod.jobs import volume_endpoint_kwargs
493
+
494
+ ensure_auth()
495
+ _patch_runpod_backoff()
496
+ isolate_flash_state(name_suffix)
497
+
498
+ friendly = canonical_gpu(friendly_gpu)
499
+ name = endpoint_name(friendly, name_suffix)
500
+ if name in _ENDPOINT_CACHE:
501
+ return _ENDPOINT_CACHE[name]
502
+ kwargs = dict(
503
+ name=name,
504
+ gpu=flash_gpu(friendly),
505
+ # GPUs per worker (= trainer + inference_gpus); >1 for disaggregated async GRPO, else 1.
506
+ gpu_count=max(1, int(getattr(getattr(spec, "gpu", None), "count", 1))),
507
+ min_cuda_version=min_cuda_for(friendly),
508
+ execution_timeout_ms=execution_timeout_ms or DEFAULT_EXECUTION_TIMEOUT_MS,
509
+ workers=(0, 1), # one dedicated worker per run; scale to zero when idle
510
+ **volume_endpoint_kwargs(spec),
511
+ )
512
+ # Prebuilt worker image (deps baked in) cuts the cold-start dep install. It's PUBLIC, so no
513
+ # registry login is needed. If WORKER_IMAGE is ever blanked, fall back to installing
514
+ # WORKER_DEPS on first use (cached as a Flash artifact across calls).
515
+ if WORKER_IMAGE:
516
+ kwargs["image"] = WORKER_IMAGE
517
+ else:
518
+ kwargs["dependencies"] = resolve_worker_deps(friendly)
519
+ kwargs["system_dependencies"] = WORKER_SYSTEM_DEPS
520
+ ep = Endpoint(**kwargs)
521
+ handler = ep(_train_body) # register the queue-based handler; returns the callable
522
+ # The resource config is cached on the Endpoint, so raising the disk on it here
523
+ # carries through to the deploy that the first handler call triggers.
524
+ from autoslm.providers.runpod.jobs import apply_disk_gb
525
+
526
+ cfg = ep._build_resource_config()
527
+ apply_disk_gb(cfg, disk_gb)
528
+ _ENDPOINT_CACHE[name] = handler
529
+ return handler
530
+
531
+
532
+ def _run_suffix(run_id: str | None) -> str | None:
533
+ """Short, COLLISION-FREE per-run endpoint suffix.
534
+
535
+ Must be unique per run_id: the endpoint name is ``endpoint_name(friendly, suffix)`` and
536
+ RunPod reuses an endpoint by name -- two runs with the same suffix share one endpoint (and
537
+ its cached image/deps/registry-auth/template), so a later run silently reuses the earlier
538
+ one's config. The old ``run_id.split("-")[-1]`` only worked for hash-tailed default ids; a
539
+ descriptive run_id ending in e.g. the card name (``...-a100``) collided across every run.
540
+ Use a stable short hash of the WHOLE run_id, with a sanitized prefix for readability."""
541
+ if not run_id:
542
+ return None
543
+ import hashlib
544
+ import re
545
+
546
+ h = hashlib.sha1(run_id.encode()).hexdigest()[:8]
547
+ prefix = re.sub(r"[^a-z0-9]", "", run_id.lower())[-12:]
548
+ return f"{prefix}{h}" if prefix else h
549
+
550
+
551
+ def stop_endpoint(friendly_gpu: str, name: str | None = None) -> None:
552
+ """Best-effort: scale cached endpoint(s) to zero / drop them.
553
+
554
+ With ``name`` only that run's cached endpoint is dropped; without it, every
555
+ cached endpoint of the GPU class is — so a per-run teardown passes ``name``
556
+ to avoid evicting a concurrent run's handler in the same process.
557
+
558
+ NOTE: this only touches THIS process's in-memory cache, so it does nothing in a fresh
559
+ ``slm cancel`` process. Use ``terminate_endpoint`` to actually delete the remote endpoint.
560
+ """
561
+ friendly = canonical_gpu(friendly_gpu)
562
+ prefix = f"autoslm-train-{gpu_short(friendly)}"
563
+ if name:
564
+ match = [k for k in _ENDPOINT_CACHE if k == name]
565
+ else:
566
+ match = [k for k in _ENDPOINT_CACHE if k.startswith(prefix)]
567
+ for key in match:
568
+ handler = _ENDPOINT_CACHE.pop(key, None)
569
+ ep = getattr(handler, "__self__", None) or getattr(handler, "endpoint", None)
570
+ for meth in ("scale_to_zero", "stop", "delete"):
571
+ fn = getattr(ep, meth, None)
572
+ if callable(fn):
573
+ try:
574
+ fn()
575
+ break
576
+ except Exception:
577
+ continue
578
+
579
+
580
+ def _select_endpoint_resources(resources: dict, target: str) -> list[str]:
581
+ """Resource ids whose resource ``.name`` contains ``target``.
582
+
583
+ The live-provisioned resource is named ``live-<endpoint_name>``, so we match by substring
584
+ to catch the prefix. ``target`` is the endpoint name (``autoslm-train-<gpu>[-<run>]``).
585
+ """
586
+ if not target:
587
+ return []
588
+ out = []
589
+ for uid, res in (resources or {}).items():
590
+ name = str(getattr(res, "name", "") or "")
591
+ if target in name:
592
+ out.append(uid)
593
+ return out
594
+
595
+
596
+ def terminate_endpoint(friendly_gpu: str, run_id: str | None = None) -> list[dict]:
597
+ """Reliably tear down the remote Flash endpoint(s) for a run — cross-process.
598
+
599
+ Unlike ``stop_endpoint`` (which only touches this process's in-memory cache), this looks
600
+ the endpoint up by name in runpod_flash's *persisted* resource registry and deletes it via
601
+ the RunPod API (``ResourceManager.undeploy_resource`` -> ``delete_endpoint``), which stops
602
+ any running worker. Best-effort: never raises. Returns the per-resource undeploy results.
603
+
604
+ With ``run_id`` it targets exactly that run's uniquely-named endpoint; without it, the
605
+ bare ``autoslm-train-<gpu>`` prefix matches every endpoint of that GPU class.
606
+ """
607
+ friendly = canonical_gpu(friendly_gpu)
608
+ target = endpoint_name(friendly, _run_suffix(run_id))
609
+ # Hold FLASH_SDK_LOCK across the ENTIRE Flash critical section, not just the undeploy.
610
+ # isolate_flash_state() swaps runpod_flash's process-wide registry globals and
611
+ # ResourceManager shares the SDK's asyncio singleton, so a concurrent deploy/undeploy on
612
+ # another thread could swap the registry scope between our lookup and our undeploy and tear
613
+ # down the wrong run's resources. Serialize isolation + lookup + undeploy together.
614
+ with FLASH_SDK_LOCK:
615
+ try:
616
+ from autoslm.providers.runpod.auth import ensure_auth
617
+
618
+ ensure_auth()
619
+ isolate_flash_state(_run_suffix(run_id))
620
+ from runpod_flash.core.resources.resource_manager import ResourceManager
621
+ except Exception as exc: # SDK/auth unavailable
622
+ return [{"success": False, "name": target, "message": f"flash unavailable: {exc}"}]
623
+
624
+ try:
625
+ rm = ResourceManager()
626
+ resources = rm.list_all_resources()
627
+ uids = _select_endpoint_resources(resources, target)
628
+ except Exception as exc:
629
+ return [{"success": False, "name": target, "message": f"resource lookup failed: {exc}"}]
630
+
631
+ async def _undeploy_all() -> list:
632
+ out = []
633
+ for uid in uids:
634
+ res = resources.get(uid)
635
+ name = getattr(res, "name", None)
636
+ try:
637
+ out.append(
638
+ await rm.undeploy_resource(uid, resource_name=name, force_remove=True)
639
+ )
640
+ except Exception as exc:
641
+ out.append({"success": False, "name": name, "message": str(exc)})
642
+ return out
643
+
644
+ try:
645
+ results = asyncio.run(_undeploy_all())
646
+ except Exception as exc:
647
+ results = [{"success": False, "name": target, "message": str(exc)}]
648
+
649
+ # Registry-less fallback: isolate_flash_state() keeps the Flash SDK's resource
650
+ # registry per-process under ~/.autoslm, so a recreated container (or a crash before
651
+ # on_handle() persisted the endpoint id) leaves the live endpoint invisible to the
652
+ # lookup above. Delete it via the RunPod REST API by its reconstructed name so it
653
+ # can't keep a paid worker alive.
654
+ if not uids:
655
+ with contextlib.suppress(Exception):
656
+ from autoslm.providers.runpod import api as runpod_api
657
+
658
+ for ep in runpod_api.find_endpoints_by_name(target):
659
+ if ep.get("name") == target and runpod_api.delete_endpoint(ep["id"]):
660
+ results.append(
661
+ {"success": True, "name": target, "message": "deleted via REST API"}
662
+ )
663
+
664
+ # also drop the in-process cached handler for THIS run only (a class-wide
665
+ # drop would evict a concurrent run's endpoint on the same GPU class).
666
+ with contextlib.suppress(Exception):
667
+ stop_endpoint(friendly, name=target)
668
+ return results
669
+
670
+
671
+ def build_worker_env(spec: JobSpec, seed: int) -> dict:
672
+ """Per-run env passed to the worker (secrets + recipe overrides)."""
673
+ # CUDA allocator conf. Colocate (TRL trainer + vLLM on one GPU) fragments over a long run,
674
+ # so expandable_segments (which reclaims fragmentation) is the right default — EXCEPT under
675
+ # GRPO vLLM sleep mode, whose CuMemAllocator memory pool is incompatible with
676
+ # expandable_segments (vLLM asserts and the run crashes at engine init). So for RL with
677
+ # sleep mode ON (the default), default to a non-expandable conf instead; SFT and
678
+ # sleep-off RL keep expandable_segments. An explicit operator override always wins.
679
+ _is_rl = str(getattr(spec, "algorithm", "")).lower() not in ("sft",)
680
+ # RL_VLLM_SLEEP may be pinned per-run via [worker_env] (highest precedence, merged into the
681
+ # worker env later) OR via the control-plane process env. Resolve it from BOTH here — with
682
+ # worker_env winning — so a per-run explicit pin counts as explicit: otherwise _sleep_set stays
683
+ # false, AUTOSLM_ALLOC_AUTO=1 is sent, and the worker can upgrade to expandable_segments while
684
+ # run_rl still enables vLLM sleep, hitting the CuMemAllocator incompatibility after provisioning.
685
+ _sleep_raw = (spec.worker_env or {}).get("RL_VLLM_SLEEP", os.environ.get("RL_VLLM_SLEEP"))
686
+ _sleep_set = _sleep_raw is not None
687
+ _sleep_on = (_sleep_raw if _sleep_raw is not None else "1") not in ("0", "false", "False")
688
+ _alloc_default = (
689
+ "garbage_collection_threshold:0.8,max_split_size_mb:256"
690
+ if (_is_rl and _sleep_on)
691
+ else "expandable_segments:True"
692
+ )
693
+ # torch >= 2.10 renamed the env to PYTORCH_ALLOC_CONF — set BOTH names for either stack.
694
+ _alloc_override = os.environ.get("PYTORCH_ALLOC_CONF") or os.environ.get(
695
+ "PYTORCH_CUDA_ALLOC_CONF"
696
+ )
697
+ _alloc_conf = _alloc_override or _alloc_default
698
+ env: dict[str, str] = {
699
+ "RUN_ID": spec.run_id,
700
+ # Compute substrate, read back by engine.worker for the RunMetrics record. Vast's
701
+ # on-instance bootstrap overrides this to "vast" (it reuses this same env builder).
702
+ "AUTOSLM_ARM": "runpod",
703
+ # GPUs provisioned on the node (= trainer + inference_gpus). The worker reads this
704
+ # (engine.disaggregated.detect_total_gpus) to compute the disaggregated rollout split
705
+ # WITHOUT initializing a torch CUDA context first. 1 = single-GPU (colocate).
706
+ "AUTOSLM_GPU_COUNT": str(max(1, int(getattr(spec.gpu, "count", 1)))),
707
+ "BENCH_HF_MODEL": spec.model,
708
+ "PYTORCH_CUDA_ALLOC_CONF": _alloc_conf,
709
+ "PYTORCH_ALLOC_CONF": _alloc_conf,
710
+ # We picked a DEFAULT alloc conf above without knowing the worker's resolved vLLM sleep
711
+ # decision (RL + RL_VLLM_SLEEP unset + no operator override). Cede the final choice to the
712
+ # worker, which resolves sleep from the model config and upgrades to expandable_segments
713
+ # when sleep is OFF (engine.worker.finalize_alloc_conf_for_sleep). Never set when the
714
+ # operator pinned an alloc conf or RL_VLLM_SLEEP explicitly — their choice is authoritative.
715
+ **(
716
+ {"AUTOSLM_ALLOC_AUTO": "1"}
717
+ if (_is_rl and not _sleep_set and not _alloc_override)
718
+ else {}
719
+ ),
720
+ # Escape hatch for torch.compile/inductor spikes (Qwen3.5 DeltaNet kernels
721
+ # compile at first forward and can OOM a tight colocate budget).
722
+ **(
723
+ {"TORCHDYNAMO_DISABLE": os.environ["TORCHDYNAMO_DISABLE"]}
724
+ if os.environ.get("TORCHDYNAMO_DISABLE")
725
+ else {}
726
+ ),
727
+ }
728
+ # HF artifact creds + PRIME_API_KEY (the worker `prime env install`s the run's Hub
729
+ # env(s), public + private) + optional reward-judge creds: a verifiers env whose rubric
730
+ # calls an LLM judge (e.g. OpenRouter gpt-oss-120b) needs the API key ON THE WORKER,
731
+ # where the reward runs. Forward any that the operator has set; absent ones are simply
732
+ # not passed.
733
+ for key in (
734
+ "HF_TOKEN",
735
+ "PRIME_API_KEY",
736
+ "OPENROUTER_API_KEY",
737
+ "OPENAI_API_KEY",
738
+ ):
739
+ if os.environ.get(key):
740
+ env[key] = os.environ[key]
741
+ # Seed the worker's own HF_REPO env from the run's [train] hf_repo (adapter/checkpoint/
742
+ # code storage + heartbeats). The worker reads HF_REPO from its own process env; that env
743
+ # is now sourced from the spec, not the operator's HF_REPO.
744
+ env["HF_REPO"] = spec.train.hf_repo
745
+ # Opt-in network volume: point the whole HF cache at the persistent mount so
746
+ # model weights survive across runs (the download becomes a one-time cost per
747
+ # volume instead of per run).
748
+ if getattr(spec.gpu, "network_volume", None):
749
+ env["HF_HOME"] = "/runpod-volume/hf-cache"
750
+ if spec.train.steps is not None:
751
+ env["RL_STEPS"] = str(spec.train.steps)
752
+ if spec.train.epochs is not None:
753
+ env["SFT_EPOCHS"] = str(spec.train.epochs)
754
+ # Forward the documented worker-tuning knobs so they actually reach the GPU worker.
755
+ # RL_VLLM_GPU_UTIL / RL_PER_DEVICE_PROMPTS are the colocate-memory knobs the docs tell
756
+ # users to set to fix vLLM OOM/KV-cache errors; they were previously dropped here.
757
+ for k in (
758
+ "SFT_PER_DEVICE_BS",
759
+ "SFT_PACKING",
760
+ # Colocate-memory knobs the docs tell users to set to fix vLLM OOM / KV-cache errors.
761
+ "RL_VLLM_GPU_UTIL",
762
+ "RL_VLLM_SLEEP",
763
+ "RL_PER_DEVICE_PROMPTS",
764
+ "VLLM_USE_V1",
765
+ # Attention-backend escape hatch: vllm's bundled flash-attn PTX can be newer
766
+ # than the host driver's JIT (sm_120 + 12.8 drivers); TRITON_ATTN/FLASHINFER
767
+ # sidestep it without restricting the host pool to CUDA-13 drivers.
768
+ "VLLM_ATTENTION_BACKEND",
769
+ "AUTOSLM_QUANT",
770
+ "WANDB_API_KEY",
771
+ "WANDB_ENTITY",
772
+ "LORA_TARGETS",
773
+ ):
774
+ # Forward when SET, even if empty: an explicit "" is a meaningful override.
775
+ if os.environ.get(k) is not None:
776
+ env[k] = os.environ[k]
777
+ # Per-run worker_env overrides win over the global os.environ allowlist: this is what lets
778
+ # ONE run differ (e.g. a per-run optimizer or LoRA-init A/B) while every other concurrent run
779
+ # keeps the global default.
780
+ for k, v in (getattr(spec, "worker_env", None) or {}).items():
781
+ env[str(k)] = str(v)
782
+ return env
783
+
784
+
785
+ def submit_train(spec: JobSpec, seed: int, log=None) -> dict:
786
+ """Provision a dedicated GPU via Flash, run training, return the metrics dict."""
787
+ timeout_s = max(60, int(spec.gpu.max_wall_seconds))
788
+ from autoslm.envs.registry import worker_hub_env_ids, worker_pip_for_env
789
+
790
+ handler = get_train_endpoint(
791
+ spec.gpu.type,
792
+ execution_timeout_ms=timeout_s * 1000,
793
+ name_suffix=_run_suffix(spec.run_id),
794
+ disk_gb=spec.gpu.disk_gb,
795
+ spec=spec,
796
+ )
797
+ payload = {
798
+ "hf_repo": spec.train.hf_repo,
799
+ "job_spec_json": spec.to_json(),
800
+ "phase": spec.phase,
801
+ "seed": int(seed),
802
+ "env": build_worker_env(spec, seed),
803
+ "extra_pip": list(spec.environment.pip) or worker_pip_for_env(spec.environment.id),
804
+ "hub_env_ids": worker_hub_env_ids(spec.environment.id, spec.environment.params),
805
+ }
806
+ if log is not None:
807
+ print(
808
+ f"submitting Flash job: gpu={spec.gpu.type} phase={spec.phase} "
809
+ f"seed={seed} model={spec.model}",
810
+ file=log,
811
+ flush=True,
812
+ )
813
+
814
+ async def _call():
815
+ res = handler(payload)
816
+ if inspect.isawaitable(res):
817
+ res = await res
818
+ return res
819
+
820
+ out = asyncio.run(_call())
821
+ if not isinstance(out, dict):
822
+ raise RuntimeError(f"flash job returned no metrics: {out!r}")
823
+ 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,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ num_gpus: int = 1,
67
+ limit: int = 64,
68
+ extra_q: dict | None = None,
69
+ ) -> list[dict]:
70
+ """Rentable single-GPU offers from verified hosts, cheapest first. We drop the server-side
71
+ datacenter-only filter so verified COMMUNITY/marketplace hosts are returned alongside
72
+ datacenter ones (usable_offers still re-checks hosting_type + verification + the reliability
73
+ floor, so quality is enforced downstream).
74
+
75
+ ``datacenter`` here is Vast's hosting-type filter (professional datacenters vs
76
+ consumer/hobbyist machines); results additionally carry ``hosting_type`` which
77
+ callers must re-check (``usable_offers``) — never trust one filter layer alone.
78
+ """
79
+ # We intentionally do NOT apply Vast's server-side datacenter-only filter: verified
80
+ # COMMUNITY/marketplace hosts are included too (scarce classes often have no verified-datacenter
81
+ # supply), and usable_offers re-checks hosting_type + verification + the reliability floor.
82
+ # Rent an instance with EXACTLY ``num_gpus`` GPUs (default 1). Exact-match (not >=) so a
83
+ # 2-GPU disaggregated run pays for a 2-GPU machine, not an 8-GPU one (dph_total is per-instance).
84
+ q: dict[str, Any] = {
85
+ "verified": {"eq": True},
86
+ "rentable": {"eq": True},
87
+ "num_gpus": {"eq": int(num_gpus)},
88
+ "gpu_ram": {"gte": int(min_vram_mb)},
89
+ "reliability2": {"gte": float(min_reliability)},
90
+ "type": "ask",
91
+ "order": [["dph_total", "asc"]],
92
+ "limit": int(limit),
93
+ }
94
+ if min_disk_gb:
95
+ q["disk_space"] = {"gte": float(min_disk_gb)}
96
+ if extra_q:
97
+ q.update(extra_q)
98
+ out = request_with_retries("/v0/search/asks/", method="PUT", body={"q": q})
99
+ offers = out.get("offers") if isinstance(out, dict) else None
100
+ return offers if isinstance(offers, list) else []
101
+
102
+
103
+ # ---------------------------------------------------------------------------
104
+ # Instances
105
+ # ---------------------------------------------------------------------------
106
+ def create_instance(
107
+ offer_id: int,
108
+ *,
109
+ image: str,
110
+ disk_gb: float,
111
+ env: dict[str, str],
112
+ onstart: str,
113
+ label: str,
114
+ runtype: str = "args",
115
+ ) -> int:
116
+ """Rent an offer -> instance id. Raises VastApiError on rejection (offer taken).
117
+
118
+ Default ``args`` runtype (verified live): the script IS the container command
119
+ (``bash -c``), so the job needs no SSH key on the account, the container's
120
+ lifecycle is the job's lifecycle, and the Vast-injected CONTAINER_API_KEY /
121
+ CONTAINER_ID env vars are available for the self-destroy backstop. ``ssh``
122
+ runtype requires an SSH key attached to the Vast account.
123
+ """
124
+ body = {
125
+ "client_id": "me",
126
+ "image": image,
127
+ "disk": float(disk_gb),
128
+ "env": dict(env),
129
+ "label": label,
130
+ "runtype": runtype,
131
+ }
132
+ # The worker image is PUBLIC, so Vast pulls it with no docker-login (no image_login / pull
133
+ # token is ever shipped to the untrusted host).
134
+ if runtype == "args":
135
+ body["args"] = ["bash", "-c", onstart]
136
+ else:
137
+ body["onstart"] = onstart
138
+ # NON-IDEMPOTENT: ``PUT /asks/{id}`` rents a NEW instance every time it succeeds.
139
+ # A blind retry on a timeout where Vast actually accepted the first request would
140
+ # double-provision (two billed instances, one invisible to our handle). So this
141
+ # call is NOT retried — a transient failure surfaces to deploy_and_submit, which
142
+ # walks to the next offer, and to the orchestrator, which consumes a run retry; a
143
+ # duplicate paid instance is the worse failure. (Idempotent calls — search,
144
+ # detail, destroy — keep their retries.)
145
+ out = request_with_retries(f"/v0/asks/{int(offer_id)}/", method="PUT", body=body, retries=0)
146
+ if not isinstance(out, dict) or not out.get("success"):
147
+ raise VastApiError(f"create_instance({offer_id}) rejected: {out}")
148
+ instance_id = out.get("new_contract")
149
+ if not instance_id:
150
+ raise VastApiError(f"create_instance({offer_id}): no instance id in response: {out}")
151
+ return int(instance_id)
152
+
153
+
154
+ def get_instance(instance_id: int) -> dict | None:
155
+ """Instance detail dict, or None once it no longer exists (destroyed).
156
+
157
+ The v0 detail route answers 200 with ``{"instances": null}`` for unknown ids
158
+ (verified live) — that is the "gone" signal, not a 404.
159
+ """
160
+ try:
161
+ out = request_with_retries(f"/v0/instances/{int(instance_id)}/")
162
+ except VastApiError as e:
163
+ if "404" in str(e):
164
+ return None
165
+ raise
166
+ if isinstance(out, dict):
167
+ if "instances" in out:
168
+ inst = out["instances"]
169
+ return inst if isinstance(inst, dict) else None
170
+ return out
171
+ return None
172
+
173
+
174
+ def list_instances() -> list[dict]:
175
+ # The v0 list route is deprecated (410 "use /api/v1/instances/", verified live);
176
+ # detail/destroy remain on v0.
177
+ out = request_with_retries("/v1/instances/")
178
+ inst = out.get("instances") if isinstance(out, dict) else None
179
+ return inst if isinstance(inst, list) else []
180
+
181
+
182
+ def instance_logs(instance_id: int, tail: int = 400, wait_s: float = 20.0) -> str | None:
183
+ """Container log tail via the logs API (request -> poll the result URL).
184
+
185
+ The only place early-bootstrap failures (pip/env errors before the worker can
186
+ reach HF) are visible. Best-effort: returns None when logs are unavailable
187
+ (e.g. the instance is already destroyed); never raises.
188
+ """
189
+ try:
190
+ out = request_with_retries(
191
+ f"/v0/instances/request_logs/{int(instance_id)}/",
192
+ method="PUT",
193
+ body={"tail": str(int(tail))},
194
+ retries=1,
195
+ )
196
+ url = out.get("result_url") if isinstance(out, dict) else None
197
+ if not url:
198
+ return None
199
+ deadline = time.time() + wait_s
200
+ while time.time() < deadline:
201
+ try:
202
+ with urllib.request.urlopen(url, timeout=15) as resp:
203
+ body = resp.read().decode(errors="replace")
204
+ if body.strip():
205
+ return body
206
+ except urllib.error.HTTPError as e:
207
+ if e.code != 404: # 404 = not materialized yet
208
+ return None
209
+ time.sleep(2.0)
210
+ except Exception:
211
+ return None
212
+ return None
213
+
214
+
215
+ def destroy_instance(instance_id: int) -> bool:
216
+ """Destroy (and stop billing for) an instance. Best-effort: never raises."""
217
+ try:
218
+ request_with_retries(f"/v0/instances/{int(instance_id)}/", method="DELETE", retries=2)
219
+ return True
220
+ except Exception:
221
+ 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,761 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ num_gpus: int = 1 # GPUs on this instance (for multi-GPU disaggregated runs + cost reporting)
80
+
81
+
82
+ def usable_offers(
83
+ min_vram_gb: int,
84
+ disk_gb: float,
85
+ exclude_machine_ids: set[int] | frozenset[int] = frozenset(),
86
+ num_gpus: int = 1,
87
+ ) -> list[VastOffer]:
88
+ """Verified offers (datacenter or community) able to run the job, cheapest first.
89
+
90
+ ``num_gpus`` (default 1) rents an instance with exactly that many GPUs — the disaggregated
91
+ async GRPO path needs a multi-GPU node ([gpu] count). ``min_vram_gb`` is the PER-GPU floor
92
+ (each card holds a trainer or rollout shard), unchanged by the count.
93
+
94
+ Server-side filters do the heavy lifting; everything load-bearing is re-checked
95
+ client-side (belt and suspenders — the result rows carry the proof fields).
96
+ """
97
+ rows = vast_api.search_offers(
98
+ int(min_vram_gb * 1024 * _SEARCH_VRAM_SLACK),
99
+ min_disk_gb=disk_gb,
100
+ min_reliability=RELIABILITY_FLOOR,
101
+ num_gpus=num_gpus,
102
+ )
103
+ # Always include Vast-VERIFIED marketplace hosts (hosting_type 0) alongside datacenter-only
104
+ # (hosting_type==1): they are still verified and reliability-floored (RELIABILITY_FLOOR above),
105
+ # just not datacenter-tier. Scarce classes are often only offered by community hosts while the
106
+ # RunPod equivalent is capacity-throttled, so as long as the reliability floor is met we take them.
107
+ allow_community = True
108
+ out: list[VastOffer] = []
109
+ for r in rows:
110
+ gpu = vast_gpu_for_offer(str(r.get("gpu_name") or ""), float(r.get("gpu_ram") or 0))
111
+ if gpu is None: # not a managed class (Ampere+ floor)
112
+ continue
113
+ info = GPU_INFO[gpu]
114
+ dph = float(r.get("dph_total") or 0)
115
+ cuda = float(r.get("cuda_max_good") or 0)
116
+ # Host tier: accept verified datacenter (hosting_type==1) AND verified community
117
+ # (hosting_type==0) hosts — community is always allowed, still gated by the reliability
118
+ # floor + verification below; any other hosting_type is rejected.
119
+ _bad_host = r.get("hosting_type") != 1 and not (
120
+ allow_community and r.get("hosting_type") == 0
121
+ )
122
+ # MULTI-GPU: require a WHOLE-machine offer with an EXPLICIT gpu_frac ~= 1.0. A fractional
123
+ # multi-GPU offer (e.g. 2 of an 8-GPU box, gpu_frac=0.25/0.5) rents 2 GPUs to the INSTANCE
124
+ # but the CONTAINER gets only 1 (Vast sets NVIDIA_VISIBLE_DEVICES=void and mounts the
125
+ # fraction's devices — verified: nvidia-smi -L=1, env void). A MISSING gpu_frac is treated
126
+ # as NOT-whole-machine here (a $0.54 missing-frac offer also yielded a 1-GPU container), so
127
+ # require the field present and >=0.99 — whole-machine offers carry gpu_frac=1.0 explicitly.
128
+ # float() guarded: a present-but-non-numeric gpu_frac (e.g. "" / null-ish string) would
129
+ # raise ValueError and abort the WHOLE offer search; treat unparseable as not-whole-machine
130
+ # (rejected), consistent with requiring an explicit numeric >=0.99.
131
+ try:
132
+ _gf_val = float(r.get("gpu_frac"))
133
+ except (TypeError, ValueError):
134
+ _gf_val = 0.0
135
+ _frac_ok = num_gpus <= 1 or _gf_val >= 0.99
136
+ if (
137
+ _bad_host
138
+ or not _frac_ok
139
+ or r.get("verification") != "verified"
140
+ # Exact class gate: guard against a board whose canonical class nominal VRAM
141
+ # is below the request (e.g. asking for 48 GB but the mapping landed on a
142
+ # 24 GB class) — the server-side gpu_ram filter only carries slack.
143
+ or info.vram_gb < min_vram_gb
144
+ or float(r.get("reliability2") or 0) < RELIABILITY_FLOOR
145
+ or float(r.get("disk_space") or 0) < float(disk_gb)
146
+ or float(r.get("inet_down") or 0) < MIN_INET_MBPS
147
+ or cuda < float(min_cuda_modern(gpu)) # Blackwell needs CUDA-13 drivers
148
+ or dph <= 0
149
+ or int(r.get("machine_id") or 0) in exclude_machine_ids
150
+ ):
151
+ continue
152
+ out.append(
153
+ VastOffer(
154
+ offer_id=int(r["id"]),
155
+ machine_id=int(r.get("machine_id") or 0),
156
+ gpu=gpu,
157
+ vram_gb=info.vram_gb,
158
+ dph_total=dph,
159
+ cuda_max_good=cuda,
160
+ disk_space=float(r.get("disk_space") or 0),
161
+ reliability=float(r.get("reliability2") or 0),
162
+ inet_down=float(r.get("inet_down") or 0),
163
+ geolocation=str(r.get("geolocation") or ""),
164
+ num_gpus=int(r.get("num_gpus") or num_gpus),
165
+ )
166
+ )
167
+ return sorted(out, key=lambda o: (o.dph_total, o.vram_gb))
168
+
169
+
170
+ def vast_image() -> str:
171
+ """Docker image for the worker: the prebuilt, PUBLIC WORKER_IMAGE (full training stack baked
172
+ in). Used for every GPU class — the Blackwell driver floor lives in the ``cuda_max_good`` offer
173
+ filter, not the image. There is no generic fallback image; the worker image is always used."""
174
+ from autoslm.providers.runpod.train import WORKER_IMAGE
175
+
176
+ return WORKER_IMAGE
177
+
178
+
179
+ @dataclass
180
+ class VastJobHandle:
181
+ """Persisted in RunStatus.remote so any process can reattach/cancel (cf. JobHandle)."""
182
+
183
+ instance_id: int
184
+ offer_id: int
185
+ machine_id: int
186
+ label: str
187
+ gpu: str
188
+ hourly_usd: float
189
+ attempt: int
190
+ started_ts: float
191
+
192
+ def to_dict(self) -> dict:
193
+ return {
194
+ "provider": "vast",
195
+ "instance_id": self.instance_id,
196
+ "offer_id": self.offer_id,
197
+ "machine_id": self.machine_id,
198
+ "label": self.label,
199
+ "gpu": self.gpu,
200
+ "hourly_usd": self.hourly_usd,
201
+ "attempt": self.attempt,
202
+ "started_ts": self.started_ts,
203
+ }
204
+
205
+ @classmethod
206
+ def from_dict(cls, d: dict) -> VastJobHandle:
207
+ return cls(
208
+ instance_id=int(d["instance_id"]),
209
+ offer_id=int(d.get("offer_id") or 0),
210
+ machine_id=int(d.get("machine_id") or 0),
211
+ label=str(d.get("label") or ""),
212
+ gpu=str(d.get("gpu") or ""),
213
+ hourly_usd=float(d.get("hourly_usd") or 0),
214
+ attempt=int(d.get("attempt") or 0),
215
+ started_ts=float(d.get("started_ts") or 0),
216
+ )
217
+
218
+
219
+ def run_label_prefix(run_id: str) -> str:
220
+ """The prefix EVERY instance label for ``run_id`` starts with.
221
+
222
+ ``instance_label`` forces the ``autoslm-`` prefix onto run ids that lack it, so the
223
+ orphan-sweep allowlist must apply the SAME transform: a raw run id (e.g. a
224
+ "fail-fast" test id) would otherwise never match its own ``autoslm-…`` labels and a
225
+ live run's instance could be swept (or fail to be protected)."""
226
+ return f"autoslm-{run_id}" if not run_id.startswith("autoslm-") else run_id
227
+
228
+
229
+ def instance_label(run_id: str, seed: int, attempt: int) -> str:
230
+ """Instance label: run-derived so ``sweep_orphans`` can tell ours from anything
231
+ else on the account. Platform run ids already start with ``autoslm-``; anything else
232
+ (direct-API callers, tests) gets the prefix forced — an instance we rented must NEVER
233
+ be invisible to the orphan sweep."""
234
+ return f"{run_label_prefix(run_id)}-s{seed}-a{attempt}"
235
+
236
+
237
+ def build_payload(spec, seed: int, attempt: int) -> dict:
238
+ """The bootstrap's input — field-compatible with _train_body's, plus the bits the
239
+ instance can't infer (HF prefix for markers, wall cap, attempt)."""
240
+ from autoslm.envs.registry import worker_hub_env_ids, worker_pip_for_env
241
+ from autoslm.providers.runpod.train import build_worker_env
242
+
243
+ return {
244
+ "hf_repo": spec.train.hf_repo,
245
+ "job_spec_json": spec.to_json(),
246
+ "phase": spec.phase,
247
+ "seed": int(seed),
248
+ "env": build_worker_env(spec, seed),
249
+ "extra_pip": list(spec.environment.pip) or worker_pip_for_env(spec.environment.id),
250
+ "hub_env_ids": worker_hub_env_ids(spec.environment.id, spec.environment.params),
251
+ "hf_prefix": f"{spec.phase}/{spec.run_id}/seed{seed}",
252
+ "max_wall_s": max(60, int(spec.gpu.max_wall_seconds)),
253
+ "attempt": int(attempt),
254
+ }
255
+
256
+
257
+ def build_onstart(payload: dict, install_deps: bool = True) -> str:
258
+ """The instance's onstart script: payload + bootstrap shipped as quoted heredocs.
259
+
260
+ Everything dynamic travels base64-encoded inside the script — never interpolated
261
+ into shell syntax and never through Vast's env plumbing — so the job-spec JSON
262
+ (quotes, spaces, anything) survives byte-exact. Secrets-wise the script carries
263
+ the same content as the worker env on RunPod (HF token; never provider keys).
264
+
265
+ The bootstrap source is the private ``_bootstrap.py`` sibling — an internal detail
266
+ of this provider, not a public module.
267
+ """
268
+ from autoslm.providers.runpod.train import resolve_worker_deps
269
+
270
+ payload_b64 = base64.encodebytes(json.dumps(payload).encode()).decode()
271
+ bootstrap_src = (Path(__file__).parent / "_bootstrap.py").read_text()
272
+ if install_deps:
273
+ deps = " ".join(shlex.quote(d) for d in resolve_worker_deps())
274
+ # Vast cold-start is dominated by this dep install (torch/vllm/transformers cu128 stack) on
275
+ # fresh hosts — RunPod caches it as a Flash artifact, but Vast reinstalls per host, so use
276
+ # `uv pip` (validated in the worker image: resolves + installs the full pinned cu128 stack
277
+ # in ~12s, ~10x faster than pip). --break-system-packages: PYBIN is the image's
278
+ # externally-managed system python (newer pytorch images dropped /opt/conda); uv refuses it
279
+ # without this flag (and ignores pip's PIP_BREAK_SYSTEM_PACKAGES), which is what silently
280
+ # broke the earlier uv attempt. The flag is a no-op on a conda/venv python, so it's safe
281
+ # across image variants.
282
+ pip_line = (
283
+ '"$PYBIN" -m pip install --no-cache-dir uv '
284
+ f'&& "$PYBIN" -m uv pip install --python "$PYBIN" --break-system-packages --no-cache {deps}'
285
+ )
286
+ else:
287
+ pip_line = ": # deps baked into the image (WORKER_IMAGE)"
288
+ # Verified live: Vast's args-mode wrapper resets PATH, so `python3` resolves to
289
+ # the OS python (Ubuntu 24.04 = PEP 668 externally-managed -> pip refuses), not
290
+ # the image's conda env. Prefer the conda python when present (torch baked in),
291
+ # and let pip install into whichever interpreter won.
292
+ return f"""#!/bin/bash
293
+ # AutoSLM vast worker (generated by autoslm.providers.vast.jobs.build_onstart)
294
+ set -x
295
+ export PIP_BREAK_SYSTEM_PACKAGES=1
296
+ PYBIN=/opt/conda/bin/python; [ -x "$PYBIN" ] || PYBIN=/usr/local/bin/python; [ -x "$PYBIN" ] || PYBIN=$(command -v python3)
297
+ mkdir -p /root/autoslm
298
+ cat > /root/autoslm/payload.b64 <<'AUTOSLM_PAYLOAD_EOF'
299
+ {payload_b64}AUTOSLM_PAYLOAD_EOF
300
+ base64 -d /root/autoslm/payload.b64 > /root/autoslm/payload.json
301
+ cat > /root/autoslm/bootstrap.py <<'AUTOSLM_BOOTSTRAP_EOF'
302
+ {bootstrap_src}AUTOSLM_BOOTSTRAP_EOF
303
+ # A base worker-stack install failure must STOP the script: continuing into
304
+ # bootstrap.py with a partially installed env turns a deterministic dependency
305
+ # failure into a later import/model crash (or a missing HF marker if
306
+ # huggingface_hub never installed). Hold the box first so the control plane can
307
+ # pull the log tail (mirrors the bootstrap-failure path below and the extra-pip
308
+ # check=True path). The no-deps branch (":") always succeeds, so this is a no-op there.
309
+ {pip_line} || {{ echo "AUTOSLM: base worker dependency install failed" >&2; sleep 600; exit 1; }}
310
+ "$PYBIN" /root/autoslm/bootstrap.py
311
+ AUTOSLM_RC=$?
312
+ # On failure, hold the box for 10 min so the control plane can pull the container
313
+ # log tail (the only home of early-bootstrap errors); it destroys us much sooner
314
+ # when alive. Success self-destroys immediately.
315
+ [ "$AUTOSLM_RC" -ne 0 ] && sleep 600
316
+ # Self-destroy backstop (the control plane's destroy is primary). CONTAINER_API_KEY
317
+ # is the Vast-injected instance-scoped key — the operator key never ships here.
318
+ # python, not curl: the worker image is not guaranteed to carry curl.
319
+ "$PYBIN" - <<'AUTOSLM_DESTROY_EOF'
320
+ import os, urllib.request
321
+ iid, key = os.environ.get("CONTAINER_ID"), os.environ.get("CONTAINER_API_KEY")
322
+ if iid and key:
323
+ req = urllib.request.Request(
324
+ f"https://console.vast.ai/api/v0/instances/{{iid}}/",
325
+ method="DELETE",
326
+ headers={{"Authorization": f"Bearer {{key}}"}},
327
+ )
328
+ try:
329
+ urllib.request.urlopen(req, timeout=30)
330
+ except Exception as exc:
331
+ print("self-destroy warn:", exc)
332
+ AUTOSLM_DESTROY_EOF
333
+ exit $AUTOSLM_RC
334
+ """
335
+
336
+
337
+ def deploy_and_submit(
338
+ spec,
339
+ seed: int,
340
+ offers: list[VastOffer],
341
+ attempt: int = 0,
342
+ log=None,
343
+ exclude_machine_ids: set[int] | frozenset[int] = frozenset(),
344
+ ) -> VastJobHandle:
345
+ """Rent the cheapest offer that will actually take the job; walk on rejection.
346
+
347
+ Offers are a live market — between search and rent the cheapest one is often
348
+ gone. We walk up to 5 ranked offers, then refresh the search once.
349
+
350
+ ``exclude_machine_ids`` is the run's blacklist (machines that stalled/failed this
351
+ run earlier). The refresh re-search MUST keep them excluded — otherwise a sick
352
+ machine the orchestrator just blacklisted gets re-selected from the fresh market.
353
+ """
354
+
355
+ def say(msg: str):
356
+ if log is not None:
357
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", file=log, flush=True)
358
+
359
+ if not offers:
360
+ raise vast_api.VastApiError("no usable vast offers (verified datacenter pool empty)")
361
+ payload = build_payload(spec, seed, attempt)
362
+ label = instance_label(spec.run_id, seed, attempt)
363
+ from autoslm.providers.runpod.train import WORKER_IMAGE
364
+
365
+ install_deps = not WORKER_IMAGE
366
+ tried: list[VastOffer] = []
367
+ candidates = list(offers[:5])
368
+ refreshed = False
369
+ last_err: Exception | None = None
370
+ while candidates:
371
+ offer = candidates.pop(0)
372
+ tried.append(offer)
373
+ onstart = build_onstart(payload, install_deps=install_deps)
374
+ try:
375
+ instance_id = vast_api.create_instance(
376
+ offer.offer_id,
377
+ image=vast_image(),
378
+ disk_gb=_effective_disk_gb(spec),
379
+ # Expose ALL rented GPUs to the container. The worker image is pytorch/pytorch
380
+ # (not nvidia/cuda) and the NVIDIA container runtime only surfaces the GPUs named
381
+ # in NVIDIA_VISIBLE_DEVICES — without this a multi-GPU offer's container can come up
382
+ # with just 1 GPU (observed: a num_gpus=2 5090 offer exposed 1 GPU, breaking the
383
+ # disaggregated split). "all" = all GPUs in the container's cgroup, i.e. exactly the
384
+ # rented ones (not other tenants'); harmless for single-GPU runs.
385
+ env={"NVIDIA_VISIBLE_DEVICES": "all"},
386
+ onstart=onstart,
387
+ label=label,
388
+ runtype="args",
389
+ )
390
+ except vast_api.VastApiError as e:
391
+ last_err = e
392
+ say(f"offer {offer.offer_id} ({offer.gpu} ${offer.dph_total:.2f}/hr) rejected: {e}")
393
+ if not candidates and not refreshed:
394
+ refreshed = True
395
+ # Exclude both the machines we just tried this attempt AND the run's
396
+ # standing blacklist (machines that stalled/failed earlier attempts) —
397
+ # otherwise the fresh search can re-select a sick machine the
398
+ # orchestrator deliberately excluded.
399
+ taken = {o.machine_id for o in tried} | set(exclude_machine_ids)
400
+ # Stay within the allocator-approved class pool: the original `offers`
401
+ # are already filtered to the allocated/pinned + validated classes, so
402
+ # the refresh must not widen to any usable offer (which could rent a
403
+ # different or unvalidated GPU than the run spec assumes).
404
+ allowed = {o.gpu for o in offers}
405
+ candidates = [
406
+ o
407
+ for o in usable_offers(
408
+ min(o.vram_gb for o in offers),
409
+ _effective_disk_gb(spec),
410
+ exclude_machine_ids=taken,
411
+ num_gpus=int(getattr(spec.gpu, "count", 1)),
412
+ )
413
+ if o.gpu in allowed
414
+ ][:5]
415
+ continue
416
+ say(
417
+ f"rented vast instance {instance_id}: {offer.gpu} ${offer.dph_total:.2f}/hr "
418
+ f"(offer {offer.offer_id}, {offer.geolocation}, reliability "
419
+ f"{offer.reliability:.3f}) attempt={attempt} seed={seed}"
420
+ )
421
+ return VastJobHandle(
422
+ instance_id=instance_id,
423
+ offer_id=offer.offer_id,
424
+ machine_id=offer.machine_id,
425
+ label=label,
426
+ gpu=offer.gpu,
427
+ hourly_usd=offer.dph_total,
428
+ attempt=attempt,
429
+ started_ts=time.time(),
430
+ )
431
+ raise vast_api.VastApiError(f"all {len(tried)} vast offers rejected the job: {last_err}")
432
+
433
+
434
+ # Rate-limited reader for one HF artifact's text content (None until it exists). Shared
435
+ # with runpod's poller via make_hf_text_reader; kept under this module-local name because
436
+ # tests monkeypatch ``vast.jobs._make_hf_file_reader`` and the poll/failure paths below
437
+ # resolve it as a module global (so a monkeypatch still takes effect).
438
+ _make_hf_file_reader = make_hf_text_reader
439
+
440
+
441
+ def _failure_detail(
442
+ hf_repo: str, prefix: str, phase: str, marker: dict | None, instance_id: int | None = None
443
+ ) -> str:
444
+ """Best root-cause detail we can assemble from the HF artifacts."""
445
+ parts = []
446
+ if marker and marker.get("error"):
447
+ parts.append(str(marker["error"]))
448
+ content = _make_hf_file_reader(hf_repo, f"{prefix}/error_{phase}.txt")(force=True)
449
+ if content:
450
+ parts.append(f"--- error_{phase}.txt ---\n{content[-2000:]}")
451
+ if instance_id:
452
+ # Early-bootstrap failures (pip/env errors before the worker can reach HF)
453
+ # only ever appear on the container console.
454
+ logs = vast_api.instance_logs(int(instance_id))
455
+ if logs:
456
+ parts.append(f"--- instance log tail ---\n{logs[-3000:]}")
457
+ return "\n".join(parts) or "vast worker terminated without a DONE sentinel"
458
+
459
+
460
+ # Vast instance states that mean "the container is gone / will not progress".
461
+ _DEAD_STATES = {"exited", "stopped", "offline", "deleted"}
462
+
463
+
464
+ def poll_vast_job(
465
+ handle: VastJobHandle,
466
+ spec,
467
+ seed: int,
468
+ log=None,
469
+ interval_s: float = 15.0,
470
+ heartbeat_reader=None,
471
+ stall_after_s: float = 1500.0,
472
+ deadline_s: float | None = None,
473
+ ) -> PollResult:
474
+ """Poll instance status + HF artifacts to a terminal state (cf. jobs.poll_job).
475
+
476
+ COMPLETED fresh DONE sentinel on HF -> metrics.json (cost stamped from the
477
+ offer's real $/hr).
478
+ FAILED attempt marker with ok=false, or instance dead without DONE.
479
+ STALLED never left loading within LOAD_TIMEOUT_S, heartbeat frozen for
480
+ stall_after_s, or the client-side deadline passed.
481
+ """
482
+
483
+ say = make_say(log)
484
+
485
+ hf_repo = spec.train.hf_repo
486
+ prefix = f"{spec.phase}/{spec.run_id}/seed{seed}"
487
+ done_reader = _make_hf_file_reader(hf_repo, f"{prefix}/DONE")
488
+ marker_reader = _make_hf_file_reader(
489
+ hf_repo, f"{prefix}/vast_attempt{handle.attempt}.json", min_interval_s=60.0
490
+ )
491
+ metrics_reader = _make_hf_file_reader(hf_repo, f"{prefix}/metrics.json")
492
+
493
+ def finish_ok(done_content: str | None = None) -> PollResult:
494
+ raw = metrics_reader(force=True)
495
+ if raw is None:
496
+ return PollResult(False, failure="job_failed", detail="DONE without metrics.json")
497
+ metrics = json.loads(raw)
498
+ # Prefer the worker's DONE timestamp when present and sane; fall back to now.
499
+ # On delayed recovery the control plane may call this hours after the instance
500
+ # wrote DONE and self-destroyed, so billing to now would over-bill by the
501
+ # downtime — accepted because a missing/garbled DONE timestamp is rare. DONE
502
+ # carries the worker's time.time().
503
+ end_ts = time.time()
504
+ if done_content:
505
+ try:
506
+ done_ts = float(done_content.strip())
507
+ if handle.started_ts <= done_ts <= end_ts:
508
+ end_ts = done_ts
509
+ except ValueError:
510
+ # Malformed DONE timestamp: keep end_ts = now rather than trusting garbage.
511
+ pass
512
+ wall_h = (end_ts - handle.started_ts) / 3600.0
513
+ metrics["cost_usd"] = round(wall_h * handle.hourly_usd, 6)
514
+ notes = metrics.get("notes") if isinstance(metrics.get("notes"), dict) else {}
515
+ notes.update(
516
+ {
517
+ "provider": "vast",
518
+ "vast_rate_usd_hr": handle.hourly_usd,
519
+ "vast_gpu": handle.gpu,
520
+ "vast_offer_id": handle.offer_id,
521
+ }
522
+ )
523
+ metrics["notes"] = notes
524
+ return PollResult(True, metrics=metrics)
525
+
526
+ def done_is_fresh(content: str) -> bool:
527
+ # DONE carries the worker's time.time(); 120 s of clock-skew grace. Anything
528
+ # older predates this attempt (leftover from a prior attempt's resume).
529
+ try:
530
+ return float(content.strip()) > handle.started_ts - 120.0
531
+ except ValueError:
532
+ return False
533
+
534
+ poll_errors = PollErrorTracker(say, interval_s)
535
+
536
+ start = time.time()
537
+ last_status = None
538
+ last_hb_key = None
539
+ last_progress = time.time()
540
+ became_running = False
541
+ missing_streak = 0
542
+ while True:
543
+ if deadline_s is not None and time.time() - start > deadline_s:
544
+ return PollResult(False, failure="stalled", detail="client-side deadline exceeded")
545
+ try:
546
+ inst = vast_api.get_instance(handle.instance_id)
547
+ poll_errors.reset()
548
+ except vast_api.VastApiError as e:
549
+ if poll_errors.record(e):
550
+ return PollResult(False, failure="poll_error", detail=str(e))
551
+ continue
552
+ # Verified live: the instance-detail route TRANSIENTLY answers
553
+ # {"instances": null} for perfectly healthy instances (and for brand-new ones
554
+ # before they materialize). A single missing read means nothing — only a
555
+ # sustained streak is a real disappearance.
556
+ missing_streak = missing_streak + 1 if inst is None else 0
557
+
558
+ status = (inst or {}).get("actual_status") or ("missing" if inst is None else "unknown")
559
+ if status != last_status:
560
+ say(f"instance {handle.instance_id}: {status}")
561
+ last_status = status
562
+ last_progress = time.time()
563
+ if status == "running":
564
+ became_running = True
565
+
566
+ done = done_reader()
567
+ if done is not None and done_is_fresh(done):
568
+ return finish_ok(done)
569
+
570
+ if missing_streak >= 4 or status in _DEAD_STATES:
571
+ # One forced final read: the worker may have finished right before the
572
+ # instance self-destroyed (the normal success order on this substrate).
573
+ done = done_reader(force=True)
574
+ if done is not None and done_is_fresh(done):
575
+ return finish_ok(done)
576
+ raw_marker = marker_reader(force=True)
577
+ marker = None
578
+ if raw_marker:
579
+ with contextlib.suppress(ValueError):
580
+ marker = json.loads(raw_marker)
581
+ return PollResult(
582
+ False,
583
+ failure="job_failed",
584
+ detail=_failure_detail(hf_repo, prefix, spec.phase, marker, handle.instance_id),
585
+ )
586
+
587
+ raw_marker = marker_reader()
588
+ if raw_marker:
589
+ try:
590
+ marker = json.loads(raw_marker)
591
+ except ValueError:
592
+ marker = None
593
+ if marker and not marker.get("ok"):
594
+ return PollResult(
595
+ False,
596
+ failure="job_failed",
597
+ detail=_failure_detail(hf_repo, prefix, spec.phase, marker, handle.instance_id),
598
+ )
599
+ if marker and marker.get("ok"):
600
+ done = done_reader(force=True)
601
+ if done is not None and done_is_fresh(done):
602
+ return finish_ok(done)
603
+
604
+ if not became_running and time.time() - start > LOAD_TIMEOUT_S:
605
+ return PollResult(
606
+ False,
607
+ failure="stalled",
608
+ detail=f"instance stuck in '{status}' for {int(time.time() - start)}s "
609
+ f"(image pull / host issue)",
610
+ )
611
+
612
+ new_key, _stage = surface_heartbeat(heartbeat_reader, last_hb_key, say)
613
+ if new_key != last_hb_key:
614
+ last_hb_key = new_key
615
+ last_progress = time.time()
616
+ if became_running and time.time() - last_progress > stall_after_s:
617
+ return PollResult(
618
+ False,
619
+ failure="stalled",
620
+ detail=f"no worker progress for {int(time.time() - last_progress)}s "
621
+ f"(instance status {status})",
622
+ )
623
+ time.sleep(interval_s)
624
+
625
+
626
+ def submit_run_vast(
627
+ spec,
628
+ seed: int,
629
+ log=None,
630
+ on_handle=None,
631
+ attempt: int = 0,
632
+ offers: list[VastOffer] | None = None,
633
+ exclude_machine_ids: set[int] | frozenset[int] = frozenset(),
634
+ ) -> PollResult:
635
+ """Vast equivalent of ``runpod.jobs.submit_run``: rent, persist, poll.
636
+
637
+ The ``finally`` destroy is the cost-safety primary: every exit path — success,
638
+ failure, stall, exception, KeyboardInterrupt — tears the paid instance down.
639
+ """
640
+ if offers is None:
641
+ # GPU_INFO is keyed by concrete GPU class; a policy word ("cheapest"/"auto") would
642
+ # KeyError opaquely here. The allocator resolves policy words to a concrete class
643
+ # upstream, so reaching this fallback with one is a caller bug — name it clearly.
644
+ if spec.gpu.type not in GPU_INFO:
645
+ raise vast_api.VastApiError(
646
+ f"submit_run_vast needs a concrete gpu class, got {spec.gpu.type!r}"
647
+ )
648
+ info = GPU_INFO[spec.gpu.type]
649
+ offers = [
650
+ o
651
+ for o in usable_offers(
652
+ info.vram_gb,
653
+ _effective_disk_gb(spec),
654
+ exclude_machine_ids=exclude_machine_ids,
655
+ num_gpus=int(getattr(spec.gpu, "count", 1)),
656
+ )
657
+ if o.gpu == spec.gpu.type
658
+ ]
659
+ handle = deploy_and_submit(
660
+ spec, seed, offers, attempt=attempt, log=log, exclude_machine_ids=exclude_machine_ids
661
+ )
662
+ # The instance is rented and billing the MOMENT deploy_and_submit returns; the
663
+ # teardown ``finally`` must guard EVERYTHING after that point — including
664
+ # ``on_handle`` (persisting the remote handle can itself raise). Entering the try
665
+ # before on_handle guarantees the paid instance is destroyed even if the handle is
666
+ # never persisted, closing the rent->persist crash window's billing leak.
667
+ try:
668
+ if on_handle is not None:
669
+ on_handle(handle.to_dict())
670
+ hf_repo = spec.train.hf_repo
671
+ prefix = f"{spec.phase}/{spec.run_id}/seed{seed}"
672
+ reader = make_hf_heartbeat_reader(hf_repo, prefix) if hf_repo else None
673
+ stall = 1500.0
674
+ # Wall cap + provision/install grace; Vast has no server-side execution
675
+ # timeout, so the client deadline (and the bootstrap's own cap) bound spend.
676
+ deadline = max(60, int(spec.gpu.max_wall_seconds)) + 1800
677
+ return poll_vast_job(
678
+ handle,
679
+ spec,
680
+ seed,
681
+ log=log,
682
+ heartbeat_reader=reader,
683
+ stall_after_s=stall,
684
+ deadline_s=deadline,
685
+ )
686
+ finally:
687
+ vast_api.destroy_instance(handle.instance_id)
688
+
689
+
690
+ def cancel(remote: dict) -> None:
691
+ """Cross-process cancel: destroy the persisted instance (stops billing)."""
692
+ instance_id = remote.get("instance_id")
693
+ if instance_id:
694
+ vast_api.destroy_instance(int(instance_id))
695
+
696
+
697
+ def destroy_run_instances(run_id: str) -> list[int]:
698
+ """Destroy every instance belonging to ONE run (labels start with its run id).
699
+
700
+ Cancel/GC path: unlike ``sweep_orphans`` this never looks at other runs, so it
701
+ is safe to call while they are in flight. Best-effort: never raises.
702
+ """
703
+ destroyed: list[int] = []
704
+ if not run_id:
705
+ return destroyed
706
+ try:
707
+ instances = vast_api.list_instances()
708
+ except Exception:
709
+ return destroyed
710
+ prefixes = (run_id, f"autoslm-{run_id}") # instance_label may force the prefix
711
+ for inst in instances:
712
+ iid = inst.get("id")
713
+ label = str(inst.get("label") or "")
714
+ # Match on the label boundary, not a raw string prefix (see ``sweep_orphans``):
715
+ # an instance label is ``f"{run_label_prefix(run_id)}-s{seed}-a{attempt}"``, so a
716
+ # run's prefix must equal the label or be followed by the ``-s`` seed boundary.
717
+ # A bare ``startswith`` would let run ``100`` also destroy run ``1000``'s instances.
718
+ if (
719
+ iid
720
+ and any(label == p or label.startswith(p + "-s") for p in prefixes)
721
+ and vast_api.destroy_instance(int(iid))
722
+ ):
723
+ destroyed.append(int(iid))
724
+ return destroyed
725
+
726
+
727
+ def sweep_orphans(active_labels: set[str] | None = None) -> list[int]:
728
+ """Destroy AutoSLM-labeled instances that no live run owns; return destroyed ids.
729
+
730
+ Run at server startup (crash recovery) and after runs (belt and suspenders).
731
+ Only labels carrying the run-id prefix are ever touched — nothing else on the
732
+ account is ours to destroy. Best-effort: never raises.
733
+
734
+ ``active_labels`` may be RAW run ids (what the server tracks) — each is passed
735
+ through ``run_label_prefix`` so it matches the SAME forced-``autoslm-`` prefix the
736
+ instance labels carry. Passing an already-prefixed label is fine (idempotent), so a
737
+ live run whose id lacks the prefix is still correctly protected.
738
+ """
739
+ destroyed: list[int] = []
740
+ try:
741
+ instances = vast_api.list_instances()
742
+ except Exception as exc:
743
+ logger.warning("vast orphan sweep skipped: %s", exc)
744
+ return destroyed
745
+ active = {run_label_prefix(a) for a in (active_labels or set())}
746
+ for inst in instances:
747
+ label = str(inst.get("label") or "")
748
+ if not label.startswith("autoslm-"):
749
+ continue
750
+ # Match on the label boundary, not a raw string prefix: an instance label is
751
+ # ``f"{run_label_prefix(run_id)}-s{seed}-a{attempt}"`` (see ``instance_label``),
752
+ # so a live run's prefix must equal the label or be followed by the ``-s`` seed
753
+ # boundary. A bare ``startswith`` would let one run's prefix (e.g. ``autoslm-100``)
754
+ # shield another run's orphan (``autoslm-1000-...``) from the sweep.
755
+ if any(label == a or label.startswith(a + "-s") for a in active):
756
+ continue
757
+ iid = inst.get("id")
758
+ if iid and vast_api.destroy_instance(int(iid)):
759
+ destroyed.append(int(iid))
760
+ logger.warning("destroyed orphaned vast instance %s (label %s)", iid, label)
761
+ 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,1037 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Fail fast: a disaggregated-only model (e.g. Qwen3.6-35B-A3B) can't run colocated GRPO.
134
+ from .engine.rollout_bench import validate_disaggregated_requirement
135
+
136
+ validate_disaggregated_requirement(
137
+ requires_disaggregated=info.requires_disaggregated,
138
+ algorithm=spec.algorithm,
139
+ inference_gpus=spec.train.inference_gpus,
140
+ )
141
+ spec = JobSpec.from_dict(
142
+ {**_with_model_disk(spec, info), "run_id": spec.run_id or new_run_id()}
143
+ )
144
+ status = RunStatus(run_id=spec.run_id, state="queued", spec=spec.to_dict())
145
+ _save_status(status)
146
+ if dry_run:
147
+ status.state = "dry_run"
148
+ _save_status(status)
149
+ return status
150
+ if background:
151
+ threading.Thread(target=_run_job, args=(spec,), daemon=True).start()
152
+ return get_status(spec.run_id)
153
+ _run_job(spec)
154
+ return get_status(spec.run_id)
155
+
156
+
157
+ def get_status(run_id: str) -> RunStatus:
158
+ path = runs_file_path(run_id, ".json")
159
+ if not os.path.exists(path):
160
+ raise FileNotFoundError(f"unknown run_id: {run_id}")
161
+ with open(path) as f:
162
+ return RunStatus(**json.load(f))
163
+
164
+
165
+ def list_runs() -> list[RunStatus]:
166
+ os.makedirs(RUNS_DIR, exist_ok=True)
167
+ runs = []
168
+ for name in sorted(os.listdir(RUNS_DIR)):
169
+ if name.endswith(".json"):
170
+ with open(os.path.join(RUNS_DIR, name)) as f:
171
+ runs.append(RunStatus(**json.load(f)))
172
+ return runs
173
+
174
+
175
+ def get_logs(run_id: str) -> str:
176
+ log_path = runs_file_path(run_id, ".log")
177
+ if not os.path.exists(log_path):
178
+ return ""
179
+ with open(log_path) as f:
180
+ return f.read()
181
+
182
+
183
+ def cancel_run(run_id: str) -> RunStatus:
184
+ """Cancel a run: delete its remote Flash endpoint (stopping the worker), then mark it
185
+ cancelled.
186
+
187
+ Uses ``terminate_endpoint`` (reconstructs the run's uniquely-named endpoint and deletes it
188
+ via the RunPod API) so the cancel works **cross-process** — a fresh ``slm cancel`` actually
189
+ stops the GPU worker, instead of leaving it running until the wall cap. Best-effort: any
190
+ teardown error is recorded but still flips the run to ``cancelled``.
191
+ """
192
+ status = get_status(run_id)
193
+ if status.state in TERMINAL_STATES:
194
+ return status
195
+ # Whether the run was a live `deployed` serving run at cancel entry. This scopes the
196
+ # final `cancelled` transition's terminal override below: only a `deployed` run can have
197
+ # a concurrent undeploy (`mark_undeployed`) race this teardown and write a non-completion
198
+ # terminal `done`. A non-deployed run (running/provisioning/queued) has an in-flight
199
+ # TRAINING thread whose only terminal `done` is a GENUINE completion — which cancel must
200
+ # never clobber. See the final _update call for how this gates the override.
201
+ entered_deployed = status.state == "deployed"
202
+ spec = JobSpec.from_dict(status.spec)
203
+ remote = status.remote or {}
204
+ # A deployed run also owns a serving endpoint (autoslm-serve-*) that the
205
+ # training-endpoint GC below does not touch; tear it down too so a
206
+ # cancelled run can't leave a billable deployment registered. Serving is
207
+ # RunPod-only, so use the class actually deployed (a Vast-only training class
208
+ # falls back to a RunPod class at deploy time).
209
+ if status.state == "deployed":
210
+ try:
211
+ from autoslm.serve.deploy import undeploy_adapter
212
+
213
+ deployed_gpu = (status.deployment or {}).get("gpu") or spec.gpu.type
214
+ deleted = undeploy_adapter(run_id, gpu_name=deployed_gpu)
215
+ # Mark the deployment inactive so /v1/deployments and /chat (which gate only
216
+ # on the deployment record's state) stop treating the cancelled run as
217
+ # active. dev mode is scale-to-zero: a never-chatted dev deployment has no
218
+ # endpoint yet, so an empty deletion is still a clean teardown — don't leave
219
+ # it "ready". always-on provisions at deploy time, so only mark it inactive
220
+ # once a deletion is confirmed (an empty deletion there is suspicious).
221
+ dev_mode = (status.deployment or {}).get("mode", "dev") == "dev"
222
+ if status.deployment and (deleted or dev_mode):
223
+ # Mark the deployment inactive through the lock-guarded path so this write
224
+ # participates in the same _STATUS_LOCK as the rest of the runner. A bare
225
+ # _save_status here would persist a stale pre-teardown snapshot OUTSIDE the
226
+ # lock, bypassing serialization and potentially clobbering a concurrent field
227
+ # update. We mark ONLY the deployment field and leave the run's state alone
228
+ # (no state re-assert): a concurrent mark_undeployed can move the run to
229
+ # terminal `done` between our get_status read and this write, and _update's
230
+ # compare-and-set rejects ANY transition off a terminal state (even a
231
+ # same-field re-assert of the stale `deployed`), which would silently leave
232
+ # the deployment advertised as `ready`. mark_deployment_undeployed flips the
233
+ # deployment regardless of (and without disturbing) the current state.
234
+ mark_deployment_undeployed(run_id)
235
+ except Exception:
236
+ # Best-effort serving teardown: a failure here must not block the cancel
237
+ # below (the run still flips to cancelled and the training endpoint is GC'd).
238
+ pass
239
+ # Durable path first: stop the exact remote worker via the handle's provider
240
+ # (works from any process); endpoint/instance teardown is shared with the GC.
241
+ # Dispatched generically through the registry — never a hardcoded per-provider branch.
242
+ if remote:
243
+ try:
244
+ from autoslm.providers import get_provider
245
+ from autoslm.providers.base import JobHandle
246
+
247
+ handle = JobHandle.from_dict(remote)
248
+ provider = get_provider(handle.provider)
249
+ provider.cancel(handle)
250
+ # Vast bills until destroyed, so also belt-and-suspenders destroy the
251
+ # instance (a no-op cost-wise for runpod, whose endpoint GC follows).
252
+ provider.destroy(handle)
253
+ except Exception:
254
+ # Best-effort remote stop; _gc_run_endpoints below still tears the endpoint down.
255
+ pass
256
+ _gc_run_endpoints(spec)
257
+ # Final transition to `cancelled`. The run was NON-terminal at entry, but teardown takes
258
+ # time and a terminal state can race in mid-teardown. We must distinguish two cases:
259
+ #
260
+ # - A concurrent mark_undeployed() (an external `DELETE /v1/runs/{id}/deploy`) flipped a
261
+ # `deployed` run to terminal `done`. That `done` is NOT a fresh result — it just
262
+ # restored the run's pre-deploy completion marker while retiring serving. The user
263
+ # explicitly asked to cancel, so this must be OVERRIDDEN to `cancelled`.
264
+ # - A genuine training-COMPLETION `done` from the run's own training thread
265
+ # (_run_job_inner / attach_run), which persisted real metrics+cost+artifacts. Cancel
266
+ # must NEVER clobber that — the run finished, so the real result is preserved.
267
+ #
268
+ # These two races are mutually exclusive on the entry state: only a `deployed` run owns a
269
+ # deployment that mark_undeployed can race, and only a non-deployed (running/provisioning/
270
+ # queued) run has an in-flight training thread that can complete mid-teardown. So scope the
271
+ # terminal override to runs that were `deployed` at entry — there a racing `done` is always
272
+ # an undeploy artifact (cancel wins); elsewhere a racing `done` is a genuine completion that
273
+ # _update's CAS correctly protects (cancel loses to a real finish).
274
+ _update(run_id, "cancelled", allow_from_terminal=entered_deployed)
275
+ return get_status(run_id)
276
+
277
+
278
+ def attach_run(run_id: str, log_stream=None) -> RunStatus:
279
+ """Re-attach to a run's remote job from ANY process (after a client crash/restart).
280
+
281
+ Uses the persisted {endpoint_id, job_id} handle to resume polling; on completion,
282
+ persists metrics exactly like the original client would have, flips the state, and
283
+ GCs the endpoint. Raises if the run has no persisted handle (it failed or was
284
+ cancelled before a worker was provisioned).
285
+ """
286
+ import sys
287
+
288
+ status = get_status(run_id)
289
+ if status.state in TERMINAL_STATES:
290
+ return status
291
+ if not status.remote:
292
+ raise ValueError(f"run {run_id} has no persisted job handle; cannot reattach")
293
+
294
+ spec = JobSpec.from_dict(status.spec)
295
+ remote = dict(status.remote)
296
+ seed = int(remote.pop("seed", spec.train.seeds[0]))
297
+ # The class the run actually provisioned (a policy retry may have walked past the
298
+ # provisional spec.gpu.type). The in-process success path stamps this into metrics;
299
+ # on recovery the worker output carries no such field, so recover it from the handle
300
+ # to cost the right card.
301
+ allocated_gpu = remote.pop("allocated_gpu", None)
302
+ log = log_stream or sys.stderr
303
+ # Dispatch the poll generically via the handle's provider (the provider owns its
304
+ # heartbeat reader + poll loop); the orchestrator stays provider-agnostic.
305
+ from autoslm.providers import get_provider
306
+ from autoslm.providers.base import JobHandle
307
+
308
+ handle = JobHandle.from_dict(remote)
309
+ print(f"attaching to {run_id}: provider={handle.provider} {handle.data}", file=log)
310
+ res = get_provider(handle.provider).poll(handle, spec, seed, log=log)
311
+ try:
312
+ # A best-effort cancel deletes the job/instance, which the poller reports as a
313
+ # failure (or a late worker may still succeed) — either way, re-read the state
314
+ # first so a recovery thread can't overwrite the user's terminal `cancelled`.
315
+ if get_status(run_id).state == "cancelled":
316
+ return get_status(run_id)
317
+ if not res.ok:
318
+ _update(run_id, "failed", error=f"{res.failure}: {res.detail}")
319
+ return get_status(run_id)
320
+ # Carry the provisioned class into metrics so _persist_metrics costs the card the
321
+ # run actually used (the in-process path stamps this; recovery must restore it).
322
+ if allocated_gpu and isinstance(res.metrics, dict):
323
+ res.metrics.setdefault("allocated_gpu", allocated_gpu)
324
+ # Earlier seeds of a multi-seed run already persisted their cost into
325
+ # status.cost_usd; add this seed's so recovery doesn't underreport spend.
326
+ total = float(status.cost_usd or 0.0) + _persist_metrics(spec, seed, res.metrics)
327
+ # A cancel can land while this thread persists the recovered seed's metrics
328
+ # (after the late-cancel check above). Re-read before the post-seed writes so
329
+ # the "running" update and the terminal "done" below can't resurrect a
330
+ # user-cancelled run (mirrors the fresh seed loop). _RunCancelled is caught
331
+ # below, leaving the cancellation intact.
332
+ if get_status(run_id).state == "cancelled":
333
+ raise _RunCancelled(f"run {run_id} was cancelled")
334
+ # The remote handle only identifies the seed that was in flight. For a
335
+ # multi-seed run, resume the remaining seeds instead of terminally
336
+ # completing the whole run after just this one.
337
+ try:
338
+ resumed_index = list(spec.train.seeds).index(seed) + 1
339
+ except ValueError:
340
+ resumed_index = len(spec.train.seeds)
341
+ more_seeds = resumed_index < len(spec.train.seeds)
342
+ # Clear the now-stale completed handle before resuming. In the
343
+ # allocation/provisioning gap before the next seed's on_handle() persists a
344
+ # fresh handle, a server restart must not reattach recovery to this finished
345
+ # job — that would double-count its cost and replay the wrong seed. Record the
346
+ # next seed index so a restart in that gap resumes the remaining seeds rather
347
+ # than failing the run. (The last seed keeps its handle for post-run
348
+ # observability, mirroring the fresh-submit seed loop.)
349
+ _update(
350
+ run_id,
351
+ "running",
352
+ cost_usd=total,
353
+ artifacts_dir=artifacts_dir(spec),
354
+ **({"remote": None, "resume_seed_index": resumed_index} if more_seeds else {}),
355
+ )
356
+ if more_seeds:
357
+ _run_seed_loop(spec, log, start_index=resumed_index, prior_cost=total)
358
+ else:
359
+ _update(run_id, "done", cost_usd=total, artifacts_dir=artifacts_dir(spec))
360
+ except _RunCancelled:
361
+ # Intentional: cancel_run already wrote the terminal `cancelled` state; leave it.
362
+ pass
363
+ except Exception as exc:
364
+ if get_status(run_id).state != "cancelled":
365
+ _update(run_id, "failed", error=str(exc))
366
+ finally:
367
+ _gc_run_endpoints(spec)
368
+ return get_status(run_id)
369
+
370
+
371
+ def resume_run(run_id: str, log_stream=None) -> RunStatus:
372
+ """Resume the remaining seeds of a multi-seed run after a restart in the inter-seed gap.
373
+
374
+ Between two seeds the completed seed's handle is cleared and ``resume_seed_index`` is
375
+ recorded (see ``_run_seed_loop``). A control-plane restart in that handle-less window
376
+ must RESUME from that index rather than fail the run and discard the finished seeds.
377
+ Unlike ``attach_run`` there is no live job to poll — the prior process already tore the
378
+ seed's endpoint down — so we start a fresh seed loop from the recorded index. The slm
379
+ package was uploaded to HF on the original submit, so the worker can still fetch it; no
380
+ re-upload is needed.
381
+ """
382
+ import sys
383
+
384
+ status = get_status(run_id)
385
+ if status.state in TERMINAL_STATES:
386
+ return status
387
+ if status.resume_seed_index is None:
388
+ raise ValueError(f"run {run_id} has no resume_seed_index; cannot resume")
389
+ spec = JobSpec.from_dict(status.spec)
390
+ log = log_stream or sys.stderr
391
+ print(f"resuming {run_id}: remaining seeds from index {status.resume_seed_index}", file=log)
392
+ try:
393
+ _run_seed_loop(
394
+ spec,
395
+ log,
396
+ start_index=status.resume_seed_index,
397
+ prior_cost=float(status.cost_usd or 0.0),
398
+ )
399
+ except _RunCancelled:
400
+ pass # cancel_run already set the terminal state
401
+ except Exception as exc:
402
+ if get_status(run_id).state != "cancelled":
403
+ _update(run_id, "failed", error=str(exc))
404
+ finally:
405
+ # Mirror _run_job: GC any endpoint a transient destroy left behind rather than
406
+ # leaking a billable RunPod endpoint.
407
+ _gc_run_endpoints(spec)
408
+ return get_status(run_id)
409
+
410
+
411
+ def mark_deployed(run_id: str, deployment: dict, expect_state: str | None = None) -> RunStatus:
412
+ # Atomic + terminal-respecting (same guard as _update): a /cancel landing during
413
+ # always-on provisioning/warmup writes `cancelled`; this must NOT overwrite it with
414
+ # `deployed` and resurrect the run as an active deployment. `done` is deployable
415
+ # though (the common case: deploy a finished run), so only the non-`done` terminal
416
+ # states block here — otherwise a freshly finished run could never be deployed.
417
+ #
418
+ # expect_state is a compare-and-set: the deploy flow passes the state it expects the
419
+ # run to still be in (the pre-deploy snapshot, or "deployed" after the provisional
420
+ # mark). If an undeploy raced finalization — deleting the endpoint and writing `done`
421
+ # with deployment.state="undeployed" mid-warmup — the state no longer matches and we
422
+ # refuse to re-advertise the just-deleted endpoint.
423
+ with _STATUS_LOCK:
424
+ status = get_status(run_id)
425
+ if status.state in _UNDEPLOYABLE_STATES:
426
+ return status
427
+ if expect_state is not None and status.state != expect_state:
428
+ return status
429
+ status.deployment = deployment
430
+ status.state = "deployed"
431
+ status.updated_at = time.time()
432
+ _save_status(status)
433
+ return status
434
+
435
+
436
+ def mark_undeployed(run_id: str) -> RunStatus:
437
+ """Record an explicit undeploy (endpoint torn down -> run back to `done`).
438
+
439
+ Lock-guarded so it serializes with a racing deploy finalization: the raw read +
440
+ _save_status the endpoint used to do could interleave with mark_deployed and be
441
+ clobbered. With this under the same lock, mark_deployed's expect_state CAS then sees
442
+ the `done`/undeployed write and won't re-advertise the deleted endpoint.
443
+ """
444
+ with _STATUS_LOCK:
445
+ status = get_status(run_id)
446
+ if status.deployment:
447
+ status.deployment = {**status.deployment, "state": "undeployed"}
448
+ # Record the teardown but don't resurrect a terminal run: undeploying a
449
+ # cancelled/failed run keeps its terminal state (only a live `deployed` run goes
450
+ # back to `done`). `done` is terminal too, so this naturally no-ops the state.
451
+ if status.state not in TERMINAL_STATES:
452
+ status.state = "done"
453
+ status.updated_at = time.time()
454
+ _save_status(status)
455
+ return status
456
+
457
+
458
+ def mark_deployment_undeployed(run_id: str) -> RunStatus:
459
+ """Flip ONLY the deployment field to ``undeployed``, leaving the run's state untouched.
460
+
461
+ Used by ``cancel_run`` to retire a deployed run's serving record. Unlike
462
+ ``mark_undeployed`` (which is a state transition: a live `deployed` run goes back to
463
+ `done`), this never asserts or changes the run state. That matters under the cancel
464
+ race: a concurrent ``mark_undeployed`` may have already moved the run to terminal
465
+ `done`, and ``_update``'s compare-and-set rejects any transition off a terminal state —
466
+ even re-asserting `deployed` to carry the deployment field — which would leave the
467
+ deployment advertised as `ready`. Marking the field directly (lock-guarded for
468
+ serialization) sidesteps the CAS so the deployment reliably ends `undeployed`, while the
469
+ trailing ``cancelled`` transition is left to ``_update``.
470
+ """
471
+ with _STATUS_LOCK:
472
+ status = get_status(run_id)
473
+ if status.deployment:
474
+ status.deployment = {**status.deployment, "state": "undeployed"}
475
+ status.updated_at = time.time()
476
+ _save_status(status)
477
+ return status
478
+
479
+
480
+ def rollback_deploy(run_id: str, snapshot: RunStatus) -> None:
481
+ """Restore the pre-deploy state/deployment after always-on provisioning fails.
482
+
483
+ Lock-guarded + terminal-respecting (same guard as _update/mark_deployed): a /cancel
484
+ that landed during provisioning/warmup already persisted `cancelled`; restoring the
485
+ pre-deploy snapshot must NOT overwrite it and resurrect the run as `done`/`deployed`.
486
+ """
487
+ with _STATUS_LOCK:
488
+ status = get_status(run_id)
489
+ if status.state in TERMINAL_STATES:
490
+ return
491
+ status.state = snapshot.state
492
+ status.deployment = snapshot.deployment
493
+ status.updated_at = time.time()
494
+ _save_status(status)
495
+
496
+
497
+ def _run_job(spec: JobSpec) -> None:
498
+ # Lazy import so dry-run / unit tests never construct a Flash endpoint.
499
+ from autoslm.providers.runpod.train import upload_code
500
+
501
+ # A cancel can land between the queued status being returned to the client and
502
+ # this background thread starting; don't overwrite a terminal state (cancelled)
503
+ # with provisioning and then launch a paid seed as if the cancel never happened.
504
+ if get_status(spec.run_id).state in TERMINAL_STATES:
505
+ return
506
+ _update(spec.run_id, "provisioning")
507
+ log_path = os.path.join(RUNS_DIR, f"{spec.run_id}.log")
508
+ try:
509
+ _run_job_inner(spec, log_path, upload_code)
510
+ finally:
511
+ # Endpoint GC: every run leaves its uniquely-named endpoint registered, and the
512
+ # account-wide *max workers quota* (5 by default) counts registered endpoints —
513
+ # after a handful of runs, ALL new submissions fail with "Max workers across all
514
+ # endpoints must not exceed your workers quota". Tear ours down on any terminal
515
+ # state (best-effort; never raises).
516
+ _gc_run_endpoints(spec)
517
+
518
+
519
+ def _spec_with_gpu(spec: JobSpec, gpu_type: str) -> JobSpec:
520
+ """The spec the workers/loggers see for THIS attempt's allocated class."""
521
+ if spec.gpu.type == gpu_type:
522
+ return spec
523
+ d = spec.to_dict()
524
+ d["gpu"] = {**d["gpu"], "type": gpu_type}
525
+ return JobSpec.from_dict(d)
526
+
527
+
528
+ def _submit_seed_supervised(spec: JobSpec, seed: int, log) -> dict:
529
+ """Run one seed with the job submit/poll path + bounded auto-retry.
530
+
531
+ Each attempt first ALLOCATES the GPU: the cheapest class across providers (RunPod
532
+ live pricing + Vast verified-datacenter offers) that fits the model — re-resolved
533
+ fresh per attempt because offers are a live market. A policy ``gpu.requested``
534
+ ("cheapest"/"auto") lets the allocator pick the class; a concrete ``gpu.requested``
535
+ pins the class (the allocator then only picks the provider); ``gpu.provider`` pins
536
+ the substrate.
537
+
538
+ Retries (fresh job on a fresh host; worker resumes from the latest HF
539
+ checkpoint) when the failure looks infra-shaped: a stall (heartbeat frozen), a
540
+ client polling breakdown, or a platform TIMED_OUT/worker-loss. Sick Vast machines
541
+ are blacklisted for the run; failover naturally crosses providers.
542
+ Genuine worker errors (the run's code crashed; traceback persisted to HF) fail
543
+ immediately. The offline test/CI marker AUTOSLM_SKIP_NET takes the blocking
544
+ in-process submit instead (the job poll path is network-only).
545
+ """
546
+ from autoslm.providers.base import PollResult
547
+ from autoslm.providers.runpod.train import submit_train
548
+
549
+ if os.environ.get("AUTOSLM_SKIP_NET"):
550
+ return submit_train(spec, seed, log=log)
551
+
552
+ from autoslm.providers import get_provider
553
+ from autoslm.providers.allocator import allocate, allocation_summary
554
+ from autoslm.providers.base import POLICY_NAMES
555
+
556
+ last_handle: dict = {}
557
+ # The friendly GPU class the CURRENT attempt provisioned (set right before each submit),
558
+ # so on_handle persists it into the run handle and a recovery via attach_run costs the
559
+ # class actually used rather than the parse-time provisional spec.gpu.type.
560
+ current_gpu: dict = {}
561
+ # Every RunPod endpoint id this run registered across attempts. Retries run on
562
+ # rN-suffixed endpoints whose names _gc_run_endpoints cannot reconstruct, and a
563
+ # failed delete during the next attempt's teardown would otherwise lose the id;
564
+ # GC the whole set at exit so no retry endpoint leaks against the worker quota.
565
+ seen_endpoints: set[str] = set()
566
+
567
+ def on_handle(handle: dict):
568
+ last_handle.clear()
569
+ last_handle.update(handle)
570
+ if handle.get("endpoint_id"):
571
+ seen_endpoints.add(handle["endpoint_id"])
572
+ _update(
573
+ spec.run_id,
574
+ "running",
575
+ remote={**handle, "seed": int(seed), "allocated_gpu": current_gpu.get("name")},
576
+ )
577
+
578
+ def _gc_seen_endpoints() -> None:
579
+ if not seen_endpoints:
580
+ return
581
+ from autoslm.providers.runpod import api as runpod_api
582
+
583
+ for eid in seen_endpoints:
584
+ with contextlib.suppress(Exception):
585
+ runpod_api.delete_endpoint(eid)
586
+
587
+ max_retries = int(spec.gpu.max_retries)
588
+ last_detail = None
589
+ bad_machines: set[int] = set()
590
+ # Re-allocate freely for policy requests ("cheapest"/"auto"); honor a concrete
591
+ # user pin by passing it through as the only candidate class.
592
+ requested = (spec.gpu.requested or "").strip().lower()
593
+ pinned_gpu = None if requested in POLICY_NAMES else spec.gpu.type
594
+ # Index into the ranked candidate list. It advances only after an attempt that
595
+ # actually provisioned a class lost it to an infra failure (see the retry tail), so a
596
+ # failed allocation — which never tried a card — can't skip past the cheapest class.
597
+ gpu_walk_offset = 0
598
+ # Two independent budgets. ``crash_retries`` (bounded by max_retries) covers genuine
599
+ # infra flakes (host died, network timeout) where we re-provision the SAME-or-next class.
600
+ # ``capacity walks`` are different: a ``no_capacity`` (throttled / stuck IN_QUEUE) result
601
+ # just means "this class has no free workers right now" — so we WALK to the next-cheapest
602
+ # candidate WITHOUT spending the crash budget and WITHOUT blacklisting the class (it may
603
+ # free up; we simply prefer one that's available now). Bounded by the candidate count so a
604
+ # fully-throttled market terminates instead of looping forever.
605
+ crash_retries = 0
606
+ attempt = -1
607
+ while True:
608
+ attempt += 1
609
+ if attempt > 0 and last_handle:
610
+ # A stalled/timed-out attempt often means the worker is pinned to a
611
+ # throttled/sick host; tear it down so the fresh deploy lands elsewhere.
612
+ # Dispatched generically via the handle's provider.
613
+ if last_handle.get("provider") == "vast":
614
+ with contextlib.suppress(Exception):
615
+ from autoslm.providers import get_provider
616
+ from autoslm.providers.base import JobHandle
617
+
618
+ get_provider("vast").destroy(JobHandle.from_dict(last_handle))
619
+ if last_handle.get("machine_id"):
620
+ bad_machines.add(int(last_handle["machine_id"]))
621
+ print(
622
+ f"retry {attempt}: destroyed vast instance "
623
+ f"{last_handle.get('instance_id')} (machine "
624
+ f"{last_handle.get('machine_id')} blacklisted for this run)",
625
+ file=log,
626
+ flush=True,
627
+ )
628
+ elif last_handle.get("endpoint_id"):
629
+ try:
630
+ from autoslm.providers.runpod import api as runpod_api
631
+
632
+ runpod_api.cancel_job(last_handle["endpoint_id"], last_handle["job_id"])
633
+ runpod_api.delete_endpoint(last_handle["endpoint_id"])
634
+ print(
635
+ f"retry {attempt}: deleted endpoint {last_handle['endpoint_id']} "
636
+ "(escaping throttled/sick host)",
637
+ file=log,
638
+ flush=True,
639
+ )
640
+ except Exception:
641
+ # Logging the host-escape note is cosmetic; never let it abort the retry.
642
+ pass
643
+ # The previous endpoint is now deleted; clear the persisted handle so a cancel
644
+ # or control-plane restart during the fresh deploy doesn't operate on (or get
645
+ # shielded by) the dead handle. The next on_handle() records the new one.
646
+ with contextlib.suppress(FileNotFoundError):
647
+ st = get_status(spec.run_id)
648
+ if st.state not in TERMINAL_STATES and st.remote is not None:
649
+ _update(spec.run_id, st.state, remote=None)
650
+ res = None
651
+ alloc = None
652
+ chosen = None
653
+ # A cancel can land after _run_seed_loop's pre-submit check but while
654
+ # allocation/pricing runs, when no handle exists yet for cancel_run() to
655
+ # delete. Re-read state right before paid provisioning so a cancelled run
656
+ # never launches a worker (the later checks only stop the final-state
657
+ # overwrite, after the GPU has already run and billed).
658
+ with contextlib.suppress(FileNotFoundError):
659
+ if get_status(spec.run_id).state == "cancelled":
660
+ raise _RunCancelled(f"run {spec.run_id} was cancelled")
661
+ try:
662
+ alloc = allocate(
663
+ spec.model,
664
+ spec.algorithm,
665
+ gpu=pinned_gpu,
666
+ provider=spec.gpu.provider,
667
+ disk_gb=spec.gpu.disk_gb,
668
+ allow_unvalidated=spec.gpu.allow_unvalidated,
669
+ exclude_machine_ids=frozenset(bad_machines),
670
+ # Multi-GPU: the allocator must search for offers with this many GPUs (Vast) — else
671
+ # it builds the offer book at num_gpus=1 and a disaggregated run rents a 1-GPU
672
+ # instance (the real cause of "container has 1 GPU"). RunPod gets gpu_count on the
673
+ # endpoint separately (deploy_train_endpoint).
674
+ gpu_count=int(getattr(spec.gpu, "count", 1)),
675
+ # Pass the run's train knobs + thinking so the VRAM estimate reflects THIS job's
676
+ # max_length / group_size / batch_size / lora_rank (and the seq escalation) instead
677
+ # of the generic defaults — else a long-context / big-group run is sized at seq=1024
678
+ # and OOMs the card it picks.
679
+ train=spec.train,
680
+ thinking=spec.thinking,
681
+ )
682
+ except Exception as exc:
683
+ from autoslm.providers.base import UnsupportedGpuError
684
+
685
+ if isinstance(exc, UnsupportedGpuError):
686
+ raise # config-shaped: no GPU anywhere can run this job
687
+ res = PollResult(False, failure="poll_error", detail=f"allocation: {exc}")
688
+ if alloc is not None:
689
+ # allocate() above ran a live-market price walk; re-check cancellation
690
+ # right before provisioning so a cancel during allocation doesn't still
691
+ # launch a paid worker.
692
+ with contextlib.suppress(FileNotFoundError):
693
+ if get_status(spec.run_id).state == "cancelled":
694
+ raise _RunCancelled(f"run {spec.run_id} was cancelled")
695
+ # Walk down the ranked candidates by the walk offset (clamped to the last): the
696
+ # first attempt takes the cheapest; each retry that provisioned a class and lost
697
+ # it to an infra failure steps to the next-cheapest, so a capacity-starved class
698
+ # can't burn the whole budget. A concrete pin yields a single candidate, so the
699
+ # clamp keeps a pinned run on its class.
700
+ chosen = alloc.candidates[min(gpu_walk_offset, len(alloc.candidates) - 1)]
701
+ print(allocation_summary(alloc), file=log, flush=True)
702
+ if chosen.gpu != alloc.gpu:
703
+ print(
704
+ f"retry {attempt}: walking past the cheapest class to {chosen.gpu} "
705
+ f"@ ${chosen.hourly_usd:.2f}/hr",
706
+ file=log,
707
+ flush=True,
708
+ )
709
+ run_spec = _spec_with_gpu(spec, chosen.gpu)
710
+ current_gpu["name"] = chosen.gpu
711
+ provider = get_provider(chosen.provider)
712
+ # Vast needs the live-market offer book for the chosen class first, then the
713
+ # other allocator-approved classes by price; RunPod ignores ``offers``.
714
+ offers = None
715
+ if chosen.provider == "vast":
716
+ ok_classes = {c.gpu for c in alloc.candidates if c.provider == "vast"}
717
+ offers = sorted(
718
+ (o for o in alloc.provider_offers if o.gpu in ok_classes),
719
+ key=lambda o: (o.gpu != chosen.gpu, o.dph_total),
720
+ )
721
+ try:
722
+ res = provider.submit_run(
723
+ run_spec,
724
+ seed,
725
+ log=log,
726
+ on_handle=on_handle,
727
+ attempt=attempt,
728
+ offers=offers,
729
+ # The run's machine blacklist must reach the provider so an in-provider
730
+ # offer REFRESH (Vast) keeps stalled/sick machines excluded.
731
+ exclude_machine_ids=frozenset(bad_machines),
732
+ )
733
+ except Exception as exc:
734
+ # Deploy/submit themselves can fail transiently (observed: RunPod
735
+ # GraphQL "Something went wrong" x3 during a retry deploy; a vast offer
736
+ # pool emptying between search and rent). That must consume a retry, not
737
+ # kill the run — the budget exists precisely for flakes.
738
+ res = PollResult(False, failure="poll_error", detail=f"deploy/submit: {exc}")
739
+ if crash_retries < max_retries:
740
+ time.sleep(10 * (crash_retries + 1)) # let the transient clear
741
+ if res.ok:
742
+ # A best-effort cancel may fail to stop the worker, which then completes
743
+ # successfully after cancel_run() persisted `cancelled`. Don't let a late
744
+ # worker success resurrect the run into running/done.
745
+ try:
746
+ if get_status(spec.run_id).state == "cancelled":
747
+ raise _RunCancelled(f"run {spec.run_id} was cancelled")
748
+ except FileNotFoundError:
749
+ # Status file not yet written (early race): treat as not-cancelled, proceed.
750
+ pass
751
+ # Worker is done (DONE sentinel seen); GC every endpoint this seed used,
752
+ # including intermediate rN retries _gc_run_endpoints can't name.
753
+ _gc_seen_endpoints()
754
+ # Record the class actually allocated so _persist_metrics rates the right
755
+ # RunPod card when a policy GPU was re-allocated away from the provisional.
756
+ if chosen is not None and isinstance(res.metrics, dict):
757
+ res.metrics.setdefault("allocated_gpu", chosen.gpu)
758
+ return res.metrics
759
+ last_detail = f"{res.failure}: {res.detail}"
760
+ # Infra-shaped failures are retried on a FRESH endpoint/host; genuine worker
761
+ # code errors are not. Detail markers cover the observed flake classes:
762
+ # platform timeouts, worker pip-install network timeouts, and sick-GPU hosts.
763
+ _infra_markers = (
764
+ "TIMED_OUT",
765
+ "Failed to fetch",
766
+ "operation timed out",
767
+ "python_dependencies failed",
768
+ "Connection reset",
769
+ "cuda not available",
770
+ "GPU never became ready",
771
+ # Host vanished mid-run: the instance went "missing"/dead and NOTHING was captured
772
+ # (no marker error, no error_<phase>.txt, no console log) so _failure_detail falls back
773
+ # to this bare sentinel. A genuine worker code crash instead yields a RICHER detail
774
+ # (the captured traceback), so this exact phrase only ever marks a dead host -> retry it
775
+ # on a fresh one. Without this, a single ~1-in-200 host death killed the whole run.
776
+ "terminated without a DONE sentinel",
777
+ )
778
+ infra_shaped = res.failure in ("stalled", "poll_error", "no_capacity") or any(
779
+ m in (res.detail or "") for m in _infra_markers
780
+ )
781
+ # A cancel deletes the endpoint, which the poller sees as an
782
+ # infra-shaped failure; retrying would resurrect the run and keep
783
+ # billing. The user's cancel wins over the retry budget.
784
+ try:
785
+ if get_status(spec.run_id).state == "cancelled":
786
+ raise _RunCancelled(f"run {spec.run_id} was cancelled")
787
+ except FileNotFoundError:
788
+ # Status file not yet written (early race): treat as not-cancelled and proceed.
789
+ pass
790
+ # A capacity walk (no_capacity: the class is throttled / has no free workers right now)
791
+ # hops to the next-cheapest candidate WITHOUT spending the crash-retry budget and WITHOUT
792
+ # blacklisting the class — we just prefer one that's available now. It stops only once
793
+ # every candidate class has been tried (a fully-throttled market). A genuine infra crash
794
+ # (host died / network) instead spends the bounded crash budget.
795
+ is_capacity = res.failure == "no_capacity"
796
+ ncand = len(alloc.candidates) if alloc is not None else 0
797
+ if is_capacity:
798
+ can_retry = infra_shaped and chosen is not None and gpu_walk_offset < ncand - 1
799
+ else:
800
+ can_retry = infra_shaped and crash_retries < max_retries
801
+ print(
802
+ f"seed={seed} attempt={attempt} failed ({res.failure}); "
803
+ f"{'retrying (resume from last checkpoint)' if can_retry else 'not retrying'}"
804
+ f"\n--- failure detail ---\n{(res.detail or '')[:2000]}\n---",
805
+ file=log,
806
+ flush=True,
807
+ )
808
+ if not can_retry:
809
+ break
810
+ # Advance to the next-cheapest candidate when THIS attempt actually provisioned one.
811
+ # An allocation/pricing failure (chosen is None) never tried a card, so the next attempt
812
+ # must retry from the cheapest, not walk past it.
813
+ if chosen is not None:
814
+ gpu_walk_offset += 1
815
+ if is_capacity:
816
+ print(
817
+ f"retry: {chosen.gpu} had no free workers (throttled / capacity-starved); "
818
+ "walking to the next-cheapest available class (not blacklisting it)",
819
+ file=log,
820
+ flush=True,
821
+ )
822
+ if not is_capacity:
823
+ crash_retries += 1
824
+ # Retry budget exhausted: GC every endpoint this seed registered (the final
825
+ # attempt's is in status.remote for _gc_run_endpoints, but intermediate rN ones
826
+ # are only known here).
827
+ _gc_seen_endpoints()
828
+ raise RuntimeError(f"seed {seed} failed after retries: {last_detail}")
829
+
830
+
831
+ def _run_job_inner(spec: JobSpec, log_path: str, upload_code) -> None:
832
+ try:
833
+ # Ship the slm package to the run's HF repo (the per-run [train] hf_repo) so the GPU
834
+ # worker — which fetches code/** from that same repo — can run it.
835
+ upload_code(spec.train.hf_repo)
836
+ with open(log_path, "a") as log:
837
+ _run_seed_loop(spec, log, start_index=0, prior_cost=0.0)
838
+ except _RunCancelled:
839
+ return # cancel_run already set the terminal state
840
+ except Exception as exc:
841
+ if get_status(spec.run_id).state != "cancelled":
842
+ _update(spec.run_id, "failed", error=str(exc))
843
+ raise
844
+
845
+
846
+ def _run_seed_loop(spec: JobSpec, log, *, start_index: int, prior_cost: float) -> None:
847
+ """Run spec.train.seeds[start_index:] under supervision; finalize the run.
848
+
849
+ Shared by a fresh submit (start_index=0) and post-restart recovery, which
850
+ resumes the remaining seeds after the in-flight one completes."""
851
+ total_cost = prior_cost
852
+ seeds = spec.train.seeds
853
+ for i in range(start_index, len(seeds)):
854
+ seed = seeds[i]
855
+ # An early cancel (before any remote handle existed) sets `cancelled`;
856
+ # do not overwrite it with `running` and submit the GPU job anyway.
857
+ if get_status(spec.run_id).state == "cancelled":
858
+ raise _RunCancelled(f"run {spec.run_id} was cancelled")
859
+ _update(spec.run_id, "running")
860
+ print(
861
+ f"starting seed={seed} phase={spec.phase} model={spec.model} gpu={spec.gpu.type}",
862
+ file=log,
863
+ flush=True,
864
+ )
865
+ metrics = _submit_seed_supervised(spec, seed, log)
866
+ total_cost += _persist_metrics(spec, seed, metrics)
867
+ # A cancel can land while this thread writes metrics — after the supervised
868
+ # late-cancel check. Re-read before the post-seed status writes so a late
869
+ # worker success doesn't resurrect a user-cancelled run via this "running"
870
+ # update (or the final "done" below).
871
+ with contextlib.suppress(FileNotFoundError):
872
+ if get_status(spec.run_id).state == "cancelled":
873
+ raise _RunCancelled(f"run {spec.run_id} was cancelled")
874
+ # If more seeds follow, this seed's endpoint/instance is already torn down, so
875
+ # clear the now-stale remote handle: a restart in the gap before the next
876
+ # seed's on_handle must not make recover_runs reattach to a deleted handle and
877
+ # fail the run. Record the next seed index so a restart in that handle-less gap
878
+ # RESUMES the remaining seeds (recover_runs) instead of discarding the completed
879
+ # ones. The last seed keeps its handle for post-run observability (the run is
880
+ # about to go terminal, which recover_runs never reattaches).
881
+ more_seeds = (i + 1) < len(seeds)
882
+ _update(
883
+ spec.run_id,
884
+ "running",
885
+ cost_usd=total_cost,
886
+ **({"remote": None, "resume_seed_index": i + 1} if more_seeds else {}),
887
+ )
888
+ print(
889
+ f"seed={seed} done: train_wall={metrics.get('wall_seconds')} cost_usd={total_cost:.4f}",
890
+ file=log,
891
+ flush=True,
892
+ )
893
+ # Final guard: a cancel landing after the last seed's check must not be overwritten
894
+ # by the terminal "done".
895
+ with contextlib.suppress(FileNotFoundError):
896
+ if get_status(spec.run_id).state == "cancelled":
897
+ raise _RunCancelled(f"run {spec.run_id} was cancelled")
898
+ _update(
899
+ spec.run_id,
900
+ "done",
901
+ cost_usd=total_cost,
902
+ artifacts_dir=artifacts_dir(spec),
903
+ resume_seed_index=None,
904
+ )
905
+
906
+
907
+ def _gc_run_endpoints(spec: JobSpec) -> None:
908
+ """Best-effort teardown of every endpoint a run may have registered.
909
+
910
+ Retried attempts run on rN-suffixed endpoints whose runpod_flash state is
911
+ isolated per-suffix, so the name-based terminate_endpoint cannot see them;
912
+ the persisted remote handle's endpoint id covers whichever attempt ran
913
+ last via the plain REST API."""
914
+ status = None
915
+ with contextlib.suppress(Exception):
916
+ status = get_status(spec.run_id)
917
+ if status is not None and status.remote:
918
+ try:
919
+ from autoslm.providers import get_provider
920
+ from autoslm.providers.base import JobHandle
921
+
922
+ handle = JobHandle.from_dict(status.remote)
923
+ get_provider(handle.provider).destroy(handle)
924
+ except Exception:
925
+ # Best-effort GC; the name-reconstructed RunPod gc below is the backstop.
926
+ pass
927
+ try:
928
+ # RunPod's gc reaps rN-suffixed endpoints the persisted handle can't name.
929
+ from autoslm.providers import get_provider
930
+
931
+ get_provider("runpod").gc(spec)
932
+ except Exception:
933
+ # Best-effort GC; an undeleted endpoint only holds worker quota, never blocks the run.
934
+ pass
935
+ # Vast instances bill until destroyed: the runner's per-attempt `finally` already
936
+ # destroys them, but a crashed supervisor thread can leave one behind. Reap any
937
+ # instance still labeled for this run via the provider's gc (best-effort).
938
+ from autoslm.providers import available_providers, get_provider
939
+
940
+ if "vast" in available_providers():
941
+ with contextlib.suppress(Exception):
942
+ get_provider("vast").gc(spec)
943
+
944
+
945
+ def _persist_metrics(spec: JobSpec, seed: int, metrics: dict) -> float:
946
+ """Write metrics to results/runpod/<phase>/<run_id>/seedN and return the cost.
947
+
948
+ The run id keeps concurrent/sequential runs of the same phase+seed from
949
+ overwriting each other's artifacts. Vast runs arrive with ``cost_usd`` already
950
+ stamped from the offer's real $/hr (plus provider notes) and short-circuit the
951
+ rate fallback below (the RunPod projection)."""
952
+ dest = os.path.join(artifacts_dir(spec), f"seed{seed}")
953
+ os.makedirs(dest, exist_ok=True)
954
+ # Rate the actually-allocated class, not the parse-time provisional spec.gpu.type:
955
+ # a policy GPU can be re-allocated to a different RunPod class at submit time, so
956
+ # the worker stamps "allocated_gpu" into metrics for the cost fallback below.
957
+ gpu_type = metrics.get("allocated_gpu") or spec.gpu.type
958
+ rate = _gpu_rate(gpu_type)
959
+ # A non-runpod provider (e.g. Vast) stamps the real cost_usd from its offer's $/hr
960
+ # AND tags notes["provider"] with its own name — and a near-zero-duration run can
961
+ # legitimately stamp cost_usd == 0.0. The RunPod arm, by contrast, never stamps a real
962
+ # cost: it arrives with cost_usd absent (or a 0.0 placeholder) and no provider note, so
963
+ # the wall-based projection below must run. A bare `cost or 0.0` would treat the Vast
964
+ # 0.0 as "absent" and re-rate it against RunPod pricing while overwriting the provider
965
+ # notes, mis-attributing the run to 'runpod'. So fall back only when the cost is
966
+ # missing/zero AND it has NOT already been attributed to a non-runpod provider.
967
+ _notes = metrics.get("notes")
968
+ _stamped_provider = _notes.get("provider") if isinstance(_notes, dict) else None
969
+ _non_runpod = bool(_stamped_provider) and _stamped_provider != "runpod"
970
+ cost = metrics.get("cost_usd")
971
+ if cost or _non_runpod:
972
+ cost = float(cost or 0.0)
973
+ else:
974
+ wall = float(metrics.get("wall_seconds") or 0.0)
975
+ cost = wall / 3600.0 * rate
976
+ metrics = {**metrics, "cost_usd": cost}
977
+ metrics.setdefault("notes", {})
978
+ if isinstance(metrics["notes"], dict):
979
+ metrics["notes"]["provider"] = "runpod"
980
+ metrics["notes"]["runpod_rate_usd_hr"] = rate
981
+ metrics["notes"]["runpod_gpu"] = gpu_type
982
+ with open(os.path.join(dest, "metrics.json"), "w") as f:
983
+ json.dump(metrics, f, indent=2)
984
+ return float(cost)
985
+
986
+
987
+ def _update(run_id: str, state: str, *, allow_from_terminal: bool = False, **updates) -> None:
988
+ # The read-check-write below must be atomic: a concurrent `slm cancel` (also via
989
+ # _update) landing between the get_status read and the _save_status write could
990
+ # otherwise be clobbered by this stale background update, resurrecting a cancelled
991
+ # run. The control plane is single-instance with per-run threads, so a process-wide
992
+ # lock serializes all status transitions into a compare-and-set.
993
+ with _STATUS_LOCK:
994
+ status = get_status(run_id)
995
+ # Terminal states are STICKY: once a run is done/failed/cancelled/dry_run, no
996
+ # other state may overwrite it. This closes the whole cancel-race class at the
997
+ # source — a cancel landing between a caller's check and a later write
998
+ # (provisioning/running, or even a late terminal done/failed from a worker that
999
+ # finished as the cancel arrived) can no longer resurrect the run. Same-state
1000
+ # writes still pass so terminal field updates (cost_usd, error, artifacts_dir)
1001
+ # are preserved.
1002
+ #
1003
+ # allow_from_terminal is the NARROW escape hatch used ONLY by cancel_run's final
1004
+ # `cancelled` transition, and ONLY when the run was `deployed` at cancel entry (see
1005
+ # cancel_run). In that case an explicit user cancel must WIN over a racing
1006
+ # mark_undeployed() that flipped the `deployed` run to terminal `done` mid-teardown —
1007
+ # that `done` is an undeploy artifact (restoring the pre-deploy completion marker while
1008
+ # retiring serving), not a fresh result. Without the override the `cancelled` write
1009
+ # no-ops against the freshly-written `done` and the run wrongly ends `done` despite the
1010
+ # user asking to cancel. cancel_run passes allow_from_terminal=False for a non-deployed
1011
+ # run, so a GENUINE training-completion `done` racing in from the run's own training
1012
+ # thread is protected by the CAS below — cancel correctly loses to a real finish.
1013
+ if status.state in TERMINAL_STATES and state != status.state and not allow_from_terminal:
1014
+ return
1015
+ status.state = state
1016
+ status.updated_at = time.time()
1017
+ for key, value in updates.items():
1018
+ setattr(status, key, value)
1019
+ _save_status(status)
1020
+
1021
+
1022
+ def _save_status(status: RunStatus) -> None:
1023
+ os.makedirs(RUNS_DIR, exist_ok=True)
1024
+ # Write-then-rename: a concurrent reader (poll on /v1/runs or /logs) must
1025
+ # never observe a half-written/truncated file and 500 on JSONDecodeError.
1026
+ # The temp name is UNIQUE per write (mkstemp) so two threads updating the same
1027
+ # run (e.g. a cancel racing the background seed update) can't clobber each
1028
+ # other's temp file mid-dump — each os.replace is atomic and independent.
1029
+ path = runs_file_path(status.run_id, ".json")
1030
+ fd, tmp = tempfile.mkstemp(dir=RUNS_DIR, prefix=f"{status.run_id}.", suffix=".tmp")
1031
+ try:
1032
+ with os.fdopen(fd, "w") as f:
1033
+ json.dump(status.to_dict(), f, indent=2, sort_keys=True)
1034
+ os.replace(tmp, path)
1035
+ finally:
1036
+ with contextlib.suppress(FileNotFoundError):
1037
+ os.unlink(tmp)
code/autoslm/schema.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # GPUs in the node dedicated to the disaggregated vLLM rollout server (0 = colocate,
292
+ # the default). >0 needs a multi-GPU node ([gpu] count = trainer + inference); the
293
+ # count>inference_gpus cross-check is in _validate_spec. minimum=0 so an explicit
294
+ # `inference_gpus = 0` (colocate) is accepted, not rejected as below-minimum.
295
+ inference_gpus=_train_int(train_raw, "inference_gpus", minimum=0) or 0,
296
+ ),
297
+ gpu=GpuSpec(
298
+ type=gpu_type,
299
+ count=int(gpu_raw.get("count", 1)),
300
+ provider=provider,
301
+ requested=requested_gpu,
302
+ allow_unvalidated=allow_unval,
303
+ disk_gb=int(gpu_raw.get("disk_gb", 60)),
304
+ max_wall_seconds=int(gpu_raw.get("max_wall_seconds", 24 * 3600)),
305
+ max_retries=int(gpu_raw.get("max_retries", 2)),
306
+ network_volume=gpu_raw.get("network_volume"),
307
+ network_volume_gb=int(gpu_raw.get("network_volume_gb", 100)),
308
+ datacenter=gpu_raw.get("datacenter"),
309
+ ),
310
+ run_id=run_id or raw.get("run_id", "local"),
311
+ worker_env=_worker_env(raw.get("worker_env")),
312
+ model_policy=model_policy,
313
+ thinking=thinking,
314
+ )
315
+ _validate_spec(spec)
316
+ return spec
317
+
318
+
319
+ def _worker_env(raw: Any) -> dict[str, str]:
320
+ """Parse the optional [worker_env] table: per-run worker env overrides (string-valued)."""
321
+ if raw is None:
322
+ return {}
323
+ if not isinstance(raw, dict):
324
+ raise ConfigError("[worker_env] must be a table of string key/values")
325
+ env = {str(k): str(v) for k, v in raw.items()}
326
+ # [worker_env] is serialized into job_spec_json (persisted + logged), so it must NOT carry
327
+ # secrets — they would leak into run artifacts. Reject secret-looking keys; operators set
328
+ # those as real process environment variables (forwarded to the worker out-of-band) instead.
329
+ # Detect by `_`-delimited WORD components (not substring): flag a secret WORD, or `KEY`
330
+ # qualified by API/SECRET/PRIVATE/ACCESS/INTERNAL/AUTH. This catches HF_TOKEN, *_API_KEY,
331
+ # SECRET_KEY, INTERNAL_KEY, CREDENTIAL, AWS_SECRET_ACCESS_KEY while allowing legit knobs whose
332
+ # names merely contain a marker (RL_VLLM_MAX_BATCHED_TOKENS -> word TOKENS, not TOKEN; a bare
333
+ # SORT_KEY -> KEY without a secret qualifier).
334
+ _secret_words = {"TOKEN", "SECRET", "PASSWORD", "PASSWD", "CREDENTIAL", "CREDENTIALS", "APIKEY", "PRIVATEKEY"}
335
+ _key_qualifiers = {"API", "SECRET", "PRIVATE", "ACCESS", "INTERNAL", "AUTH", "SIGNING", "ENCRYPTION"}
336
+
337
+ def _is_secret_key(name: str) -> bool:
338
+ words = set(name.upper().split("_"))
339
+ return bool(words & _secret_words) or ("KEY" in words and bool(words & _key_qualifiers))
340
+
341
+ secrets = sorted(k for k in env if _is_secret_key(k))
342
+ if secrets:
343
+ raise ConfigError(
344
+ f"[worker_env] must not contain secret-bearing keys ({', '.join(secrets)}); these are "
345
+ "serialized into run artifacts — set them as real environment variables instead"
346
+ )
347
+ return env
348
+
349
+
350
+ def _validate_spec(spec: JobSpec) -> None:
351
+ if not spec.train.seeds:
352
+ raise ConfigError("train.seeds must contain at least one seed")
353
+ try:
354
+ canonical_gpu(spec.gpu.type)
355
+ except UnsupportedGpuError as exc:
356
+ raise ConfigError(str(exc)) from exc
357
+ # GRPO is step-driven; SFT is epoch-driven. Reject a non-positive explicit count
358
+ # for whichever the algorithm consumes, so an invalid config fails here instead of
359
+ # provisioning a worker that silently falls back to a default count.
360
+ if spec.algorithm == "grpo" and spec.train.steps is not None and spec.train.steps <= 0:
361
+ raise ConfigError("train.steps must be positive for GRPO")
362
+ if spec.algorithm == "sft" and spec.train.epochs is not None and spec.train.epochs <= 0:
363
+ raise ConfigError("train.epochs must be positive for SFT")
364
+ # Verifiers-only: every run must name an environment by its verifiers/Prime Hub slug
365
+ # via [environment] id. There is no default environment and no local path mode.
366
+ if not spec.environment.id:
367
+ raise ConfigError(
368
+ "config must set [environment] id (a verifiers/Prime Hub env slug, e.g. "
369
+ '"owner/name"); there is no local path mode'
370
+ )
371
+ # The id must be a full Prime Hub slug "owner/name": exactly one slash, both parts
372
+ # non-empty. A bare id like "gsm8k" passes the presence check but then the worker runs
373
+ # `prime env install gsm8k` (invalid — Prime needs owner/name) and fails after provisioning.
374
+ _require_slug(
375
+ spec.environment.id,
376
+ '[environment] id must be a published Prime Hub slug "owner/name"',
377
+ )
378
+ # A separate eval env ([environment.params] eval_env_id) is also prime-installed on the worker
379
+ # (worker_hub_env_ids), so it must be a full "owner/name" slug too — else a bare eval id passes
380
+ # --dry-run but fails `prime env install` after a GPU is provisioned.
381
+ if "eval_env" in spec.environment.params:
382
+ # Legacy alias: `eval_env` is no longer mapped (the worker installs only eval_env_id, and
383
+ # a stray `eval_env` would be forwarded into load_environment). Reject at parse rather than
384
+ # silently evaluating against the training env.
385
+ raise ConfigError(
386
+ "[environment.params] eval_env is no longer supported; use eval_env_id "
387
+ '(a published Prime Hub slug "owner/name")'
388
+ )
389
+ eval_ref = spec.environment.params.get("eval_env_id")
390
+ if eval_ref:
391
+ _require_slug(
392
+ str(eval_ref),
393
+ '[environment.params] eval_env_id must be a published Prime Hub slug "owner/name"',
394
+ )
395
+ if spec.train.lora_rank <= 0:
396
+ raise ConfigError("train.lora_rank must be positive")
397
+ # The per-run HF artifact repo (adapters/checkpoints/code + serving) is required: there
398
+ # is no operator-wide default anymore. It must look like "owner/name" (exactly one slash,
399
+ # both parts non-empty) — a malformed value would reach the worker/serve as an unusable id.
400
+ if not spec.train.hf_repo:
401
+ raise ConfigError(
402
+ "train.hf_repo is required: the HF dataset repo for this run's adapters/checkpoints, "
403
+ 'e.g. "owner/name"'
404
+ )
405
+ _require_slug(
406
+ spec.train.hf_repo,
407
+ 'train.hf_repo must be a HuggingFace repo of the form "owner/name"',
408
+ )
409
+ # GRPO recipe knobs (group_size/temperature/max_tokens/kl_penalty_coef/advantage_clip/
410
+ # thinking_length_penalty_coef) are range-validated at parse time by the _train_int/
411
+ # _train_float coercers above (including the thinking_length_penalty_coef <= 1.0 upper
412
+ # bound), so no re-check is needed here.
413
+ # lora_alpha scales the adapter contribution; 0 (or negative) trains a paid run
414
+ # that produces a no-op adapter (zero scaling at serve). Reject up front.
415
+ if spec.train.lora_alpha <= 0:
416
+ raise ConfigError("train.lora_alpha must be positive")
417
+ # Multi-GPU / disaggregated-rollout topology ([gpu] count, [train] inference_gpus).
418
+ if spec.gpu.count < 1:
419
+ raise ConfigError("gpu.count must be >= 1")
420
+ if spec.train.inference_gpus < 0:
421
+ raise ConfigError("train.inference_gpus must be >= 0")
422
+ if spec.train.inference_gpus > 0:
423
+ # The disaggregated async rollout (vLLM server on dedicated GPUs) is a GRPO-only path —
424
+ # SFT has no rollout engine, so inference_gpus would just strand paid GPUs.
425
+ if spec.algorithm != "grpo":
426
+ raise ConfigError(
427
+ "train.inference_gpus is only valid for grpo (the disaggregated rollout server); "
428
+ "SFT has no rollout engine"
429
+ )
430
+ # Need at least one trainer GPU left after carving off the inference GPUs.
431
+ if spec.gpu.count <= spec.train.inference_gpus:
432
+ raise ConfigError(
433
+ f"gpu.count ({spec.gpu.count}) must be greater than train.inference_gpus "
434
+ f"({spec.train.inference_gpus}) — at least one GPU must train "
435
+ "(gpu.count = trainer GPUs + inference_gpus)"
436
+ )
437
+ # train_gpus>1 (2:1, 3:1, 2:2) runs the trainer as an FSDP group via `accelerate launch`
438
+ # (run_rl's disaggregated launcher re-execs the worker across the train devices). Supported.