Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- code/flash/__init__.py +11 -0
- code/flash/_fileio.py +35 -0
- code/flash/_logging.py +49 -0
- code/flash/catalog.py +219 -0
- code/flash/cli/__init__.py +1 -0
- code/flash/cli/main.py +919 -0
- code/flash/client/__init__.py +14 -0
- code/flash/client/config.py +46 -0
- code/flash/client/http.py +187 -0
- code/flash/client/specs.py +23 -0
- code/flash/engine/__init__.py +7 -0
- code/flash/engine/accounting.py +37 -0
- code/flash/engine/chalk_kernels.py +162 -0
- code/flash/engine/midrun_eval.py +446 -0
- code/flash/engine/multiturn_rollout.py +266 -0
- code/flash/engine/recipe.py +86 -0
- code/flash/engine/vram.py +367 -0
- code/flash/engine/worker.py +0 -0
- code/flash/envs/__init__.py +10 -0
- code/flash/envs/adapter.py +717 -0
- code/flash/envs/base.py +49 -0
- code/flash/envs/registry.py +79 -0
- code/flash/mcp/__init__.py +1 -0
- code/flash/mcp/server.py +83 -0
- code/flash/providers/__init__.py +60 -0
- code/flash/providers/_auth.py +24 -0
- code/flash/providers/_http.py +100 -0
- code/flash/providers/_poll.py +87 -0
- code/flash/providers/allocator.py +262 -0
- code/flash/providers/base.py +540 -0
- code/flash/providers/preflight.py +80 -0
- code/flash/providers/runpod/__init__.py +108 -0
- code/flash/providers/runpod/api.py +117 -0
- code/flash/providers/runpod/auth.py +24 -0
- code/flash/providers/runpod/gpus.py +46 -0
- code/flash/providers/runpod/jobs.py +519 -0
- code/flash/providers/runpod/preflight.py +30 -0
- code/flash/providers/runpod/pricing.py +110 -0
- code/flash/providers/runpod/train.py +952 -0
- code/flash/providers/vast/__init__.py +124 -0
- code/flash/providers/vast/_bootstrap.py +282 -0
- code/flash/providers/vast/api.py +219 -0
- code/flash/providers/vast/auth.py +24 -0
- code/flash/providers/vast/gpus.py +21 -0
- code/flash/providers/vast/jobs.py +729 -0
- code/flash/providers/vast/preflight.py +26 -0
- code/flash/providers/vast/pricing.py +51 -0
- code/flash/providers/vast/train.py +27 -0
- code/flash/py.typed +0 -0
- code/flash/runner.py +994 -0
code/flash/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Flash — 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/flash/_fileio.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small shared file-IO helpers for credential/manifest JSON under ``~/.flash``."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import contextlib
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def read_json_or_empty(path: Path) -> dict:
|
| 12 |
+
"""Parse a JSON object file, returning ``{}`` if it's missing or unreadable."""
|
| 13 |
+
try:
|
| 14 |
+
return json.loads(path.read_text())
|
| 15 |
+
except (OSError, ValueError):
|
| 16 |
+
return {}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def secure_json_write(path: Path, data: dict) -> None:
|
| 20 |
+
"""Write ``data`` as JSON with private permissions (the file may hold a secret).
|
| 21 |
+
|
| 22 |
+
Creates the parent dir (0700) and opens the file 0600 from the start — never
|
| 23 |
+
write_text + chmod, which leaves it umask-readable in between. ``O_NOFOLLOW``
|
| 24 |
+
(where available) refuses to follow a symlink planted at ``path`` so the write
|
| 25 |
+
can't be redirected to clobber an arbitrary file.
|
| 26 |
+
"""
|
| 27 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 28 |
+
with contextlib.suppress(OSError):
|
| 29 |
+
os.chmod(path.parent, 0o700)
|
| 30 |
+
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0)
|
| 31 |
+
fd = os.open(path, flags, 0o600)
|
| 32 |
+
with os.fdopen(fd, "w") as f:
|
| 33 |
+
json.dump(data, f, indent=2, sort_keys=True)
|
| 34 |
+
with contextlib.suppress(OSError):
|
| 35 |
+
os.chmod(path, 0o600)
|
code/flash/_logging.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Package logging helpers.
|
| 2 |
+
|
| 3 |
+
Library code logs through the ``flash`` logger and never configures handlers on import (it
|
| 4 |
+
attaches a :class:`logging.NullHandler`), so importing Flash 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``.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import logging
|
| 12 |
+
|
| 13 |
+
_ROOT_NAME = "flash"
|
| 14 |
+
|
| 15 |
+
# Attach a NullHandler once so "No handlers could be found" warnings never appear and
|
| 16 |
+
# importing the library produces no output unless the app opts in.
|
| 17 |
+
_root = logging.getLogger(_ROOT_NAME)
|
| 18 |
+
if not any(isinstance(h, logging.NullHandler) for h in _root.handlers):
|
| 19 |
+
_root.addHandler(logging.NullHandler())
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_logger(name: str | None = None) -> logging.Logger:
|
| 23 |
+
"""Return a logger under the ``flash`` namespace (e.g. ``get_logger(__name__)``)."""
|
| 24 |
+
if not name or name == _ROOT_NAME:
|
| 25 |
+
return logging.getLogger(_ROOT_NAME)
|
| 26 |
+
if name.startswith(_ROOT_NAME + "."):
|
| 27 |
+
return logging.getLogger(name)
|
| 28 |
+
return logging.getLogger(f"{_ROOT_NAME}.{name}")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def configure_logging(verbosity: int = 0, level: int | None = None) -> None:
|
| 32 |
+
"""Attach a console handler to the ``flash`` logger and set its level.
|
| 33 |
+
|
| 34 |
+
``verbosity`` maps repeated ``-v`` flags to levels (0=WARNING, 1=INFO, >=2=DEBUG).
|
| 35 |
+
An explicit ``level`` overrides the verbosity mapping.
|
| 36 |
+
"""
|
| 37 |
+
if level is None:
|
| 38 |
+
level = {0: logging.WARNING, 1: logging.INFO}.get(verbosity, logging.DEBUG)
|
| 39 |
+
|
| 40 |
+
logger = logging.getLogger(_ROOT_NAME)
|
| 41 |
+
logger.setLevel(level)
|
| 42 |
+
# Replace any prior console handler we installed so repeated calls don't stack handlers.
|
| 43 |
+
for h in [h for h in logger.handlers if getattr(h, "_flash_console", False)]:
|
| 44 |
+
logger.removeHandler(h)
|
| 45 |
+
handler = logging.StreamHandler() # stderr
|
| 46 |
+
handler.setLevel(level)
|
| 47 |
+
handler.setFormatter(logging.Formatter("%(levelname)s %(name)s: %(message)s"))
|
| 48 |
+
handler._flash_console = True # type: ignore[attr-defined]
|
| 49 |
+
logger.addHandler(handler)
|
code/flash/catalog.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Curated model catalog for one-consumer-GPU LoRA jobs."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from dataclasses import asdict, dataclass
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
ALGORITHMS = ("sft", "grpo")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def normalize_algorithm(value: str) -> str:
|
| 13 |
+
"""Canonical (lowercased, validated) algorithm name."""
|
| 14 |
+
value = (value or "grpo").lower()
|
| 15 |
+
if value not in ALGORITHMS:
|
| 16 |
+
raise ValueError(f"unsupported algorithm: {value}; known: {', '.join(ALGORITHMS)}")
|
| 17 |
+
return value
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# The default GPU class a run lands on when none is pinned (also the open-model-policy
|
| 21 |
+
# sizing reference and the spec/from_dict fallback). The validated GPU class set
|
| 22 |
+
# (SUPPORTED/is_validated) lives in providers.base; per-provider classes and pricing live
|
| 23 |
+
# under providers/{runpod,vast}. Defined above ModelInfo so it can back the
|
| 24 |
+
# recommended_gpu field default.
|
| 25 |
+
DEFAULT_GPU = "RTX 5090"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass(frozen=True)
|
| 29 |
+
class ModelInfo:
|
| 30 |
+
id: str
|
| 31 |
+
display_name: str
|
| 32 |
+
params: str
|
| 33 |
+
algos: tuple[str, ...]
|
| 34 |
+
min_vram_gb: int
|
| 35 |
+
quant: str = "bf16"
|
| 36 |
+
recommended_gpu: str = DEFAULT_GPU
|
| 37 |
+
# GRPO needs more VRAM than SFT (a colocated vLLM rollout engine holds a second copy of
|
| 38 |
+
# the weights + KV cache). 0 => GRPO uses ``min_vram_gb`` like SFT; set it when the GRPO
|
| 39 |
+
# tier needs a bigger card than SFT (the colocate 2nd weight copy + KV pool). Consumed by
|
| 40 |
+
# engine.vram.model_required_vram_gb.
|
| 41 |
+
grpo_min_vram_gb: int = 0
|
| 42 |
+
notes: str = ""
|
| 43 |
+
# Worker container disk this model needs (GB). 0 = the platform default (64 GB)
|
| 44 |
+
# suffices. The runner raises gpu.disk_gb to at least this, so big-checkpoint
|
| 45 |
+
# models whose weights alone exceed 64 GB work out of the box.
|
| 46 |
+
min_disk_gb: int = 0
|
| 47 |
+
# Thinking/reasoning capability of the checkpoint's chat template:
|
| 48 |
+
# "none" no <think> support (or a non-thinking variant) — `thinking = true` is
|
| 49 |
+
# rejected for these models
|
| 50 |
+
# "hybrid" template honors enable_thinking (Qwen3-style hybrid reasoning)
|
| 51 |
+
# "always" the model always emits reasoning; enable_thinking can't turn it off,
|
| 52 |
+
# so `thinking = true` is required
|
| 53 |
+
# "unknown" open-model-policy entries (capability not verified)
|
| 54 |
+
thinking: str = "none"
|
| 55 |
+
|
| 56 |
+
def to_dict(self) -> dict[str, Any]:
|
| 57 |
+
return asdict(self)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# The default model Flash trains when a config omits one. A current-gen dense 4B
|
| 61 |
+
# (text-only fine-tune) on the modern worker stack — the safe out-of-the-box choice for
|
| 62 |
+
# the average developer. It is thinking-"hybrid"; the thinking flag now defaults ON.
|
| 63 |
+
DEFAULT_MODEL = "Qwen/Qwen3.5-4B"
|
| 64 |
+
|
| 65 |
+
MODELS: dict[str, ModelInfo] = {
|
| 66 |
+
"openbmb/MiniCPM5-1B": ModelInfo(
|
| 67 |
+
id="openbmb/MiniCPM5-1B",
|
| 68 |
+
display_name="MiniCPM5 1B",
|
| 69 |
+
params="1.2B dense (Llama arch)",
|
| 70 |
+
algos=("sft", "grpo"),
|
| 71 |
+
min_vram_gb=12,
|
| 72 |
+
recommended_gpu="RTX 4090",
|
| 73 |
+
thinking="hybrid",
|
| 74 |
+
notes="On-device class SLM (131k ctx); standard Llama architecture.",
|
| 75 |
+
),
|
| 76 |
+
# ---- Qwen3.5 dense family: validated on the modern worker stack ----
|
| 77 |
+
# (trl 1.x / vllm 0.19 / transformers 5.x). Trained + served TEXT-ONLY: the
|
| 78 |
+
# checkpoints are natively multimodal, so LoRA excludes the vision tower and vLLM
|
| 79 |
+
# loads language_model_only (see flash.engine.worker). Each entry passed a real
|
| 80 |
+
# train+eval smoke on its recommended GPU (bench/results/phase1/).
|
| 81 |
+
"Qwen/Qwen3.5-0.8B": ModelInfo(
|
| 82 |
+
id="Qwen/Qwen3.5-0.8B",
|
| 83 |
+
display_name="Qwen3.5 0.8B",
|
| 84 |
+
params="0.9B (text-only fine-tune)",
|
| 85 |
+
algos=("sft", "grpo"),
|
| 86 |
+
min_vram_gb=12,
|
| 87 |
+
recommended_gpu="RTX 4090",
|
| 88 |
+
thinking="hybrid",
|
| 89 |
+
notes="Smallest Qwen3.5; cheap smoke/dev runs with the modern arch.",
|
| 90 |
+
),
|
| 91 |
+
"Qwen/Qwen3.5-2B": ModelInfo(
|
| 92 |
+
id="Qwen/Qwen3.5-2B",
|
| 93 |
+
display_name="Qwen3.5 2B",
|
| 94 |
+
params="2.3B (text-only fine-tune)",
|
| 95 |
+
algos=("sft", "grpo"),
|
| 96 |
+
min_vram_gb=16,
|
| 97 |
+
recommended_gpu="RTX 4090",
|
| 98 |
+
thinking="hybrid",
|
| 99 |
+
),
|
| 100 |
+
"Qwen/Qwen3.5-4B": ModelInfo(
|
| 101 |
+
id="Qwen/Qwen3.5-4B",
|
| 102 |
+
display_name="Qwen3.5 4B",
|
| 103 |
+
params="4.7B (text-only fine-tune)",
|
| 104 |
+
algos=("sft", "grpo"),
|
| 105 |
+
min_vram_gb=32,
|
| 106 |
+
recommended_gpu="RTX 5090",
|
| 107 |
+
thinking="hybrid",
|
| 108 |
+
notes="Current-gen 4B. GRPO uses the sleep-mode memory recipe (hybrid arch needs "
|
| 109 |
+
"extra engine state-cache); fused DeltaNet kernels ship in the default stack.",
|
| 110 |
+
),
|
| 111 |
+
"Qwen/Qwen3.5-9B": ModelInfo(
|
| 112 |
+
id="Qwen/Qwen3.5-9B",
|
| 113 |
+
display_name="Qwen3.5 9B",
|
| 114 |
+
params="9.7B (text-only fine-tune)",
|
| 115 |
+
algos=("sft", "grpo"),
|
| 116 |
+
min_vram_gb=16,
|
| 117 |
+
# MEMORY-OPTIMIZED: 4-bit NF4 frozen base + bf16 LoRA adapter (QLoRA). The base
|
| 118 |
+
# drops from ~19 GB bf16 to ~5.3 GB, so colocated GRPO holds two 4-bit copies
|
| 119 |
+
# (trainer + bnb-quantized vLLM rollout) instead of two bf16 copies -> it fits a
|
| 120 |
+
# ~24-32 GB card instead of an 80 GB A100. NF4 is near-lossless for adapter training
|
| 121 |
+
# (QLoRA paper + follow-ups), a small quality trade for a ~3x cheaper GPU. No GRPO
|
| 122 |
+
# floor: the matrix sizes the (much smaller) 4-bit footprint directly.
|
| 123 |
+
grpo_min_vram_gb=0,
|
| 124 |
+
quant="4bit-qlora",
|
| 125 |
+
recommended_gpu="RTX 5090",
|
| 126 |
+
thinking="hybrid",
|
| 127 |
+
notes="QLoRA (4-bit NF4 base + bf16 LoRA). GRPO's colocated vLLM rollout loads the "
|
| 128 |
+
"base 4-bit via bitsandbytes too, so both copies are 4-bit -> fits ~24-32 GB "
|
| 129 |
+
"instead of 80 GB bf16. ~near-lossless vs bf16 LoRA.",
|
| 130 |
+
),
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def list_models() -> list[ModelInfo]:
|
| 135 |
+
return sorted(MODELS.values(), key=lambda m: (m.min_vram_gb, m.id))
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def get_model(model_id: str) -> ModelInfo:
|
| 139 |
+
try:
|
| 140 |
+
return MODELS[model_id]
|
| 141 |
+
except KeyError as exc:
|
| 142 |
+
allowed = ", ".join(MODELS)
|
| 143 |
+
raise ValueError(
|
| 144 |
+
f"unsupported model {model_id!r}; choose one of: {allowed} — or set "
|
| 145 |
+
f'model_policy = "allow" in the config to run any HF model that fits the GPU '
|
| 146 |
+
f"(open-model policy)"
|
| 147 |
+
) from exc
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def resolve_model(
|
| 151 |
+
model_id: str,
|
| 152 |
+
algorithm: str,
|
| 153 |
+
policy: str = "catalog",
|
| 154 |
+
gpu: str | None = None,
|
| 155 |
+
) -> ModelInfo:
|
| 156 |
+
"""Resolve a model under the configured policy.
|
| 157 |
+
|
| 158 |
+
``catalog`` (default): the model must be a curated catalog entry.
|
| 159 |
+
``allow``: any HF model is accepted; a coarse VRAM-fit estimate (HF safetensors
|
| 160 |
+
metadata, no download) blocks only provably-impossible fits and warns on tight ones.
|
| 161 |
+
"""
|
| 162 |
+
algo = normalize_algorithm(algorithm)
|
| 163 |
+
if model_id in MODELS:
|
| 164 |
+
return validate_model_for_algorithm(model_id, algo)
|
| 165 |
+
if policy != "allow":
|
| 166 |
+
# Reuse get_model's error (includes the open-model hint).
|
| 167 |
+
return get_model(model_id)
|
| 168 |
+
return _resolve_open_model(model_id, algo, gpu)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _resolve_open_model(model_id: str, algo: str, gpu: str | None) -> ModelInfo:
|
| 172 |
+
"""Synthesize a ModelInfo for the open-model "allow" policy from a coarse VRAM-fit
|
| 173 |
+
estimate (HF safetensors metadata, no download). Blocks provably-impossible fits and
|
| 174 |
+
warns on tight ones. Isolates the engine.vram dependency + disk-floor heuristic from
|
| 175 |
+
the curated-catalog path in resolve_model."""
|
| 176 |
+
from flash.engine.vram import check_fit
|
| 177 |
+
|
| 178 |
+
est = check_fit(model_id, algo, gpu or DEFAULT_GPU)
|
| 179 |
+
if est.verdict == "too_big":
|
| 180 |
+
raise ValueError(
|
| 181 |
+
f"{model_id} does not fit the requested GPU: {est.describe()}. "
|
| 182 |
+
f"Pick a smaller model or a larger supported GPU."
|
| 183 |
+
)
|
| 184 |
+
if est.verdict in ("tight", "unknown"):
|
| 185 |
+
print(f"warning: open-model policy: {est.describe()}")
|
| 186 |
+
params = f"{est.params_b:.1f}B" if est.params_b else "unknown size"
|
| 187 |
+
# Disk floor for the open model: a bf16 checkpoint is ~2 GB per billion params;
|
| 188 |
+
# add worker-stack headroom so a large model that passes the VRAM check can't
|
| 189 |
+
# provision a paid worker and then fail in prefetch_model when the checkpoint
|
| 190 |
+
# overflows the 64 GB container default. 0 (unknown size) leaves the default
|
| 191 |
+
# (the user can still raise it with gpu.disk_gb).
|
| 192 |
+
min_disk = int(est.params_b * 2) + 64 if est.params_b else 0
|
| 193 |
+
return ModelInfo(
|
| 194 |
+
id=model_id,
|
| 195 |
+
display_name=model_id,
|
| 196 |
+
params=params,
|
| 197 |
+
algos=ALGORITHMS,
|
| 198 |
+
min_vram_gb=math.ceil(est.est_gb) if est.est_gb else 24,
|
| 199 |
+
min_disk_gb=min_disk,
|
| 200 |
+
recommended_gpu=gpu or DEFAULT_GPU,
|
| 201 |
+
thinking="unknown",
|
| 202 |
+
notes="unlisted model accepted via the open-model policy (not curated/validated)",
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def validate_model_for_algorithm(model_id: str, algorithm: str) -> ModelInfo:
|
| 207 |
+
info = get_model(model_id)
|
| 208 |
+
algo = normalize_algorithm(algorithm)
|
| 209 |
+
# Catalog entries advertise the capability classes "sft" and "grpo": grpo needs the
|
| 210 |
+
# colocated rollout engine, sft is trainer-only.
|
| 211 |
+
required = "grpo" if algo == "grpo" else "sft"
|
| 212 |
+
if required not in info.algos:
|
| 213 |
+
allowed = ", ".join(info.algos)
|
| 214 |
+
raise ValueError(f"{model_id} supports {allowed}, not {algo}")
|
| 215 |
+
return info
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def public_model_rows() -> list[dict[str, Any]]:
|
| 219 |
+
return [m.to_dict() for m in list_models()]
|
code/flash/cli/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""CLI package."""
|
code/flash/cli/main.py
ADDED
|
@@ -0,0 +1,919 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CLI for the managed Flash service.
|
| 2 |
+
|
| 3 |
+
Every run-lifecycle command is a thin HTTP call to the Flash 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 flash import __version__
|
| 20 |
+
from flash._logging import configure_logging, get_logger
|
| 21 |
+
from flash.catalog import public_model_rows
|
| 22 |
+
from flash.client import (
|
| 23 |
+
ApiClient,
|
| 24 |
+
ClientError,
|
| 25 |
+
client_from_config,
|
| 26 |
+
save_credentials,
|
| 27 |
+
verify_freesolo_key,
|
| 28 |
+
)
|
| 29 |
+
from flash.client.config import load_credentials
|
| 30 |
+
from flash.client.specs import spec_payload
|
| 31 |
+
from flash.runner import TERMINAL_STATES, new_run_id
|
| 32 |
+
from flash.schema import ConfigError, spec_from_file
|
| 33 |
+
|
| 34 |
+
logger = get_logger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# Exceptions that represent expected user/config errors: report them as a clean one-line
|
| 38 |
+
# message instead of a Python traceback (use --debug to see the full trace).
|
| 39 |
+
_USER_ERRORS = (
|
| 40 |
+
ConfigError,
|
| 41 |
+
ClientError,
|
| 42 |
+
FileNotFoundError,
|
| 43 |
+
ValueError,
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
# Run states after which nothing more will happen (polling can stop).
|
| 47 |
+
_CLI_DONE_STATES = TERMINAL_STATES | {"deployed"}
|
| 48 |
+
_OK_STATES = {"done", "dry_run", "deployed"}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def main(argv: list[str] | None = None) -> int:
|
| 52 |
+
parser = argparse.ArgumentParser(prog="slm", description="Managed LoRA post-training")
|
| 53 |
+
parser.add_argument("-V", "--version", action="version", version=f"slm {__version__}")
|
| 54 |
+
parser.add_argument(
|
| 55 |
+
"--debug",
|
| 56 |
+
action="store_true",
|
| 57 |
+
help="show full tracebacks on error",
|
| 58 |
+
)
|
| 59 |
+
parser.add_argument(
|
| 60 |
+
"-v",
|
| 61 |
+
"--verbose",
|
| 62 |
+
action="count",
|
| 63 |
+
default=0,
|
| 64 |
+
help="increase log verbosity (-v for info, -vv for debug)",
|
| 65 |
+
)
|
| 66 |
+
sub = parser.add_subparsers(dest="cmd", required=True)
|
| 67 |
+
|
| 68 |
+
version = sub.add_parser("version", help="print the Flash version")
|
| 69 |
+
version.set_defaults(func=cmd_version)
|
| 70 |
+
|
| 71 |
+
login = sub.add_parser("login", help="log in with your freesolo API key (verified by freesolo)")
|
| 72 |
+
login.add_argument(
|
| 73 |
+
"--api-key",
|
| 74 |
+
help="your freesolo API key (default: FREESOLO_API_KEY); created in the dashboard",
|
| 75 |
+
)
|
| 76 |
+
login.add_argument(
|
| 77 |
+
"--freesolo-url",
|
| 78 |
+
dest="freesolo_url",
|
| 79 |
+
help="freesolo backend base URL (default: FREESOLO_BASE_URL or https://api.freesolo.co)",
|
| 80 |
+
)
|
| 81 |
+
login.add_argument(
|
| 82 |
+
"--api-url", help="flash control-plane URL for training calls (default: FLASH_API_URL)"
|
| 83 |
+
)
|
| 84 |
+
login.set_defaults(func=cmd_login)
|
| 85 |
+
|
| 86 |
+
whoami = sub.add_parser("whoami", help="show the identity behind your stored key")
|
| 87 |
+
whoami.set_defaults(func=cmd_whoami)
|
| 88 |
+
|
| 89 |
+
lab = sub.add_parser("lab", help="local authoring scaffolds")
|
| 90 |
+
lab_sub = lab.add_subparsers(dest="lab_cmd", required=True)
|
| 91 |
+
setup = lab_sub.add_parser("setup", help="scaffold environments/ + configs/ in the cwd")
|
| 92 |
+
setup.set_defaults(func=cmd_lab_setup)
|
| 93 |
+
|
| 94 |
+
models = sub.add_parser("models", help="list supported base models")
|
| 95 |
+
models.set_defaults(func=cmd_models)
|
| 96 |
+
|
| 97 |
+
gpus = sub.add_parser("gpus", help="list managed GPU classes with live $/hr")
|
| 98 |
+
gpus.set_defaults(func=cmd_gpus)
|
| 99 |
+
|
| 100 |
+
env = sub.add_parser("env", help="manage verifiers environments")
|
| 101 |
+
env_sub = env.add_subparsers(dest="env_cmd", required=True)
|
| 102 |
+
init = env_sub.add_parser("init", help="scaffold a new local verifiers environment")
|
| 103 |
+
init.add_argument("name")
|
| 104 |
+
init.set_defaults(func=cmd_env_init)
|
| 105 |
+
|
| 106 |
+
env_list = env_sub.add_parser("list", help="list installed + local environments")
|
| 107 |
+
env_list.set_defaults(func=cmd_env_list)
|
| 108 |
+
|
| 109 |
+
env_install = env_sub.add_parser("install", help="install a published Prime Hub environment")
|
| 110 |
+
env_install.add_argument("env_id", help='the env id to install (a Hub slug, "owner/name")')
|
| 111 |
+
env_install.set_defaults(func=cmd_env_install)
|
| 112 |
+
|
| 113 |
+
env_push = env_sub.add_parser(
|
| 114 |
+
"push", help="publish a local verifiers env to the Prime Hub (private); prints its env id"
|
| 115 |
+
)
|
| 116 |
+
env_push.add_argument("path", nargs="?", default=".")
|
| 117 |
+
env_push.set_defaults(func=cmd_env_push)
|
| 118 |
+
|
| 119 |
+
train = sub.add_parser("train", help="submit a managed training run from a TOML config")
|
| 120 |
+
train.add_argument("config")
|
| 121 |
+
train.add_argument(
|
| 122 |
+
"--config",
|
| 123 |
+
dest="extra_configs",
|
| 124 |
+
action="append",
|
| 125 |
+
default=[],
|
| 126 |
+
help="additional TOML to deep-merge (config composition); repeatable",
|
| 127 |
+
)
|
| 128 |
+
train.add_argument(
|
| 129 |
+
"--set",
|
| 130 |
+
dest="overrides",
|
| 131 |
+
action="append",
|
| 132 |
+
default=[],
|
| 133 |
+
metavar="key=value",
|
| 134 |
+
help="override a config value; repeatable",
|
| 135 |
+
)
|
| 136 |
+
train.add_argument("--dry-run", action="store_true")
|
| 137 |
+
train.add_argument(
|
| 138 |
+
"--background",
|
| 139 |
+
action="store_true",
|
| 140 |
+
help="submit and return immediately instead of following logs",
|
| 141 |
+
)
|
| 142 |
+
train.set_defaults(func=cmd_train)
|
| 143 |
+
|
| 144 |
+
status = sub.add_parser("status", help="show a run's full status JSON")
|
| 145 |
+
status.add_argument("run_id")
|
| 146 |
+
status.set_defaults(func=cmd_status)
|
| 147 |
+
|
| 148 |
+
attach = sub.add_parser(
|
| 149 |
+
"attach", help="follow a running job's logs to completion (resumable any time)"
|
| 150 |
+
)
|
| 151 |
+
attach.add_argument("run_id")
|
| 152 |
+
attach.set_defaults(func=cmd_attach)
|
| 153 |
+
|
| 154 |
+
ps = sub.add_parser("ps", help="list runs and their state/cost")
|
| 155 |
+
ps.set_defaults(func=cmd_ps)
|
| 156 |
+
|
| 157 |
+
cost = sub.add_parser("cost", help="show a run's accrued cost (USD)")
|
| 158 |
+
cost.add_argument("run_id")
|
| 159 |
+
cost.set_defaults(func=cmd_cost)
|
| 160 |
+
|
| 161 |
+
cancel = sub.add_parser("cancel", help="cancel a run (best-effort)")
|
| 162 |
+
cancel.add_argument("run_id")
|
| 163 |
+
cancel.set_defaults(func=cmd_cancel)
|
| 164 |
+
|
| 165 |
+
logs = sub.add_parser("logs")
|
| 166 |
+
logs.add_argument("run_id")
|
| 167 |
+
logs.add_argument("-f", "--follow", action="store_true", help="stream new log lines")
|
| 168 |
+
logs.set_defaults(func=cmd_logs)
|
| 169 |
+
|
| 170 |
+
deploy = sub.add_parser("deploy")
|
| 171 |
+
deploy.add_argument("run_id")
|
| 172 |
+
deploy.add_argument(
|
| 173 |
+
"--mode",
|
| 174 |
+
choices=["dev", "always-on"],
|
| 175 |
+
default="dev",
|
| 176 |
+
help="dev: scale-to-zero, cold start after idle, $0 when unused (default). "
|
| 177 |
+
"always-on: one warm worker 24/7, no cold starts, continuous billing.",
|
| 178 |
+
)
|
| 179 |
+
deploy.add_argument(
|
| 180 |
+
"--idle-timeout",
|
| 181 |
+
type=int,
|
| 182 |
+
default=300,
|
| 183 |
+
help="dev mode: seconds of inactivity before the worker scales to zero (default 300)",
|
| 184 |
+
)
|
| 185 |
+
deploy.add_argument("--dry-run", action="store_true")
|
| 186 |
+
deploy.set_defaults(func=cmd_deploy)
|
| 187 |
+
|
| 188 |
+
undeploy = sub.add_parser("undeploy", help="tear down a run's serving endpoint")
|
| 189 |
+
undeploy.add_argument("run_id")
|
| 190 |
+
undeploy.set_defaults(func=cmd_undeploy)
|
| 191 |
+
|
| 192 |
+
deployments = sub.add_parser("deployments", help="list active serving deployments")
|
| 193 |
+
deployments.set_defaults(func=cmd_deployments)
|
| 194 |
+
|
| 195 |
+
chat = sub.add_parser("chat", help="chat with a deployed adapter")
|
| 196 |
+
chat.add_argument("run_id")
|
| 197 |
+
chat.add_argument("-m", "--message", required=True)
|
| 198 |
+
chat.add_argument("--max-tokens", type=int, default=512)
|
| 199 |
+
chat.add_argument("--temperature", type=float, default=0.0)
|
| 200 |
+
chat.set_defaults(func=cmd_chat)
|
| 201 |
+
|
| 202 |
+
# The control plane is operator-only and run as a separate one-off service via the
|
| 203 |
+
# `flash-server` console script (flash.server.__main__:main), not a `slm` subcommand.
|
| 204 |
+
|
| 205 |
+
args = parser.parse_args(argv)
|
| 206 |
+
configure_logging(verbosity=getattr(args, "verbose", 0))
|
| 207 |
+
debug = getattr(args, "debug", False)
|
| 208 |
+
try:
|
| 209 |
+
return args.func(args)
|
| 210 |
+
except _USER_ERRORS as exc:
|
| 211 |
+
if debug:
|
| 212 |
+
raise
|
| 213 |
+
print(f"error: {exc}", file=sys.stderr)
|
| 214 |
+
return 1
|
| 215 |
+
except KeyboardInterrupt:
|
| 216 |
+
print("aborted", file=sys.stderr)
|
| 217 |
+
return 130
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def cmd_version(args) -> int:
|
| 221 |
+
print(f"slm {__version__}")
|
| 222 |
+
return 0
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def cmd_login(args) -> int:
|
| 226 |
+
# Login is handled by the freesolo backend (not the flash control plane): the user
|
| 227 |
+
# supplies the freesolo API key they created in the dashboard, and we verify it against
|
| 228 |
+
# freesolo before storing it. The same key authenticates flash's control plane.
|
| 229 |
+
api_key = args.api_key or os.environ.get("FREESOLO_API_KEY")
|
| 230 |
+
if not api_key:
|
| 231 |
+
raise ClientError(
|
| 232 |
+
"no API key provided: pass `--api-key <key>` or set FREESOLO_API_KEY. "
|
| 233 |
+
"Create a key in your freesolo dashboard."
|
| 234 |
+
)
|
| 235 |
+
verify_freesolo_key(api_key, base_url=getattr(args, "freesolo_url", None))
|
| 236 |
+
api_url = args.api_url or load_credentials()[0]
|
| 237 |
+
# save_credentials clears the stored url when it's the default, so logging into the
|
| 238 |
+
# default plane also drops a stale custom url from a previous custom-URL login.
|
| 239 |
+
path = save_credentials(api_key, api_url=api_url)
|
| 240 |
+
# Never echo the key itself; the stored file is the single source of truth.
|
| 241 |
+
print(f"logged in: freesolo verified your key (saved to {path})")
|
| 242 |
+
print("you're ready to train — try `slm train <config.toml>`")
|
| 243 |
+
return 0
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def cmd_whoami(args) -> int:
|
| 247 |
+
print(json.dumps(client_from_config().me(), indent=2))
|
| 248 |
+
return 0
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
_STARTER_ENV_PY = '''\
|
| 252 |
+
"""Starter local verifiers environment.
|
| 253 |
+
|
| 254 |
+
Replace the dataset and rubric with your task, then publish it to the Prime Hub with
|
| 255 |
+
`slm env push environments/starter_env.py`. A managed run references the published env by
|
| 256 |
+
its Hub slug: set [environment] id = "owner/name" in the config.
|
| 257 |
+
See https://github.com/PrimeIntellect-ai/verifiers for the full API.
|
| 258 |
+
"""
|
| 259 |
+
|
| 260 |
+
import verifiers as vf
|
| 261 |
+
from datasets import Dataset
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def load_environment(**kwargs) -> vf.Environment:
|
| 265 |
+
dataset = Dataset.from_list(
|
| 266 |
+
[
|
| 267 |
+
{"prompt": [{"role": "user", "content": "What is 2 + 2?"}], "answer": "4"},
|
| 268 |
+
{"prompt": [{"role": "user", "content": "What is 3 + 5?"}], "answer": "8"},
|
| 269 |
+
]
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
def correct_answer(completion, answer, **_):
|
| 273 |
+
"""Reward 1.0 when the gold answer appears in the model's final message."""
|
| 274 |
+
text = completion[-1]["content"] if isinstance(completion, list) else str(completion)
|
| 275 |
+
return 1.0 if str(answer) in text else 0.0
|
| 276 |
+
|
| 277 |
+
rubric = vf.Rubric(funcs=[correct_answer], weights=[1.0])
|
| 278 |
+
return vf.SingleTurnEnv(dataset=dataset, rubric=rubric, **kwargs)
|
| 279 |
+
'''
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def cmd_lab_setup(args) -> int:
|
| 283 |
+
Path("environments").mkdir(exist_ok=True)
|
| 284 |
+
Path("configs").mkdir(exist_ok=True)
|
| 285 |
+
Path("configs/endpoints.toml").write_text(
|
| 286 |
+
"# OpenAI-compatible endpoints returned by `slm deploy` can be stored here.\n"
|
| 287 |
+
)
|
| 288 |
+
starter_env = Path("environments/starter_env.py")
|
| 289 |
+
if not starter_env.exists():
|
| 290 |
+
starter_env.write_text(_STARTER_ENV_PY)
|
| 291 |
+
sample = Path("configs/verifiers_grpo.toml")
|
| 292 |
+
if not sample.exists():
|
| 293 |
+
sample.write_text(
|
| 294 |
+
'model = "Qwen/Qwen3.5-4B"\n'
|
| 295 |
+
'algorithm = "grpo"\n\n'
|
| 296 |
+
"# Environment: a verifiers / Prime Hub env slug. Publish the scaffolded\n"
|
| 297 |
+
"# environments/starter_env.py with `slm env push environments/starter_env.py`\n"
|
| 298 |
+
"# (then `slm env install owner/name`) to get the slug, and set it below.\n"
|
| 299 |
+
"[environment]\n"
|
| 300 |
+
'id = "owner/name" # a verifiers / Prime Hub env slug\n\n'
|
| 301 |
+
"[train]\n"
|
| 302 |
+
'hf_repo = "your-org/your-runs" # HF dataset repo for adapters/checkpoints\n'
|
| 303 |
+
"steps = 150\n"
|
| 304 |
+
"lora_rank = 32\n"
|
| 305 |
+
"seeds = [0]\n\n"
|
| 306 |
+
"# Managed GPU (RTX 4090 or RTX 5090 only).\n"
|
| 307 |
+
"[gpu]\n"
|
| 308 |
+
'type = "RTX 5090"\n'
|
| 309 |
+
)
|
| 310 |
+
print(
|
| 311 |
+
"created environments/, environments/starter_env.py, configs/, "
|
| 312 |
+
"configs/verifiers_grpo.toml, configs/endpoints.toml"
|
| 313 |
+
)
|
| 314 |
+
return 0
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def cmd_models(args) -> int:
|
| 318 |
+
for row in public_model_rows():
|
| 319 |
+
print(
|
| 320 |
+
f"{row['id']}\t{row['params']}\talgos={','.join(row['algos'])}\t{row['quant']}"
|
| 321 |
+
f"\tthinking={row.get('thinking', 'none')}"
|
| 322 |
+
)
|
| 323 |
+
return 0
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def cmd_gpus(args) -> int:
|
| 327 |
+
"""List GPU classes, VRAM, per-provider $/hr and live validation."""
|
| 328 |
+
from flash.providers import available_providers
|
| 329 |
+
from flash.providers.base import GPU_INFO
|
| 330 |
+
from flash.providers.runpod.pricing import live_rates
|
| 331 |
+
|
| 332 |
+
rates = live_rates()
|
| 333 |
+
# Cheapest live verified-datacenter offer per class (vast key + network only).
|
| 334 |
+
vast_rates: dict[str, float] = {}
|
| 335 |
+
if "vast" in available_providers():
|
| 336 |
+
try:
|
| 337 |
+
from flash.providers.vast.jobs import usable_offers
|
| 338 |
+
|
| 339 |
+
for offer in usable_offers(0, 0):
|
| 340 |
+
vast_rates.setdefault(offer.gpu, offer.dph_total) # offers are price-sorted
|
| 341 |
+
except Exception as exc:
|
| 342 |
+
print(f"warning: vast offers unavailable ({exc})", file=sys.stderr)
|
| 343 |
+
|
| 344 |
+
def fmt_rate(v: float | None) -> str:
|
| 345 |
+
return f"{v:>10.2f}" if v else f"{'-':>10}"
|
| 346 |
+
|
| 347 |
+
print(f"{'gpu':<16}{'vram':>6}{'runpod$/hr':>11}{'vast$/hr':>10} validated_on")
|
| 348 |
+
for info in sorted(GPU_INFO.values(), key=lambda g: rates.get(g.name, g.hourly_usd)):
|
| 349 |
+
runpod_rate = rates.get(info.name, info.hourly_usd) if info.enum_member else None
|
| 350 |
+
validated = ",".join(info.validated_on) or "- (needs gpu.allow_unvalidated)"
|
| 351 |
+
print(
|
| 352 |
+
f"{info.name:<16}{info.vram_gb:>5}G{fmt_rate(runpod_rate):>11}"
|
| 353 |
+
f"{fmt_rate(vast_rates.get(info.name))} {validated}"
|
| 354 |
+
)
|
| 355 |
+
print(
|
| 356 |
+
'\nTip: omit gpu.type (or set "cheapest") to allocate the cheapest validated class\n'
|
| 357 |
+
"across providers that fits the model; gpu.provider pins runpod/vast."
|
| 358 |
+
)
|
| 359 |
+
return 0
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def cmd_env_init(args) -> int:
|
| 363 |
+
mod = args.name.replace("-", "_")
|
| 364 |
+
root = Path("environments") / mod
|
| 365 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 366 |
+
# Verifiers-only: scaffold a real verifiers env whose load_environment returns a
|
| 367 |
+
# vf.Environment (here a SingleTurnEnv + Rubric over a datasets.Dataset). This is what
|
| 368 |
+
# a Hub push expects, so a freshly scaffolded env actually loads.
|
| 369 |
+
(root / f"{mod}.py").write_text(
|
| 370 |
+
f'"""Custom verifiers environment ({args.name}).\n\n'
|
| 371 |
+
"Replace the dataset and rubric with your task, then publish it to the Prime Hub\n"
|
| 372 |
+
f"with `slm env push environments/{mod}/{mod}.py` and reference it by id\n"
|
| 373 |
+
'([environment] id = "owner/name") in your config.\n'
|
| 374 |
+
"See https://github.com/PrimeIntellect-ai/verifiers for the full API.\n"
|
| 375 |
+
'"""\n\n'
|
| 376 |
+
"import verifiers as vf\n"
|
| 377 |
+
"from datasets import Dataset\n\n\n"
|
| 378 |
+
"def load_environment(**kwargs) -> vf.Environment:\n"
|
| 379 |
+
" dataset = Dataset.from_list(\n"
|
| 380 |
+
" [\n"
|
| 381 |
+
' {"prompt": [{"role": "user", "content": "What is 2 + 2?"}], "answer": "4"},\n'
|
| 382 |
+
' {"prompt": [{"role": "user", "content": "What is 3 + 5?"}], "answer": "8"},\n'
|
| 383 |
+
" ]\n"
|
| 384 |
+
" )\n\n"
|
| 385 |
+
" def correct_answer(completion, answer, **_):\n"
|
| 386 |
+
' """Reward 1.0 when the gold answer appears in the model\'s final message."""\n'
|
| 387 |
+
" text = (\n"
|
| 388 |
+
' completion[-1]["content"] if isinstance(completion, list) else str(completion)\n'
|
| 389 |
+
" )\n"
|
| 390 |
+
" return 1.0 if str(answer) in text else 0.0\n\n"
|
| 391 |
+
" rubric = vf.Rubric(funcs=[correct_answer], weights=[1.0])\n"
|
| 392 |
+
" return vf.SingleTurnEnv(dataset=dataset, rubric=rubric, **kwargs)\n"
|
| 393 |
+
)
|
| 394 |
+
(root / "README.md").write_text(f"# {args.name}\n\nCustom verifiers environment for Flash.\n")
|
| 395 |
+
print(f"created {root}")
|
| 396 |
+
print(
|
| 397 |
+
f"publish it to the Prime Hub with `slm env push environments/{mod}/{mod}.py`, "
|
| 398 |
+
'then reference it by id ([environment] id = "owner/name") in your config.'
|
| 399 |
+
)
|
| 400 |
+
return 0
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def cmd_env_list(args) -> int:
|
| 404 |
+
from flash.envs.registry import list_installed_verifiers_envs
|
| 405 |
+
|
| 406 |
+
installed = list_installed_verifiers_envs()
|
| 407 |
+
if installed:
|
| 408 |
+
print("installed (verifiers / Prime Hub):")
|
| 409 |
+
for env_id in installed:
|
| 410 |
+
print(f" {env_id}")
|
| 411 |
+
local = Path("environments")
|
| 412 |
+
if local.is_dir():
|
| 413 |
+
# Both directory envs (environments/<name>/<name>.py) and top-level single-file
|
| 414 |
+
# modules (environments/<name>.py, e.g. the `slm lab` starter env). These are local
|
| 415 |
+
# env SOURCES — publish one with `slm env push <path>` to run it on the managed
|
| 416 |
+
# service by its Hub id.
|
| 417 |
+
paths: list[str] = []
|
| 418 |
+
for p in local.iterdir():
|
| 419 |
+
if p.name.startswith("__"):
|
| 420 |
+
continue
|
| 421 |
+
if p.is_dir():
|
| 422 |
+
# `slm env init` maps a hyphenated dir to an underscored inner module file
|
| 423 |
+
# (my-env/ -> my-env/my_env.py). List that exact path, and only when it
|
| 424 |
+
# actually exists (an empty/incomplete folder isn't a publishable source).
|
| 425 |
+
stem = p.name.replace("-", "_")
|
| 426 |
+
module = p / f"{stem}.py"
|
| 427 |
+
if module.is_file():
|
| 428 |
+
paths.append(f"environments/{p.name}/{stem}.py")
|
| 429 |
+
elif p.suffix == ".py":
|
| 430 |
+
paths.append(f"environments/{p.name}")
|
| 431 |
+
if paths:
|
| 432 |
+
print("local env sources (publish with `slm env push <path>`):")
|
| 433 |
+
for path in sorted(paths):
|
| 434 |
+
print(f" {path}")
|
| 435 |
+
return 0
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
# Prime Intellect Environments Hub pip index. Each org's wheels live under ITS OWN namespace
|
| 439 |
+
# (e.g. freesolo-co/flash-bench -> .../freesolo-co/simple/), so derive the index from the
|
| 440 |
+
# slug owner — a hardcoded `primeintellect` index 404s on any non-primeintellect env.
|
| 441 |
+
PRIME_HUB_INDEX_TMPL = "https://hub.primeintellect.ai/{owner}/simple/"
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def _prime_hub_index(env_id: str) -> str:
|
| 445 |
+
owner = env_id.split("/", 1)[0] if "/" in env_id else "primeintellect"
|
| 446 |
+
return PRIME_HUB_INDEX_TMPL.format(owner=owner)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def cmd_env_install(args) -> int:
|
| 450 |
+
import shutil
|
| 451 |
+
import subprocess
|
| 452 |
+
|
| 453 |
+
from flash.envs.registry import _bare_wheel_name, record_installed_env
|
| 454 |
+
|
| 455 |
+
env_id = args.env_id
|
| 456 |
+
# Managed envs are Prime Hub slugs: exactly one `/` with non-empty owner and name. A bare
|
| 457 |
+
# id (`gsm8k`) or a malformed slug can't be resolved on the Hub, so reject it up front
|
| 458 |
+
# rather than letting `prime`/pip fail with an opaque error.
|
| 459 |
+
parts = env_id.split("/")
|
| 460 |
+
if len(parts) != 2 or not parts[0] or not parts[1]:
|
| 461 |
+
print(
|
| 462 |
+
f'env id must be a Prime Hub slug "owner/name" (got {env_id!r})',
|
| 463 |
+
file=sys.stderr,
|
| 464 |
+
)
|
| 465 |
+
return 1
|
| 466 |
+
# `slm env install` is a LOCAL-client convenience: it installs the env into the client's
|
| 467 |
+
# interpreter and records it in ~/.flash/envs.json for local authoring/dry-run. The
|
| 468 |
+
# managed worker does NOT reinstall from this record — it installs Hub envs itself via an
|
| 469 |
+
# authenticated `prime env install` on the GPU box. A Hub slug `owner/name` maps to the pip
|
| 470 |
+
# wheel `name` on the Prime Intellect Hub index; we record that index alongside the env.
|
| 471 |
+
extras = {"extra_index_url": _prime_hub_index(env_id)}
|
| 472 |
+
if shutil.which("prime"):
|
| 473 |
+
# The `prime` CLI resolves the Hub + index itself (and is the only path that can fetch a
|
| 474 |
+
# PRIVATE Hub env — flash publishes envs PRIVATE).
|
| 475 |
+
cmd = ["prime", "env", "install", env_id]
|
| 476 |
+
else:
|
| 477 |
+
# The pip fallback hits the PUBLIC Hub index only; it cannot fetch PRIVATE Hub envs
|
| 478 |
+
# (the public index never serves private wheels). Be explicit instead of letting a
|
| 479 |
+
# private install fail confusingly, but still attempt pip for the public case.
|
| 480 |
+
print(
|
| 481 |
+
f"note: `prime` CLI not found; attempting a pip install of {env_id} from the "
|
| 482 |
+
"PUBLIC Hub index. PRIVATE Hub envs require the `prime` CLI — install it "
|
| 483 |
+
"(https://docs.primeintellect.ai) to install a private env."
|
| 484 |
+
)
|
| 485 |
+
installer = (
|
| 486 |
+
# `uv pip install` outside an active venv errors with "No virtual environment
|
| 487 |
+
# found"; --python targets the CLI's own interpreter so a global/pipx `slm`
|
| 488 |
+
# install still records the env.
|
| 489 |
+
["uv", "pip", "install", "--python", sys.executable]
|
| 490 |
+
if shutil.which("uv")
|
| 491 |
+
else [sys.executable, "-m", "pip", "install"]
|
| 492 |
+
)
|
| 493 |
+
cmd = [*installer, _bare_wheel_name(env_id), "--extra-index-url", extras["extra_index_url"]]
|
| 494 |
+
print("running:", " ".join(cmd))
|
| 495 |
+
rc = subprocess.run(cmd).returncode
|
| 496 |
+
if rc != 0:
|
| 497 |
+
print("install failed")
|
| 498 |
+
return rc
|
| 499 |
+
record_installed_env(env_id, package=_bare_wheel_name(env_id), extras=extras)
|
| 500 |
+
print(f"installed {env_id}; recorded in ~/.flash/envs.json")
|
| 501 |
+
print(f'use it via: [environment]\\nid = "{env_id}"')
|
| 502 |
+
return 0
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
# A verifiers env packaged for the Prime Hub is a pyproject + an importable module exposing
|
| 506 |
+
# load_environment(). When `slm env push` is pointed at a bare module (a single `.py`, as the
|
| 507 |
+
# freesolo training agent emits, or a dir without a pyproject), we wrap it in this layout so the
|
| 508 |
+
# push Just Works instead of erroring on "pyproject.toml not found".
|
| 509 |
+
_ENV_PUSH_PYPROJECT = """\
|
| 510 |
+
[project]
|
| 511 |
+
name = "{name}"
|
| 512 |
+
version = "{version}"
|
| 513 |
+
description = "Flash verifiers environment ({name})."
|
| 514 |
+
requires-python = ">=3.10"
|
| 515 |
+
dependencies = ["verifiers"]
|
| 516 |
+
|
| 517 |
+
[build-system]
|
| 518 |
+
requires = ["hatchling"]
|
| 519 |
+
build-backend = "hatchling.build"
|
| 520 |
+
|
| 521 |
+
[tool.hatch.build.targets.wheel]
|
| 522 |
+
packages = ["{module}"]
|
| 523 |
+
"""
|
| 524 |
+
|
| 525 |
+
_PUSH_INITIAL_VERSION = "0.1.0"
|
| 526 |
+
_PUSH_MAX_ATTEMPTS = 8
|
| 527 |
+
_PUSH_CONFLICT_MARKERS = ("already exists", "version already", "duplicate", "conflict", "409")
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def _push_env_name(raw: str) -> str:
|
| 531 |
+
import re
|
| 532 |
+
|
| 533 |
+
name = re.sub(r"[^a-z0-9]+", "-", raw.lower()).strip("-")
|
| 534 |
+
return name or "flash-env"
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def _push_is_version_conflict(text: str) -> bool:
|
| 538 |
+
lowered = text.lower()
|
| 539 |
+
return any(marker in lowered for marker in _PUSH_CONFLICT_MARKERS)
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def _push_slug_from(env_dir, output: str) -> str | None:
|
| 543 |
+
import re
|
| 544 |
+
|
| 545 |
+
meta = Path(env_dir) / ".prime" / ".env-metadata.json"
|
| 546 |
+
try:
|
| 547 |
+
data = json.loads(meta.read_text())
|
| 548 |
+
owner, name = data.get("owner"), data.get("name")
|
| 549 |
+
if owner and name:
|
| 550 |
+
return f"{owner}/{name}"
|
| 551 |
+
except (OSError, json.JSONDecodeError):
|
| 552 |
+
pass
|
| 553 |
+
match = re.search(r"[Ss]uccessfully pushed\s+([A-Za-z0-9][\w.-]*/[\w.-]+)", output)
|
| 554 |
+
return match.group(1) if match else None
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
def _config_env_name(config_path) -> str | None:
|
| 558 |
+
"""The `name` part of a sibling flash.toml's `[environment] id = "owner/name"`, or None.
|
| 559 |
+
|
| 560 |
+
Used so a bare `environment.py` re-publishes under its EXISTING Hub env (minting a new
|
| 561 |
+
version) instead of deriving a fresh name from the file stem. Owner still comes from the
|
| 562 |
+
authenticated Prime account/team, so only the name part is consumed here."""
|
| 563 |
+
import tomllib
|
| 564 |
+
|
| 565 |
+
path = Path(config_path)
|
| 566 |
+
if not path.is_file():
|
| 567 |
+
return None
|
| 568 |
+
try:
|
| 569 |
+
data = tomllib.loads(path.read_text())
|
| 570 |
+
except (OSError, tomllib.TOMLDecodeError):
|
| 571 |
+
return None
|
| 572 |
+
env = data.get("environment")
|
| 573 |
+
env_id = str(env.get("id") or "").strip() if isinstance(env, dict) else ""
|
| 574 |
+
if "/" in env_id:
|
| 575 |
+
name = env_id.split("/", 1)[1].strip()
|
| 576 |
+
return name or None
|
| 577 |
+
return None
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def _config_env_name_from_dir(config_dir) -> str | None:
|
| 581 |
+
"""The Hub env name declared by the sibling per-phase flash configs
|
| 582 |
+
(``flash_grpo.toml``/``flash_sft.toml``). Without this, pushing ``environment.py`` finds
|
| 583 |
+
no id and mints a brand-new env, so the run trains against the stale id in the configs.
|
| 584 |
+
"""
|
| 585 |
+
config_dir = Path(config_dir)
|
| 586 |
+
for cfg in ("flash_grpo.toml", "flash_sft.toml"):
|
| 587 |
+
name = _config_env_name(config_dir / cfg)
|
| 588 |
+
if name:
|
| 589 |
+
return name
|
| 590 |
+
return None
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def _with_syspath_bootstrap(env_source: str) -> str:
|
| 594 |
+
"""Prepend a sys.path bootstrap so a published env (run as the package __init__) can resolve
|
| 595 |
+
BARE absolute imports of its shipped sibling helpers (`import config` / `from utils import x`)
|
| 596 |
+
even without its own sys.path.insert — otherwise `prime env install`/load_environment fails
|
| 597 |
+
with ModuleNotFoundError. Inserted AFTER the module docstring and any `from __future__` imports
|
| 598 |
+
(which must stay first). Mirrors the platform hub publisher."""
|
| 599 |
+
bootstrap = (
|
| 600 |
+
"import os as _flash_os, sys as _flash_sys\n"
|
| 601 |
+
"_flash_sys.path.insert(0, _flash_os.path.dirname(__file__))\n"
|
| 602 |
+
)
|
| 603 |
+
try:
|
| 604 |
+
tree = ast.parse(env_source)
|
| 605 |
+
except SyntaxError:
|
| 606 |
+
return bootstrap + env_source
|
| 607 |
+
insert_after = 0
|
| 608 |
+
body = tree.body
|
| 609 |
+
i = 0
|
| 610 |
+
if (
|
| 611 |
+
body
|
| 612 |
+
and isinstance(body[0], ast.Expr)
|
| 613 |
+
and isinstance(getattr(body[0], "value", None), ast.Constant)
|
| 614 |
+
and isinstance(body[0].value.value, str)
|
| 615 |
+
):
|
| 616 |
+
insert_after = body[0].end_lineno or 0
|
| 617 |
+
i = 1
|
| 618 |
+
while i < len(body) and isinstance(body[i], ast.ImportFrom) and body[i].module == "__future__":
|
| 619 |
+
insert_after = body[i].end_lineno or insert_after
|
| 620 |
+
i += 1
|
| 621 |
+
lines = env_source.splitlines(keepends=True)
|
| 622 |
+
return "".join(lines[:insert_after]) + bootstrap + "".join(lines[insert_after:])
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def _run_prime_push(env_dir, *, is_new: bool, name: str | None = None) -> int:
|
| 626 |
+
"""Run `prime env push` on a packaged env dir (always PRIVATE), climbing past conflicts.
|
| 627 |
+
|
| 628 |
+
When `name` is given it is passed as `--name` so the push targets that exact Hub env."""
|
| 629 |
+
import subprocess
|
| 630 |
+
|
| 631 |
+
# Published environments are always PRIVATE — they can hold proprietary task data.
|
| 632 |
+
base = ["prime", "env", "push", "--plain", "--path", str(env_dir), "--visibility", "PRIVATE"]
|
| 633 |
+
if name:
|
| 634 |
+
base += ["--name", name]
|
| 635 |
+
# Disable prime's interactive version check so a push isn't blocked in non-interactive
|
| 636 |
+
# use (PRIME_API_KEY is inherited from the user's environment).
|
| 637 |
+
env = {**os.environ, "PRIME_DISABLE_VERSION_CHECK": "1"}
|
| 638 |
+
auto_bump = not is_new # a re-publish must land on a fresh version
|
| 639 |
+
for _ in range(_PUSH_MAX_ATTEMPTS):
|
| 640 |
+
cmd = [*base, "--auto-bump"] if auto_bump else list(base)
|
| 641 |
+
proc = subprocess.run(cmd, capture_output=True, text=True, env=env)
|
| 642 |
+
output = f"{proc.stdout or ''}{proc.stderr or ''}"
|
| 643 |
+
if proc.stdout:
|
| 644 |
+
print(proc.stdout, end="")
|
| 645 |
+
if proc.stderr:
|
| 646 |
+
print(proc.stderr, end="")
|
| 647 |
+
if proc.returncode == 0:
|
| 648 |
+
slug = _push_slug_from(env_dir, output)
|
| 649 |
+
if slug:
|
| 650 |
+
print(f"published {slug}")
|
| 651 |
+
else:
|
| 652 |
+
# Don't report a clean success we can't confirm: the push exited 0 but we
|
| 653 |
+
# couldn't parse the owner/name id, so the env reference may be unrecorded.
|
| 654 |
+
print(
|
| 655 |
+
"warning: `prime env push` exited 0 but no owner/name id could be parsed; "
|
| 656 |
+
"verify the environment on the Prime Hub before training against it",
|
| 657 |
+
file=sys.stderr,
|
| 658 |
+
)
|
| 659 |
+
return 0
|
| 660 |
+
if _push_is_version_conflict(output):
|
| 661 |
+
auto_bump = True
|
| 662 |
+
continue
|
| 663 |
+
return proc.returncode
|
| 664 |
+
print(f"push failed after {_PUSH_MAX_ATTEMPTS} version-conflict retries", file=sys.stderr)
|
| 665 |
+
return 1
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
def cmd_env_push(args) -> int:
|
| 669 |
+
import shutil
|
| 670 |
+
import tempfile
|
| 671 |
+
|
| 672 |
+
if not shutil.which("prime"):
|
| 673 |
+
print("the `prime` CLI is required to publish to the Environments Hub.")
|
| 674 |
+
print("install it (https://docs.primeintellect.ai) then re-run `slm env push`.")
|
| 675 |
+
return 1
|
| 676 |
+
|
| 677 |
+
src = Path(args.path)
|
| 678 |
+
if not src.exists():
|
| 679 |
+
print(f"no such path: {src}", file=sys.stderr)
|
| 680 |
+
return 1
|
| 681 |
+
|
| 682 |
+
# A proper env directory (has a pyproject.toml) is pushed as-is; its name comes from the
|
| 683 |
+
# pyproject. Otherwise the published env name is derived from the env's path.
|
| 684 |
+
if src.is_dir() and (src / "pyproject.toml").is_file():
|
| 685 |
+
# First attempt never forces --auto-bump; the version-conflict retry enables it only
|
| 686 |
+
# when the version actually collides, so a genuine first publish keeps its version.
|
| 687 |
+
return _run_prime_push(src, is_new=True)
|
| 688 |
+
|
| 689 |
+
# Wrap a bare verifiers module (a single .py, or a one-module dir) into a Prime-compatible
|
| 690 |
+
# env package and push that. `--auto-bump` retries handle re-publishes. `data_dir` is a
|
| 691 |
+
# committed `datasets/` sibling of the module (if any); we ship it inside the package so an
|
| 692 |
+
# env that reads a `__file__`-relative data file still resolves once installed.
|
| 693 |
+
if src.is_file() and src.suffix == ".py":
|
| 694 |
+
module_source = src.read_text()
|
| 695 |
+
# Re-publish to the SAME Hub env when a sibling flash config names one: use its
|
| 696 |
+
# `[environment] id` name part so an edited environment.py mints a new version of the
|
| 697 |
+
# existing env instead of creating a fresh env from the file stem.
|
| 698 |
+
sibling_name = _config_env_name_from_dir(src.parent)
|
| 699 |
+
env_name = sibling_name or _push_env_name(src.stem)
|
| 700 |
+
data_dir = src.parent / "datasets"
|
| 701 |
+
# Ship the env's sibling helper modules (config.py/utils.py/...) so an environment.py that
|
| 702 |
+
# does `sys.path.insert(0, dir(__file__)); import utils` resolves once installed.
|
| 703 |
+
sibling_modules = [
|
| 704 |
+
p for p in sorted(src.parent.glob("*.py")) if p != src and not p.name.startswith("__")
|
| 705 |
+
]
|
| 706 |
+
# A sibling config id means we're re-publishing an EXISTING Hub env: auto-bump from the
|
| 707 |
+
# first attempt so it doesn't restart at 0.1.0 and climb through version conflicts.
|
| 708 |
+
is_new = sibling_name is None
|
| 709 |
+
elif src.is_dir():
|
| 710 |
+
modules = [p for p in sorted(src.glob("*.py")) if not p.name.startswith("__")]
|
| 711 |
+
if len(modules) != 1:
|
| 712 |
+
print(
|
| 713 |
+
f"{src} has no pyproject.toml and {'no' if not modules else 'multiple'} "
|
| 714 |
+
"top-level .py module(s); point `slm env push` at the env's .py file or add a "
|
| 715 |
+
"pyproject.toml.",
|
| 716 |
+
file=sys.stderr,
|
| 717 |
+
)
|
| 718 |
+
return 1
|
| 719 |
+
module_source = modules[0].read_text()
|
| 720 |
+
env_name = _push_env_name(src.name)
|
| 721 |
+
data_dir = src / "datasets"
|
| 722 |
+
sibling_modules = []
|
| 723 |
+
is_new = True
|
| 724 |
+
else:
|
| 725 |
+
print(f"cannot publish {src}: expected a verifiers .py module or an env directory.")
|
| 726 |
+
return 1
|
| 727 |
+
|
| 728 |
+
module = env_name.replace("-", "_")
|
| 729 |
+
# A Python package name can't start with a digit, so prefix one (e.g. "2026-task").
|
| 730 |
+
if module[:1].isdigit():
|
| 731 |
+
module = f"env_{module}"
|
| 732 |
+
with tempfile.TemporaryDirectory(prefix="slm-env-push-") as tmp:
|
| 733 |
+
pkg = Path(tmp)
|
| 734 |
+
(pkg / module).mkdir()
|
| 735 |
+
(pkg / module / "__init__.py").write_text(_with_syspath_bootstrap(module_source))
|
| 736 |
+
# Ship committed sibling data inside the package dir (it lands at <module>/datasets/, so a
|
| 737 |
+
# `os.path.dirname(__file__)/datasets/...` read resolves on the worker); the whole package
|
| 738 |
+
# dir ships via `[tool.hatch.build.targets.wheel] packages = ["<module>"]`.
|
| 739 |
+
if data_dir.is_dir() and any(data_dir.iterdir()):
|
| 740 |
+
shutil.copytree(data_dir, pkg / module / "datasets")
|
| 741 |
+
for mod in sibling_modules:
|
| 742 |
+
shutil.copy2(mod, pkg / module / mod.name)
|
| 743 |
+
(pkg / "pyproject.toml").write_text(
|
| 744 |
+
_ENV_PUSH_PYPROJECT.format(name=env_name, module=module, version=_PUSH_INITIAL_VERSION)
|
| 745 |
+
)
|
| 746 |
+
(pkg / "README.md").write_text(f"# {env_name}\n\nFlash verifiers environment.\n")
|
| 747 |
+
return _run_prime_push(pkg, is_new=is_new, name=env_name)
|
| 748 |
+
|
| 749 |
+
|
| 750 |
+
def cmd_train(args) -> int:
|
| 751 |
+
spec = spec_from_file(
|
| 752 |
+
args.config,
|
| 753 |
+
run_id=new_run_id() if args.dry_run else None,
|
| 754 |
+
overrides=getattr(args, "overrides", None),
|
| 755 |
+
extra_configs=getattr(args, "extra_configs", None),
|
| 756 |
+
)
|
| 757 |
+
if args.dry_run:
|
| 758 |
+
# Fully local: validate the id-based config without credentials, a server, or a GPU.
|
| 759 |
+
print(
|
| 760 |
+
json.dumps(
|
| 761 |
+
{"run_id": spec.run_id, "state": "dry_run", "spec": spec.to_dict()}, indent=2
|
| 762 |
+
)
|
| 763 |
+
)
|
| 764 |
+
return 0
|
| 765 |
+
client = client_from_config()
|
| 766 |
+
status = client.create_run(spec_payload(spec))
|
| 767 |
+
run_id = status["run_id"]
|
| 768 |
+
logger.info(
|
| 769 |
+
"submitted run %s: model=%s algorithm=%s gpu=%s seeds=%s",
|
| 770 |
+
run_id,
|
| 771 |
+
spec.model,
|
| 772 |
+
spec.algorithm,
|
| 773 |
+
spec.gpu.type,
|
| 774 |
+
list(spec.train.seeds),
|
| 775 |
+
)
|
| 776 |
+
if args.background:
|
| 777 |
+
print(json.dumps(status, indent=2))
|
| 778 |
+
return 0
|
| 779 |
+
print(
|
| 780 |
+
f"run {run_id} submitted; following logs (Ctrl-C detaches, `slm attach {run_id}` resumes)",
|
| 781 |
+
file=sys.stderr,
|
| 782 |
+
)
|
| 783 |
+
return _follow_run(client, run_id)
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
def _poll_logs(client: ApiClient, run_id: str, interval: float) -> str:
|
| 787 |
+
"""Stream offset-paged logs until the run reaches a terminal state; return that state."""
|
| 788 |
+
offset = 0
|
| 789 |
+
while True:
|
| 790 |
+
page = client.get_logs(run_id, offset=offset)
|
| 791 |
+
if page["logs"]:
|
| 792 |
+
print(page["logs"], end="", flush=True)
|
| 793 |
+
offset = page["offset"]
|
| 794 |
+
if page["state"] in _CLI_DONE_STATES:
|
| 795 |
+
return page["state"]
|
| 796 |
+
time.sleep(interval)
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
def _follow_run(client: ApiClient, run_id: str) -> int:
|
| 800 |
+
"""Poll logs until the run reaches a terminal state, then print the final status."""
|
| 801 |
+
state = _poll_logs(client, run_id, interval=2.0)
|
| 802 |
+
print(json.dumps(client.get_run(run_id), indent=2))
|
| 803 |
+
return 0 if state in _OK_STATES else 1
|
| 804 |
+
|
| 805 |
+
|
| 806 |
+
def cmd_status(args) -> int:
|
| 807 |
+
print(json.dumps(client_from_config().get_run(args.run_id), indent=2))
|
| 808 |
+
return 0
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
def cmd_attach(args) -> int:
|
| 812 |
+
client = client_from_config()
|
| 813 |
+
return _follow_run(client, args.run_id)
|
| 814 |
+
|
| 815 |
+
|
| 816 |
+
def cmd_ps(args) -> int:
|
| 817 |
+
runs = client_from_config().list_runs()
|
| 818 |
+
if not runs:
|
| 819 |
+
print("no runs yet")
|
| 820 |
+
return 0
|
| 821 |
+
print(f"{'RUN_ID':<32} {'STATE':<11} {'COST($)':>8} {'GPU':<22} MODEL")
|
| 822 |
+
for r in sorted(runs, key=lambda r: r.get("updated_at", 0), reverse=True):
|
| 823 |
+
spec = r.get("spec") or {}
|
| 824 |
+
model = spec.get("model", "")
|
| 825 |
+
remote = r.get("remote") or {}
|
| 826 |
+
# the remote handle knows what actually ran; the spec is the parse-time pick
|
| 827 |
+
provider = remote.get("provider") or (
|
| 828 |
+
"runpod" if remote else (spec.get("gpu") or {}).get("provider", "")
|
| 829 |
+
)
|
| 830 |
+
gpu = remote.get("gpu") or (spec.get("gpu") or {}).get("type", "")
|
| 831 |
+
where = f"{gpu}@{provider}" if provider else gpu
|
| 832 |
+
print(
|
| 833 |
+
f"{r['run_id']:<32} {r['state']:<11} {r.get('cost_usd', 0.0):>8.4f} "
|
| 834 |
+
f"{where:<22} {model}"
|
| 835 |
+
)
|
| 836 |
+
return 0
|
| 837 |
+
|
| 838 |
+
|
| 839 |
+
def cmd_cost(args) -> int:
|
| 840 |
+
status = client_from_config().get_run(args.run_id)
|
| 841 |
+
print(
|
| 842 |
+
json.dumps(
|
| 843 |
+
{
|
| 844 |
+
"run_id": args.run_id,
|
| 845 |
+
"state": status["state"],
|
| 846 |
+
"cost_usd": status.get("cost_usd", 0.0),
|
| 847 |
+
},
|
| 848 |
+
indent=2,
|
| 849 |
+
)
|
| 850 |
+
)
|
| 851 |
+
return 0
|
| 852 |
+
|
| 853 |
+
|
| 854 |
+
def cmd_cancel(args) -> int:
|
| 855 |
+
status = client_from_config().cancel_run(args.run_id)
|
| 856 |
+
print(json.dumps({"run_id": args.run_id, "state": status["state"]}, indent=2))
|
| 857 |
+
return 0
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
def cmd_logs(args) -> int:
|
| 861 |
+
client = client_from_config()
|
| 862 |
+
if not args.follow:
|
| 863 |
+
print(client.get_logs(args.run_id)["logs"], end="")
|
| 864 |
+
return 0
|
| 865 |
+
_poll_logs(client, args.run_id, interval=1.0)
|
| 866 |
+
return 0
|
| 867 |
+
|
| 868 |
+
|
| 869 |
+
def cmd_deploy(args) -> int:
|
| 870 |
+
dep = client_from_config().deploy(
|
| 871 |
+
args.run_id,
|
| 872 |
+
mode=args.mode,
|
| 873 |
+
idle_timeout_s=args.idle_timeout,
|
| 874 |
+
dry_run=args.dry_run,
|
| 875 |
+
)
|
| 876 |
+
print(json.dumps(dep, indent=2))
|
| 877 |
+
if dep.get("mode") == "always-on":
|
| 878 |
+
print(
|
| 879 |
+
f"note: always-on keeps a {dep.get('gpu')} warm 24/7 "
|
| 880 |
+
f"(~${dep.get('est_idle_cost_usd_per_day')}/day). Use `slm undeploy {args.run_id}` "
|
| 881 |
+
"to stop billing.",
|
| 882 |
+
file=sys.stderr,
|
| 883 |
+
)
|
| 884 |
+
return 0
|
| 885 |
+
|
| 886 |
+
|
| 887 |
+
def cmd_undeploy(args) -> int:
|
| 888 |
+
print(json.dumps(client_from_config().undeploy(args.run_id), indent=2))
|
| 889 |
+
return 0
|
| 890 |
+
|
| 891 |
+
|
| 892 |
+
def cmd_deployments(args) -> int:
|
| 893 |
+
rows = client_from_config().deployments()
|
| 894 |
+
if not rows:
|
| 895 |
+
print("no active deployments")
|
| 896 |
+
return 0
|
| 897 |
+
print(f"{'RUN_ID':<32} {'MODE':<10} {'GPU':<9} {'$/DAY':>7} ENDPOINT")
|
| 898 |
+
for r in rows:
|
| 899 |
+
d = r.get("deployment") or {}
|
| 900 |
+
print(
|
| 901 |
+
f"{r['run_id']:<32} {d.get('mode', '?'):<10} {d.get('gpu', '?'):<9} "
|
| 902 |
+
f"{d.get('est_idle_cost_usd_per_day', 0):>7} {d.get('endpoint_name', '')}"
|
| 903 |
+
)
|
| 904 |
+
return 0
|
| 905 |
+
|
| 906 |
+
|
| 907 |
+
def cmd_chat(args) -> int:
|
| 908 |
+
resp = client_from_config().chat(
|
| 909 |
+
args.run_id,
|
| 910 |
+
messages=[{"role": "user", "content": args.message}],
|
| 911 |
+
temperature=args.temperature,
|
| 912 |
+
max_tokens=args.max_tokens,
|
| 913 |
+
)
|
| 914 |
+
print(resp["choices"][0]["message"]["content"])
|
| 915 |
+
return 0
|
| 916 |
+
|
| 917 |
+
|
| 918 |
+
if __name__ == "__main__":
|
| 919 |
+
sys.exit(main())
|
code/flash/client/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HTTP client for the managed Flash 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/flash/client/config.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Client-side credential storage: the Flash API key + control-plane URL.
|
| 2 |
+
|
| 3 |
+
Stored in ``~/.flash/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, ``FLASH_API_URL`` for the URL.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
from .._fileio import read_json_or_empty, secure_json_write
|
| 14 |
+
|
| 15 |
+
DEFAULT_API_URL = "https://flash.freesolo.co"
|
| 16 |
+
|
| 17 |
+
CONFIG_DIR = Path.home() / ".flash"
|
| 18 |
+
CONFIG_PATH = CONFIG_DIR / "config.json"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _read_config() -> dict:
|
| 22 |
+
return read_json_or_empty(CONFIG_PATH)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def load_credentials() -> tuple[str, str | None]:
|
| 26 |
+
"""Resolve (api_url, api_key); the key is None when the user hasn't logged in."""
|
| 27 |
+
cfg = _read_config()
|
| 28 |
+
api_url = os.environ.get("FLASH_API_URL") or cfg.get("api_url") or DEFAULT_API_URL
|
| 29 |
+
api_key = os.environ.get("FREESOLO_API_KEY") or cfg.get("api_key")
|
| 30 |
+
return api_url.rstrip("/"), api_key
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def save_credentials(api_key: str, api_url: str | None = None) -> Path:
|
| 34 |
+
"""Persist the key (and optionally a non-default URL) with private permissions."""
|
| 35 |
+
cfg = _read_config()
|
| 36 |
+
cfg["api_key"] = api_key
|
| 37 |
+
if api_url:
|
| 38 |
+
# Record the plane actually authenticated against. When it's the default, drop any
|
| 39 |
+
# stored url instead of pinning it — this also clears a stale custom url from a
|
| 40 |
+
# previous custom FLASH_API_URL login so later commands don't keep hitting the old host.
|
| 41 |
+
if api_url.rstrip("/") == DEFAULT_API_URL.rstrip("/"):
|
| 42 |
+
cfg.pop("api_url", None)
|
| 43 |
+
else:
|
| 44 |
+
cfg["api_url"] = api_url.rstrip("/")
|
| 45 |
+
secure_json_write(CONFIG_PATH, cfg)
|
| 46 |
+
return CONFIG_PATH
|
code/flash/client/http.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stdlib HTTP client for the Flash 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 flash control plane): `slm login`
|
| 30 |
+
# verifies the user's freesolo API key here. The same key authenticates the flash
|
| 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 Flash service at {self.api_url} ({exc.reason}); "
|
| 113 |
+
"check your network connection and FLASH_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/flash/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 ``~/.flash/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 flash.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 flash.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/flash/engine/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Substrate-neutral fine-tuning internals for the Flash 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 ``flash.providers.runpod`` invokes ``flash.engine.worker`` on the
|
| 6 |
+
provisioned GPU.
|
| 7 |
+
"""
|
code/flash/engine/accounting.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Cost accounting + the standard run-metrics record for Flash 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/flash/engine/chalk_kernels.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Optional chalk GPU kernels (the ``freesolo-chalk`` package).
|
| 2 |
+
|
| 3 |
+
Chalk holds Freesolo's hand-written Triton/CUDA kernels that complement Liger
|
| 4 |
+
(fused GEMMs, the LoRA-delta matmuls, the QKV norm+RoPE epilogue, embedding gather,
|
| 5 |
+
FP8 frozen-base GEMMs).
|
| 6 |
+
|
| 7 |
+
Chalk follows the **install-on-call** model (mirroring Liger's
|
| 8 |
+
``apply_liger_kernel_to_qwen3``): chalk reads NO env vars — *calling* an installer IS
|
| 9 |
+
the opt-in. Each installer then arch-gates itself, runs a numeric self-test on install,
|
| 10 |
+
patches only frozen ``nn.Linear`` layers, and silently falls back to the eager / Liger
|
| 11 |
+
path (a no-op on CPU / the control plane) on any failure.
|
| 12 |
+
|
| 13 |
+
Because chalk no longer gates itself, the FLASH WORKER must decide *which* installers to
|
| 14 |
+
call. :func:`install_chalk_kernels` reads per-kernel ``FLASH_*`` selection flags (set by
|
| 15 |
+
the operator, forwarded to the worker by ``providers.runpod.train.build_worker_env``) and
|
| 16 |
+
calls ONLY the selected chalk installers. With NO flags set (the default) it calls
|
| 17 |
+
nothing, so it is always safe to invoke; and if ``freesolo-chalk`` isn't installed at all
|
| 18 |
+
(e.g. on the control plane, or a worker without a chalk spec) the whole module degrades to
|
| 19 |
+
a no-op.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import os
|
| 25 |
+
|
| 26 |
+
from flash._logging import get_logger
|
| 27 |
+
|
| 28 |
+
log = get_logger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _truthy(name: str) -> bool:
|
| 32 |
+
"""A FLASH_* flag counts as ON when set to a non-empty, non-false value."""
|
| 33 |
+
v = os.environ.get(name)
|
| 34 |
+
return v is not None and v.strip().lower() not in ("", "0", "false", "no", "off")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _int_env(name: str, default: int) -> int:
|
| 38 |
+
raw = os.environ.get(name)
|
| 39 |
+
if raw is None or not raw.strip():
|
| 40 |
+
return default
|
| 41 |
+
try:
|
| 42 |
+
return int(raw.strip())
|
| 43 |
+
except ValueError:
|
| 44 |
+
log.warning("ignoring non-integer %s=%r (using %d)", name, raw, default)
|
| 45 |
+
return default
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _selected_installers() -> list[tuple[str, bool, dict]]:
|
| 49 |
+
"""The chalk installers the operator selected via ``FLASH_*`` flags.
|
| 50 |
+
|
| 51 |
+
Returns ``(installer_name, needs_model, kwargs)`` for each ENABLED kernel. ``needs_model``
|
| 52 |
+
marks the instance-level installers (they patch the materialized ``nn.Module`` and must be
|
| 53 |
+
skipped when no model is available yet); the class/function-level ones install with no model.
|
| 54 |
+
|
| 55 |
+
Default (no flags set) is an empty list -> :func:`install_chalk_kernels` calls nothing.
|
| 56 |
+
"""
|
| 57 |
+
selected: list[tuple[str, bool, dict]] = []
|
| 58 |
+
# Class/function-level kernels (patch the model class / a global fn; no model arg needed).
|
| 59 |
+
# chalk signatures: install_qwen35_mlp(model=None), install_qwen35_qkv(model=None),
|
| 60 |
+
# install_lora() [no model param], install_qwen35_rope() [no model param].
|
| 61 |
+
if _truthy("FLASH_MLP_KERNEL"):
|
| 62 |
+
selected.append(("install_qwen35_mlp", False, {}))
|
| 63 |
+
if _truthy("FLASH_QKV_KERNEL"):
|
| 64 |
+
selected.append(("install_qwen35_qkv", False, {}))
|
| 65 |
+
if _truthy("FLASH_TRITON_LORA"):
|
| 66 |
+
selected.append(("install_lora", False, {}))
|
| 67 |
+
if _truthy("FLASH_ROPE_KERNEL"):
|
| 68 |
+
selected.append(("install_qwen35_rope", False, {}))
|
| 69 |
+
# Instance-level kernels (need the built nn.Module).
|
| 70 |
+
# chalk signatures: install_qwen35_mlp_fp8(model, *, down=True),
|
| 71 |
+
# install_fp8_base(model, *, attn=True, mlp=True, min_k=256),
|
| 72 |
+
# install_qwen35_embedding(model).
|
| 73 |
+
if _truthy("FLASH_MLP_FP8"):
|
| 74 |
+
# FLASH_MLP_FP8_DOWN selects whether the down-projection is fused too (chalk default True).
|
| 75 |
+
down = os.environ.get("FLASH_MLP_FP8_DOWN")
|
| 76 |
+
kwargs = {} if down is None else {"down": _truthy("FLASH_MLP_FP8_DOWN")}
|
| 77 |
+
selected.append(("install_qwen35_mlp_fp8", True, kwargs))
|
| 78 |
+
if _truthy("FLASH_FP8_BASE"):
|
| 79 |
+
# Per-kernel scope knobs mirror chalk's install_fp8_base kwargs; only forward the ones the
|
| 80 |
+
# operator set so chalk's own defaults (attn=True, mlp=True, min_k=256) apply otherwise.
|
| 81 |
+
kwargs = {}
|
| 82 |
+
if os.environ.get("FLASH_FP8_BASE_ATTN") is not None:
|
| 83 |
+
kwargs["attn"] = _truthy("FLASH_FP8_BASE_ATTN")
|
| 84 |
+
if os.environ.get("FLASH_FP8_BASE_MLP") is not None:
|
| 85 |
+
kwargs["mlp"] = _truthy("FLASH_FP8_BASE_MLP")
|
| 86 |
+
if os.environ.get("FLASH_FP8_BASE_MIN_K") is not None:
|
| 87 |
+
kwargs["min_k"] = _int_env("FLASH_FP8_BASE_MIN_K", 256)
|
| 88 |
+
selected.append(("install_fp8_base", True, kwargs))
|
| 89 |
+
if _truthy("FLASH_EMBED_KERNEL"):
|
| 90 |
+
selected.append(("install_qwen35_embedding", True, {}))
|
| 91 |
+
return selected
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def install_chalk_kernels(model=None) -> dict:
|
| 95 |
+
"""Install the chalk kernels the operator selected via ``FLASH_*`` flags.
|
| 96 |
+
|
| 97 |
+
chalk reads NO env vars (install-on-call), so the WORKER decides which installers to call:
|
| 98 |
+
each enabled ``FLASH_*`` flag maps to one chalk installer (see :func:`_selected_installers`).
|
| 99 |
+
With no flags set this calls nothing and returns ``{}``.
|
| 100 |
+
|
| 101 |
+
Call this TWICE per training run — exactly the two passes the worker makes — and each kernel
|
| 102 |
+
installs on the ONE pass it belongs to (never twice):
|
| 103 |
+
|
| 104 |
+
* ``install_chalk_kernels()`` (``model is None``, the PRE-build pass) installs only the
|
| 105 |
+
class/function-level kernels (LoRA delta, fused MLP/QKV, RoPE) — global monkeypatches that
|
| 106 |
+
must be in place before the trainer builds the model. Instance-level kernels are skipped (no
|
| 107 |
+
module yet).
|
| 108 |
+
* ``install_chalk_kernels(trainer.model)`` (``model is not None``, the POST-build pass) installs
|
| 109 |
+
only the instance-level kernels (FP8 base, embedding, FP8 MLP) against the materialized
|
| 110 |
+
module. The class/function-level monkeypatches were already applied on the pre-build pass, so
|
| 111 |
+
re-running them here would double-patch — they are deliberately NOT re-run.
|
| 112 |
+
|
| 113 |
+
Returns a ``{installer_name: result}`` map for the installers that ran ON THIS PASS (``{}`` when
|
| 114 |
+
no flag is set, chalk isn't installed, or no selected kernel belongs to this pass).
|
| 115 |
+
"""
|
| 116 |
+
selected = _selected_installers()
|
| 117 |
+
if not selected:
|
| 118 |
+
# No FLASH_* kernel flag set -> the operator opted into nothing. Don't even import chalk.
|
| 119 |
+
return {}
|
| 120 |
+
|
| 121 |
+
try:
|
| 122 |
+
import chalk.transformers as ck
|
| 123 |
+
except ImportError:
|
| 124 |
+
# A FLASH_* flag is set but chalk isn't installed (control plane, or a worker without a
|
| 125 |
+
# chalk spec in FLASH_CHALK_SPEC/extra_pip). Documented as always safe — warn and no-op.
|
| 126 |
+
log.warning(
|
| 127 |
+
"FLASH_* chalk kernel(s) requested but freesolo-chalk is not installed "
|
| 128 |
+
"(set FLASH_CHALK_SPEC to an installable spec on the worker); skipping."
|
| 129 |
+
)
|
| 130 |
+
return {}
|
| 131 |
+
except Exception as e:
|
| 132 |
+
# A partially-installed / version-incompatible chalk can raise non-ImportError errors at
|
| 133 |
+
# import time (e.g. a Triton/torch mismatch surfaced on import of a kernel module). This
|
| 134 |
+
# hook is documented as always safe and must never abort training, so degrade to a no-op.
|
| 135 |
+
log.warning("chalk import failed (ignored, kernels disabled): %s", e)
|
| 136 |
+
return {}
|
| 137 |
+
|
| 138 |
+
results: dict[str, object] = {}
|
| 139 |
+
for name, needs_model, kwargs in selected:
|
| 140 |
+
# Each kernel installs on exactly ONE of the two passes, so the second call never
|
| 141 |
+
# re-applies what the first already installed:
|
| 142 |
+
# * class/function-level (needs_model=False): global monkeypatches -> PRE-build pass only
|
| 143 |
+
# (model is None). Skipping them when a model is present avoids re-installing the global
|
| 144 |
+
# patch the pre-build call already applied (double-patch).
|
| 145 |
+
# * instance-level (needs_model=True): patch the built nn.Module -> POST-build pass only
|
| 146 |
+
# (model is not None); there is no module to patch on the pre-build pass.
|
| 147 |
+
if needs_model != (model is not None):
|
| 148 |
+
continue
|
| 149 |
+
fn = getattr(ck, name, None)
|
| 150 |
+
if fn is None:
|
| 151 |
+
log.warning("chalk has no installer %s (skipping)", name)
|
| 152 |
+
continue
|
| 153 |
+
try:
|
| 154 |
+
results[name] = fn(model, **kwargs) if needs_model else fn(**kwargs)
|
| 155 |
+
except Exception as e: # never block training on an optional kernel
|
| 156 |
+
log.warning("chalk %s failed (ignored): %s", name, e)
|
| 157 |
+
results[name] = f"error: {e}"
|
| 158 |
+
|
| 159 |
+
enabled = {k: v for k, v in results.items() if v not in (False, None) and not str(v).startswith("error")}
|
| 160 |
+
if enabled:
|
| 161 |
+
log.info("chalk kernels active: %s", ", ".join(enabled))
|
| 162 |
+
return results
|
code/flash/engine/midrun_eval.py
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Periodic mid-run evaluation for GRPO (greedy eval on a held-out split, between steps).
|
| 2 |
+
|
| 3 |
+
GRPO's only live signal is the per-step *training* reward — noisy, on-policy, temperature>0,
|
| 4 |
+
and (by design) often a SHAPED reward rather than the metric you actually care about. This
|
| 5 |
+
module adds a deterministic eval signal: every ``N`` optimizer steps it samples the current
|
| 6 |
+
policy GREEDILY on a fixed held-out split and scores it, then streams the result through the
|
| 7 |
+
worker ``heartbeat`` so the orchestrating agent sees an eval curve mid-run (early-stop, plateau
|
| 8 |
+
detection, checkpoint selection) instead of only the reward stream.
|
| 9 |
+
|
| 10 |
+
Evaluation distinct from reward lives in the environment. A verifiers
|
| 11 |
+
``environment.py`` expresses an evaluation metric SEPARATE from the GRPO reward as a
|
| 12 |
+
**eval-metric rubric func** (``rubric.add_metric(fn, weight=0.0)``): it does not shape training
|
| 13 |
+
but is computed and reported. The adapter's :meth:`VerifiersEnvironment.evaluate` returns both
|
| 14 |
+
the weighted training ``reward`` and those eval-metric ``metrics`` in one rubric pass, and this
|
| 15 |
+
module surfaces both — so the agent watches the env's true eval metric, not just the reward.
|
| 16 |
+
|
| 17 |
+
It generates with the **trainer's own model** (``trainer.model.generate`` in eval/no-grad mode),
|
| 18 |
+
NOT the colocate vLLM engine. Calling ``engine.generate`` out-of-band from a ``TrainerCallback``
|
| 19 |
+
deadlocks GRPO (the engine is only safe to drive inside TRL's managed ``rollout_func`` window;
|
| 20 |
+
an external call from ``on_step_end`` hangs the training thread — verified on a live GPU run).
|
| 21 |
+
Generating on the already-loaded trainer model avoids the engine entirely, works on BOTH the
|
| 22 |
+
vLLM-colocate and transformers-generation backends, and keeps memory bounded: ONE prompt at a
|
| 23 |
+
time (a single sequence's KV cache), and an OOM there is a *catchable* error -> graceful
|
| 24 |
+
``eval_skipped``, never a training-freezing hang.
|
| 25 |
+
|
| 26 |
+
Design mirrors :mod:`flash.engine.multiturn_rollout`: the core (:class:`PeriodicEval`, the
|
| 27 |
+
scorers, :func:`evaluate_policy`, :func:`summarize`) is pure Python with ``render`` / ``generate``
|
| 28 |
+
/ engine access INJECTED, so cadence gating, engine binding, skip handling and heartbeat
|
| 29 |
+
emission are unit-tested without a GPU, tokenizer, or vLLM. Only :func:`build_hf_greedy_generate`
|
| 30 |
+
(wired in ``worker.run_rl``) touches torch / the live model.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
from __future__ import annotations
|
| 34 |
+
|
| 35 |
+
import random
|
| 36 |
+
from collections.abc import Callable
|
| 37 |
+
from dataclasses import dataclass, field
|
| 38 |
+
|
| 39 |
+
from flash.engine.multiturn_rollout import rollout_one
|
| 40 |
+
|
| 41 |
+
# A failed single rollout (template violation, env exception) scores 0 rather than crashing the
|
| 42 |
+
# whole eval — and a crashing eval must never abort a paid training run, so the callback also
|
| 43 |
+
# swallows eval-wide failures and heartbeats a skip reason.
|
| 44 |
+
_EVAL_ERROR_REWARD = 0.0
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass(frozen=True)
|
| 48 |
+
class EvalRecord:
|
| 49 |
+
"""One example's eval result: the training ``reward`` and the env's eval-metric ``metrics``."""
|
| 50 |
+
|
| 51 |
+
reward: float
|
| 52 |
+
metrics: dict[str, float] = field(default_factory=dict)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@dataclass(frozen=True)
|
| 56 |
+
class EvalSummary:
|
| 57 |
+
"""Aggregate of one mid-run eval pass over the held-out set."""
|
| 58 |
+
|
| 59 |
+
n: int
|
| 60 |
+
mean_reward: float
|
| 61 |
+
pass_rate: float
|
| 62 |
+
min_reward: float
|
| 63 |
+
max_reward: float
|
| 64 |
+
metric_means: dict[str, float] = field(default_factory=dict)
|
| 65 |
+
rewards: list[float] = field(default_factory=list)
|
| 66 |
+
step: int | None = None
|
| 67 |
+
|
| 68 |
+
def as_heartbeat_fields(self) -> dict:
|
| 69 |
+
"""The flat fields streamed under the ``rl_eval`` heartbeat stage. Each env eval metric
|
| 70 |
+
is reported as ``eval_metric_<name>`` so it sits alongside the reward, distinct from it."""
|
| 71 |
+
fields: dict[str, float | int] = {
|
| 72 |
+
"eval_n": self.n,
|
| 73 |
+
"eval_reward": self.mean_reward,
|
| 74 |
+
"eval_pass_rate": self.pass_rate,
|
| 75 |
+
"eval_reward_min": self.min_reward,
|
| 76 |
+
"eval_reward_max": self.max_reward,
|
| 77 |
+
}
|
| 78 |
+
for name, value in self.metric_means.items():
|
| 79 |
+
fields[f"eval_metric_{name}"] = value
|
| 80 |
+
return fields
|
| 81 |
+
|
| 82 |
+
def as_record(self) -> dict:
|
| 83 |
+
"""A compact per-eval record for the run's ``metrics.json`` ``notes['eval_history']`` —
|
| 84 |
+
what the orchestrating agent reads post-run to judge the model on the EVAL metric, not
|
| 85 |
+
just the training reward. Drops the per-example list to keep metrics.json small."""
|
| 86 |
+
return {
|
| 87 |
+
"step": self.step,
|
| 88 |
+
"eval_reward": self.mean_reward,
|
| 89 |
+
"eval_pass_rate": self.pass_rate,
|
| 90 |
+
"eval_n": self.n,
|
| 91 |
+
"eval_metrics": dict(self.metric_means),
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def summarize(
|
| 96 |
+
records: list[EvalRecord], *, step: int | None = None, pass_threshold: float = 0.5
|
| 97 |
+
) -> EvalSummary:
|
| 98 |
+
"""Reduce per-example records to an :class:`EvalSummary` (empty -> all-zero, n=0).
|
| 99 |
+
|
| 100 |
+
``pass_rate`` is the fraction with training ``reward >= pass_threshold``; each env metric is
|
| 101 |
+
averaged independently across the examples that reported it.
|
| 102 |
+
"""
|
| 103 |
+
if not records:
|
| 104 |
+
return EvalSummary(0, 0.0, 0.0, 0.0, 0.0, {}, [], step)
|
| 105 |
+
rewards = [float(r.reward) for r in records]
|
| 106 |
+
n = len(rewards)
|
| 107 |
+
metric_sums: dict[str, float] = {}
|
| 108 |
+
metric_counts: dict[str, int] = {}
|
| 109 |
+
for rec in records:
|
| 110 |
+
for name, value in rec.metrics.items():
|
| 111 |
+
metric_sums[name] = metric_sums.get(name, 0.0) + float(value)
|
| 112 |
+
metric_counts[name] = metric_counts.get(name, 0) + 1
|
| 113 |
+
metric_means = {name: metric_sums[name] / metric_counts[name] for name in metric_sums}
|
| 114 |
+
return EvalSummary(
|
| 115 |
+
n=n,
|
| 116 |
+
mean_reward=sum(rewards) / n,
|
| 117 |
+
pass_rate=sum(1 for r in rewards if r >= pass_threshold) / n,
|
| 118 |
+
min_reward=min(rewards),
|
| 119 |
+
max_reward=max(rewards),
|
| 120 |
+
metric_means=metric_means,
|
| 121 |
+
rewards=rewards,
|
| 122 |
+
step=step,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def evaluate_policy(
|
| 127 |
+
examples: list[dict],
|
| 128 |
+
score_one: Callable[[dict], EvalRecord],
|
| 129 |
+
*,
|
| 130 |
+
step: int | None = None,
|
| 131 |
+
pass_threshold: float = 0.5,
|
| 132 |
+
on_error: str = "zero",
|
| 133 |
+
on_warn: Callable[[str], None] | None = None,
|
| 134 |
+
) -> EvalSummary:
|
| 135 |
+
"""Score every example with ``score_one`` and summarize.
|
| 136 |
+
|
| 137 |
+
``on_error="zero"`` (default) makes a per-example scoring failure a zero-reward record (so
|
| 138 |
+
one bad rollout doesn't sink the pass); ``on_error="raise"`` re-raises (tests).
|
| 139 |
+
|
| 140 |
+
A SYSTEMIC failure (every example errors — e.g. generation OOMs each call) raises instead of
|
| 141 |
+
returning ``eval_reward=0``: a flat-zero curve reads as "the model got everything wrong",
|
| 142 |
+
which is misleading when the eval simply couldn't run. The caller turns that into a skip.
|
| 143 |
+
"""
|
| 144 |
+
records: list[EvalRecord] = []
|
| 145 |
+
errors = 0
|
| 146 |
+
last_error: Exception | None = None
|
| 147 |
+
for ex in examples:
|
| 148 |
+
try:
|
| 149 |
+
records.append(score_one(ex))
|
| 150 |
+
except Exception as exc: # a bad rollout must not abort the eval/run
|
| 151 |
+
if on_error == "raise":
|
| 152 |
+
raise
|
| 153 |
+
errors += 1
|
| 154 |
+
last_error = exc
|
| 155 |
+
if on_warn:
|
| 156 |
+
on_warn(f"mid-run eval: example scored 0 after error: {exc}")
|
| 157 |
+
records.append(EvalRecord(_EVAL_ERROR_REWARD, {}))
|
| 158 |
+
if examples and errors == len(examples):
|
| 159 |
+
raise RuntimeError(
|
| 160 |
+
f"mid-run eval: all {errors} examples failed to generate "
|
| 161 |
+
f"(last error: {last_error}) — reporting a skip, not eval_reward=0"
|
| 162 |
+
)
|
| 163 |
+
return summarize(records, step=step, pass_threshold=pass_threshold)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def single_turn_scorer(
|
| 167 |
+
active_env,
|
| 168 |
+
render_prompt_ids: Callable[[dict], list[int]],
|
| 169 |
+
generate: Callable[[list[int], int], tuple[list[int], list[float], str]],
|
| 170 |
+
max_new_tokens: int,
|
| 171 |
+
graded_text: Callable[[str | None], str | None] = lambda c: c,
|
| 172 |
+
) -> Callable[[dict], EvalRecord]:
|
| 173 |
+
"""Per-example scorer for a single-turn env: render -> greedy generate -> env evaluate.
|
| 174 |
+
|
| 175 |
+
``generate(prefix_ids, max_tokens) -> (token_ids, logprobs, text)`` mirrors the colocate
|
| 176 |
+
engine wrapper used by the multi-turn rollout; only ``text`` is used here. ``graded_text``
|
| 177 |
+
strips ``<think>`` blocks before scoring on thinking runs (worker parity). Uses the env's
|
| 178 |
+
:meth:`evaluate` so the env's eval-metric metrics come back alongside the reward."""
|
| 179 |
+
|
| 180 |
+
def score(example: dict) -> EvalRecord:
|
| 181 |
+
prefix_ids = render_prompt_ids(example)
|
| 182 |
+
_ids, _lps, text = generate(prefix_ids, max_new_tokens)
|
| 183 |
+
result = active_env.evaluate(graded_text(text), example)
|
| 184 |
+
return EvalRecord(
|
| 185 |
+
reward=float(result["reward"]),
|
| 186 |
+
metrics={k: float(v) for k, v in (result.get("metrics") or {}).items()},
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
return score
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def multi_turn_scorer(
|
| 193 |
+
active_env,
|
| 194 |
+
render_messages: Callable[[list, bool], list[int]],
|
| 195 |
+
generate: Callable[[list[int], int], tuple[list[int], list[float], str]],
|
| 196 |
+
*,
|
| 197 |
+
max_turns: int,
|
| 198 |
+
max_new_tokens: int,
|
| 199 |
+
engine_max_len: int | None = None,
|
| 200 |
+
on_warn: Callable[[str], None] | None = None,
|
| 201 |
+
) -> Callable[[dict], EvalRecord]:
|
| 202 |
+
"""Per-example scorer for a multi-turn env: drive the env turn loop GREEDILY via
|
| 203 |
+
:func:`rollout_one` and read its rubric reward. (Per-metric breakdown for multi-turn is a
|
| 204 |
+
follow-up — ``rollout_one`` returns only the scalar reward — so ``metrics`` is empty here.)"""
|
| 205 |
+
|
| 206 |
+
def score(example: dict) -> EvalRecord:
|
| 207 |
+
result = rollout_one(
|
| 208 |
+
example=example,
|
| 209 |
+
active_env=active_env,
|
| 210 |
+
render=render_messages,
|
| 211 |
+
generate=generate,
|
| 212 |
+
max_turns=max_turns,
|
| 213 |
+
per_turn_max_tokens=max_new_tokens,
|
| 214 |
+
engine_max_len=engine_max_len,
|
| 215 |
+
on_warn=on_warn,
|
| 216 |
+
)
|
| 217 |
+
return EvalRecord(reward=float(result["reward"]), metrics={})
|
| 218 |
+
|
| 219 |
+
return score
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class PeriodicEval:
|
| 223 |
+
"""Pure cadence + engine-binding + heartbeat logic for mid-run eval (no GPU/transformers).
|
| 224 |
+
|
| 225 |
+
``score_one_builder(engine) -> score_one`` defers all GPU-specific wiring (the vLLM
|
| 226 |
+
SamplingParams, the tokenizer render) to call time, so this class is fully unit-testable
|
| 227 |
+
with a fake engine getter, a fake builder, and a fake heartbeat sink.
|
| 228 |
+
"""
|
| 229 |
+
|
| 230 |
+
def __init__(
|
| 231 |
+
self,
|
| 232 |
+
*,
|
| 233 |
+
examples: list[dict],
|
| 234 |
+
score_one_builder: Callable[[object], Callable[[dict], EvalRecord]],
|
| 235 |
+
every_steps: int,
|
| 236 |
+
heartbeat_fn: Callable[..., object],
|
| 237 |
+
model_getter: Callable[[], object] | None = None,
|
| 238 |
+
pass_threshold: float = 0.5,
|
| 239 |
+
label: str = "rl_eval",
|
| 240 |
+
on_warn: Callable[[str], None] = print,
|
| 241 |
+
) -> None:
|
| 242 |
+
self.examples = list(examples)
|
| 243 |
+
self.score_one_builder = score_one_builder
|
| 244 |
+
self.every_steps = int(every_steps)
|
| 245 |
+
self.heartbeat_fn = heartbeat_fn
|
| 246 |
+
self.model_getter = model_getter
|
| 247 |
+
self.pass_threshold = float(pass_threshold)
|
| 248 |
+
self.label = label
|
| 249 |
+
self.on_warn = on_warn
|
| 250 |
+
self._disabled = False
|
| 251 |
+
# Accumulated eval curve, persisted into metrics.json so the agent reads it post-run.
|
| 252 |
+
self.history: list[EvalSummary] = []
|
| 253 |
+
|
| 254 |
+
def history_records(self) -> list[dict]:
|
| 255 |
+
"""The eval curve as compact dicts for ``metrics.json`` ``notes['eval_history']``."""
|
| 256 |
+
return [s.as_record() for s in self.history]
|
| 257 |
+
|
| 258 |
+
def bind_model_getter(self, getter: Callable[[], object]) -> None:
|
| 259 |
+
"""Attach the (late-bound) accessor for the live generation model — the trainer that owns
|
| 260 |
+
it does not exist when the callback is constructed."""
|
| 261 |
+
self.model_getter = getter
|
| 262 |
+
|
| 263 |
+
def should_run(self, step: int) -> bool:
|
| 264 |
+
return (
|
| 265 |
+
not self._disabled
|
| 266 |
+
and self.every_steps > 0
|
| 267 |
+
and step > 0
|
| 268 |
+
and bool(self.examples)
|
| 269 |
+
and step % self.every_steps == 0
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
def maybe_run(self, step: int) -> EvalSummary | None:
|
| 273 |
+
if not self.should_run(step):
|
| 274 |
+
return None
|
| 275 |
+
return self.run_eval(step)
|
| 276 |
+
|
| 277 |
+
def run_final(self, step: int) -> EvalSummary | None:
|
| 278 |
+
"""Evaluate the FINAL trained policy once, after training ends.
|
| 279 |
+
|
| 280 |
+
The cadence (``maybe_run``) only fires on exact multiples of ``every_steps``; when the run
|
| 281 |
+
length is not a multiple (the common case), the last cadence eval predates the saved
|
| 282 |
+
adapter. This runs one more eval on the final model so ``eval_history`` ends on the policy
|
| 283 |
+
that was actually saved — unless the last recorded eval is already this exact step (run
|
| 284 |
+
length was an exact multiple, so the final step was already evaluated)."""
|
| 285 |
+
if self._disabled or self.every_steps <= 0 or step <= 0 or not self.examples:
|
| 286 |
+
return None
|
| 287 |
+
if self.history and self.history[-1].step == step:
|
| 288 |
+
return None # the final step coincided with a cadence eval; don't double-run
|
| 289 |
+
return self.run_eval(step)
|
| 290 |
+
|
| 291 |
+
def run_eval(self, step: int) -> EvalSummary | None:
|
| 292 |
+
"""Evaluate the current policy once and heartbeat the result (or a skip reason).
|
| 293 |
+
|
| 294 |
+
Never raises (even if the model getter itself throws): any failure heartbeats a skip
|
| 295 |
+
reason for THIS step and lets training continue. A missing model only skips this cadence
|
| 296 |
+
— it does NOT permanently disable eval, since the getter resolves the live model each
|
| 297 |
+
time and a one-off ``None`` (e.g. a teardown race) can resolve by the next cadence.
|
| 298 |
+
"""
|
| 299 |
+
try:
|
| 300 |
+
model = self.model_getter() if self.model_getter is not None else None
|
| 301 |
+
except Exception as exc: # the getter (attribute access on the trainer) must not abort
|
| 302 |
+
self.heartbeat_fn(
|
| 303 |
+
self.label, step=step, eval_skipped=True, eval_reason=f"model getter failed: {exc}"
|
| 304 |
+
)
|
| 305 |
+
return None
|
| 306 |
+
if model is None:
|
| 307 |
+
self.heartbeat_fn(
|
| 308 |
+
self.label, step=step, eval_skipped=True, eval_reason="no model available"
|
| 309 |
+
)
|
| 310 |
+
return None
|
| 311 |
+
try:
|
| 312 |
+
score_one = self.score_one_builder(model)
|
| 313 |
+
summary = evaluate_policy(
|
| 314 |
+
self.examples,
|
| 315 |
+
score_one,
|
| 316 |
+
step=step,
|
| 317 |
+
pass_threshold=self.pass_threshold,
|
| 318 |
+
on_warn=self.on_warn,
|
| 319 |
+
)
|
| 320 |
+
except Exception as exc: # eval must never abort training
|
| 321 |
+
self.heartbeat_fn(
|
| 322 |
+
self.label,
|
| 323 |
+
step=step,
|
| 324 |
+
eval_skipped=True,
|
| 325 |
+
eval_reason=f"{type(exc).__name__}: {exc}",
|
| 326 |
+
)
|
| 327 |
+
return None
|
| 328 |
+
self.history.append(summary) # accumulate the curve for metrics.json (agent reads it)
|
| 329 |
+
self.heartbeat_fn(self.label, step=step, **summary.as_heartbeat_fields())
|
| 330 |
+
return summary
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def make_periodic_eval_callback(periodic: PeriodicEval):
|
| 334 |
+
"""Wrap a :class:`PeriodicEval` in a transformers ``TrainerCallback`` (lazy import).
|
| 335 |
+
|
| 336 |
+
Mirrors ``worker.make_reward_heartbeat_callback``: the callback fires on every optimizer
|
| 337 |
+
step end and delegates the cadence decision to ``periodic.maybe_run``."""
|
| 338 |
+
from transformers import TrainerCallback
|
| 339 |
+
|
| 340 |
+
class _PeriodicEvalCallback(TrainerCallback):
|
| 341 |
+
def on_step_end(self, args, state, control, **kwargs):
|
| 342 |
+
step = int(getattr(state, "global_step", 0) or 0)
|
| 343 |
+
periodic.maybe_run(step)
|
| 344 |
+
|
| 345 |
+
return _PeriodicEvalCallback()
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
# ---------------------------------------------------------------------------
|
| 349 |
+
# GPU-side wiring (the only part that touches torch / the model). From worker.run_rl.
|
| 350 |
+
# ---------------------------------------------------------------------------
|
| 351 |
+
DEFAULT_EVAL_NUM = 64
|
| 352 |
+
# Fixed seed for the held-out random sample, so every eval pass scores the SAME subset and the
|
| 353 |
+
# eval curve is comparable across steps.
|
| 354 |
+
EVAL_SAMPLE_SEED = 12345
|
| 355 |
+
# Default pool size to MATERIALIZE and sample from when `eval_examples` is small (data load is
|
| 356 |
+
# cheap; only generation is the real cost), so a multi-million-row Hub split isn't fully built just
|
| 357 |
+
# to pick a few-dozen-row sample. The pool must hold at least `n` rows to draw an n-row sample, so
|
| 358 |
+
# the caller materializes max(n, EVAL_POOL_CAP): this cap is the FLOOR for the common small-n case,
|
| 359 |
+
# not a ceiling — a run that explicitly sets eval_examples ABOVE the cap is asking to score that
|
| 360 |
+
# many rows and gets exactly that (the bound is only a default for the few-dozen-row default n).
|
| 361 |
+
EVAL_POOL_CAP = 2048
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def sample_eval_rows(pool: list, n: int, seed: int = EVAL_SAMPLE_SEED) -> list:
|
| 365 |
+
"""A FIXED seeded random sample of ``n`` rows from ``pool`` (kept in original order).
|
| 366 |
+
|
| 367 |
+
The whole pool is returned when ``n <= 0`` or ``n >= len(pool)`` (asking for at least as many
|
| 368 |
+
as exist means "eval them all"). Same ``seed`` -> same subset on every pass, so the held-out
|
| 369 |
+
eval curve is comparable across optimizer steps rather than jumping around on a fresh sample.
|
| 370 |
+
"""
|
| 371 |
+
if n <= 0 or n >= len(pool):
|
| 372 |
+
return pool
|
| 373 |
+
idx = sorted(random.Random(seed).sample(range(len(pool)), n))
|
| 374 |
+
return [pool[i] for i in idx]
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def eval_config(
|
| 378 |
+
default_max_new: int, *, spec_every: int | None = None, spec_eval_examples: int | None = None
|
| 379 |
+
) -> dict:
|
| 380 |
+
"""Resolve the mid-run-eval knobs, both from the run's ``[train]`` TOML:
|
| 381 |
+
* CADENCE — ``eval_every_steps`` (``spec_every``); 0/unset disables.
|
| 382 |
+
* SAMPLE SIZE — ``eval_examples`` (``spec_eval_examples``): how many held-out rows each pass
|
| 383 |
+
scores. The eval takes a FIXED seeded random sample of this many rows instead of the whole
|
| 384 |
+
split, so a huge eval set can't dominate training and the curve stays comparable across
|
| 385 |
+
passes. None/0 -> the built-in default (``DEFAULT_EVAL_NUM``).
|
| 386 |
+
|
| 387 |
+
Everything else comes from the ENVIRONMENT: the eval queries are the env's held-out
|
| 388 |
+
``eval_dataset``, the grading is its rubric (reward + eval-metric metrics), the completion
|
| 389 |
+
budget equals the run's normal ``max_tokens`` (``default_max_new``), and the pass threshold
|
| 390 |
+
is the env's own.
|
| 391 |
+
"""
|
| 392 |
+
every = max(0, int(spec_every)) if spec_every is not None else 0
|
| 393 |
+
spec_num = spec_eval_examples if (spec_eval_examples and spec_eval_examples > 0) else None
|
| 394 |
+
num_examples = spec_num if spec_num is not None else DEFAULT_EVAL_NUM
|
| 395 |
+
return {
|
| 396 |
+
"every_steps": every,
|
| 397 |
+
"num_examples": max(1, num_examples), # the held-out random-sample size (>=1)
|
| 398 |
+
"max_new_tokens": max(1, int(default_max_new)), # = the run's normal completion budget
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def build_hf_greedy_generate(
|
| 403 |
+
model, tok, *, stop: list[str] | None
|
| 404 |
+
) -> Callable[[list[int], int], tuple[list[int], list[float], str]]:
|
| 405 |
+
"""A greedy (deterministic) generate over the TRAINER'S model via ``transformers.generate``,
|
| 406 |
+
returning ``(token_ids, logprobs, text)`` like the multi-turn rollout's generate.
|
| 407 |
+
|
| 408 |
+
Uses the model directly (NOT the colocate vLLM engine, whose out-of-band use from a callback
|
| 409 |
+
hangs GRPO). Runs in eval + ``no_grad`` and restores train mode; ``use_cache=True`` is forced
|
| 410 |
+
so generation works even when training has it off under gradient checkpointing (no backward
|
| 411 |
+
happens here, so checkpointing is irrelevant). One prompt at a time keeps the KV footprint to
|
| 412 |
+
a single sequence; an OOM raises (caught upstream -> ``eval_skipped``), never hangs.
|
| 413 |
+
|
| 414 |
+
Stop sequences are honored via ``stop_strings`` so generation actually STOPS at the stop
|
| 415 |
+
(rather than post-hoc truncating the text only) — this keeps the returned ``token_ids`` and
|
| 416 |
+
``text`` in lockstep (``text == decode(token_ids)``), which the multi-turn ``rollout_one``
|
| 417 |
+
prefix invariant requires; truncating text alone would desync them."""
|
| 418 |
+
import torch
|
| 419 |
+
|
| 420 |
+
pad_id = tok.pad_token_id if tok.pad_token_id is not None else tok.eos_token_id
|
| 421 |
+
stop_kwargs = {"stop_strings": list(stop), "tokenizer": tok} if stop else {}
|
| 422 |
+
|
| 423 |
+
def generate(prefix_ids: list[int], max_tokens: int):
|
| 424 |
+
input_ids = torch.tensor([list(prefix_ids)], dtype=torch.long, device=model.device)
|
| 425 |
+
was_training = model.training
|
| 426 |
+
try:
|
| 427 |
+
model.eval()
|
| 428 |
+
with torch.no_grad():
|
| 429 |
+
out = model.generate(
|
| 430 |
+
input_ids,
|
| 431 |
+
attention_mask=torch.ones_like(input_ids),
|
| 432 |
+
max_new_tokens=max(1, int(max_tokens)),
|
| 433 |
+
do_sample=False, # greedy / deterministic eval
|
| 434 |
+
use_cache=True,
|
| 435 |
+
pad_token_id=pad_id,
|
| 436 |
+
**stop_kwargs,
|
| 437 |
+
)
|
| 438 |
+
finally:
|
| 439 |
+
if was_training:
|
| 440 |
+
model.train()
|
| 441 |
+
# text == decode(new_ids): never post-hoc truncate one without the other (see docstring).
|
| 442 |
+
new_ids = [int(t) for t in out[0][input_ids.shape[1] :].tolist()]
|
| 443 |
+
text = tok.decode(new_ids, skip_special_tokens=True)
|
| 444 |
+
return new_ids, [0.0] * len(new_ids), text
|
| 445 |
+
|
| 446 |
+
return generate
|
code/flash/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/flash/engine/recipe.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frozen, shared Flash 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 |
+
from dataclasses import dataclass, field
|
| 11 |
+
|
| 12 |
+
# ----------------------------------------------------------------------------
|
| 13 |
+
# Model identity
|
| 14 |
+
# ----------------------------------------------------------------------------
|
| 15 |
+
# Recipe fallback base model. The worker resolves JOB_SPEC.model (carried by the full
|
| 16 |
+
# JobSpec) first and only falls back to RECIPE.hf_model_id; this literal is the
|
| 17 |
+
# last-resort default when the spec carries no model.
|
| 18 |
+
# Keep it in sync with catalog.DEFAULT_MODEL (a proven dense text-only instruction model
|
| 19 |
+
# that loads on the current worker stack: transformers 5.x / TRL 1.x / vLLM 0.19.x; the
|
| 20 |
+
# natively-multimodal Qwen3.5/3.6 checkpoints are also catalog'd, trained/served text-only).
|
| 21 |
+
HF_MODEL_ID = "Qwen/Qwen3.5-4B" # catalog DEFAULT_MODEL
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# ----------------------------------------------------------------------------
|
| 25 |
+
# LoRA (rank is the main user-controllable knob)
|
| 26 |
+
# ----------------------------------------------------------------------------
|
| 27 |
+
@dataclass(frozen=True)
|
| 28 |
+
class LoRAConfig:
|
| 29 |
+
rank: int = 32
|
| 30 |
+
alpha: int = 64
|
| 31 |
+
dropout: float = 0.0
|
| 32 |
+
# The worker adapts all linear projections ("all-linear" — see engine.worker);
|
| 33 |
+
# `rank`/`alpha` are the main user-controllable knobs here.
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# ----------------------------------------------------------------------------
|
| 37 |
+
# SFT (Phase 1)
|
| 38 |
+
# ----------------------------------------------------------------------------
|
| 39 |
+
@dataclass(frozen=True)
|
| 40 |
+
class SFTConfig:
|
| 41 |
+
max_seq_len: int = 1024
|
| 42 |
+
# Thinking-mode sequence cap: <think> traces in targets need headroom. A deliberate
|
| 43 |
+
# consumer-GPU compromise (SFT cost/VRAM scales with sequence length).
|
| 44 |
+
max_seq_len_thinking: int = 2048
|
| 45 |
+
learning_rate: float = 1e-4
|
| 46 |
+
warmup_frac: float = 0.03
|
| 47 |
+
# Effective batch = per_device_batch * grad_accum (Arm A) / batch of datums (Arm B)
|
| 48 |
+
effective_batch: int = 32
|
| 49 |
+
num_epochs: int = 2
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# ----------------------------------------------------------------------------
|
| 53 |
+
# RL / GRPO (Phase 2)
|
| 54 |
+
# ----------------------------------------------------------------------------
|
| 55 |
+
@dataclass(frozen=True)
|
| 56 |
+
class RLConfig:
|
| 57 |
+
learning_rate: float = 1e-5
|
| 58 |
+
# Default engine prompt budget. 512 was too small for real envs with non-trivial system
|
| 59 |
+
# prompts (e.g. a schema/instructions block + the user query), which made every prompt
|
| 60 |
+
# overflow before training started. 2048 fits typical instruction prompts; the run's
|
| 61 |
+
# [train].max_length sets the engine length explicitly when it needs more/less.
|
| 62 |
+
max_prompt_len: int = 2048
|
| 63 |
+
max_completion_len: int = 320
|
| 64 |
+
# Thinking-mode completion budget: <think> blocks consume most of it (phase 0
|
| 65 |
+
# showed 320 is hopeless — every completion hit the cap). 1536 is a consumer-GPU
|
| 66 |
+
# compromise (KV cache + rollout cost scale linearly with completion length, ~5x
|
| 67 |
+
# tokens/step vs non-thinking); the run's [train].max_tokens overrides it explicitly.
|
| 68 |
+
max_completion_len_thinking: int = 1536
|
| 69 |
+
prompts_per_step: int = 64
|
| 70 |
+
group_size: int = 8 # G completions per prompt
|
| 71 |
+
num_steps: int = 150 # overridable per-run via the TOML `train.steps`
|
| 72 |
+
sampling_temperature: float = 1.0 # on-policy sampling for rollouts
|
| 73 |
+
sampling_top_p: float = 1.0
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@dataclass(frozen=True)
|
| 77 |
+
class Recipe:
|
| 78 |
+
"""The complete shared recipe."""
|
| 79 |
+
|
| 80 |
+
hf_model_id: str = HF_MODEL_ID
|
| 81 |
+
lora: LoRAConfig = field(default_factory=LoRAConfig)
|
| 82 |
+
sft: SFTConfig = field(default_factory=SFTConfig)
|
| 83 |
+
rl: RLConfig = field(default_factory=RLConfig)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
RECIPE = Recipe()
|
code/flash/engine/vram.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 flash.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 |
+
# SFT activations peak on the worker's PER-DEVICE micro-batch, not [train].batch_size
|
| 45 |
+
# (which is the global/effective batch realized via gradient accumulation). The worker
|
| 46 |
+
# caps the micro-batch at 4: per_device = min(batch_size, 4). Mirror that here so an
|
| 47 |
+
# unset/long-context SFT run (batch defaults low) still reserves the micro-batch activation
|
| 48 |
+
# peak, and a large effective batch isn't mis-counted as resident VRAM (it's grad-accum,
|
| 49 |
+
# not in-flight activations).
|
| 50 |
+
_SFT_PER_DEVICE_BS_DEFAULT = 4
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _sft_per_device_bs() -> int:
|
| 54 |
+
"""The worker's per-device SFT micro-batch — the activation-peak driver to size against.
|
| 55 |
+
|
| 56 |
+
SFT micro-batch is a MANAGED default: the control plane no longer forwards
|
| 57 |
+
``SFT_PER_DEVICE_BS`` to the worker (build_worker_env dropped the tuning allowlist), and the
|
| 58 |
+
worker's own process env never carries it, so the worker always runs the fixed default. The
|
| 59 |
+
allocator must size against that SAME fixed value — reading the control-plane process env here
|
| 60 |
+
would size a card for a micro-batch the worker never uses, under-routing an
|
| 61 |
+
``SFT_PER_DEVICE_BS=1`` operator env to a too-small GPU that then OOMs at the default
|
| 62 |
+
micro-batch 4 (the asymmetry the env-knobs cleanup removed everywhere else)."""
|
| 63 |
+
return _SFT_PER_DEVICE_BS_DEFAULT
|
| 64 |
+
# Colocated-GRPO vLLM KV pool: grows with the engine's max context (seq) and model
|
| 65 |
+
# width, but vLLM bounds the pool to a fraction of the card and PAGES rather than OOMs,
|
| 66 |
+
# so it's capped (_KV_CAP) instead of growing without bound at long context.
|
| 67 |
+
_KV_COEF = 2.0
|
| 68 |
+
_KV_CAP = 8.0
|
| 69 |
+
# GRPO backward (activations + fp32 logits over the completion micro-batch) per unit
|
| 70 |
+
# context x model width. Grad checkpointing makes this MILD in seq -- calibrated to
|
| 71 |
+
# measured boundaries: 0.8B GRPO fits 24 GB up to seq 32k (seq ~free), while 4.7B GRPO
|
| 72 |
+
# steps off a 32 GB card between seq 16k and 32k. group size scales it sublinearly.
|
| 73 |
+
_TRAIN_COEF = 0.27
|
| 74 |
+
# Fixed floor for colocated-vLLM GRPO: the vLLM engine's CUDA context + KV pool (sized to the
|
| 75 |
+
# CARD's VRAM via gpu_util, not the model) + the 2nd resident weight copy is ~model-independent
|
| 76 |
+
# for small models and dominates their param estimate, so tiny/mid models all need the 32 GB tier.
|
| 77 |
+
# MEASURED at the default group_size=8: 0.8B GRPO OOMs a 20 GB card; 2B GRPO OOMs a 24 GB card
|
| 78 |
+
# (-> both need 32); 4B GRPO fits 32 (param est ~31 already clears this floor, so it's untouched).
|
| 79 |
+
_VLLM_COLOCATE_FLOOR_GB = 28.0
|
| 80 |
+
_VOCAB_DEFAULT = 152_000 # Qwen3.x tokenizer vocab (drives the fp32-logits GRPO term)
|
| 81 |
+
# Matches the worker's logits budget (6 GB): the per-device fp32 logits are capped to this
|
| 82 |
+
# (rl_per_device_comps spills the rest into grad-accum), so the estimator never reserves above it.
|
| 83 |
+
_LOGITS_BUDGET_GB = 6.0
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def grpo_seq_escalation_gb(params_b: float | None, seq_len: int) -> int:
|
| 87 |
+
"""Extra GB a long-context GRPO run needs beyond its base footprint.
|
| 88 |
+
|
| 89 |
+
Big-model GRPO is tight: colocate holds 2 weight copies + a KV pool, so headroom shrinks
|
| 90 |
+
with model size and long context overflows it. Calibrated on a bf16 9.7B GRPO run (RunPod):
|
| 91 |
+
fits 80 GB to seq 4096 but OOMs at 8192. Safe headroom ~ 48500/params_b tokens; past that
|
| 92 |
+
escalate, STEEPER for bigger models. Applies to both catalog and open-model GRPO so neither
|
| 93 |
+
under-provisions.
|
| 94 |
+
"""
|
| 95 |
+
coef = 0.9
|
| 96 |
+
if not params_b:
|
| 97 |
+
return 0
|
| 98 |
+
seq_thresh = 48_500.0 / params_b
|
| 99 |
+
if seq_len <= seq_thresh:
|
| 100 |
+
return 0
|
| 101 |
+
return math.ceil(coef * params_b * (seq_len / seq_thresh - 1))
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def params_b_from_str(s: str | None) -> float | None:
|
| 105 |
+
"""Leading param count (billions) from a catalog ``params`` string, e.g.
|
| 106 |
+
"4.7B (text-only fine-tune)" -> 4.7, "9.7B (text-only fine-tune)" -> 9.7."""
|
| 107 |
+
if not s:
|
| 108 |
+
return None
|
| 109 |
+
m = re.search(r"([0-9]+(?:\.[0-9]+)?)\s*B", s)
|
| 110 |
+
return float(m.group(1)) if m else None
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@dataclass(frozen=True)
|
| 114 |
+
class VramEstimate:
|
| 115 |
+
params_b: float | None
|
| 116 |
+
algorithm: str
|
| 117 |
+
quant: str
|
| 118 |
+
est_gb: float | None
|
| 119 |
+
gpu: str
|
| 120 |
+
gpu_gb: int
|
| 121 |
+
verdict: str # "fits" | "tight" | "too_big" | "unknown"
|
| 122 |
+
|
| 123 |
+
def describe(self) -> str:
|
| 124 |
+
if self.est_gb is None:
|
| 125 |
+
return f"{self.gpu}: VRAM need unknown (could not read model size)"
|
| 126 |
+
return (
|
| 127 |
+
f"{self.gpu} ({self.gpu_gb} GB): estimated ~{self.est_gb:.0f} GB needed "
|
| 128 |
+
f"({self.params_b:.1f}B params, {self.quant}, {self.algorithm}) -> {self.verdict}"
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def estimate_vram_gb(
|
| 133 |
+
params_b: float,
|
| 134 |
+
algorithm: str,
|
| 135 |
+
quant: str = "bf16",
|
| 136 |
+
*,
|
| 137 |
+
seq_len: int = 1024,
|
| 138 |
+
max_tokens: int | None = None,
|
| 139 |
+
lora_rank: int = 32,
|
| 140 |
+
batch_size: int = 1,
|
| 141 |
+
group_size: int = 8,
|
| 142 |
+
thinking: bool = False,
|
| 143 |
+
use_vllm: bool = True,
|
| 144 |
+
) -> float:
|
| 145 |
+
"""Estimated peak VRAM (GB) for a LoRA job on one GPU, over the full knob matrix.
|
| 146 |
+
|
| 147 |
+
Terms (all in GB):
|
| 148 |
+
weights params x bytes/param (bf16=2, 4bit-qlora=0.55)
|
| 149 |
+
base CUDA context + framework + fragmentation headroom
|
| 150 |
+
lora_opt LoRA adapter + grads + Adam states (rank-linear, model-scaled)
|
| 151 |
+
activations grad-checkpointed activations ~ batch x seq x sqrt(params)
|
| 152 |
+
grpo only:
|
| 153 |
+
+weights colocated vLLM holds a 2nd resident weight copy at the rollout peak
|
| 154 |
+
(sleep mode offloads it BETWEEN steps, not during) -- skipped when
|
| 155 |
+
use_vllm is False (transformers generation, single copy)
|
| 156 |
+
kv vLLM KV pool ~ seq x sqrt(params)
|
| 157 |
+
logits fp32 logits [per_device_comps, completion, vocab]
|
| 158 |
+
"""
|
| 159 |
+
bpp = _BYTES_PER_PARAM.get(quant, 2.0)
|
| 160 |
+
weights = params_b * bpp
|
| 161 |
+
algo = "grpo" if (algorithm or "").lower() in ("grpo", "rl") else "sft"
|
| 162 |
+
width = math.sqrt(max(params_b, 0.1))
|
| 163 |
+
lora_opt = (lora_rank / 16.0) * (0.3 + 0.04 * params_b)
|
| 164 |
+
base = weights + _BASE_OVERHEAD_GB + lora_opt
|
| 165 |
+
if algo == "grpo":
|
| 166 |
+
# GRPO alternates two phases that DON'T peak together (sleep mode offloads the
|
| 167 |
+
# vLLM engine during the backward), so peak = max(rollout, train), not the sum:
|
| 168 |
+
# rollout: colocated vLLM 2nd weight copy + KV pool (skipped if use_vllm=False)
|
| 169 |
+
# train: backward activations + fp32 logits -- MILD in seq (grad ckpt)
|
| 170 |
+
rollout = 0.0
|
| 171 |
+
if use_vllm:
|
| 172 |
+
rollout = weights + min(_KV_COEF * (seq_len / 1024.0) * width, _KV_CAP)
|
| 173 |
+
group_factor = max(1.0, (max(1, group_size) / 4.0) ** 0.5)
|
| 174 |
+
think_factor = 1.3 if thinking else 1.0
|
| 175 |
+
activations = _TRAIN_COEF * (seq_len / 1024.0) * width * group_factor * think_factor
|
| 176 |
+
# fp32 logits [per_device, completion, vocab] are the documented GRPO OOM driver. The
|
| 177 |
+
# worker MEMORY-CAPS per_device (rl_per_device_comps) so the live logits never exceed the
|
| 178 |
+
# logits budget (6 GB) and the rest spills into grad-accum -- so the IRREDUCIBLE floor the
|
| 179 |
+
# card must hold is the per_device=1 logits for the completion length: it scales with
|
| 180 |
+
# max_tokens (NOT seq_len) and is capped at the budget. completion defaults to the recipe
|
| 181 |
+
# budget (~min(seq_len, 1024)) when max_tokens is unset.
|
| 182 |
+
completion = max_tokens if max_tokens else min(seq_len, 1024)
|
| 183 |
+
logits = min(completion * _VOCAB_DEFAULT * 4 / 1e9, _LOGITS_BUDGET_GB)
|
| 184 |
+
train = activations + logits
|
| 185 |
+
return base + max(rollout, train)
|
| 186 |
+
# SFT: the activation peak is the worker's per-device micro-batch (capped at 4),
|
| 187 |
+
# NOT the global/effective batch_size (gradient accumulation realizes
|
| 188 |
+
# that). Size to the micro-batch the worker actually runs: a default/long-context run reserves
|
| 189 |
+
# for the per-device cap (no under-routing to a too-small card), while a large effective
|
| 190 |
+
# batch_size is capped at it (no over-routing, since accum isn't resident VRAM).
|
| 191 |
+
sft_per_device = min(max(1, batch_size), _sft_per_device_bs())
|
| 192 |
+
return base + _ACT_COEF * sft_per_device * (seq_len / 1024.0) * width
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def model_required_vram_gb(
|
| 196 |
+
model_id: str,
|
| 197 |
+
algorithm: str,
|
| 198 |
+
*,
|
| 199 |
+
train=None,
|
| 200 |
+
thinking: bool = False,
|
| 201 |
+
headroom: float = 1.1,
|
| 202 |
+
) -> int:
|
| 203 |
+
"""Cheapest-sufficient VRAM (GB) for a specific run -- the matrix the allocator and
|
| 204 |
+
``resolve_gpu_policy`` both size against.
|
| 205 |
+
|
| 206 |
+
Catalog models size from their known param count + the run's actual knobs (``train``
|
| 207 |
+
may be a TrainSpec, a dict, or None for recipe defaults). Curated GRPO floors
|
| 208 |
+
(``grpo_min_vram_gb``) stay as HARD floors so we never under-provision a validated
|
| 209 |
+
model; the matrix only ever sizes UP from there. Unlisted open models size from HF
|
| 210 |
+
metadata, falling back to the 24 GB tier when the size can't be read.
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
# Best-effort knob extraction: this provisional sizing runs at parse time BEFORE the
|
| 214 |
+
# dedicated train validators, so malformed knobs (nan/inf/strings/<=0) must fall back
|
| 215 |
+
# to a default here, never crash -- config_schema raises the proper ConfigError next.
|
| 216 |
+
def _g(obj, key):
|
| 217 |
+
if obj is None:
|
| 218 |
+
return None
|
| 219 |
+
return obj.get(key) if isinstance(obj, dict) else getattr(obj, key, None)
|
| 220 |
+
|
| 221 |
+
def _pos_int(v, default):
|
| 222 |
+
try:
|
| 223 |
+
if isinstance(v, bool):
|
| 224 |
+
return default
|
| 225 |
+
f = float(v)
|
| 226 |
+
return int(f) if math.isfinite(f) and f >= 1 else default
|
| 227 |
+
except (TypeError, ValueError):
|
| 228 |
+
return default
|
| 229 |
+
|
| 230 |
+
max_tokens = _pos_int(_g(train, "max_tokens"), None)
|
| 231 |
+
# Default sequence length when [train].max_length is unset. For GRPO this must MIRROR what
|
| 232 |
+
# run_rl() actually starts vLLM at — max(1024, RLConfig.max_prompt_len + completion) — not a
|
| 233 |
+
# flat 1024, or the allocator can pick a GPU sized for 1024 tokens while the worker launches a
|
| 234 |
+
# ~2368-token (3584 with thinking) engine and OOMs after provisioning. Completion = the run's
|
| 235 |
+
# [train].max_tokens override, else the recipe's thinking/non-thinking completion default.
|
| 236 |
+
if (algorithm or "").lower() in ("grpo", "rl"):
|
| 237 |
+
from flash.engine.recipe import RECIPE
|
| 238 |
+
|
| 239 |
+
_rl = RECIPE.rl
|
| 240 |
+
_completion = max_tokens or (
|
| 241 |
+
_rl.max_completion_len_thinking if thinking else _rl.max_completion_len
|
| 242 |
+
)
|
| 243 |
+
_grpo_default_len = max(1024, _rl.max_prompt_len + int(_completion))
|
| 244 |
+
else:
|
| 245 |
+
_grpo_default_len = 1024
|
| 246 |
+
seq_len = _pos_int(_g(train, "max_length"), _grpo_default_len)
|
| 247 |
+
lora_rank = _pos_int(_g(train, "lora_rank"), 32)
|
| 248 |
+
group_size = _pos_int(_g(train, "group_size"), 8)
|
| 249 |
+
# Default to the worker's per-device SFT micro-batch (4): an unset
|
| 250 |
+
# [train].batch_size still realizes that micro-batch on the worker, so size for it
|
| 251 |
+
# rather than 1 (which would under-route a long-context SFT run to a too-small card).
|
| 252 |
+
batch_size = _pos_int(_g(train, "batch_size"), _sft_per_device_bs())
|
| 253 |
+
|
| 254 |
+
def _need(
|
| 255 |
+
params_b: float, algorithm: str, *, quant: str = "bf16", use_vllm: bool = True
|
| 256 |
+
) -> int:
|
| 257 |
+
# estimate over the run's full knob matrix, then apply the safety headroom. Both the
|
| 258 |
+
# catalog and open-model paths size through here so they stay in sync on the knob set.
|
| 259 |
+
est = estimate_vram_gb(
|
| 260 |
+
params_b,
|
| 261 |
+
algorithm,
|
| 262 |
+
quant,
|
| 263 |
+
seq_len=seq_len,
|
| 264 |
+
max_tokens=max_tokens,
|
| 265 |
+
lora_rank=lora_rank,
|
| 266 |
+
batch_size=batch_size,
|
| 267 |
+
group_size=group_size,
|
| 268 |
+
thinking=thinking,
|
| 269 |
+
use_vllm=use_vllm,
|
| 270 |
+
)
|
| 271 |
+
return math.ceil(est * headroom)
|
| 272 |
+
|
| 273 |
+
from flash.catalog import MODELS
|
| 274 |
+
|
| 275 |
+
info = MODELS.get(model_id)
|
| 276 |
+
is_grpo = (algorithm or "").lower() in ("grpo", "rl")
|
| 277 |
+
if info is not None:
|
| 278 |
+
params_b = params_b_from_str(info.params)
|
| 279 |
+
quant = getattr(info, "quant", "bf16") or "bf16"
|
| 280 |
+
# GRPO always runs the rollout on a colocated vLLM engine, so sizing must reserve room for
|
| 281 |
+
# the 2nd (rollout) weight copy on the same card.
|
| 282 |
+
use_vllm = True
|
| 283 |
+
need = _need(params_b or 4.0, algorithm, quant=quant, use_vllm=use_vllm)
|
| 284 |
+
# Hard floor the param-based matrix can't see: a curated GRPO floor.
|
| 285 |
+
floor = 0
|
| 286 |
+
if is_grpo and getattr(info, "grpo_min_vram_gb", 0):
|
| 287 |
+
floor = int(info.grpo_min_vram_gb)
|
| 288 |
+
if quant == "4bit-qlora":
|
| 289 |
+
# GRPO needs the curated grpo_min_vram_gb (2 weight copies + KV); SFT is single-copy and
|
| 290 |
+
# fits the smaller min_vram_gb. Don't leak the GRPO floor into SFT allocations or SFT
|
| 291 |
+
# over-provisions.
|
| 292 |
+
_q_floor = (
|
| 293 |
+
int(getattr(info, "grpo_min_vram_gb", 0) or info.min_vram_gb)
|
| 294 |
+
if is_grpo
|
| 295 |
+
else int(info.min_vram_gb)
|
| 296 |
+
)
|
| 297 |
+
floor = max(floor, _q_floor)
|
| 298 |
+
# Big-model GRPO is TIGHT at its floor (2 weight copies + KV pool), so long context
|
| 299 |
+
# overflows it -> escalate to a bigger tier. See grpo_seq_escalation_gb.
|
| 300 |
+
if is_grpo and floor:
|
| 301 |
+
floor += grpo_seq_escalation_gb(params_b, seq_len)
|
| 302 |
+
need = max(need, floor)
|
| 303 |
+
# vLLM-colocate floor: the engine (CUDA context + KV pool sized to the CARD's VRAM +
|
| 304 |
+
# framework) + the 2nd resident weight copy add a ~constant the param estimate misses,
|
| 305 |
+
# so small-model GRPO under-provisions. MEASURED at the default group_size=8: 0.8B GRPO
|
| 306 |
+
# fits a 24 GB card but OOMs 20 (est ~18, ~6 GB headroom on 24); 2B GRPO OOMs a 24 GB
|
| 307 |
+
# card (est ~20 but the colocate cost tips it past 24 -> needs the 32 tier). So sub-~1B
|
| 308 |
+
# models floor at 24, while larger small-models that the param estimate still under-shoots
|
| 309 |
+
# floor at the 32 tier. 4B+ already exceed this via their param estimate, so untouched.
|
| 310 |
+
if is_grpo and use_vllm:
|
| 311 |
+
floor_gb = 24 if (params_b or 0.0) <= 1.0 else int(_VLLM_COLOCATE_FLOOR_GB)
|
| 312 |
+
need = max(need, floor_gb)
|
| 313 |
+
return need
|
| 314 |
+
# Unlisted open model: size from HF metadata (GRPO is the heavier phase).
|
| 315 |
+
params_b = fetch_hf_params_b(model_id)
|
| 316 |
+
if params_b is None:
|
| 317 |
+
return 24
|
| 318 |
+
# Open models size against the heavier GRPO phase regardless of the requested algorithm.
|
| 319 |
+
need = _need(params_b, "grpo")
|
| 320 |
+
# Same long-context GRPO escalation as the catalog path so a big open model isn't
|
| 321 |
+
# under-provisioned at long context either.
|
| 322 |
+
if is_grpo:
|
| 323 |
+
need += grpo_seq_escalation_gb(params_b, seq_len)
|
| 324 |
+
return need
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def fetch_hf_params_b(model_id: str) -> float | None:
|
| 328 |
+
"""Total params (billions) from the HF API safetensors metadata (no download)."""
|
| 329 |
+
if os.environ.get("FLASH_SKIP_NET"):
|
| 330 |
+
return None
|
| 331 |
+
try:
|
| 332 |
+
from huggingface_hub import HfApi
|
| 333 |
+
|
| 334 |
+
info = HfApi(token=os.environ.get("HF_TOKEN")).model_info(
|
| 335 |
+
model_id, expand=["safetensors"]
|
| 336 |
+
)
|
| 337 |
+
total = getattr(getattr(info, "safetensors", None), "total", None)
|
| 338 |
+
if total:
|
| 339 |
+
return float(total) / 1e9
|
| 340 |
+
except Exception:
|
| 341 |
+
# Best-effort size probe (network/HF-metadata may be unavailable); fall through
|
| 342 |
+
# to None so callers report "size unknown" rather than failing.
|
| 343 |
+
pass
|
| 344 |
+
return None
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def check_fit(
|
| 348 |
+
model_id: str,
|
| 349 |
+
algorithm: str,
|
| 350 |
+
gpu: str,
|
| 351 |
+
quant: str = "bf16",
|
| 352 |
+
params_b: float | None = None,
|
| 353 |
+
) -> VramEstimate:
|
| 354 |
+
"""Estimate whether ``model_id`` plausibly trains on ``gpu``; never raises."""
|
| 355 |
+
gpu_gb = GPU_VRAM_GB.get(gpu, 32)
|
| 356 |
+
if params_b is None:
|
| 357 |
+
params_b = fetch_hf_params_b(model_id)
|
| 358 |
+
if params_b is None:
|
| 359 |
+
return VramEstimate(None, algorithm, quant, None, gpu, gpu_gb, "unknown")
|
| 360 |
+
est = estimate_vram_gb(params_b, algorithm, quant)
|
| 361 |
+
if est > gpu_gb * 1.15:
|
| 362 |
+
verdict = "too_big"
|
| 363 |
+
elif est > gpu_gb * 0.85:
|
| 364 |
+
verdict = "tight"
|
| 365 |
+
else:
|
| 366 |
+
verdict = "fits"
|
| 367 |
+
return VramEstimate(params_b, algorithm, quant, est, gpu, gpu_gb, verdict)
|
code/flash/engine/worker.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
code/flash/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/flash/envs/adapter.py
ADDED
|
@@ -0,0 +1,717 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Adapter that runs Prime Intellect ``verifiers`` / Environments Hub envs on Flash.
|
| 2 |
+
|
| 3 |
+
Wraps a ``verifiers`` ``Environment`` (``SingleTurnEnv``, ``MultiTurnEnv``, ``ToolEnv`` and
|
| 4 |
+
its subclasses) in Flash's small ``Environment`` protocol so Hub environments run unchanged
|
| 5 |
+
on Flash'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 — ``flash.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 |
+
eval-metric 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 |
+
# Flash-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 Flash-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 Flash-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, n: int = -1):
|
| 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`` (default -1 = all rows — the adapter does its
|
| 153 |
+
own fixed subset selection; callers pass a positive cap to avoid materializing a huge split)
|
| 154 |
+
and the seed when the signature declares them; a genuine failure propagates (fail loudly)
|
| 155 |
+
instead of silently emptying the split."""
|
| 156 |
+
fn = getattr(obj, method_name, None)
|
| 157 |
+
if not callable(fn):
|
| 158 |
+
return None
|
| 159 |
+
try:
|
| 160 |
+
param_names = set(inspect.signature(fn).parameters)
|
| 161 |
+
except (TypeError, ValueError):
|
| 162 |
+
param_names = set()
|
| 163 |
+
kwargs = {}
|
| 164 |
+
if "n" in param_names:
|
| 165 |
+
kwargs["n"] = n
|
| 166 |
+
if "seed" in param_names:
|
| 167 |
+
kwargs["seed"] = seed
|
| 168 |
+
return fn(**kwargs)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _rows_to_list(ds) -> list[dict]:
|
| 172 |
+
if ds is None:
|
| 173 |
+
return []
|
| 174 |
+
try:
|
| 175 |
+
return [dict(r) for r in ds]
|
| 176 |
+
except Exception:
|
| 177 |
+
return list(ds)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _flatten_rubric(rubric) -> list[tuple]:
|
| 181 |
+
"""Collect ``(func, weight)`` pairs from a rubric, recursing into ``RubricGroup``.
|
| 182 |
+
|
| 183 |
+
verifiers composes rubrics (e.g. a ``RubricGroup`` wrapping a ``MathRubric`` plus a
|
| 184 |
+
``MultiTurnMonitorRubric``); the real reward funcs live on the *nested* rubrics while the
|
| 185 |
+
group's own ``funcs`` is empty. Flattening finds them all.
|
| 186 |
+
"""
|
| 187 |
+
funcs = list(getattr(rubric, "funcs", None) or getattr(rubric, "reward_funcs", None) or [])
|
| 188 |
+
weights = list(
|
| 189 |
+
getattr(rubric, "weights", None) or getattr(rubric, "reward_weights", None) or []
|
| 190 |
+
)
|
| 191 |
+
if len(weights) < len(funcs):
|
| 192 |
+
weights += [1.0] * (len(funcs) - len(weights))
|
| 193 |
+
pairs = list(zip(funcs, weights, strict=False))
|
| 194 |
+
for sub in getattr(rubric, "rubrics", None) or []:
|
| 195 |
+
pairs.extend(_flatten_rubric(sub))
|
| 196 |
+
return pairs
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _find_judge_rubric(rubric):
|
| 200 |
+
"""Return the first ``JudgeRubric`` in a rubric tree (or None), for judge-arg injection."""
|
| 201 |
+
if rubric is None:
|
| 202 |
+
return None
|
| 203 |
+
try:
|
| 204 |
+
import verifiers as vf
|
| 205 |
+
|
| 206 |
+
judge_cls = getattr(vf, "JudgeRubric", None)
|
| 207 |
+
except ImportError:
|
| 208 |
+
judge_cls = None
|
| 209 |
+
if judge_cls is not None and isinstance(rubric, judge_cls):
|
| 210 |
+
return rubric
|
| 211 |
+
# Duck-type fallback: anything exposing a `judge` method + a judge_client attr.
|
| 212 |
+
if callable(getattr(rubric, "judge", None)) and hasattr(rubric, "judge_client"):
|
| 213 |
+
return rubric
|
| 214 |
+
for sub in getattr(rubric, "rubrics", None) or []:
|
| 215 |
+
found = _find_judge_rubric(sub)
|
| 216 |
+
if found is not None:
|
| 217 |
+
return found
|
| 218 |
+
return None
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _judge_kwargs(judge_rubric) -> dict:
|
| 222 |
+
"""The judge-related kwargs a reward func may declare, sourced from a JudgeRubric."""
|
| 223 |
+
if judge_rubric is None:
|
| 224 |
+
return {}
|
| 225 |
+
return {name: getattr(judge_rubric, name, None) for name in _JUDGE_KWARG_NAMES}
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def _invoke_reward(func, available: dict) -> float:
|
| 229 |
+
"""Call a verifiers reward func passing only the kwargs it declares; await if async.
|
| 230 |
+
|
| 231 |
+
Exceptions PROPAGATE. ``scores_breakdown`` invokes this for *weighted* reward funcs, so an
|
| 232 |
+
exception here is a real (weighted) reward func genuinely failing (e.g. a JudgeRubric judge
|
| 233 |
+
raising on an API/rate-limit error, or a parse error on row data). Swallowing it as 0.0
|
| 234 |
+
would silently train/score on an all-zero signal and waste a paid run, so we fail loudly
|
| 235 |
+
instead. Eval-metric (optional/monitor) funcs are run through ``_run_eval_metric``,
|
| 236 |
+
which swallows their exceptions — they contribute 0 either way and may exist only for their
|
| 237 |
+
side effects (mutating shared ``state`` / logging), so a thrown monitor must not fail a run.
|
| 238 |
+
"""
|
| 239 |
+
try:
|
| 240 |
+
params = inspect.signature(func).parameters
|
| 241 |
+
if any(p.kind == p.VAR_KEYWORD for p in params.values()):
|
| 242 |
+
kwargs = dict(available)
|
| 243 |
+
else:
|
| 244 |
+
kwargs = {k: v for k, v in available.items() if k in params}
|
| 245 |
+
except (TypeError, ValueError):
|
| 246 |
+
kwargs = dict(available)
|
| 247 |
+
result = func(**kwargs)
|
| 248 |
+
if inspect.isawaitable(result):
|
| 249 |
+
result = _run_async(result)
|
| 250 |
+
return float(result or 0.0)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def _run_eval_metric(func, available: dict) -> None:
|
| 254 |
+
"""Run a eval-metric monitor/diagnostic reward func, swallowing any exception.
|
| 255 |
+
|
| 256 |
+
Per verifiers semantics every reward func RUNS, even weight-0 ones: they may mutate the
|
| 257 |
+
shared ``state`` (so a later weighted func sees their work) or simply be logged. They never
|
| 258 |
+
contribute to the reward (weight is 0), so their result is discarded and a failure must NOT
|
| 259 |
+
fail the run — guard the exception. Weighted funcs go through ``_invoke_reward`` instead,
|
| 260 |
+
where exceptions propagate.
|
| 261 |
+
"""
|
| 262 |
+
with contextlib.suppress(Exception):
|
| 263 |
+
_invoke_reward(func, available)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def _is_multi_turn(vf_env) -> bool:
|
| 267 |
+
"""True for a tool/multi-turn verifiers env (NOT a plain SingleTurnEnv)."""
|
| 268 |
+
try:
|
| 269 |
+
import verifiers as vf
|
| 270 |
+
except ImportError:
|
| 271 |
+
return False
|
| 272 |
+
tool = getattr(vf, "ToolEnv", None)
|
| 273 |
+
multi = getattr(vf, "MultiTurnEnv", None)
|
| 274 |
+
single = getattr(vf, "SingleTurnEnv", None)
|
| 275 |
+
if tool is not None and isinstance(vf_env, tool):
|
| 276 |
+
return True
|
| 277 |
+
if multi is not None and isinstance(vf_env, multi):
|
| 278 |
+
# SingleTurnEnv subclasses MultiTurnEnv in verifiers; exempt it.
|
| 279 |
+
return not (single is not None and isinstance(vf_env, single))
|
| 280 |
+
return False
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def _is_tool_env(vf_env) -> bool:
|
| 284 |
+
"""True for a verifiers ``ToolEnv`` or any subclass (Stateful/Sandbox/Python).
|
| 285 |
+
|
| 286 |
+
Tool envs expose Python tool callables; the worker hands those to TRL's
|
| 287 |
+
``GRPOTrainer(tools=...)`` so TRL drives the tool-call loop natively (it owns generation,
|
| 288 |
+
tool execution, and assistant-only token masking). A *pure* ``MultiTurnEnv`` (env turns are
|
| 289 |
+
arbitrary content, e.g. a simulated user) is multi-turn but NOT a tool env, and takes the
|
| 290 |
+
``rollout_func`` path instead."""
|
| 291 |
+
try:
|
| 292 |
+
import verifiers as vf
|
| 293 |
+
except ImportError:
|
| 294 |
+
return False
|
| 295 |
+
tool = getattr(vf, "ToolEnv", None)
|
| 296 |
+
return tool is not None and isinstance(vf_env, tool)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class VerifiersEnvironment(BaseEnvironment):
|
| 300 |
+
"""Flash environment backed by a verifiers ``Environment`` instance.
|
| 301 |
+
|
| 302 |
+
GRPO training supports three env shapes (the worker routes on these flags):
|
| 303 |
+
* **single-turn** (``multi_turn`` False) — TRL's single-shot rollout (original path);
|
| 304 |
+
* **tool** (``is_tool_env`` True) — TRL drives the tool-call loop natively via
|
| 305 |
+
``GRPOTrainer(tools=...)`` (:meth:`tools`); the reward scores the full transcript
|
| 306 |
+
(:meth:`reward_from_messages`);
|
| 307 |
+
* **pure multi-turn** (``multi_turn`` True, ``is_tool_env`` False) — TRL's
|
| 308 |
+
``rollout_func`` drives this env's turn loop (:meth:`new_rollout_state` /
|
| 309 |
+
:meth:`record_model_turn` / :meth:`env_reply` / :meth:`rollout_done`).
|
| 310 |
+
"""
|
| 311 |
+
|
| 312 |
+
def __init__(
|
| 313 |
+
self,
|
| 314 |
+
vf_env,
|
| 315 |
+
env_id: str,
|
| 316 |
+
eval_vf_env=None,
|
| 317 |
+
eval_examples: int | None = None,
|
| 318 |
+
eval_seed: int = 12345,
|
| 319 |
+
):
|
| 320 |
+
super().__init__(id=env_id)
|
| 321 |
+
self._env = vf_env
|
| 322 |
+
self._eval_env = eval_vf_env # optional separate eval Hub env
|
| 323 |
+
self._eval_examples = int(eval_examples) if eval_examples else 0
|
| 324 |
+
self._eval_seed = int(eval_seed)
|
| 325 |
+
self.multi_turn = _is_multi_turn(vf_env)
|
| 326 |
+
self.is_tool_env = _is_tool_env(vf_env)
|
| 327 |
+
# Turn cap for the tool / multi-turn rollout loop (verifiers ToolEnv defaults to 10).
|
| 328 |
+
self.max_turns = int(getattr(vf_env, "max_turns", 10) or 10)
|
| 329 |
+
# The shared scorer is the TRAIN env's (flattened) rubric + parser, so the reward used
|
| 330 |
+
# for RL and the grader used at eval are byte-for-byte identical.
|
| 331 |
+
rubric = getattr(vf_env, "rubric", None)
|
| 332 |
+
self._reward_pairs = _flatten_rubric(rubric) if rubric is not None else []
|
| 333 |
+
self._judge_rubric = _find_judge_rubric(rubric)
|
| 334 |
+
# Fail fast on a group/batch reward func: the worker scores one completion at a time
|
| 335 |
+
# and cannot supply its plural batch args, so it would silently score 0.0 and train a
|
| 336 |
+
# paid run on an all-zero signal. Only weighted funcs matter (eval-metric ones skip).
|
| 337 |
+
for func, weight in self._reward_pairs:
|
| 338 |
+
if not weight:
|
| 339 |
+
continue
|
| 340 |
+
missing = _reward_requires_unavailable_args(func)
|
| 341 |
+
if missing:
|
| 342 |
+
raise ValueError(
|
| 343 |
+
f"verifiers reward function {getattr(func, '__name__', func)!r} requires "
|
| 344 |
+
f"argument {missing!r}, which the Flash adapter cannot supply (it scores "
|
| 345 |
+
"one completion at a time, with no group/batch context such as "
|
| 346 |
+
"completions/prompts/answers). This environment uses a group-based reward "
|
| 347 |
+
"not supported on Flash; use a per-completion reward."
|
| 348 |
+
)
|
| 349 |
+
self._parser = getattr(vf_env, "parser", None)
|
| 350 |
+
|
| 351 |
+
# -- data -------------------------------------------------------------
|
| 352 |
+
def dataset(self, split: str, limit: int | None = None) -> list[dict]:
|
| 353 |
+
is_eval = split in {"eval", "validation", "test"}
|
| 354 |
+
if is_eval:
|
| 355 |
+
src = self._eval_env or self._env
|
| 356 |
+
# ``limit`` caps materialization at the source (mid-run eval only needs a small slice);
|
| 357 |
+
# a getter that ignores ``n`` still returns everything, so _fixed_subset / the caller's
|
| 358 |
+
# slice remain the backstop. -1 = all rows (the no-cap default).
|
| 359 |
+
n = limit if (limit is not None and limit > 0) else -1
|
| 360 |
+
# Resolve the eval source with explicit ``is None`` checks (NOT ``or``): an
|
| 361 |
+
# empty-but-configured eval split (``[]``) is falsy, so ``or`` would wrongly
|
| 362 |
+
# fall through to the next source and ultimately to the TRAIN split — evaluating
|
| 363 |
+
# on training data. Only fall back when the eval source is genuinely *absent*
|
| 364 |
+
# (None), not merely empty. ``get_eval_dataset``/``eval_dataset`` returning [] is
|
| 365 |
+
# a deliberate empty eval set and must be honored as such.
|
| 366 |
+
eval_ds = _call_dataset_getter(src, "get_eval_dataset", seed=self._eval_seed, n=n)
|
| 367 |
+
if eval_ds is None:
|
| 368 |
+
eval_ds = getattr(src, "eval_dataset", None)
|
| 369 |
+
if eval_ds is None: # no eval split configured at all: use the env's train split
|
| 370 |
+
eval_ds = _call_dataset_getter(src, "get_dataset", seed=self._eval_seed, n=n)
|
| 371 |
+
if eval_ds is None:
|
| 372 |
+
eval_ds = getattr(src, "dataset", None)
|
| 373 |
+
rows = _rows_to_list(eval_ds)
|
| 374 |
+
# An explicit positive ``limit`` means the caller (mid-run eval) wants a RAW pool of up
|
| 375 |
+
# to ``limit`` rows and does its OWN seeded sampling on top — so don't also apply the
|
| 376 |
+
# ``[environment.params] eval_examples`` subset here, which would silently shrink the
|
| 377 |
+
# pool below ``limit`` and starve the caller's sample (it already capped the pool size
|
| 378 |
+
# via ``limit``). ``_fixed_subset`` still governs the plain ``dataset("eval")`` path
|
| 379 |
+
# (the "eval on a different env" feature, where the param IS the intended sample size).
|
| 380 |
+
if limit is not None and limit > 0:
|
| 381 |
+
return rows
|
| 382 |
+
return self._fixed_subset(rows)
|
| 383 |
+
ds = _call_dataset_getter(self._env, "get_dataset", seed=0)
|
| 384 |
+
if ds is None:
|
| 385 |
+
ds = getattr(self._env, "dataset", None)
|
| 386 |
+
return _rows_to_list(ds)
|
| 387 |
+
|
| 388 |
+
def has_eval_split(self) -> bool:
|
| 389 |
+
"""True when a DISTINCT held-out eval split exists (a separate eval env, or the env's
|
| 390 |
+
``get_eval_dataset``/``eval_dataset``). False means :meth:`dataset` would fall back to
|
| 391 |
+
train rows — so a caller (mid-run eval) can warn instead of reporting train data as
|
| 392 |
+
held-out. Best-effort: a getter that raises is treated as no eval split."""
|
| 393 |
+
if self._eval_env is not None:
|
| 394 |
+
return True
|
| 395 |
+
try:
|
| 396 |
+
if (
|
| 397 |
+
_call_dataset_getter(self._env, "get_eval_dataset", seed=self._eval_seed)
|
| 398 |
+
is not None
|
| 399 |
+
):
|
| 400 |
+
return True
|
| 401 |
+
except Exception:
|
| 402 |
+
return False
|
| 403 |
+
return getattr(self._env, "eval_dataset", None) is not None
|
| 404 |
+
|
| 405 |
+
def _fixed_subset(self, rows: list[dict]) -> list[dict]:
|
| 406 |
+
n = self._eval_examples
|
| 407 |
+
if n <= 0 or n >= len(rows):
|
| 408 |
+
return rows
|
| 409 |
+
idx = sorted(random.Random(self._eval_seed).sample(range(len(rows)), n))
|
| 410 |
+
return [rows[i] for i in idx]
|
| 411 |
+
|
| 412 |
+
# -- task interface ---------------------------------------------------
|
| 413 |
+
def prompt_messages(self, example: dict) -> list[dict]:
|
| 414 |
+
prompt = example.get("prompt")
|
| 415 |
+
if isinstance(prompt, list) and prompt:
|
| 416 |
+
msgs = [dict(m) for m in prompt]
|
| 417 |
+
else:
|
| 418 |
+
question = example.get("question") or example.get("prompt") or ""
|
| 419 |
+
msgs = [{"role": "user", "content": str(question)}]
|
| 420 |
+
system_prompt = getattr(self._env, "system_prompt", None)
|
| 421 |
+
if system_prompt and not any(m.get("role") == "system" for m in msgs):
|
| 422 |
+
msgs = [{"role": "system", "content": system_prompt}, *msgs]
|
| 423 |
+
return msgs
|
| 424 |
+
|
| 425 |
+
def sft_target(self, example: dict) -> str:
|
| 426 |
+
for key in ("answer", "completion", "target", "response"):
|
| 427 |
+
value = example.get(key)
|
| 428 |
+
if value:
|
| 429 |
+
if isinstance(value, list): # chat messages
|
| 430 |
+
return str(value[-1].get("content", ""))
|
| 431 |
+
return str(value)
|
| 432 |
+
return ""
|
| 433 |
+
|
| 434 |
+
# -- reward / scoring -------------------------------------------------
|
| 435 |
+
def _normalize_info(self, example: dict) -> dict:
|
| 436 |
+
# Hub rows may store `info` as a JSON string (a supported Verifiers row shape);
|
| 437 |
+
# parse it so reward funcs that do `info[...]` get a dict, not a str (which would
|
| 438 |
+
# raise TypeError, be swallowed as 0.0, and poison the signal).
|
| 439 |
+
info = example.get("info") or {}
|
| 440 |
+
if isinstance(info, str):
|
| 441 |
+
try:
|
| 442 |
+
info = json.loads(info)
|
| 443 |
+
except (ValueError, TypeError):
|
| 444 |
+
info = {}
|
| 445 |
+
return info
|
| 446 |
+
|
| 447 |
+
def _reward_available(self, completion: str, example: dict, state: dict | None) -> dict:
|
| 448 |
+
# In multi-turn/tool mode the accumulated transcript lives on ``state`` (built by the
|
| 449 |
+
# rollout helpers): ``state["completion"]`` is the full assistant + tool/env message
|
| 450 |
+
# list and ``state["prompt"]`` is the initial prompt. Reward/tool funcs that inspect the
|
| 451 |
+
# whole message list need that transcript, not the scalar ``completion`` string wrapped
|
| 452 |
+
# as a lone synthesized assistant message. Single-turn falls back to wrapping the scalar.
|
| 453 |
+
completion_msgs: list[dict] | None = None
|
| 454 |
+
prompt_msgs = None
|
| 455 |
+
if self.multi_turn and state:
|
| 456 |
+
transcript = state.get("completion")
|
| 457 |
+
if isinstance(transcript, list) and transcript:
|
| 458 |
+
completion_msgs = [dict(m) for m in transcript]
|
| 459 |
+
state_prompt = state.get("prompt")
|
| 460 |
+
if isinstance(state_prompt, list) and state_prompt:
|
| 461 |
+
prompt_msgs = [dict(m) for m in state_prompt]
|
| 462 |
+
if completion_msgs is None:
|
| 463 |
+
completion_msgs = [{"role": "assistant", "content": completion}]
|
| 464 |
+
if prompt_msgs is None:
|
| 465 |
+
prompt_msgs = example.get("prompt") or self.prompt_messages(example)
|
| 466 |
+
available = {
|
| 467 |
+
"completion": completion_msgs,
|
| 468 |
+
"prompt": prompt_msgs,
|
| 469 |
+
"answer": example.get("answer"),
|
| 470 |
+
"info": self._normalize_info(example),
|
| 471 |
+
"state": state if state is not None else {},
|
| 472 |
+
"parser": self._parser,
|
| 473 |
+
"task": example,
|
| 474 |
+
}
|
| 475 |
+
available.update(_judge_kwargs(self._judge_rubric))
|
| 476 |
+
return available
|
| 477 |
+
|
| 478 |
+
def scores_breakdown(
|
| 479 |
+
self, completion: str, example: dict, state: dict | None = None
|
| 480 |
+
) -> dict[str, float]:
|
| 481 |
+
"""Per-scorer weighted scores: ``{func_name: weighted_score, ..., "total": sum}``.
|
| 482 |
+
|
| 483 |
+
Every WEIGHTED rubric func contributes one entry (by ``func.__name__``); the
|
| 484 |
+
``"total"`` is their sum (== :meth:`reward`). Used to preserve the frontend per-scorer
|
| 485 |
+
breakdown + W&B series instead of collapsing to a single binary ``correct``.
|
| 486 |
+
|
| 487 |
+
Per verifiers semantics EVERY reward func runs, including eval-metric ones — they may
|
| 488 |
+
mutate the shared ``state`` (so a subsequent weighted func sees their work) or exist
|
| 489 |
+
only to be logged. Eval-metric funcs run with GUARDED exceptions (a thrown monitor must
|
| 490 |
+
not fail the run) and contribute 0, so they are not added to the breakdown/total; the
|
| 491 |
+
order is preserved so a eval-metric func can prepare state for a later weighted one.
|
| 492 |
+
Weighted funcs propagate exceptions (a thrown weighted reward fails the run).
|
| 493 |
+
"""
|
| 494 |
+
breakdown: dict[str, float] = {}
|
| 495 |
+
if not self._reward_pairs:
|
| 496 |
+
answer = str(example.get("answer") or "")
|
| 497 |
+
score = 1.0 if answer and answer in (completion or "") else 0.0
|
| 498 |
+
return {"answer_match": score, "total": score}
|
| 499 |
+
available = self._reward_available(completion, example, state)
|
| 500 |
+
total = 0.0
|
| 501 |
+
for func, weight in self._reward_pairs:
|
| 502 |
+
if not weight:
|
| 503 |
+
# Eval-metric monitor/diagnostic func: RUN it (for its side effects on shared
|
| 504 |
+
# state / logging) with guarded exceptions, but it contributes 0 and is not in
|
| 505 |
+
# the named breakdown.
|
| 506 |
+
_run_eval_metric(func, available)
|
| 507 |
+
continue
|
| 508 |
+
name = getattr(func, "__name__", str(func))
|
| 509 |
+
score = float(weight) * _invoke_reward(func, available)
|
| 510 |
+
# Collisions (two funcs share a name): keep them distinct so neither is lost.
|
| 511 |
+
# Probe for an unused exact key — a prefix/length heuristic can recompute a
|
| 512 |
+
# suffix that collides with an already-recorded key (e.g. ``score`` vs
|
| 513 |
+
# ``score_detail``) and silently overwrite a scorer.
|
| 514 |
+
if name in breakdown:
|
| 515 |
+
base = name
|
| 516 |
+
i = 1
|
| 517 |
+
while name in breakdown:
|
| 518 |
+
name = f"{base}_{i}"
|
| 519 |
+
i += 1
|
| 520 |
+
breakdown[name] = score
|
| 521 |
+
total += score
|
| 522 |
+
breakdown["total"] = total
|
| 523 |
+
return breakdown
|
| 524 |
+
|
| 525 |
+
def reward(self, completion: str, example: dict, state: dict | None = None) -> float:
|
| 526 |
+
return float(self.scores_breakdown(completion, example, state)["total"])
|
| 527 |
+
|
| 528 |
+
def evaluate(self, completion: str, example: dict, state: dict | None = None) -> dict:
|
| 529 |
+
"""One pass over the rubric returning the training ``reward`` AND the env's separate
|
| 530 |
+
``metrics`` — each EVAL-METRIC rubric func's raw (unweighted) score, by name.
|
| 531 |
+
|
| 532 |
+
Eval-metric funcs are how a verifiers ``environment.py`` expresses an EVALUATION signal
|
| 533 |
+
distinct from the GRPO reward: an ``exact_match`` / ``accuracy`` monitor added with
|
| 534 |
+
``rubric.add_metric(fn, weight=0.0)`` does not shape training (weight 0) but measures
|
| 535 |
+
quality. :meth:`scores_breakdown`/:meth:`reward` deliberately omit these; mid-run eval
|
| 536 |
+
wants them, so this method surfaces them WITHOUT a second rubric pass (a ``JudgeRubric``
|
| 537 |
+
is sampled at most once). Weighted funcs still propagate exceptions (a broken weighted
|
| 538 |
+
reward fails the run); eval-metric monitors stay guarded (a thrown monitor is skipped,
|
| 539 |
+
never fails eval). Order is preserved so a monitor can prep shared ``state`` for a later
|
| 540 |
+
weighted func, exactly as in :meth:`scores_breakdown`.
|
| 541 |
+
|
| 542 |
+
Returns ``{"reward": <weighted total>, "metrics": {name: raw_score, ...}}``; an env with
|
| 543 |
+
no rubric falls back to the substring ``answer_match`` as both reward and (empty) metrics.
|
| 544 |
+
"""
|
| 545 |
+
if not self._reward_pairs:
|
| 546 |
+
answer = str(example.get("answer") or "")
|
| 547 |
+
score = 1.0 if answer and answer in (completion or "") else 0.0
|
| 548 |
+
return {"reward": score, "metrics": {}}
|
| 549 |
+
available = self._reward_available(completion, example, state)
|
| 550 |
+
total = 0.0
|
| 551 |
+
metrics: dict[str, float] = {}
|
| 552 |
+
for func, weight in self._reward_pairs:
|
| 553 |
+
name = getattr(func, "__name__", str(func))
|
| 554 |
+
if not weight:
|
| 555 |
+
# Eval-metric = an eval/monitor metric: run it (guarded — a thrown monitor must
|
| 556 |
+
# not fail eval) and record its RAW score; it never touches the reward total.
|
| 557 |
+
try:
|
| 558 |
+
raw = _invoke_reward(func, available)
|
| 559 |
+
except Exception:
|
| 560 |
+
continue
|
| 561 |
+
key = name
|
| 562 |
+
i = 1
|
| 563 |
+
while key in metrics: # keep colliding metric names distinct
|
| 564 |
+
key = f"{name}_{i}"
|
| 565 |
+
i += 1
|
| 566 |
+
metrics[key] = raw
|
| 567 |
+
continue
|
| 568 |
+
total += float(weight) * _invoke_reward(func, available)
|
| 569 |
+
return {"reward": total, "metrics": metrics}
|
| 570 |
+
|
| 571 |
+
def tools(self) -> list:
|
| 572 |
+
"""The underlying ToolEnv's Python tool callables (``[]`` for non-tool envs).
|
| 573 |
+
|
| 574 |
+
Handed to ``GRPOTrainer(tools=...)`` so TRL runs the tool-call loop and does the
|
| 575 |
+
assistant-only token masking itself. Each is a plain function with type hints + a
|
| 576 |
+
Google-style docstring (verifiers and TRL share that requirement)."""
|
| 577 |
+
return list(getattr(self._env, "tools", None) or [])
|
| 578 |
+
|
| 579 |
+
def reward_from_messages(
|
| 580 |
+
self, completion_msgs: list[dict], example: dict, prompt_msgs: list[dict] | None = None
|
| 581 |
+
) -> float:
|
| 582 |
+
"""Reward for a full transcript (assistant + tool/env messages) via the rubric.
|
| 583 |
+
|
| 584 |
+
The tool / multi-turn training path produces a *message list* rollout rather than a
|
| 585 |
+
single completion string; this routes it through the same weighted-rubric scoring as
|
| 586 |
+
:meth:`reward` by handing the transcript to the env's reward funcs as ``state``."""
|
| 587 |
+
state: dict = {"completion": [dict(m) for m in completion_msgs]}
|
| 588 |
+
if prompt_msgs:
|
| 589 |
+
state["prompt"] = [dict(m) for m in prompt_msgs]
|
| 590 |
+
return self.reward("", example, state)
|
| 591 |
+
|
| 592 |
+
def grade(self, completion: str, example: dict, state: dict | None = None) -> bool:
|
| 593 |
+
threshold = getattr(self._env, "pass_threshold", 0.5)
|
| 594 |
+
return self.reward(completion, example, state) >= threshold
|
| 595 |
+
|
| 596 |
+
# -- multi-turn rollout (driven by the worker) ------------------------
|
| 597 |
+
def new_rollout_state(self, example: dict) -> dict:
|
| 598 |
+
"""A fresh per-rollout ``state`` dict, threaded through env_reply/reward.
|
| 599 |
+
|
| 600 |
+
Mirrors the verifiers rollout ``state``: holds the running ``prompt``, the
|
| 601 |
+
accumulated ``completion`` (assistant + tool/env turns), the ``answer``/``info``, and
|
| 602 |
+
a ``turn`` counter. Reward funcs that read ``state`` see this dict.
|
| 603 |
+
"""
|
| 604 |
+
prompt = self.prompt_messages(example)
|
| 605 |
+
state = {
|
| 606 |
+
"prompt": [dict(m) for m in prompt],
|
| 607 |
+
"completion": [],
|
| 608 |
+
"answer": example.get("answer"),
|
| 609 |
+
"info": self._normalize_info(example),
|
| 610 |
+
"responses": [],
|
| 611 |
+
"turn": 0,
|
| 612 |
+
}
|
| 613 |
+
setup = getattr(self._env, "setup_state", None)
|
| 614 |
+
if callable(setup):
|
| 615 |
+
with contextlib.suppress(Exception):
|
| 616 |
+
state = _run_async(setup(state)) or state
|
| 617 |
+
return state
|
| 618 |
+
|
| 619 |
+
def env_reply(self, messages: list[dict], state: dict) -> list[dict]:
|
| 620 |
+
"""One environment turn: given the conversation so far (incl. the latest model
|
| 621 |
+
message), return the env's reply messages (tool results / next user turn) and advance
|
| 622 |
+
``state``. Empty list when the env has nothing to add. Single-turn envs return []."""
|
| 623 |
+
if not self.multi_turn:
|
| 624 |
+
return []
|
| 625 |
+
fn = getattr(self._env, "env_response", None)
|
| 626 |
+
if not callable(fn):
|
| 627 |
+
return []
|
| 628 |
+
try:
|
| 629 |
+
reply = _run_async(fn(messages, state))
|
| 630 |
+
except NotImplementedError:
|
| 631 |
+
# Legitimate "this env has no env turn" signal -> no env reply.
|
| 632 |
+
return []
|
| 633 |
+
except Exception as exc:
|
| 634 |
+
# Mirror `_invoke_reward`: a genuine bug in the env's `env_response` must
|
| 635 |
+
# NOT be swallowed. Silently returning [] would collapse every multi-turn
|
| 636 |
+
# rollout to a single turn and train a paid GRPO run on degenerate
|
| 637 |
+
# transcripts. The rollout loop (multiturn_rollout.py) calls this directly
|
| 638 |
+
# with no surrounding swallow, so re-raising propagates and fails the run
|
| 639 |
+
# fast (and the context is printed first so it never vanishes silently).
|
| 640 |
+
print(f"[env_reply] env_response failed (turn={state.get('turn', 0)}): {exc!r}")
|
| 641 |
+
raise
|
| 642 |
+
if reply is None:
|
| 643 |
+
return []
|
| 644 |
+
if isinstance(reply, dict):
|
| 645 |
+
reply = [reply]
|
| 646 |
+
out = [dict(m) for m in reply]
|
| 647 |
+
state["completion"].extend(out)
|
| 648 |
+
state["turn"] = int(state.get("turn", 0)) + 1
|
| 649 |
+
return out
|
| 650 |
+
|
| 651 |
+
def rollout_done(self, state: dict, max_turns: int | None = None) -> bool:
|
| 652 |
+
"""Whether the multi-turn rollout should stop (env says completed, or turn cap hit)."""
|
| 653 |
+
if not self.multi_turn:
|
| 654 |
+
return True
|
| 655 |
+
if max_turns is not None and int(state.get("turn", 0)) >= int(max_turns):
|
| 656 |
+
return True
|
| 657 |
+
fn = getattr(self._env, "is_completed", None)
|
| 658 |
+
if not callable(fn):
|
| 659 |
+
return True
|
| 660 |
+
try:
|
| 661 |
+
return bool(_run_async(fn(state)))
|
| 662 |
+
except NotImplementedError:
|
| 663 |
+
# Env doesn't implement a completion check -> rely on the turn cap only.
|
| 664 |
+
return True
|
| 665 |
+
except Exception as exc:
|
| 666 |
+
# Mirror `_invoke_reward` / `env_reply`: a real bug in `is_completed` must
|
| 667 |
+
# not be silently treated as "done" (which would truncate every rollout and
|
| 668 |
+
# train on degenerate transcripts). Print context, then re-raise so the run
|
| 669 |
+
# fails fast (the rollout loop calls this directly with no surrounding swallow).
|
| 670 |
+
print(f"[rollout_done] is_completed failed (turn={state.get('turn', 0)}): {exc!r}")
|
| 671 |
+
raise
|
| 672 |
+
|
| 673 |
+
def record_model_turn(self, state: dict, content: str) -> dict:
|
| 674 |
+
"""Append a model (assistant) turn to ``state`` before calling ``env_reply``."""
|
| 675 |
+
msg = {"role": "assistant", "content": content}
|
| 676 |
+
state["completion"].append(msg)
|
| 677 |
+
state.setdefault("responses", []).append(content)
|
| 678 |
+
return msg
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
def _import_vf():
|
| 682 |
+
try:
|
| 683 |
+
import verifiers as vf
|
| 684 |
+
|
| 685 |
+
return vf
|
| 686 |
+
except ImportError as exc:
|
| 687 |
+
raise ImportError(
|
| 688 |
+
"the 'verifiers' package is required to run Prime Hub environments; "
|
| 689 |
+
"install it (e.g. `uv pip install verifiers`) or run `slm env install <env>`"
|
| 690 |
+
) from exc
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
def load_verifiers_environment(
|
| 694 |
+
env_id: str,
|
| 695 |
+
eval_env_id: str | None = None,
|
| 696 |
+
eval_examples: int | None = None,
|
| 697 |
+
eval_seed: int = 12345,
|
| 698 |
+
**kwargs,
|
| 699 |
+
) -> VerifiersEnvironment:
|
| 700 |
+
"""Load an installed / Hub verifiers environment by id and wrap it for Flash.
|
| 701 |
+
|
| 702 |
+
``env_id`` may be a Hub slug (``owner/name``); it is mapped to the bare verifiers load id.
|
| 703 |
+
Pass ``eval_env_id`` to evaluate on a *different* Hub env, with ``eval_examples`` /
|
| 704 |
+
``eval_seed`` selecting a fixed eval subset. Remaining ``kwargs`` are forwarded to the train
|
| 705 |
+
env's ``vf.load_environment``.
|
| 706 |
+
"""
|
| 707 |
+
vf = _import_vf()
|
| 708 |
+
vf_env = vf.load_environment(vf_load_id(env_id), **_drop_reserved_kwargs(kwargs))
|
| 709 |
+
eval_ref = eval_env_id
|
| 710 |
+
eval_vf_env = vf.load_environment(vf_load_id(eval_ref)) if eval_ref else None
|
| 711 |
+
return VerifiersEnvironment(
|
| 712 |
+
vf_env,
|
| 713 |
+
env_id,
|
| 714 |
+
eval_vf_env=eval_vf_env,
|
| 715 |
+
eval_examples=eval_examples,
|
| 716 |
+
eval_seed=eval_seed,
|
| 717 |
+
)
|
code/flash/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/flash/envs/registry.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
from .._fileio import read_json_or_empty, secure_json_write
|
| 16 |
+
from .base import Environment
|
| 17 |
+
|
| 18 |
+
# Manifest of installed verifiers / Prime Hub environments (written by `slm env install`).
|
| 19 |
+
INSTALLED_MANIFEST = Path.home() / ".flash" / "envs.json"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def load_installed_manifest() -> dict:
|
| 23 |
+
return read_json_or_empty(INSTALLED_MANIFEST)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def list_installed_verifiers_envs() -> list[str]:
|
| 27 |
+
"""Names of verifiers/Hub environments installed via `slm env install`."""
|
| 28 |
+
return sorted(load_installed_manifest())
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def record_installed_env(env_id: str, package: str, extras: dict | None = None) -> None:
|
| 32 |
+
manifest = load_installed_manifest()
|
| 33 |
+
manifest[env_id] = {"package": package, **(extras or {})}
|
| 34 |
+
# The manifest can hold a credentialed --extra-index-url, so write it with private perms.
|
| 35 |
+
secure_json_write(INSTALLED_MANIFEST, manifest)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _bare_wheel_name(env_ref: str) -> str:
|
| 39 |
+
"""``owner/name`` Hub slug -> the bare pip wheel name (``name``)."""
|
| 40 |
+
return env_ref.split("/", 1)[1] if "/" in env_ref else env_ref
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def worker_pip_for_env(env_id: str) -> list[str]:
|
| 44 |
+
"""Pip deps the GPU worker needs to run ``env_id`` (a verifiers/Hub env): just ``verifiers``.
|
| 45 |
+
|
| 46 |
+
The environment itself (and any separate eval env) is installed on the worker via the
|
| 47 |
+
authenticated ``prime env install`` (see :func:`worker_hub_env_ids`), not pip — the public
|
| 48 |
+
pip index does not serve private env wheels. Override with ``[environment] pip`` if a run
|
| 49 |
+
needs extra packages.
|
| 50 |
+
"""
|
| 51 |
+
return ["verifiers"]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def worker_hub_env_ids(env_id: str, params: dict | None = None) -> list[str]:
|
| 55 |
+
"""The Prime Hub env ids the worker must ``prime env install`` for this run.
|
| 56 |
+
|
| 57 |
+
The training env plus a separate **eval** Hub env (``[environment.params] eval_env_id``)
|
| 58 |
+
when configured. ``prime env install`` is authenticated by ``PRIME_API_KEY`` and installs
|
| 59 |
+
public and private envs alike.
|
| 60 |
+
"""
|
| 61 |
+
params = params or {}
|
| 62 |
+
ids = [env_id, params.get("eval_env_id")]
|
| 63 |
+
return list(dict.fromkeys(str(i) for i in ids if i))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def load_environment(env_id: str, params: dict | None = None) -> Environment:
|
| 67 |
+
"""Load a verifiers environment and wrap it in Flash's protocol.
|
| 68 |
+
|
| 69 |
+
``env_id`` is resolved as an installed / Prime Hub verifiers env slug.
|
| 70 |
+
"""
|
| 71 |
+
params = params or {}
|
| 72 |
+
from .adapter import load_verifiers_environment
|
| 73 |
+
|
| 74 |
+
if not env_id:
|
| 75 |
+
raise ValueError(
|
| 76 |
+
"no environment specified: set [environment] id to a verifiers/Prime Hub env "
|
| 77 |
+
"slug (e.g. 'owner/name')"
|
| 78 |
+
)
|
| 79 |
+
return load_verifiers_environment(env_id, **params)
|
code/flash/mcp/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""MCP integration package."""
|
code/flash/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 Flash 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 flash.catalog import public_model_rows
|
| 18 |
+
from flash.client import client_from_config
|
| 19 |
+
from flash.client.specs import spec_payload
|
| 20 |
+
from flash.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/flash/providers/__init__.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pluggable GPU substrates (RunPod Flash + Vast.ai verified datacenters).
|
| 2 |
+
|
| 3 |
+
The training worker (``flash.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 flash.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 flash.providers.runpod import PROVIDER
|
| 41 |
+
|
| 42 |
+
return PROVIDER
|
| 43 |
+
if key == "vast":
|
| 44 |
+
from flash.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 FLASH_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/flash/providers/_auth.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared operator-credential helpers for the GPU providers.
|
| 2 |
+
|
| 3 |
+
Every provider authenticates the same way: a single API key read ONLY from an
|
| 4 |
+
environment variable on the control-plane host (never config files, never shipped to
|
| 5 |
+
workers). The per-provider ``auth.py`` modules wrap these with their own env-var name
|
| 6 |
+
and error message.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def load_provider_key(env_var: str) -> str | None:
|
| 15 |
+
"""Provider API key from ``env_var`` (operator configuration), or None."""
|
| 16 |
+
return os.environ.get(env_var) or None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def ensure_provider_auth(env_var: str, missing_message: str) -> str:
|
| 20 |
+
"""Return the provider key from ``env_var``; raise ``missing_message`` if unset."""
|
| 21 |
+
key = load_provider_key(env_var)
|
| 22 |
+
if not key:
|
| 23 |
+
raise RuntimeError(missing_message)
|
| 24 |
+
return key
|
code/flash/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/flash/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/flash/providers/allocator.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Cross-provider GPU allocation: the cheapest class that comfortably fits the run.
|
| 2 |
+
|
| 3 |
+
Given a base model (+ algorithm), compute the VRAM the FULL run needs — sized for the
|
| 4 |
+
heavier phase, GRPO, since the typical pipeline is SFT followed by GRPO — then rank
|
| 5 |
+
every provisionable candidate across ALL registered providers by live $/hr and pick the
|
| 6 |
+
cheapest:
|
| 7 |
+
|
| 8 |
+
runpod every Flash-provisionable class (live pricing, cached; static fallback)
|
| 9 |
+
vast live verified-datacenter offers (usable_offers' quality floors applied)
|
| 10 |
+
|
| 11 |
+
Allocation happens at SUBMIT time in the runner (offers are a volatile market);
|
| 12 |
+
the parse-time resolution in schema is a RunPod-static provisional for
|
| 13 |
+
validation/dry-run display. Offline (FLASH_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 flash._logging import get_logger
|
| 25 |
+
from flash.providers import PROVIDER_NAMES, available_providers, get_provider
|
| 26 |
+
from flash.providers.base import (
|
| 27 |
+
Allocation,
|
| 28 |
+
Candidate,
|
| 29 |
+
UnsupportedGpuError,
|
| 30 |
+
canonical_gpu,
|
| 31 |
+
unvalidated_allowed,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
logger = get_logger(__name__)
|
| 35 |
+
|
| 36 |
+
# "Comfortably" = the open-model VRAM estimate plus headroom, so a full SFT+GRPO run
|
| 37 |
+
# never lands in check_fit's "tight" band by construction. Curated catalog entries
|
| 38 |
+
# already carry measured minimums and are used as-is. The headroom (default 1.1 ==
|
| 39 |
+
# model_required_vram_gb's own default) is read at call time via vram_headroom() so allocate()
|
| 40 |
+
# and resolve_gpu_policy size identically and pick up a value exported after import.
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def vram_headroom() -> float:
|
| 44 |
+
"""The sizing headroom multiplier, honored by both the submit-time allocator and the
|
| 45 |
+
parse-time resolve_gpu_policy so they never disagree (PR #176 review). A validated constant."""
|
| 46 |
+
return 1.1
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def required_vram_gb(
|
| 50 |
+
model_id: str,
|
| 51 |
+
algorithm: str,
|
| 52 |
+
*,
|
| 53 |
+
train=None,
|
| 54 |
+
thinking: bool = False,
|
| 55 |
+
) -> int:
|
| 56 |
+
"""VRAM the full run needs, sized to the run's actual knobs (context length, LoRA
|
| 57 |
+
rank, batch / group size, thinking) via the shared ``model_required_vram_gb`` matrix.
|
| 58 |
+
|
| 59 |
+
Catalog GRPO floors stay hard floors (never under-provision a validated model); the
|
| 60 |
+
matrix sizes up from there for big contexts/groups and down to a cheaper card for
|
| 61 |
+
small runs. Unlisted open models size from HF metadata, falling back to the 24 GB tier
|
| 62 |
+
when unreadable (handled inside model_required_vram_gb)."""
|
| 63 |
+
from flash.engine.vram import model_required_vram_gb
|
| 64 |
+
|
| 65 |
+
return model_required_vram_gb(
|
| 66 |
+
model_id,
|
| 67 |
+
algorithm,
|
| 68 |
+
train=train,
|
| 69 |
+
thinking=thinking,
|
| 70 |
+
headroom=vram_headroom(),
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _runpod_candidates(need: int, pinned_gpu: str | None, allow_unval: bool) -> list[Candidate]:
|
| 75 |
+
"""RunPod's fitting classes priced live (static fallback)."""
|
| 76 |
+
provider = get_provider("runpod")
|
| 77 |
+
out: list[Candidate] = []
|
| 78 |
+
for g in provider.gpu_classes():
|
| 79 |
+
if g.vram_gb < need:
|
| 80 |
+
continue
|
| 81 |
+
if pinned_gpu and g.name != pinned_gpu:
|
| 82 |
+
continue
|
| 83 |
+
if "runpod" not in g.validated_on and not allow_unval:
|
| 84 |
+
continue
|
| 85 |
+
out.append(
|
| 86 |
+
Candidate(
|
| 87 |
+
"runpod",
|
| 88 |
+
g.name,
|
| 89 |
+
provider.hourly_rate(g.name),
|
| 90 |
+
g.vram_gb,
|
| 91 |
+
"runpod" in g.validated_on,
|
| 92 |
+
)
|
| 93 |
+
)
|
| 94 |
+
return out
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _vast_candidates(
|
| 98 |
+
need: int,
|
| 99 |
+
pinned_gpu: str | None,
|
| 100 |
+
allow_unval: bool,
|
| 101 |
+
disk_gb: int,
|
| 102 |
+
exclude_machine_ids,
|
| 103 |
+
*,
|
| 104 |
+
required: bool,
|
| 105 |
+
) -> tuple[list[Candidate], tuple]:
|
| 106 |
+
"""Vast's fitting classes from the live offer book (cheapest per class).
|
| 107 |
+
|
| 108 |
+
Returns (candidates, full_offer_book). ``required`` (a hard ``provider="vast"``
|
| 109 |
+
pin) re-raises a search failure; otherwise it degrades to RunPod-only.
|
| 110 |
+
"""
|
| 111 |
+
from flash.providers.base import GPU_INFO
|
| 112 |
+
from flash.providers.vast.jobs import MIN_DISK_GB, usable_offers
|
| 113 |
+
|
| 114 |
+
# When a larger class is pinned for a small model, search at the PINNED class's VRAM,
|
| 115 |
+
# not the (smaller) model requirement: the offer search returns the cheapest ``limit``
|
| 116 |
+
# offers from a VRAM floor, so a search at ``need`` can fill that window entirely with
|
| 117 |
+
# small cheap cards and never surface the pinned larger class. ``need`` is still the
|
| 118 |
+
# validity floor (allocate() rejects an undersized pin before we get here).
|
| 119 |
+
search_vram = max(need, GPU_INFO[pinned_gpu].vram_gb) if pinned_gpu else need
|
| 120 |
+
book: list = []
|
| 121 |
+
try:
|
| 122 |
+
# The offer search must use the SAME disk floor instances are actually
|
| 123 |
+
# provisioned with (``create_instance``/``_effective_disk_gb``); searching at a
|
| 124 |
+
# smaller requested ``disk_gb`` would surface offers that then fail to rent.
|
| 125 |
+
book = usable_offers(
|
| 126 |
+
search_vram, max(float(disk_gb), MIN_DISK_GB), exclude_machine_ids=exclude_machine_ids
|
| 127 |
+
)
|
| 128 |
+
except Exception as exc:
|
| 129 |
+
if required:
|
| 130 |
+
raise UnsupportedGpuError(f"vast offer search failed: {exc}") from exc
|
| 131 |
+
logger.warning("vast offer search failed (%s); allocating on runpod only", exc)
|
| 132 |
+
out: list[Candidate] = []
|
| 133 |
+
seen: set[str] = set()
|
| 134 |
+
for o in book:
|
| 135 |
+
if pinned_gpu and o.gpu != pinned_gpu:
|
| 136 |
+
continue
|
| 137 |
+
info = GPU_INFO[o.gpu]
|
| 138 |
+
if "vast" not in info.validated_on and not allow_unval:
|
| 139 |
+
continue
|
| 140 |
+
if o.gpu in seen: # offers are price-sorted; keep the cheapest per class
|
| 141 |
+
continue
|
| 142 |
+
seen.add(o.gpu)
|
| 143 |
+
out.append(
|
| 144 |
+
Candidate(
|
| 145 |
+
"vast", o.gpu, o.dph_total, info.vram_gb, "vast" in info.validated_on, offer=o
|
| 146 |
+
)
|
| 147 |
+
)
|
| 148 |
+
return out, tuple(book)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def allocate(
|
| 152 |
+
model_id: str,
|
| 153 |
+
algorithm: str,
|
| 154 |
+
*,
|
| 155 |
+
gpu: str | None = None,
|
| 156 |
+
provider: str = "auto",
|
| 157 |
+
disk_gb: int = 60,
|
| 158 |
+
allow_unvalidated: bool | None = None,
|
| 159 |
+
exclude_machine_ids: set[int] | frozenset[int] = frozenset(),
|
| 160 |
+
train=None,
|
| 161 |
+
thinking: bool = False,
|
| 162 |
+
) -> Allocation:
|
| 163 |
+
"""Pick the cheapest (provider, GPU class) able to run the job across providers.
|
| 164 |
+
|
| 165 |
+
``gpu`` pins the class (the allocator then only picks the provider); ``provider``
|
| 166 |
+
pins the substrate ("auto"/"runpod"/"vast"). Both default to fully automatic.
|
| 167 |
+
``train``/``thinking`` size the requirement to the run's actual knobs (context, group,
|
| 168 |
+
rank, batch) via the matrix — long context / large group route up, small runs down.
|
| 169 |
+
"""
|
| 170 |
+
if provider not in ("auto", *PROVIDER_NAMES):
|
| 171 |
+
raise UnsupportedGpuError(
|
| 172 |
+
f"unknown provider {provider!r} (auto, {', '.join(PROVIDER_NAMES)})"
|
| 173 |
+
)
|
| 174 |
+
pinned_gpu = canonical_gpu(gpu) if gpu else None
|
| 175 |
+
# The model's requirement is the floor regardless of a pin: an undersized concrete
|
| 176 |
+
# pin (e.g. Qwen3-8B on a 24 GB card) must drop out of the candidate filter and
|
| 177 |
+
# raise here, not provision a paid worker that OOMs. The pin only narrows WHICH
|
| 178 |
+
# fitting class is chosen, never lowers the VRAM bar.
|
| 179 |
+
need = required_vram_gb(model_id, algorithm, train=train, thinking=thinking)
|
| 180 |
+
allow_unval = unvalidated_allowed(allow_unvalidated)
|
| 181 |
+
live = available_providers()
|
| 182 |
+
if provider != "auto" and provider not in live:
|
| 183 |
+
raise UnsupportedGpuError(
|
| 184 |
+
f"provider {provider!r} requested but not available on this control plane "
|
| 185 |
+
f"(available: {', '.join(live) or '(none)'}; vast needs VAST_API_KEY)"
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
def _gather(pin: str | None) -> tuple[list[Candidate], tuple]:
|
| 189 |
+
cands: list[Candidate] = []
|
| 190 |
+
book: tuple = ()
|
| 191 |
+
if provider in ("auto", "runpod") and "runpod" in live:
|
| 192 |
+
cands += _runpod_candidates(need, pin, allow_unval)
|
| 193 |
+
if provider in ("auto", "vast") and "vast" in live:
|
| 194 |
+
vcands, book = _vast_candidates(
|
| 195 |
+
need, pin, allow_unval, disk_gb, exclude_machine_ids, required=(provider == "vast")
|
| 196 |
+
)
|
| 197 |
+
cands += vcands
|
| 198 |
+
return cands, book
|
| 199 |
+
|
| 200 |
+
candidates, offer_book = _gather(pinned_gpu)
|
| 201 |
+
# NEVER hard-fail on availability: a pin that no live provider can serve (the class isn't
|
| 202 |
+
# offered right now, or is below ``need`` so it's filtered out) escalates to the cheapest
|
| 203 |
+
# FITTING class across providers instead of raising -- "one spot larger, and so on". The
|
| 204 |
+
# ``need`` floor is still absolute (we never drop below it -> no OOM), and the pin is only a
|
| 205 |
+
# preference. We only raise when NOTHING >= need is available anywhere (truly unsatisfiable).
|
| 206 |
+
escalated_from = None
|
| 207 |
+
if not candidates and pinned_gpu is not None:
|
| 208 |
+
escalated_from = pinned_gpu
|
| 209 |
+
candidates, offer_book = _gather(None)
|
| 210 |
+
if not candidates:
|
| 211 |
+
raise UnsupportedGpuError(
|
| 212 |
+
f"no allocatable GPU (>= {need} GB VRAM for {model_id}, provider={provider}, "
|
| 213 |
+
f"validated_only={not allow_unval}); widen with gpu.allow_unvalidated = true, add a "
|
| 214 |
+
f"provider (VAST_API_KEY), or the run genuinely exceeds every available GPU class"
|
| 215 |
+
)
|
| 216 |
+
if escalated_from is not None:
|
| 217 |
+
order0 = {n: i for i, n in enumerate(PROVIDER_NAMES)}
|
| 218 |
+
_cheapest = sorted(candidates, key=lambda c: (c.hourly_usd, c.vram_gb, order0.get(c.provider, 99)))[0]
|
| 219 |
+
# WARNING level so it surfaces at default `slm train` verbosity (configure_logging is
|
| 220 |
+
# WARNING) — a silently-escalated pin changes cost/hardware and operators must see it;
|
| 221 |
+
# still routed through the logger (stderr), so machine-readable stdout stays clean.
|
| 222 |
+
logger.warning(
|
| 223 |
+
"pinned GPU %r unavailable or below need (%s GB) on provider=%s; "
|
| 224 |
+
"escalated to cheapest fitting class %s (%s GB, %s)",
|
| 225 |
+
escalated_from,
|
| 226 |
+
need,
|
| 227 |
+
provider,
|
| 228 |
+
_cheapest.gpu,
|
| 229 |
+
_cheapest.vram_gb,
|
| 230 |
+
_cheapest.provider,
|
| 231 |
+
)
|
| 232 |
+
# Cheapest first; equal rates prefer less VRAM (don't burn a big card on a small
|
| 233 |
+
# job), then registry order (runpod is the longest-validated substrate).
|
| 234 |
+
order = {n: i for i, n in enumerate(PROVIDER_NAMES)}
|
| 235 |
+
ranked = sorted(candidates, key=lambda c: (c.hourly_usd, c.vram_gb, order.get(c.provider, 99)))
|
| 236 |
+
best = ranked[0]
|
| 237 |
+
return Allocation(
|
| 238 |
+
provider=best.provider,
|
| 239 |
+
gpu=best.gpu,
|
| 240 |
+
hourly_usd=best.hourly_usd,
|
| 241 |
+
min_vram_gb=need,
|
| 242 |
+
candidates=tuple(ranked),
|
| 243 |
+
offer=best.offer,
|
| 244 |
+
provider_offers=offer_book,
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def allocation_summary(a: Allocation) -> str:
|
| 249 |
+
head = (
|
| 250 |
+
f"allocated {a.gpu} on {a.provider} at ${a.hourly_usd:.2f}/hr "
|
| 251 |
+
f"(need >= {a.min_vram_gb} GB VRAM"
|
| 252 |
+
)
|
| 253 |
+
# ``a.offer`` is an OPAQUE per-provider provisioning hint, not necessarily a Vast
|
| 254 |
+
# offer — only format Vast specifics when the chosen provider is vast, so a future
|
| 255 |
+
# provider's hint never misformats or raises on a missing attribute.
|
| 256 |
+
if a.provider == "vast" and a.offer is not None:
|
| 257 |
+
head += f", vast offer {a.offer.offer_id} in {a.offer.geolocation}"
|
| 258 |
+
head += ")"
|
| 259 |
+
if len(a.candidates) > 1:
|
| 260 |
+
nxt = a.candidates[1]
|
| 261 |
+
head += f"; next-best: {nxt.gpu}@{nxt.provider} ${nxt.hourly_usd:.2f}/hr"
|
| 262 |
+
return head
|
code/flash/providers/base.py
ADDED
|
@@ -0,0 +1,540 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from dataclasses import dataclass, field
|
| 29 |
+
from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
|
| 30 |
+
|
| 31 |
+
if TYPE_CHECKING:
|
| 32 |
+
from flash.spec import JobSpec
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# ---------------------------------------------------------------------------
|
| 36 |
+
# GPU class registry (provider-agnostic identity + per-provider validation)
|
| 37 |
+
# ---------------------------------------------------------------------------
|
| 38 |
+
@dataclass(frozen=True)
|
| 39 |
+
class GpuClass:
|
| 40 |
+
"""One managed GPU class: a friendly name + per-provider identity/metadata.
|
| 41 |
+
|
| 42 |
+
Provider-agnostic by design — the identity columns (``enum_member`` for RunPod's
|
| 43 |
+
Flash ``GpuType``; ``vast_name`` for the Vast offer ``gpu_name``) and
|
| 44 |
+
``validated_on`` carry the per-provider facts, but a class is a single canonical
|
| 45 |
+
row so the catalog / config / serving all agree on what e.g. "RTX 5090" is.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
name: str # canonical friendly name used in configs / the catalog
|
| 49 |
+
enum_member: str | None # runpod_flash GpuType member name; None -> not on RunPod
|
| 50 |
+
vram_gb: int
|
| 51 |
+
short: str # endpoint-name-safe token (e.g. "4090", "a5000")
|
| 52 |
+
sm: str # CUDA arch (informational; sm80+ only)
|
| 53 |
+
hourly_usd: float # static fallback rate; live pricing overrides (pricing.py)
|
| 54 |
+
# Providers where this class passed Flash's live train+eval smoke. Validation is
|
| 55 |
+
# per-provider: the same silicon behind a different provisioning path (Flash deps
|
| 56 |
+
# install vs a Vast docker image) is a different failure surface.
|
| 57 |
+
validated_on: tuple[str, ...] = ()
|
| 58 |
+
# Min host CUDA (driver) on the modern stack. None -> 12.8. Blackwell (sm120/sm100)
|
| 59 |
+
# needs CUDA-13 drivers to JIT the wheels' PTX (no SASS shipped).
|
| 60 |
+
min_cuda_modern: str | None = None
|
| 61 |
+
# Vast.ai offer ``gpu_name`` for this class; None -> not provisionable on Vast.
|
| 62 |
+
# A100 SXM4 boards exist in 40 GB and 80 GB variants under ONE Vast name — offers
|
| 63 |
+
# are disambiguated by ``gpu_ram`` (see ``vast_gpu_for_offer``).
|
| 64 |
+
vast_name: str | None = None
|
| 65 |
+
|
| 66 |
+
@property
|
| 67 |
+
def validated(self) -> bool: # validated on ANY provider
|
| 68 |
+
return bool(self.validated_on)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# Fallback hourly rates are RunPod secure-cloud on-demand (snapshot 2026-06-11); live
|
| 72 |
+
# rates from the provider pricing module override them. Vast-only classes
|
| 73 |
+
# (enum_member=None) carry a Vast verified-datacenter snapshot instead.
|
| 74 |
+
GPU_CLASSES: tuple[GpuClass, ...] = (
|
| 75 |
+
# ---- validated: passed the full train+eval matrix (bench/results/phase1) ----
|
| 76 |
+
GpuClass(
|
| 77 |
+
"RTX 4090",
|
| 78 |
+
"NVIDIA_GEFORCE_RTX_4090",
|
| 79 |
+
24,
|
| 80 |
+
"4090",
|
| 81 |
+
"sm89",
|
| 82 |
+
0.69,
|
| 83 |
+
validated_on=("runpod",),
|
| 84 |
+
vast_name="RTX 4090",
|
| 85 |
+
),
|
| 86 |
+
# Vast-validated 2026-06-12: Qwen3-0.6B SFT train+eval smoke on a verified
|
| 87 |
+
# datacenter ($0.60/hr South Korea), incl. vLLM eval on a CUDA-13 driver.
|
| 88 |
+
GpuClass(
|
| 89 |
+
"RTX 5090",
|
| 90 |
+
"NVIDIA_GEFORCE_RTX_5090",
|
| 91 |
+
32,
|
| 92 |
+
"5090",
|
| 93 |
+
"sm120",
|
| 94 |
+
0.99,
|
| 95 |
+
validated_on=("runpod", "vast"),
|
| 96 |
+
min_cuda_modern="13.0",
|
| 97 |
+
vast_name="RTX 5090",
|
| 98 |
+
),
|
| 99 |
+
# ---- Ampere/Ada workstation + datacenter cards (cheap capacity pools) ----
|
| 100 |
+
GpuClass("RTX A4000", "NVIDIA_RTX_A4000", 16, "a4000", "sm86", 0.25, vast_name="RTX A4000"),
|
| 101 |
+
GpuClass(
|
| 102 |
+
"RTX 2000 Ada",
|
| 103 |
+
"NVIDIA_RTX_2000_ADA_GENERATION",
|
| 104 |
+
16,
|
| 105 |
+
"2000ada",
|
| 106 |
+
"sm89",
|
| 107 |
+
0.24,
|
| 108 |
+
vast_name="RTX 2000Ada",
|
| 109 |
+
),
|
| 110 |
+
GpuClass("RTX A4500", "NVIDIA_RTX_A4500", 20, "a4500", "sm86", 0.25, vast_name="RTX A4500"),
|
| 111 |
+
GpuClass(
|
| 112 |
+
"RTX 4000 Ada",
|
| 113 |
+
"NVIDIA_RTX_4000_ADA_GENERATION",
|
| 114 |
+
20,
|
| 115 |
+
"4000ada",
|
| 116 |
+
"sm89",
|
| 117 |
+
0.26,
|
| 118 |
+
vast_name="RTX 4000Ada",
|
| 119 |
+
),
|
| 120 |
+
# Validated 2026-06-11: Qwen3-0.6B SFT + GRPO smokes passed — cheapest 24 GB class.
|
| 121 |
+
GpuClass(
|
| 122 |
+
"RTX A5000",
|
| 123 |
+
"NVIDIA_RTX_A5000",
|
| 124 |
+
24,
|
| 125 |
+
"a5000",
|
| 126 |
+
"sm86",
|
| 127 |
+
0.27,
|
| 128 |
+
validated_on=("runpod",),
|
| 129 |
+
vast_name="RTX A5000",
|
| 130 |
+
),
|
| 131 |
+
# Vast-validated 2026-06-12: Qwen3-0.6B SFT train+eval smoke ($0.25/hr Czechia).
|
| 132 |
+
GpuClass(
|
| 133 |
+
"RTX 3090",
|
| 134 |
+
"NVIDIA_GEFORCE_RTX_3090",
|
| 135 |
+
24,
|
| 136 |
+
"3090",
|
| 137 |
+
"sm86",
|
| 138 |
+
0.46,
|
| 139 |
+
validated_on=("vast",),
|
| 140 |
+
vast_name="RTX 3090",
|
| 141 |
+
),
|
| 142 |
+
GpuClass("L4", "NVIDIA_L4", 24, "l4", "sm89", 0.39, vast_name="L4"),
|
| 143 |
+
# Blackwell workstation card; cheap verified-datacenter capacity on Vast.
|
| 144 |
+
# Vast-validated 2026-06-12: Qwen3-0.6B SFT train+eval smoke incl. vLLM eval on a
|
| 145 |
+
# CUDA-13 driver with the cu128 stack image ($0.34/hr Hungary). Vast-only.
|
| 146 |
+
GpuClass(
|
| 147 |
+
"RTX Pro 4000",
|
| 148 |
+
None,
|
| 149 |
+
24,
|
| 150 |
+
"pro4000",
|
| 151 |
+
"sm120",
|
| 152 |
+
0.34,
|
| 153 |
+
validated_on=("vast",),
|
| 154 |
+
min_cuda_modern="13.0",
|
| 155 |
+
vast_name="RTX PRO 4000",
|
| 156 |
+
),
|
| 157 |
+
GpuClass("RTX A6000", "NVIDIA_RTX_A6000", 48, "a6000", "sm86", 0.49, vast_name="RTX A6000"),
|
| 158 |
+
GpuClass("A40", "NVIDIA_A40", 48, "a40", "sm86", 0.44, vast_name="A40"),
|
| 159 |
+
GpuClass(
|
| 160 |
+
"RTX 6000 Ada",
|
| 161 |
+
"NVIDIA_RTX_6000_ADA_GENERATION",
|
| 162 |
+
48,
|
| 163 |
+
"6000ada",
|
| 164 |
+
"sm89",
|
| 165 |
+
0.77,
|
| 166 |
+
vast_name="RTX 6000Ada",
|
| 167 |
+
),
|
| 168 |
+
# L40S exists at RunPod but not in the Flash SDK's GpuType enum -> Vast-only.
|
| 169 |
+
GpuClass("L40S", None, 48, "l40s", "sm89", 0.87, vast_name="L40S"),
|
| 170 |
+
# ---- big-VRAM tier (large-MoE QLoRA, future >9B bf16) ----
|
| 171 |
+
# 40 GB SXM4 boards share Vast's "A100 SXM4" name with the 80 GB variant; offers
|
| 172 |
+
# are split by gpu_ram (vast_gpu_for_offer). Not a RunPod Flash class -> Vast-only.
|
| 173 |
+
GpuClass("A100 SXM 40GB", None, 40, "a100sxm40", "sm80", 0.89, vast_name="A100 SXM4"),
|
| 174 |
+
# Validated 2026-06-11: 0.6B SFT smoke (phase6).
|
| 175 |
+
GpuClass(
|
| 176 |
+
"A100 PCIe",
|
| 177 |
+
"NVIDIA_A100_80GB_PCIe",
|
| 178 |
+
80,
|
| 179 |
+
"a100pcie",
|
| 180 |
+
"sm80",
|
| 181 |
+
1.39,
|
| 182 |
+
validated_on=("runpod",),
|
| 183 |
+
vast_name="A100 PCIE",
|
| 184 |
+
),
|
| 185 |
+
GpuClass(
|
| 186 |
+
"A100 SXM", "NVIDIA_A100_SXM4_80GB", 80, "a100sxm", "sm80", 1.49, vast_name="A100 SXM4"
|
| 187 |
+
),
|
| 188 |
+
GpuClass("H100", "NVIDIA_H100_80GB_HBM3", 80, "h100", "sm90", 3.29, vast_name="H100 SXM"),
|
| 189 |
+
# H100 NVL (94 GB) has no RunPod Flash GpuType member -> Vast-only. Cheaper than the
|
| 190 |
+
# 80 GB SXM H100 on the live market and carries 14 GB more VRAM, so it's a strong
|
| 191 |
+
# cost/VRAM pick for big-context GRPO tiers.
|
| 192 |
+
GpuClass(
|
| 193 |
+
"H100 NVL", None, 94, "h100nvl", "sm90", 2.39, validated_on=("vast",), vast_name="H100 NVL"
|
| 194 |
+
),
|
| 195 |
+
GpuClass(
|
| 196 |
+
"RTX Pro 6000",
|
| 197 |
+
"NVIDIA_RTX_PRO_6000_BLACKWELL_SERVER_EDITION",
|
| 198 |
+
96,
|
| 199 |
+
"pro6000",
|
| 200 |
+
"sm120",
|
| 201 |
+
2.09,
|
| 202 |
+
min_cuda_modern="13.0",
|
| 203 |
+
),
|
| 204 |
+
# RTX Pro 6000 Blackwell Workstation Edition: same 96 GB die as the Server Edition,
|
| 205 |
+
# a distinct RunPod GpuType, typically a touch cheaper. Also offered on Vast. The
|
| 206 |
+
# single biggest non-datacenter 96 GB option -> cheapest 80 GB-floor GRPO host.
|
| 207 |
+
GpuClass(
|
| 208 |
+
"RTX Pro 6000 WK",
|
| 209 |
+
"NVIDIA_RTX_PRO_6000_BLACKWELL_WORKSTATION_EDITION",
|
| 210 |
+
96,
|
| 211 |
+
"pro6000wk",
|
| 212 |
+
"sm120",
|
| 213 |
+
1.79,
|
| 214 |
+
validated_on=("runpod", "vast"),
|
| 215 |
+
min_cuda_modern="13.0",
|
| 216 |
+
vast_name="RTX PRO 6000",
|
| 217 |
+
),
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
GPU_INFO: dict[str, GpuClass] = {g.name: g for g in GPU_CLASSES}
|
| 221 |
+
|
| 222 |
+
# Canonical friendly names Flash exposes in configs / the catalog.
|
| 223 |
+
KNOWN = tuple(GPU_INFO)
|
| 224 |
+
# Classes proven by a live train+eval smoke (the default selection pool).
|
| 225 |
+
SUPPORTED = tuple(g.name for g in GPU_INFO.values() if g.validated)
|
| 226 |
+
|
| 227 |
+
# GPU-policy keywords accepted in ``gpu.type`` (resolved to a concrete class at parse
|
| 228 |
+
# time by ``resolve_gpu_policy``; the submit-time allocator re-resolves them live).
|
| 229 |
+
POLICY_NAMES = ("cheapest", "auto")
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def _alias_keys(name: str) -> set[str]:
|
| 233 |
+
"""All accepted spellings of a friendly name (lowercased)."""
|
| 234 |
+
base = name.lower()
|
| 235 |
+
keys = {base, base.replace(" ", ""), base.replace(" ", "_"), base.replace(" ", "-")}
|
| 236 |
+
if base.startswith("rtx "):
|
| 237 |
+
tail = base[4:]
|
| 238 |
+
keys |= {tail, tail.replace(" ", ""), tail.replace(" ", "_")}
|
| 239 |
+
keys.add(f"nvidia {base}")
|
| 240 |
+
return keys
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
_ALIASES: dict[str, str] = {}
|
| 244 |
+
for _info in GPU_INFO.values():
|
| 245 |
+
for _k in _alias_keys(_info.name):
|
| 246 |
+
_ALIASES[_k] = _info.name
|
| 247 |
+
# Spellings that don't fall out of the generic rules: full marketing names (what
|
| 248 |
+
# nvidia-smi / the RunPod API print) and historical Flash aliases.
|
| 249 |
+
_ALIASES.update(
|
| 250 |
+
{
|
| 251 |
+
"nvidia geforce rtx 4090": "RTX 4090",
|
| 252 |
+
"nvidia geforce rtx 5090": "RTX 5090",
|
| 253 |
+
"nvidia geforce rtx 3090": "RTX 3090",
|
| 254 |
+
"nvidia l4": "L4",
|
| 255 |
+
"nvidia a40": "A40",
|
| 256 |
+
"nvidia rtx 6000 ada generation": "RTX 6000 Ada",
|
| 257 |
+
"rtx 6000 ada generation": "RTX 6000 Ada",
|
| 258 |
+
"nvidia rtx 4000 ada generation": "RTX 4000 Ada",
|
| 259 |
+
"nvidia rtx 2000 ada generation": "RTX 2000 Ada",
|
| 260 |
+
"nvidia a100 80gb pcie": "A100 PCIe",
|
| 261 |
+
"a100 80gb pcie": "A100 PCIe",
|
| 262 |
+
"a100-80g-pcie": "A100 PCIe",
|
| 263 |
+
"nvidia a100-sxm4-80gb": "A100 SXM",
|
| 264 |
+
"a100-sxm4-80gb": "A100 SXM",
|
| 265 |
+
"a100": "A100 PCIe",
|
| 266 |
+
"nvidia h100 80gb hbm3": "H100",
|
| 267 |
+
"h100 80gb hbm3": "H100",
|
| 268 |
+
"rtx pro 6000 blackwell": "RTX Pro 6000",
|
| 269 |
+
"nvidia rtx pro 6000 blackwell server edition": "RTX Pro 6000",
|
| 270 |
+
}
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
class UnsupportedGpuError(ValueError):
|
| 275 |
+
pass
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def canonical_gpu(name: str) -> str:
|
| 279 |
+
"""Normalize a friendly GPU name to one of ``KNOWN``; raise otherwise."""
|
| 280 |
+
key = (name or "").strip().lower()
|
| 281 |
+
if key in _ALIASES:
|
| 282 |
+
return _ALIASES[key]
|
| 283 |
+
raise UnsupportedGpuError(
|
| 284 |
+
f'unsupported gpu {name!r}; Flash manages {", ".join(KNOWN)} (or gpu.type = "cheapest")'
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def get_gpu_info(name: str) -> GpuClass:
|
| 289 |
+
return GPU_INFO[canonical_gpu(name)]
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def is_validated(name: str, provider: str | None = None) -> bool:
|
| 293 |
+
"""Validated on ``provider`` (when given) or on any provider (provider=None)."""
|
| 294 |
+
info = get_gpu_info(name)
|
| 295 |
+
if provider is None or provider == "auto":
|
| 296 |
+
return info.validated
|
| 297 |
+
return provider in info.validated_on
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def providers_for(name: str) -> tuple[str, ...]:
|
| 301 |
+
"""Providers that can provision this GPU class."""
|
| 302 |
+
info = get_gpu_info(name)
|
| 303 |
+
out = []
|
| 304 |
+
if info.enum_member:
|
| 305 |
+
out.append("runpod")
|
| 306 |
+
if info.vast_name:
|
| 307 |
+
out.append("vast")
|
| 308 |
+
return tuple(out)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
# Boards under-report usable VRAM vs the class's nominal size (measured live: L4
|
| 312 |
+
# offers carry 23034 MB for the 24 GB class, A40 offers 46068 MB for the 48 GB
|
| 313 |
+
# class — ~3 GB under), so class matching gets a tolerance. Safe at 3.5 GB: names
|
| 314 |
+
# shared across VRAM variants differ by >= 40 GB (A100 SXM4 40/80).
|
| 315 |
+
_VRAM_MATCH_TOLERANCE_GB = 3.5
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def vast_gpu_for_offer(gpu_name: str, gpu_ram_mb: float) -> str | None:
|
| 319 |
+
"""Map a Vast offer (``gpu_name`` + ``gpu_ram`` MB) to a canonical GPU class.
|
| 320 |
+
|
| 321 |
+
Returns None for anything not in the managed table — that's the hard Ampere+
|
| 322 |
+
floor (T4/2080 Ti/Quadro RTX offers never match). Names shared across VRAM
|
| 323 |
+
variants (A100 SXM4 40/80 GB) resolve to the largest class the board's actual
|
| 324 |
+
RAM covers.
|
| 325 |
+
"""
|
| 326 |
+
fitting = [
|
| 327 |
+
g
|
| 328 |
+
for g in GPU_INFO.values()
|
| 329 |
+
if g.vast_name == gpu_name and g.vram_gb <= gpu_ram_mb / 1024 + _VRAM_MATCH_TOLERANCE_GB
|
| 330 |
+
]
|
| 331 |
+
if not fitting:
|
| 332 |
+
return None
|
| 333 |
+
return max(fitting, key=lambda g: g.vram_gb).name
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def unvalidated_allowed(explicit: bool | None = None) -> bool:
|
| 337 |
+
"""Whether configs may target a non-``validated`` GPU class — the per-run ``[gpu]
|
| 338 |
+
allow_unvalidated`` flag only (managed; no global env override)."""
|
| 339 |
+
return bool(explicit)
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def gpu_short(name: str) -> str:
|
| 343 |
+
"""Short, endpoint-name-safe token for a GPU (e.g. '4090')."""
|
| 344 |
+
return get_gpu_info(name).short
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def min_cuda_modern(name: str) -> str:
|
| 348 |
+
"""Minimum host CUDA (driver) version for this GPU class on the modern stack."""
|
| 349 |
+
return get_gpu_info(name).min_cuda_modern or "12.8"
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def cheapest_gpu(min_vram_gb: int, include_unvalidated: bool = False) -> str:
|
| 353 |
+
"""Cheapest RunPod GPU class with at least ``min_vram_gb`` VRAM (live rates, cached).
|
| 354 |
+
|
| 355 |
+
RunPod-static by design (the cross-provider equivalent lives in
|
| 356 |
+
``flash.providers.allocator``): Vast-only classes are excluded so the result is
|
| 357 |
+
always deployable via Flash, and offline resolution stays deterministic.
|
| 358 |
+
"""
|
| 359 |
+
pool = [
|
| 360 |
+
g
|
| 361 |
+
for g in GPU_INFO.values()
|
| 362 |
+
if g.enum_member
|
| 363 |
+
and g.vram_gb >= min_vram_gb
|
| 364 |
+
and (include_unvalidated or "runpod" in g.validated_on)
|
| 365 |
+
]
|
| 366 |
+
if not pool:
|
| 367 |
+
raise UnsupportedGpuError(
|
| 368 |
+
f"no {'known' if include_unvalidated else 'validated'} GPU has >= {min_vram_gb} GB VRAM"
|
| 369 |
+
)
|
| 370 |
+
from flash.providers.runpod.pricing import hourly_rate
|
| 371 |
+
|
| 372 |
+
return min(pool, key=lambda g: (hourly_rate(g.name), g.vram_gb)).name
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def resolve_gpu_policy(
|
| 376 |
+
requested: str,
|
| 377 |
+
model_id: str,
|
| 378 |
+
allow_unvalidated: bool | None = None,
|
| 379 |
+
algorithm: str = "sft",
|
| 380 |
+
*,
|
| 381 |
+
train=None,
|
| 382 |
+
thinking: bool = False,
|
| 383 |
+
) -> str:
|
| 384 |
+
"""Resolve ``gpu.type`` (a concrete class or a policy word) to a friendly name.
|
| 385 |
+
|
| 386 |
+
Parse-time, RunPod-static provisional: "cheapest"/"auto" pick the cheapest
|
| 387 |
+
RunPod-validated class whose VRAM covers the model; concrete names are
|
| 388 |
+
canonicalized. The submit-time allocator (``flash.providers.allocator``)
|
| 389 |
+
re-resolves policy words live across providers.
|
| 390 |
+
"""
|
| 391 |
+
key = (requested or "").strip().lower()
|
| 392 |
+
if key not in POLICY_NAMES:
|
| 393 |
+
return canonical_gpu(requested)
|
| 394 |
+
from flash.engine.vram import model_required_vram_gb
|
| 395 |
+
from flash.providers.allocator import vram_headroom
|
| 396 |
+
|
| 397 |
+
# Honor FLASH_VRAM_HEADROOM here too so parse-time sizing matches the submit-time
|
| 398 |
+
# allocator exactly (PR #176 review: they previously diverged on the headroom knob).
|
| 399 |
+
min_vram = model_required_vram_gb(
|
| 400 |
+
model_id, algorithm, train=train, thinking=thinking, headroom=vram_headroom()
|
| 401 |
+
)
|
| 402 |
+
return cheapest_gpu(min_vram, include_unvalidated=unvalidated_allowed(allow_unvalidated))
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
# ---------------------------------------------------------------------------
|
| 406 |
+
# Handles + poll outcomes (round-tripped through any provider)
|
| 407 |
+
# ---------------------------------------------------------------------------
|
| 408 |
+
@dataclass
|
| 409 |
+
class JobHandle:
|
| 410 |
+
"""Provider-tagged, persisted handle: enough to reattach/cancel from any process.
|
| 411 |
+
|
| 412 |
+
Each provider owns the rest of its handle shape (RunPod: endpoint_id/job_id; Vast:
|
| 413 |
+
instance_id/offer_id/...). ``provider`` is the routing key the orchestrator uses to
|
| 414 |
+
dispatch poll/cancel/destroy generically through the registry.
|
| 415 |
+
"""
|
| 416 |
+
|
| 417 |
+
provider: str
|
| 418 |
+
data: dict = field(default_factory=dict)
|
| 419 |
+
|
| 420 |
+
def to_dict(self) -> dict:
|
| 421 |
+
return {"provider": self.provider, **self.data}
|
| 422 |
+
|
| 423 |
+
@classmethod
|
| 424 |
+
def from_dict(cls, d: dict) -> JobHandle:
|
| 425 |
+
d = dict(d)
|
| 426 |
+
provider = d.pop("provider", "runpod")
|
| 427 |
+
return cls(provider=provider, data=d)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
@dataclass
|
| 431 |
+
class PollResult:
|
| 432 |
+
ok: bool
|
| 433 |
+
metrics: dict | None = None
|
| 434 |
+
failure: str | None = None # "job_failed" | "stalled" | "poll_error"
|
| 435 |
+
detail: str | None = None
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
# ---------------------------------------------------------------------------
|
| 439 |
+
# Allocation result (cross-provider)
|
| 440 |
+
# ---------------------------------------------------------------------------
|
| 441 |
+
@dataclass(frozen=True)
|
| 442 |
+
class Candidate:
|
| 443 |
+
provider: str
|
| 444 |
+
gpu: str
|
| 445 |
+
hourly_usd: float
|
| 446 |
+
vram_gb: int
|
| 447 |
+
validated: bool
|
| 448 |
+
# Opaque per-provider provisioning hint (e.g. the chosen Vast offer). The
|
| 449 |
+
# allocator stays provider-agnostic; the provider interprets it at submit time.
|
| 450 |
+
offer: Any = None
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
@dataclass(frozen=True)
|
| 454 |
+
class Allocation:
|
| 455 |
+
provider: str
|
| 456 |
+
gpu: str
|
| 457 |
+
hourly_usd: float
|
| 458 |
+
min_vram_gb: int
|
| 459 |
+
candidates: tuple[Candidate, ...] # full ranked list (retry walks this)
|
| 460 |
+
offer: Any = None # the chosen provider's provisioning hint (vast offer | None)
|
| 461 |
+
# Per-provider book of provisioning hints for the live-market walk (vast offers).
|
| 462 |
+
provider_offers: tuple[Any, ...] = ()
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
# ---------------------------------------------------------------------------
|
| 466 |
+
# The provider interface (FIXED method set both providers implement)
|
| 467 |
+
# ---------------------------------------------------------------------------
|
| 468 |
+
@runtime_checkable
|
| 469 |
+
class Provider(Protocol):
|
| 470 |
+
"""The pluggable GPU-substrate interface.
|
| 471 |
+
|
| 472 |
+
Both ``providers/runpod`` and ``providers/vast`` expose ``PROVIDER`` implementing
|
| 473 |
+
this protocol with an identical module layout (api/auth/pricing/gpus/jobs/
|
| 474 |
+
train/preflight). The orchestrator/allocator only ever talk to these methods, so a
|
| 475 |
+
provider is swappable without touching the control plane.
|
| 476 |
+
"""
|
| 477 |
+
|
| 478 |
+
name: str
|
| 479 |
+
|
| 480 |
+
def is_configured(self) -> bool:
|
| 481 |
+
"""Whether this provider is usable right now (creds present, net reachable)."""
|
| 482 |
+
...
|
| 483 |
+
|
| 484 |
+
def preflight(self, require_hf: bool = True) -> list[str]:
|
| 485 |
+
"""Missing-config problems (empty list == ready). The control plane aggregates
|
| 486 |
+
these into one fail-fast error at startup."""
|
| 487 |
+
...
|
| 488 |
+
|
| 489 |
+
def gpu_classes(self) -> list[GpuClass]:
|
| 490 |
+
"""The GPU classes this provider can provision (its rows of the shared table)."""
|
| 491 |
+
...
|
| 492 |
+
|
| 493 |
+
def hourly_rate(self, gpu: str) -> float:
|
| 494 |
+
"""$/hr for one friendly GPU name (live if available, else static)."""
|
| 495 |
+
...
|
| 496 |
+
|
| 497 |
+
def submit_run(
|
| 498 |
+
self,
|
| 499 |
+
spec: JobSpec,
|
| 500 |
+
seed: int,
|
| 501 |
+
*,
|
| 502 |
+
log: Any = None,
|
| 503 |
+
on_handle: Any = None,
|
| 504 |
+
attempt: int = 0,
|
| 505 |
+
offers: Any = None,
|
| 506 |
+
exclude_machine_ids: Any = frozenset(),
|
| 507 |
+
) -> PollResult:
|
| 508 |
+
"""Deploy/rent -> submit -> persist handle (via ``on_handle``) -> poll.
|
| 509 |
+
|
| 510 |
+
``exclude_machine_ids`` is the run's blacklist (machines that already failed
|
| 511 |
+
this run); a provider that re-searches the live market mid-submit (Vast) must
|
| 512 |
+
keep them excluded so a stalled/sick machine is never re-picked. RunPod ignores
|
| 513 |
+
it (no in-provider market re-search)."""
|
| 514 |
+
...
|
| 515 |
+
|
| 516 |
+
def poll(self, handle: JobHandle, spec: JobSpec, seed: int, *, log: Any = None) -> PollResult:
|
| 517 |
+
"""Reattach to a persisted handle and poll it to a terminal state."""
|
| 518 |
+
...
|
| 519 |
+
|
| 520 |
+
def cancel(self, handle: JobHandle) -> None:
|
| 521 |
+
"""Stop the exact remote worker for this handle (cross-process)."""
|
| 522 |
+
...
|
| 523 |
+
|
| 524 |
+
def destroy(self, handle: JobHandle) -> None:
|
| 525 |
+
"""Tear down the billable resource this handle owns (idempotent)."""
|
| 526 |
+
...
|
| 527 |
+
|
| 528 |
+
def gc(self, spec: JobSpec) -> None:
|
| 529 |
+
"""Best-effort: reap any resource this run may have left registered."""
|
| 530 |
+
...
|
| 531 |
+
|
| 532 |
+
def sweep_orphans(self, active_labels: set[str] | None = None) -> list[int]:
|
| 533 |
+
"""Destroy any billable resource this provider owns that no live run claims.
|
| 534 |
+
|
| 535 |
+
Crash recovery: run at server startup (and after runs). ``active_labels`` is the
|
| 536 |
+
set of instance-label PREFIXES still owned by recoverable runs — anything this
|
| 537 |
+
provider rented that matches none of them is an orphan. Returns the destroyed
|
| 538 |
+
resource ids. Providers without a standing-billing substrate (RunPod's
|
| 539 |
+
serverless endpoints self-reap) implement this as a no-op."""
|
| 540 |
+
...
|
code/flash/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 ``flash.providers.<name>.preflight``.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
+
from flash.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 flash.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 Flash control plane is missing required operator configuration:\n"
|
| 78 |
+
+ "\n".join(problems)
|
| 79 |
+
+ "\n\nSet these on the control-plane host."
|
| 80 |
+
)
|
code/flash/providers/runpod/__init__.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RunPod Flash provider: managed, serverless GPUs (no Docker) for Flash.
|
| 2 |
+
|
| 3 |
+
Fine-tuning runs on a dedicated RunPod GPU provisioned by Flash. A decorated Python
|
| 4 |
+
handler (``train._train_body``) executes ``flash.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 flash.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 flash.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 flash.providers.runpod.gpus import gpu_classes
|
| 39 |
+
|
| 40 |
+
return gpu_classes()
|
| 41 |
+
|
| 42 |
+
def hourly_rate(self, gpu: str) -> float:
|
| 43 |
+
from flash.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 flash.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 flash.providers.runpod.jobs import JobHandle as RunpodJobHandle
|
| 67 |
+
from flash.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 flash.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 flash.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 flash.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/flash/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 flash.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: ~/.flash/config.json holds the *Flash* 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/flash/providers/runpod/auth.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 Flash
|
| 6 |
+
key. Deliberately env-only: ``~/.flash/config.json`` holds the *Flash* key, which
|
| 7 |
+
must never be mistaken for a RunPod key.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
from .._auth import ensure_provider_auth, load_provider_key
|
| 13 |
+
|
| 14 |
+
_ENV_VAR = "RUNPOD_API_KEY"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def load_api_key() -> str | None:
|
| 18 |
+
"""API key from the environment (operator configuration)."""
|
| 19 |
+
return load_provider_key(_ENV_VAR)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def ensure_auth() -> str:
|
| 23 |
+
"""Ensure ``RUNPOD_API_KEY`` is set; raise if unavailable."""
|
| 24 |
+
return ensure_provider_auth(_ENV_VAR, "no RunPod API key found; set RUNPOD_API_KEY on the control-plane host")
|
code/flash/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 flash.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 flash.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/flash/providers/runpod/jobs.py
ADDED
|
@@ -0,0 +1,519 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 flash._logging import get_logger
|
| 26 |
+
from flash.providers._poll import PollErrorTracker, make_say, surface_heartbeat
|
| 27 |
+
from flash.providers.base import PollResult, canonical_gpu
|
| 28 |
+
from flash.providers.runpod import api as runpod_api
|
| 29 |
+
from flash.providers.runpod.gpus import flash_gpu
|
| 30 |
+
from flash.providers.runpod.train import (
|
| 31 |
+
DEFAULT_EXECUTION_TIMEOUT_MS,
|
| 32 |
+
FLASH_SDK_LOCK,
|
| 33 |
+
WORKER_IMAGE,
|
| 34 |
+
WORKER_SYSTEM_DEPS,
|
| 35 |
+
_patch_runpod_backoff,
|
| 36 |
+
_train_body,
|
| 37 |
+
endpoint_name,
|
| 38 |
+
isolate_flash_state,
|
| 39 |
+
min_cuda_for,
|
| 40 |
+
resolve_worker_deps,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
logger = get_logger(__name__)
|
| 44 |
+
|
| 45 |
+
# Re-export so callers/tests that did ``from ...jobs import PollResult`` keep working.
|
| 46 |
+
__all__ = [
|
| 47 |
+
"JobHandle",
|
| 48 |
+
"PollResult",
|
| 49 |
+
"apply_disk_gb",
|
| 50 |
+
"build_function_input",
|
| 51 |
+
"decode_output",
|
| 52 |
+
"deploy_train_endpoint",
|
| 53 |
+
"make_hf_heartbeat_reader",
|
| 54 |
+
"make_hf_text_reader",
|
| 55 |
+
"poll_job",
|
| 56 |
+
"submit_run",
|
| 57 |
+
"volume_endpoint_kwargs",
|
| 58 |
+
]
|
| 59 |
+
|
| 60 |
+
TERMINAL_OK = {"COMPLETED"}
|
| 61 |
+
TERMINAL_FAIL = {"FAILED", "CANCELLED", "TIMED_OUT"}
|
| 62 |
+
|
| 63 |
+
# Heartbeat stages the worker emits DURING cold start, BEFORE the model is loaded and the
|
| 64 |
+
# training loop begins (boot -> sft_start/rl_start, then later sft_model_load/rl_train_start).
|
| 65 |
+
# Receiving one proves the worker is alive but NOT that the slow setup (model download +
|
| 66 |
+
# vLLM init) finished, so they must not flip stall detection to the tight training window.
|
| 67 |
+
_SETUP_HEARTBEAT_STAGES = frozenset(
|
| 68 |
+
{"boot", "sft_start", "rl_start", "sft_model_load", "rl_train_start"}
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def stall_kwargs() -> dict:
|
| 73 |
+
"""``poll_job`` stall-window kwargs, shared by the submit and reattach paths so a recovered
|
| 74 |
+
run uses the same tuning as the original submit. ``stall_after_s`` = post-training-heartbeat
|
| 75 |
+
window; ``setup_grace_s`` = the larger cold-start window before the first training heartbeat.
|
| 76 |
+
"""
|
| 77 |
+
return {"stall_after_s": 1500.0, "setup_grace_s": 3000.0}
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def volume_endpoint_kwargs(spec) -> dict:
|
| 81 |
+
"""Endpoint kwargs for the OPT-IN persistent network volume (cross-run HF cache).
|
| 82 |
+
|
| 83 |
+
Returns {} unless ``gpu.network_volume`` is set. The volume pins the endpoint to
|
| 84 |
+
one datacenter (``gpu.datacenter``, default EU-RO-1 — the SDK's storage default),
|
| 85 |
+
which shrinks the available GPU pool; that trade-off is why this is opt-in.
|
| 86 |
+
"""
|
| 87 |
+
nv = getattr(spec.gpu, "network_volume", None) if spec is not None else None
|
| 88 |
+
if not nv:
|
| 89 |
+
return {}
|
| 90 |
+
from runpod_flash import NetworkVolume
|
| 91 |
+
from runpod_flash.core.resources.datacenter import DataCenter
|
| 92 |
+
|
| 93 |
+
dc = DataCenter.from_string(spec.gpu.datacenter) if spec.gpu.datacenter else None
|
| 94 |
+
volume = NetworkVolume(
|
| 95 |
+
name=str(nv),
|
| 96 |
+
size=int(getattr(spec.gpu, "network_volume_gb", 100) or 100),
|
| 97 |
+
**({"datacenter": dc} if dc else {}),
|
| 98 |
+
)
|
| 99 |
+
kwargs: dict = {"volume": volume}
|
| 100 |
+
if dc:
|
| 101 |
+
kwargs["datacenter"] = dc
|
| 102 |
+
return kwargs
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def apply_disk_gb(config, disk_gb: int | None) -> None:
|
| 106 |
+
"""Raise the worker's container disk on a built endpoint config.
|
| 107 |
+
|
| 108 |
+
The Flash SDK's ``PodTemplate.containerDiskInGb`` defaults to 64 GB and the
|
| 109 |
+
``Endpoint`` wrapper exposes no disk knob, which is what blocked models whose
|
| 110 |
+
checkpoint alone exceeds 64 GB. The template
|
| 111 |
+
is already populated by the SDK's validators when the resource config is built, so
|
| 112 |
+
raising the field here is the supported injection point. Raise-only: shrinking
|
| 113 |
+
below the SDK default buys nothing (serverless disk isn't billed separately) and
|
| 114 |
+
would regress runs whose configs carry the historical ``disk_gb = 60`` default.
|
| 115 |
+
"""
|
| 116 |
+
if not disk_gb:
|
| 117 |
+
return
|
| 118 |
+
template = getattr(config, "template", None)
|
| 119 |
+
if template is None:
|
| 120 |
+
logger.warning("disk_gb=%s requested but endpoint config has no template", disk_gb)
|
| 121 |
+
return
|
| 122 |
+
template.containerDiskInGb = max(int(disk_gb), int(template.containerDiskInGb or 0))
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@dataclass
|
| 126 |
+
class JobHandle:
|
| 127 |
+
endpoint_id: str
|
| 128 |
+
endpoint_name: str
|
| 129 |
+
job_id: str
|
| 130 |
+
|
| 131 |
+
def to_dict(self) -> dict:
|
| 132 |
+
return {
|
| 133 |
+
"provider": "runpod",
|
| 134 |
+
"endpoint_id": self.endpoint_id,
|
| 135 |
+
"endpoint_name": self.endpoint_name,
|
| 136 |
+
"job_id": self.job_id,
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
@classmethod
|
| 140 |
+
def from_dict(cls, d: dict) -> JobHandle:
|
| 141 |
+
# `provider` is routing metadata consumed upstream (runner); handles
|
| 142 |
+
# persisted before it existed default to runpod there.
|
| 143 |
+
return cls(d["endpoint_id"], d.get("endpoint_name", ""), d["job_id"])
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def deploy_train_endpoint(
|
| 147 |
+
friendly_gpu: str,
|
| 148 |
+
execution_timeout_ms: int | None = None,
|
| 149 |
+
name_suffix: str | None = None,
|
| 150 |
+
disk_gb: int | None = None,
|
| 151 |
+
spec=None,
|
| 152 |
+
) -> tuple[str, str]:
|
| 153 |
+
"""Deploy (or reuse) the run's uniquely-named worker endpoint; return (id, name)."""
|
| 154 |
+
os.environ["FLASH_IS_LIVE_PROVISIONING"] = "true"
|
| 155 |
+
from runpod_flash import Endpoint
|
| 156 |
+
|
| 157 |
+
from flash.providers.runpod.auth import ensure_auth
|
| 158 |
+
|
| 159 |
+
ensure_auth()
|
| 160 |
+
_patch_runpod_backoff()
|
| 161 |
+
friendly = canonical_gpu(friendly_gpu)
|
| 162 |
+
name = endpoint_name(friendly, name_suffix)
|
| 163 |
+
# The baked WORKER_IMAGE is now a self-contained RunPod Serverless worker (its CMD runs
|
| 164 |
+
# rp_handler.py, which reads job["input"] and runs the training) — deploy it directly (Flash
|
| 165 |
+
# "client mode"). build_function_input then sends the payload as the job input. FLASH_WORKER_IMAGE
|
| 166 |
+
# overrides the baked image (e.g. a hotfix tag); since WORKER_IMAGE is a non-empty constant the
|
| 167 |
+
# image is always set, so the boot-install/live-function path is only reachable if both are
|
| 168 |
+
# explicitly cleared (not a normal configuration).
|
| 169 |
+
image = os.environ.get("FLASH_WORKER_IMAGE") or 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 |
+
gpu_count=1,
|
| 182 |
+
min_cuda_version=min_cuda_for(friendly),
|
| 183 |
+
execution_timeout_ms=execution_timeout_ms or DEFAULT_EXECUTION_TIMEOUT_MS,
|
| 184 |
+
workers=(0, 1),
|
| 185 |
+
**volume_endpoint_kwargs(spec),
|
| 186 |
+
)
|
| 187 |
+
if image:
|
| 188 |
+
kwargs["image"] = image
|
| 189 |
+
else:
|
| 190 |
+
# Pass the resolved GPU so Hopper (sm90) gets its fla-drop treatment (resolve_worker_deps
|
| 191 |
+
# is GPU-scoped); a bare call would ship the generic deps and run fla's #640-buggy GDN
|
| 192 |
+
# Triton kernel on an H100 instead of the correct pure-PyTorch delta rule.
|
| 193 |
+
kwargs["dependencies"] = resolve_worker_deps(friendly)
|
| 194 |
+
kwargs["system_dependencies"] = WORKER_SYSTEM_DEPS
|
| 195 |
+
ep = Endpoint(**kwargs)
|
| 196 |
+
ep._qb_target = _train_body
|
| 197 |
+
config = ep._build_resource_config()
|
| 198 |
+
apply_disk_gb(config, disk_gb)
|
| 199 |
+
# Worker image is PUBLIC, so no container-registry credential is needed to pull it.
|
| 200 |
+
rm = ResourceManager()
|
| 201 |
+
resource = asyncio.run(rm.get_or_deploy_resource(config))
|
| 202 |
+
endpoint_id = getattr(resource, "id", None)
|
| 203 |
+
if not endpoint_id:
|
| 204 |
+
raise RuntimeError(f"deploy_train_endpoint: no endpoint id on resource {resource!r}")
|
| 205 |
+
return endpoint_id, name
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def build_function_input(payload: dict, friendly_gpu: str | None = None) -> dict:
|
| 209 |
+
"""The FunctionRequest dict a Flash queue worker expects for `_train_body(payload)`.
|
| 210 |
+
|
| 211 |
+
``friendly_gpu`` is threaded into ``resolve_worker_deps`` so the request-level dependency
|
| 212 |
+
list is GPU-scoped exactly like the endpoint config (deploy_train_endpoint): on Hopper (sm90)
|
| 213 |
+
it must drop ``flash-linear-attention`` so the worker uses the pure-PyTorch delta rule instead
|
| 214 |
+
of fla's #640-buggy GDN Triton kernel. A bare call would reinstall the generic deps and
|
| 215 |
+
reintroduce that sm90 correctness issue even when the endpoint was configured correctly.
|
| 216 |
+
"""
|
| 217 |
+
if os.environ.get("FLASH_WORKER_IMAGE") or WORKER_IMAGE:
|
| 218 |
+
# Baked serverless-worker image (client mode): the image's rp_handler reads job["input"]
|
| 219 |
+
# and calls _train_body, so the job input IS the train payload (submit_job wraps it in
|
| 220 |
+
# {"input": ...}). No live-function source, no boot-install deps.
|
| 221 |
+
return payload
|
| 222 |
+
# Boot-install fallback (Flash default image + live function): ship _train_body's source for the
|
| 223 |
+
# generic worker to run, plus the GPU-scoped deps to install on first use (drops fla on Hopper).
|
| 224 |
+
from runpod_flash.runtime.serialization import serialize_args
|
| 225 |
+
from runpod_flash.stubs.live_serverless import get_function_source
|
| 226 |
+
|
| 227 |
+
source, _src_hash = get_function_source(_train_body)
|
| 228 |
+
return {
|
| 229 |
+
"function_name": "_train_body",
|
| 230 |
+
"function_code": source,
|
| 231 |
+
"args": serialize_args((payload,)),
|
| 232 |
+
"accelerate_downloads": True,
|
| 233 |
+
"dependencies": resolve_worker_deps(canonical_gpu(friendly_gpu) if friendly_gpu else None),
|
| 234 |
+
"system_dependencies": WORKER_SYSTEM_DEPS,
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def decode_output(output) -> dict:
|
| 239 |
+
"""Decode a queue-job output into the worker's metrics dict. Handles BOTH job shapes:
|
| 240 |
+
|
| 241 |
+
- Flash LIVE-function (boot-install path): a FunctionResponse envelope
|
| 242 |
+
``{"success": True, "result": <base64 cloudpickle of the dict>}``.
|
| 243 |
+
- Client-mode SERVERLESS handler (baked-image path): our baked rp_handler returns
|
| 244 |
+
``_train_body(...)``'s metrics dict, which RunPod surfaces as ``job["output"]`` directly —
|
| 245 |
+
no envelope. The metrics dict has no ``success``/``result`` keys, so we return it as-is.
|
| 246 |
+
"""
|
| 247 |
+
if isinstance(output, str):
|
| 248 |
+
try:
|
| 249 |
+
output = json.loads(output)
|
| 250 |
+
except json.JSONDecodeError as exc:
|
| 251 |
+
raise RuntimeError(f"unexpected job output: {output[:200]}") from exc
|
| 252 |
+
if not isinstance(output, dict):
|
| 253 |
+
raise RuntimeError(f"unexpected job output type: {type(output)}")
|
| 254 |
+
# Flash live-function envelope (has success/result/error keys).
|
| 255 |
+
if "success" in output or "result" in output:
|
| 256 |
+
if output.get("success") and output.get("result") is not None:
|
| 257 |
+
import cloudpickle
|
| 258 |
+
|
| 259 |
+
result = cloudpickle.loads(base64.b64decode(output["result"]))
|
| 260 |
+
if not isinstance(result, dict):
|
| 261 |
+
raise RuntimeError(f"flash job returned no metrics: {result!r}")
|
| 262 |
+
return result
|
| 263 |
+
err = output.get("error") or "unknown worker error"
|
| 264 |
+
stdout_tail = (output.get("stdout") or "")[-1500:]
|
| 265 |
+
raise RuntimeError(
|
| 266 |
+
f"Remote execution failed: {err}\n--- worker stdout tail ---\n{stdout_tail}"
|
| 267 |
+
)
|
| 268 |
+
# Client-mode serverless handler: the metrics dict IS the output (baked rp_handler).
|
| 269 |
+
if output.get("error"):
|
| 270 |
+
# Mirror the Flash path: append the worker stdout tail when present so poll_job's
|
| 271 |
+
# root-cause diagnostics (e.g. a vLLM crash) survive the client-mode failure shape too.
|
| 272 |
+
stdout_tail = (output.get("stdout") or "")[-1500:]
|
| 273 |
+
msg = f"Remote execution failed: {output['error']}"
|
| 274 |
+
if stdout_tail:
|
| 275 |
+
msg += f"\n--- worker stdout tail ---\n{stdout_tail}"
|
| 276 |
+
raise RuntimeError(msg)
|
| 277 |
+
return output
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def poll_job(
|
| 281 |
+
handle: JobHandle,
|
| 282 |
+
log=None,
|
| 283 |
+
interval_s: float = 10.0,
|
| 284 |
+
heartbeat_reader=None,
|
| 285 |
+
stall_after_s: float = 1200.0,
|
| 286 |
+
setup_grace_s: float = 3000.0,
|
| 287 |
+
unhealthy_grace_s: float = 240.0,
|
| 288 |
+
deadline_s: float | None = None,
|
| 289 |
+
) -> PollResult:
|
| 290 |
+
"""Poll a queue job to completion; resilient to transient API errors.
|
| 291 |
+
|
| 292 |
+
Two stall windows: the cold-start phase (dep install, per-run env pip, model download,
|
| 293 |
+
vLLM init) is slow and only emits *setup* heartbeats (``_SETUP_HEARTBEAT_STAGES``).
|
| 294 |
+
Until a *training* heartbeat arrives we apply the larger ``setup_grace_s`` budget so a
|
| 295 |
+
slow cold start isn't misread as a stall; after it we use the tight ``stall_after_s``.
|
| 296 |
+
Needs a ``heartbeat_reader`` to tell the phases apart — without one we keep
|
| 297 |
+
``stall_after_s`` throughout (no regression).
|
| 298 |
+
"""
|
| 299 |
+
|
| 300 |
+
say = make_say(log)
|
| 301 |
+
poll_errors = PollErrorTracker(say, interval_s)
|
| 302 |
+
|
| 303 |
+
start = time.time()
|
| 304 |
+
last_status = None
|
| 305 |
+
last_hb_key = None
|
| 306 |
+
last_progress = time.time()
|
| 307 |
+
seen_heartbeat = False
|
| 308 |
+
last_health_probe = 0.0
|
| 309 |
+
unhealthy_since: float | None = None # first time the worker was seen stuck UNHEALTHY
|
| 310 |
+
while True:
|
| 311 |
+
if deadline_s is not None and time.time() - start > deadline_s:
|
| 312 |
+
return PollResult(False, failure="stalled", detail="client-side deadline exceeded")
|
| 313 |
+
try:
|
| 314 |
+
st = runpod_api.job_status(handle.endpoint_id, handle.job_id)
|
| 315 |
+
poll_errors.reset()
|
| 316 |
+
except runpod_api.RunpodApiError as e:
|
| 317 |
+
if poll_errors.record(e):
|
| 318 |
+
return PollResult(False, failure="poll_error", detail=str(e))
|
| 319 |
+
continue
|
| 320 |
+
status = st.get("status")
|
| 321 |
+
if status != last_status:
|
| 322 |
+
say(f"job {handle.job_id}: {status}")
|
| 323 |
+
last_status = status
|
| 324 |
+
last_progress = time.time()
|
| 325 |
+
if status in TERMINAL_OK:
|
| 326 |
+
try:
|
| 327 |
+
return PollResult(True, metrics=decode_output(st.get("output")))
|
| 328 |
+
except RuntimeError as e:
|
| 329 |
+
return PollResult(False, failure="job_failed", detail=str(e))
|
| 330 |
+
if status in TERMINAL_FAIL:
|
| 331 |
+
detail = str(st.get("error") or "")[:1500]
|
| 332 |
+
out = st.get("output")
|
| 333 |
+
if isinstance(out, dict) and out.get("stdout"):
|
| 334 |
+
# Worker stdout tail is the only place the REAL root cause lives for
|
| 335 |
+
# crashes inside subprocesses (e.g. vLLM EngineCore deaths).
|
| 336 |
+
detail += "\n--- worker stdout tail ---\n" + str(out["stdout"])[-2000:]
|
| 337 |
+
elif not detail:
|
| 338 |
+
detail = str(out)[:1500]
|
| 339 |
+
# Prefix the terminal status so the runner's infra-retry markers
|
| 340 |
+
# (e.g. TIMED_OUT) match even when RunPod sets no error/output text.
|
| 341 |
+
return PollResult(False, failure="job_failed", detail=f"[{status}] {detail}")
|
| 342 |
+
# While queued, surface worker availability (throttled hosts are the common
|
| 343 |
+
# cause of silent multi-minute waits — make them visible in the run log).
|
| 344 |
+
if status == "IN_QUEUE" and time.time() - last_health_probe > 90:
|
| 345 |
+
last_health_probe = time.time()
|
| 346 |
+
try:
|
| 347 |
+
h = runpod_api.endpoint_health(handle.endpoint_id)
|
| 348 |
+
workers = h.get("workers") or {}
|
| 349 |
+
usable = workers.get("running") or workers.get("ready") or workers.get("idle")
|
| 350 |
+
recovering = workers.get("initializing")
|
| 351 |
+
if any(workers.get(k) for k in ("throttled", "unhealthy", "initializing")) or not usable:
|
| 352 |
+
say(f"queued; workers: {workers}")
|
| 353 |
+
# Fail fast on a worker stuck UNHEALTHY: a dead worker / failed image pull won't
|
| 354 |
+
# self-recover, so don't burn the full setup_grace_s (~50 min) waiting on it — once
|
| 355 |
+
# it has stayed unhealthy with nothing usable or (re)initializing for
|
| 356 |
+
# unhealthy_grace_s, return a (retryable) stall so the runner re-provisions a FRESH
|
| 357 |
+
# endpoint (fresh image pull, likely a different host). Observed: a mutable image
|
| 358 |
+
# tag republished mid-pull corrupts the worker -> unhealthy, and a fresh pull fixes it.
|
| 359 |
+
if workers.get("unhealthy") and not usable and not recovering:
|
| 360 |
+
if unhealthy_since is None:
|
| 361 |
+
unhealthy_since = time.time()
|
| 362 |
+
elif time.time() - unhealthy_since > unhealthy_grace_s:
|
| 363 |
+
return PollResult(
|
| 364 |
+
False,
|
| 365 |
+
failure="stalled",
|
| 366 |
+
detail=f"worker stuck unhealthy for "
|
| 367 |
+
f"{int(time.time() - unhealthy_since)}s while IN_QUEUE (likely a failed "
|
| 368 |
+
f"image pull); retrying on a fresh endpoint",
|
| 369 |
+
)
|
| 370 |
+
else:
|
| 371 |
+
unhealthy_since = None # recovered / usable worker appeared
|
| 372 |
+
except Exception:
|
| 373 |
+
# Health surfacing is diagnostic only; a probe failure must not stop polling.
|
| 374 |
+
pass
|
| 375 |
+
# heartbeat progress surfacing + stall detection
|
| 376 |
+
new_key, stage = surface_heartbeat(heartbeat_reader, last_hb_key, say)
|
| 377 |
+
if new_key != last_hb_key:
|
| 378 |
+
last_hb_key = new_key
|
| 379 |
+
last_progress = time.time()
|
| 380 |
+
# Only a training-phase heartbeat means cold-start setup is done and we
|
| 381 |
+
# can switch to the tight window; setup heartbeats keep the grace budget.
|
| 382 |
+
if stage not in _SETUP_HEARTBEAT_STAGES:
|
| 383 |
+
seen_heartbeat = True
|
| 384 |
+
# Cold start (before any training-phase heartbeat) gets the larger setup_grace_s,
|
| 385 |
+
# but only when a heartbeat_reader lets us tell setup from training; without one we
|
| 386 |
+
# can't, so stay on stall_after_s (no regression).
|
| 387 |
+
in_setup = heartbeat_reader is not None and not seen_heartbeat
|
| 388 |
+
stall_limit = setup_grace_s if in_setup else stall_after_s
|
| 389 |
+
if time.time() - last_progress > stall_limit:
|
| 390 |
+
phase = "setup (pre-training)" if in_setup else "training"
|
| 391 |
+
return PollResult(
|
| 392 |
+
False,
|
| 393 |
+
failure="stalled",
|
| 394 |
+
detail=f"no worker progress for {int(time.time() - last_progress)}s "
|
| 395 |
+
f"during {phase} (job status {status}, limit {int(stall_limit)}s)",
|
| 396 |
+
)
|
| 397 |
+
time.sleep(interval_s)
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def submit_run(spec, seed: int, log=None, on_handle=None, attempt: int = 0) -> PollResult:
|
| 401 |
+
"""Durable equivalent of ``submit_train``: deploy, submit, persist handle, poll.
|
| 402 |
+
|
| 403 |
+
``on_handle(handle_dict)`` is invoked as soon as the job is queued so the
|
| 404 |
+
runner can persist {endpoint_id, job_id} for cross-process reattach.
|
| 405 |
+
"""
|
| 406 |
+
from flash.envs.registry import worker_hub_env_ids, worker_pip_for_env
|
| 407 |
+
from flash.providers.runpod.train import _run_suffix, build_worker_env, chalk_extra_pip
|
| 408 |
+
|
| 409 |
+
timeout_s = max(60, int(spec.gpu.max_wall_seconds))
|
| 410 |
+
# Per-attempt endpoint name: a retry must land on a genuinely fresh endpoint —
|
| 411 |
+
# reusing the name lets the SDK/platform pin the job back onto the same
|
| 412 |
+
# (possibly throttled/sick) host.
|
| 413 |
+
suffix = _run_suffix(spec.run_id)
|
| 414 |
+
if attempt:
|
| 415 |
+
suffix = f"{suffix}r{attempt}"
|
| 416 |
+
# Resolve the worker env BEFORE provisioning: an unrecorded Hub env raises here, and
|
| 417 |
+
# doing it after deploy_train_endpoint() would leak the just-created endpoint (its
|
| 418 |
+
# rN-suffixed name can't be reconstructed from the run id later) against the account
|
| 419 |
+
# quota — the runner would also treat the raise as a retryable poll_error.
|
| 420 |
+
# extra_pip runs for EVERY job here (the durable baked-image path skips resolve_worker_deps /
|
| 421 |
+
# FLASH_WORKER_EXTRA_DEPS in build_function_input, but _train_body always pip-installs
|
| 422 |
+
# extra_pip), so the opt-in chalk spec is appended here to reach default runs.
|
| 423 |
+
extra_pip = (
|
| 424 |
+
list(spec.environment.pip) or worker_pip_for_env(spec.environment.id)
|
| 425 |
+
) + chalk_extra_pip(spec)
|
| 426 |
+
worker_env = build_worker_env(spec, seed)
|
| 427 |
+
endpoint_id, name = deploy_train_endpoint(
|
| 428 |
+
spec.gpu.type,
|
| 429 |
+
execution_timeout_ms=timeout_s * 1000,
|
| 430 |
+
name_suffix=suffix,
|
| 431 |
+
disk_gb=spec.gpu.disk_gb,
|
| 432 |
+
spec=spec,
|
| 433 |
+
)
|
| 434 |
+
payload = {
|
| 435 |
+
"hf_repo": spec.train.hf_repo,
|
| 436 |
+
"job_spec_json": spec.to_json(),
|
| 437 |
+
"phase": spec.phase,
|
| 438 |
+
"seed": int(seed),
|
| 439 |
+
"env": worker_env,
|
| 440 |
+
"extra_pip": extra_pip,
|
| 441 |
+
"hub_env_ids": worker_hub_env_ids(spec.environment.id, spec.environment.params),
|
| 442 |
+
}
|
| 443 |
+
try:
|
| 444 |
+
job_id = runpod_api.submit_job(endpoint_id, build_function_input(payload, spec.gpu.type))
|
| 445 |
+
except Exception:
|
| 446 |
+
# The endpoint is registered but no run handle exists yet, and a
|
| 447 |
+
# retry endpoint's rN-suffixed name can't be reconstructed from the run
|
| 448 |
+
# id later — delete it now so a transient submit failure doesn't leak a
|
| 449 |
+
# serverless endpoint against the account quota.
|
| 450 |
+
with contextlib.suppress(Exception):
|
| 451 |
+
runpod_api.delete_endpoint(endpoint_id)
|
| 452 |
+
raise
|
| 453 |
+
handle = JobHandle(endpoint_id, name, job_id)
|
| 454 |
+
if log is not None:
|
| 455 |
+
print(
|
| 456 |
+
f"submitted job: endpoint={name} ({endpoint_id}) job={job_id} "
|
| 457 |
+
f"attempt={attempt} gpu={spec.gpu.type} phase={spec.phase} seed={seed}",
|
| 458 |
+
file=log,
|
| 459 |
+
flush=True,
|
| 460 |
+
)
|
| 461 |
+
if on_handle is not None:
|
| 462 |
+
on_handle(handle.to_dict())
|
| 463 |
+
hf_repo = spec.train.hf_repo
|
| 464 |
+
prefix = f"{spec.phase}/{spec.run_id}/seed{seed}"
|
| 465 |
+
reader = make_hf_heartbeat_reader(hf_repo, prefix) if hf_repo else None
|
| 466 |
+
return poll_job(handle, log=log, heartbeat_reader=reader, **stall_kwargs())
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def make_hf_text_reader(hf_repo: str, path_in_repo: str, min_interval_s: float = 45.0):
|
| 470 |
+
"""Rate-limited reader for one HF artifact's text content (None until it exists).
|
| 471 |
+
|
| 472 |
+
Generic helper shared by both providers' pollers (runpod heartbeats + vast's
|
| 473 |
+
DONE/metrics/error artifacts). ``read(force=False)`` re-downloads at most once per
|
| 474 |
+
``min_interval_s`` (``force=True`` bypasses the gate); it never raises — any HF error
|
| 475 |
+
(artifact absent, network) returns None.
|
| 476 |
+
"""
|
| 477 |
+
state = {"last": 0.0}
|
| 478 |
+
|
| 479 |
+
def read(force: bool = False) -> str | None:
|
| 480 |
+
if not hf_repo:
|
| 481 |
+
return None
|
| 482 |
+
if not force and time.time() - state["last"] < min_interval_s:
|
| 483 |
+
return None
|
| 484 |
+
state["last"] = time.time()
|
| 485 |
+
try:
|
| 486 |
+
from huggingface_hub import hf_hub_download
|
| 487 |
+
|
| 488 |
+
p = hf_hub_download(
|
| 489 |
+
hf_repo,
|
| 490 |
+
path_in_repo,
|
| 491 |
+
repo_type="dataset",
|
| 492 |
+
token=os.environ.get("HF_TOKEN"),
|
| 493 |
+
force_download=True,
|
| 494 |
+
)
|
| 495 |
+
with open(p) as f:
|
| 496 |
+
return f.read()
|
| 497 |
+
except Exception:
|
| 498 |
+
return None
|
| 499 |
+
|
| 500 |
+
return read
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def make_hf_heartbeat_reader(hf_repo: str, prefix: str, min_interval_s: float = 30.0):
|
| 504 |
+
"""Reader for the worker's heartbeat.json on HF (rate-limited, never raises).
|
| 505 |
+
|
| 506 |
+
Thin JSON-parsing wrapper over :func:`make_hf_text_reader` bound to ``{prefix}/heartbeat.json``.
|
| 507 |
+
"""
|
| 508 |
+
text_reader = make_hf_text_reader(hf_repo, f"{prefix}/heartbeat.json", min_interval_s)
|
| 509 |
+
|
| 510 |
+
def read() -> dict | None:
|
| 511 |
+
raw = text_reader()
|
| 512 |
+
if raw is None:
|
| 513 |
+
return None
|
| 514 |
+
try:
|
| 515 |
+
return json.loads(raw)
|
| 516 |
+
except (ValueError, TypeError):
|
| 517 |
+
return None
|
| 518 |
+
|
| 519 |
+
return read
|
code/flash/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 Flash 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 Flash key?", see flash/client).
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
+
from flash.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/flash/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 flash._logging import get_logger
|
| 22 |
+
|
| 23 |
+
logger = get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
CACHE_TTL_S = 6 * 3600.0 # 6h price cache
|
| 26 |
+
_CACHE_PATH = Path.home() / ".flash" / "gpu_rates.json"
|
| 27 |
+
_MEM: dict = {"ts": 0.0, "rates": {}}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _static_rates() -> dict[str, float]:
|
| 31 |
+
from flash.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 flash.providers.base import GPU_INFO
|
| 51 |
+
from flash.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: FLASH_SKIP_NET (or any fetch failure) returns the static rates.
|
| 73 |
+
"""
|
| 74 |
+
static = _static_rates()
|
| 75 |
+
if os.environ.get("FLASH_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 flash.providers.base import canonical_gpu
|
| 108 |
+
|
| 109 |
+
name = canonical_gpu(gpu_name)
|
| 110 |
+
return live_rates().get(name) or _static_rates()[name]
|
code/flash/providers/runpod/train.py
ADDED
|
@@ -0,0 +1,952 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 ``flash`` package from the HF dataset repo (uploaded by
|
| 8 |
+
``upload_code`` before submit), adds it to ``PYTHONPATH``, and runs
|
| 9 |
+
``flash.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 flash._logging import get_logger
|
| 23 |
+
from flash.providers.base import canonical_gpu, gpu_short
|
| 24 |
+
from flash.providers.runpod.gpus import flash_gpu
|
| 25 |
+
from flash.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 |
+
# NB: freesolo-chalk (custom Triton/CUDA kernels, install-on-call — calling an installer IS
|
| 83 |
+
# the opt-in; chalk reads NO env vars) is NOT baked in by default — it isn't on PyPI yet, and a
|
| 84 |
+
# bad/inaccessible spec here would abort worker boot. flash auto-detects chalk if present
|
| 85 |
+
# (flash/engine/chalk_kernels.py). To enable kernels on a DEFAULT remote run: set the per-kernel
|
| 86 |
+
# FLASH_* selection flags (FLASH_MLP_KERNEL, FLASH_FP8_BASE, FLASH_TRITON_LORA, ...) AND set
|
| 87 |
+
# FLASH_CHALK_SPEC to an installable chalk spec (a git URL with access, or a wheel). The submit
|
| 88 |
+
# path (chalk_extra_pip) then appends that spec to the worker's `extra_pip`, which the worker
|
| 89 |
+
# pip-installs for EVERY job (baked-image RunPod _train_body + Vast bootstrap). Do NOT rely on
|
| 90 |
+
# FLASH_WORKER_EXTRA_DEPS / FLASH_WORKER_DEPS for this: the durable baked-image submit path
|
| 91 |
+
# (jobs.build_function_input) returns the raw payload and never consults resolve_worker_deps, so
|
| 92 |
+
# those vars don't reach a default run; and FLASH_WORKER_DEPS would also REPLACE the whole stack.
|
| 93 |
+
]
|
| 94 |
+
# NOTE on download speed: Flash's runtime already ships hf_transfer and exports
|
| 95 |
+
# HF_HUB_ENABLE_HF_TRANSFER=1 on workers (measured: Qwen3-4B's ~8 GB pulled in 6.3 s,
|
| 96 |
+
# NIC-saturated — bench/results/phase6). Adding hf_transfer here is redundant; don't.
|
| 97 |
+
# Override the whole pinned stack per-run with FLASH_WORKER_DEPS="pkgA==1 pkgB>=2"
|
| 98 |
+
# (whitespace-separated, or a JSON list for specs containing commas).
|
| 99 |
+
WORKER_SYSTEM_DEPS = ["build-essential"] # Triton/Inductor need a C compiler
|
| 100 |
+
|
| 101 |
+
# The prebuilt worker image (full training stack baked in; built by Dockerfile.worker /
|
| 102 |
+
# .github/workflows/worker-image.yml). PUBLIC under the org namespace, so no registry login is
|
| 103 |
+
# ever needed. Always used on both Vast and RunPod — there is no operator override and no generic
|
| 104 |
+
# fallback image. Must be published to GHCR + made public before runs can pull it.
|
| 105 |
+
WORKER_IMAGE = "ghcr.io/freesolo-co/flash-worker:cu128"
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def resolve_worker_deps(friendly_gpu: str | None = None) -> list[str]:
|
| 109 |
+
"""The dependency list Flash installs on the GPU worker for this run.
|
| 110 |
+
|
| 111 |
+
Precedence: FLASH_WORKER_DEPS (explicit list) > the pinned ``WORKER_DEPS``.
|
| 112 |
+
|
| 113 |
+
GPU-specific: on HOPPER (sm90, H100), DROP flash-linear-attention — its gated
|
| 114 |
+
chunk_bwd Triton kernel is miscomputed there (Triton>=3.4, fla #640). Without fla,
|
| 115 |
+
transformers uses the correct pure-PyTorch delta rule (slower but correct).
|
| 116 |
+
Ampere/Ada/Blackwell keep fla for the speedup.
|
| 117 |
+
"""
|
| 118 |
+
explicit = os.environ.get("FLASH_WORKER_DEPS")
|
| 119 |
+
if explicit:
|
| 120 |
+
# JSON list (use this for specs containing commas, e.g.
|
| 121 |
+
# "transformers>=5.6,<5.13") or a whitespace-separated string.
|
| 122 |
+
if explicit.strip().startswith("["):
|
| 123 |
+
import json as _json
|
| 124 |
+
|
| 125 |
+
deps = [str(d).strip() for d in _json.loads(explicit) if str(d).strip()]
|
| 126 |
+
else:
|
| 127 |
+
# shlex (whitespace) splitting, NOT comma: a comma is part of a PEP 440
|
| 128 |
+
# range like `transformers>=5.6,<5.11` and must not be split.
|
| 129 |
+
import shlex
|
| 130 |
+
|
| 131 |
+
deps = [d for d in shlex.split(explicit) if d.strip()]
|
| 132 |
+
if deps:
|
| 133 |
+
return deps
|
| 134 |
+
deps = list(WORKER_DEPS)
|
| 135 |
+
# Hopper (sm90) fla strategy: DROP flash-linear-attention -> the correct pure-PyTorch delta
|
| 136 |
+
# rule. fla's gated chunk_bwd Triton kernel is miscomputed on Hopper (Triton>=3.4, fla #640),
|
| 137 |
+
# so on H100 we run without it (the dense Qwen3.5 GDN models route to consumer cards by
|
| 138 |
+
# default, where fla stays). Ampere/Ada/Blackwell keep fla for the speedup.
|
| 139 |
+
if friendly_gpu:
|
| 140 |
+
try:
|
| 141 |
+
from flash.providers.base import get_gpu_info
|
| 142 |
+
|
| 143 |
+
if get_gpu_info(friendly_gpu).sm == "sm90":
|
| 144 |
+
deps = [d for d in deps if not d.startswith("flash-linear-attention")]
|
| 145 |
+
except Exception:
|
| 146 |
+
pass
|
| 147 |
+
# Additive per-run extras (e.g. an extra pinned wheel for an A/B) without
|
| 148 |
+
# restating the whole pinned stack the way FLASH_WORKER_DEPS requires.
|
| 149 |
+
extra = os.environ.get("FLASH_WORKER_EXTRA_DEPS")
|
| 150 |
+
if extra:
|
| 151 |
+
import shlex
|
| 152 |
+
|
| 153 |
+
deps = deps + [d for d in shlex.split(extra) if d.strip()]
|
| 154 |
+
return deps
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# FLASH_* flags that select a chalk install-on-call kernel (see engine.chalk_kernels). Any one
|
| 158 |
+
# of these being set means the run opted into chalk, so chalk must be installed on the worker.
|
| 159 |
+
_CHALK_KERNEL_FLAGS = (
|
| 160 |
+
"FLASH_MLP_KERNEL",
|
| 161 |
+
"FLASH_MLP_FP8",
|
| 162 |
+
"FLASH_FP8_BASE",
|
| 163 |
+
"FLASH_TRITON_LORA",
|
| 164 |
+
"FLASH_EMBED_KERNEL",
|
| 165 |
+
"FLASH_QKV_KERNEL",
|
| 166 |
+
"FLASH_ROPE_KERNEL",
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _effective_worker_env(spec=None) -> dict[str, str]:
|
| 171 |
+
"""The env the WORKER process will actually see, for chalk-selection decisions.
|
| 172 |
+
|
| 173 |
+
chalk install-on-call is selected by ``FLASH_*`` flags read on the worker from its own process
|
| 174 |
+
env, which ``build_worker_env`` builds as the control-plane ``os.environ`` allowlist with the
|
| 175 |
+
run's ``[worker_env]`` overrides merged ON TOP (per-run ``spec.worker_env`` wins). A run that
|
| 176 |
+
opts into chalk via its ``[worker_env]`` block therefore sets the flag the worker reads — so the
|
| 177 |
+
SAME merge must decide whether chalk is selected and whether its spec is added to ``extra_pip``;
|
| 178 |
+
reading bare ``os.environ`` here would miss a per-run ``[worker_env]`` opt-in and the kernels
|
| 179 |
+
would never install for that run.
|
| 180 |
+
|
| 181 |
+
Returns ``os.environ`` overlaid with ``spec.worker_env`` (string-coerced). ``spec=None`` (no
|
| 182 |
+
per-run env) collapses to plain ``os.environ``.
|
| 183 |
+
"""
|
| 184 |
+
eff: dict[str, str] = dict(os.environ)
|
| 185 |
+
for k, v in (getattr(spec, "worker_env", None) or {}).items():
|
| 186 |
+
eff[str(k)] = str(v)
|
| 187 |
+
return eff
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def _chalk_selected(spec=None) -> bool:
|
| 191 |
+
"""True if any FLASH_* chalk kernel-selection flag is truthy in the EFFECTIVE worker env.
|
| 192 |
+
|
| 193 |
+
Reads the per-run ``[worker_env]`` (``spec.worker_env``) merged over ``os.environ`` so a chalk
|
| 194 |
+
opt-in set only in the run's ``[worker_env]`` block is detected (see ``_effective_worker_env``).
|
| 195 |
+
"""
|
| 196 |
+
env = _effective_worker_env(spec)
|
| 197 |
+
for name in _CHALK_KERNEL_FLAGS:
|
| 198 |
+
v = env.get(name)
|
| 199 |
+
if v is not None and v.strip().lower() not in ("", "0", "false", "no", "off"):
|
| 200 |
+
return True
|
| 201 |
+
return False
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def chalk_extra_pip(spec=None) -> list[str]:
|
| 205 |
+
"""Chalk pip spec(s) to ADD to the worker's ``extra_pip`` when a chalk kernel is selected.
|
| 206 |
+
|
| 207 |
+
This is the install hook that runs for DEFAULT remote jobs: the baked-image RunPod path
|
| 208 |
+
(``_train_body`` -> ``pip install *extra_pip``) and the Vast bootstrap both consume the
|
| 209 |
+
payload's ``extra_pip`` regardless of ``WORKER_IMAGE`` — unlike ``FLASH_WORKER_EXTRA_DEPS``
|
| 210 |
+
/ ``resolve_worker_deps``, which the durable ``build_function_input`` baked-image path skips.
|
| 211 |
+
|
| 212 |
+
Selection (and the ``FLASH_CHALK_SPEC`` lookup) is resolved against the EFFECTIVE worker env —
|
| 213 |
+
the run's ``[worker_env]`` merged over ``os.environ`` — so it matches exactly what the worker
|
| 214 |
+
process will see (``build_worker_env``) and a per-run ``[worker_env]`` opt-in installs chalk.
|
| 215 |
+
|
| 216 |
+
freesolo-chalk is unpublished, so there is no auto-installable default: the operator MUST set
|
| 217 |
+
``FLASH_CHALK_SPEC`` to an installable spec (a git URL with access, or a wheel/path). When a
|
| 218 |
+
chalk kernel flag is set but ``FLASH_CHALK_SPEC`` is empty we log a warning and add nothing —
|
| 219 |
+
``install_chalk_kernels`` then finds no chalk on the worker and safely no-ops.
|
| 220 |
+
"""
|
| 221 |
+
if not _chalk_selected(spec):
|
| 222 |
+
return []
|
| 223 |
+
spec_str = _effective_worker_env(spec).get("FLASH_CHALK_SPEC", "").strip()
|
| 224 |
+
if not spec_str:
|
| 225 |
+
logger.warning(
|
| 226 |
+
"a FLASH_* chalk kernel is selected but FLASH_CHALK_SPEC is unset; freesolo-chalk is "
|
| 227 |
+
"unpublished so it can't be auto-installed — set FLASH_CHALK_SPEC to an installable "
|
| 228 |
+
"spec (git URL or wheel) or the chalk kernels will no-op on the worker."
|
| 229 |
+
)
|
| 230 |
+
return []
|
| 231 |
+
import shlex
|
| 232 |
+
|
| 233 |
+
return [d for d in shlex.split(spec_str) if d.strip()]
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
DEFAULT_EXECUTION_TIMEOUT_MS = 6 * 3600 * 1000 # 6h RunPod worker execution cap
|
| 237 |
+
|
| 238 |
+
_ENDPOINT_CACHE: dict[str, Any] = {}
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def upload_code(repo: str | None = None) -> str:
|
| 242 |
+
"""Upload the ``flash`` package to the run's HF artifact repo.
|
| 243 |
+
|
| 244 |
+
``repo`` is the per-run artifact repo (``spec.train.hf_repo``); the worker fetches
|
| 245 |
+
``code/**`` from the same repo it is given in the submit payload, so the code must land in
|
| 246 |
+
that per-run repo.
|
| 247 |
+
|
| 248 |
+
The worker downloads ``code/**`` to ``/runcode``. Verifiers-only: there are no built-in
|
| 249 |
+
example environments to ship — Hub/installed envs are pip-installed on the worker (see
|
| 250 |
+
``registry.worker_pip_for_env``).
|
| 251 |
+
|
| 252 |
+
Only the ``flash`` package is uploaded, NOT the client's project tree. Managed runs must
|
| 253 |
+
reference a published Hub env by ``id`` (``slm env push`` to publish a local env first); the
|
| 254 |
+
worker pip-installs the env wheel.
|
| 255 |
+
"""
|
| 256 |
+
from huggingface_hub import HfApi
|
| 257 |
+
|
| 258 |
+
import flash
|
| 259 |
+
|
| 260 |
+
if not repo:
|
| 261 |
+
raise RuntimeError(
|
| 262 |
+
"hf_repo must be set (the run's [train] hf_repo: HF dataset repo for code + artifacts)"
|
| 263 |
+
)
|
| 264 |
+
token = os.environ.get("HF_TOKEN")
|
| 265 |
+
pkg_dir = os.path.dirname(os.path.abspath(flash.__file__))
|
| 266 |
+
api = HfApi(token=token)
|
| 267 |
+
# Run artifact repos are private by default. TEST-ONLY escape hatch (NOT for production):
|
| 268 |
+
# FLASH_HF_REPO_PRIVATE=0 makes them public so a free-tier/wrong-namespace HF account can run
|
| 269 |
+
# without the private-storage 403. Production keeps private=True.
|
| 270 |
+
_priv = os.environ.get("FLASH_HF_REPO_PRIVATE", "1").strip().lower() not in ("0", "false", "no")
|
| 271 |
+
api.create_repo(repo, repo_type="dataset", exist_ok=True, private=_priv)
|
| 272 |
+
api.update_repo_settings(repo_id=repo, repo_type="dataset", private=_priv)
|
| 273 |
+
api.upload_folder(
|
| 274 |
+
folder_path=pkg_dir,
|
| 275 |
+
path_in_repo="code/flash",
|
| 276 |
+
repo_id=repo,
|
| 277 |
+
repo_type="dataset",
|
| 278 |
+
ignore_patterns=["__pycache__/*", "*.pyc"],
|
| 279 |
+
)
|
| 280 |
+
return repo
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def _train_body(input_data: dict) -> dict:
|
| 284 |
+
"""Runs ON the RunPod GPU worker: fetch code, train (phase), return metrics.
|
| 285 |
+
|
| 286 |
+
NOTE: Flash serializes this handler and runs it standalone, so every name it uses
|
| 287 |
+
must be imported INSIDE the function body (module-level imports are not in scope).
|
| 288 |
+
"""
|
| 289 |
+
import contextlib
|
| 290 |
+
import json
|
| 291 |
+
import os
|
| 292 |
+
import shutil
|
| 293 |
+
import subprocess
|
| 294 |
+
import sys
|
| 295 |
+
|
| 296 |
+
from huggingface_hub import snapshot_download
|
| 297 |
+
|
| 298 |
+
# NB: the Hopper fla guard lives in engine.worker._drop_fla_on_hopper (runs in the worker
|
| 299 |
+
# process AFTER all installs, before any model import) — doing it here would be undone by a
|
| 300 |
+
# later extra_pip / `prime env install` that pulls fla back, and depends on a handler redeploy.
|
| 301 |
+
|
| 302 |
+
# Extra pip deps for verifiers / Prime Hub environments (installed per-run).
|
| 303 |
+
extra_pip = input_data.get("extra_pip") or []
|
| 304 |
+
if extra_pip:
|
| 305 |
+
# check=True: a deterministic dependency failure should fail fast here,
|
| 306 |
+
# not after model download + worker startup with a less actionable error.
|
| 307 |
+
subprocess.run([sys.executable, "-m", "pip", "install", *extra_pip], check=True)
|
| 308 |
+
|
| 309 |
+
# NB: fla is dropped on Hopper (sm90) automatically — resolve_worker_deps omits it from the
|
| 310 |
+
# install list, and engine.worker._drop_fla_on_hopper removes any baked-in copy at worker
|
| 311 |
+
# startup (fla's GDN backward is miscomputed on sm90, #640). No env toggle: fla only ever runs
|
| 312 |
+
# on the consumer archs where its Triton kernel is correct.
|
| 313 |
+
|
| 314 |
+
# Install the run's verifiers environment(s) from the Prime Hub via the authenticated
|
| 315 |
+
# `prime` CLI. The public pip index does not serve PRIVATE env wheels, so a plain pip
|
| 316 |
+
# install can't fetch them; `prime env install` pulls/builds/installs public + private
|
| 317 |
+
# alike, authenticated by PRIME_API_KEY forwarded from the control plane.
|
| 318 |
+
hub_env_ids = input_data.get("hub_env_ids") or []
|
| 319 |
+
if hub_env_ids:
|
| 320 |
+
worker_env = {k: str(v) for k, v in (input_data.get("env") or {}).items()}
|
| 321 |
+
prime_key = worker_env.get("PRIME_API_KEY") or os.environ.get("PRIME_API_KEY")
|
| 322 |
+
if not prime_key:
|
| 323 |
+
raise RuntimeError(
|
| 324 |
+
"PRIME_API_KEY is required to install the Prime Hub environment on the worker"
|
| 325 |
+
)
|
| 326 |
+
# Only install `prime` when it isn't already on the worker (it's often baked into
|
| 327 |
+
# the worker image) — an unconditional install adds latency and a per-run PyPI
|
| 328 |
+
# failure point every run.
|
| 329 |
+
if shutil.which("prime") is None:
|
| 330 |
+
subprocess.run([sys.executable, "-m", "pip", "install", "prime"], check=True)
|
| 331 |
+
# --with pip: install the env into THIS (the trainer's) python via pip. The default
|
| 332 |
+
# (`--with uv`) installs into prime's own isolated uv env, so the trainer then can't
|
| 333 |
+
# import the env module (ModuleNotFoundError at load_environment). PIP_BREAK_SYSTEM_PACKAGES
|
| 334 |
+
# lets pip write to a PEP-668 "externally-managed" base python (the worker image's).
|
| 335 |
+
install_env = {
|
| 336 |
+
**os.environ,
|
| 337 |
+
"PRIME_API_KEY": prime_key,
|
| 338 |
+
"PRIME_DISABLE_VERSION_CHECK": "1",
|
| 339 |
+
"PIP_BREAK_SYSTEM_PACKAGES": "1",
|
| 340 |
+
}
|
| 341 |
+
for env_id in hub_env_ids:
|
| 342 |
+
subprocess.run(
|
| 343 |
+
["prime", "env", "install", env_id, "--with", "pip"], check=True, env=install_env
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
overrides = {k: str(v) for k, v in (input_data.get("env") or {}).items()}
|
| 347 |
+
snapshot_download(
|
| 348 |
+
repo_id=input_data["hf_repo"],
|
| 349 |
+
repo_type="dataset",
|
| 350 |
+
allow_patterns=["code/**"],
|
| 351 |
+
local_dir="/runcode",
|
| 352 |
+
token=overrides.get("HF_TOKEN"),
|
| 353 |
+
)
|
| 354 |
+
code_dir = "/runcode/code"
|
| 355 |
+
|
| 356 |
+
env = dict(os.environ)
|
| 357 |
+
env.update(overrides)
|
| 358 |
+
# Always pass the spec via a file (FLASH_JOB_SPEC_PATH): a large inline spec can blow past the
|
| 359 |
+
# ~128 KiB per-env-string exec limit ("Argument list too long"), and a file is ONE code path for
|
| 360 |
+
# every size (cheap write). load_job_spec_from_env reads it.
|
| 361 |
+
spec_path = "/tmp/job_spec.json"
|
| 362 |
+
with open(spec_path, "w") as sf:
|
| 363 |
+
sf.write(input_data["job_spec_json"])
|
| 364 |
+
env["FLASH_JOB_SPEC_PATH"] = spec_path
|
| 365 |
+
env.pop("FLASH_JOB_SPEC_JSON", None)
|
| 366 |
+
env["PHASE"] = input_data["phase"]
|
| 367 |
+
env["SEED"] = str(input_data["seed"])
|
| 368 |
+
env["PYTHONPATH"] = code_dir + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
|
| 369 |
+
|
| 370 |
+
def run_mode(mode: str, check: bool) -> int:
|
| 371 |
+
"""Run one worker process, tee its console to a file, and on failure upload the
|
| 372 |
+
tail to HF as console_<mode>.txt — the engine-core root cause of crashes like
|
| 373 |
+
vLLM EngineDeadError only ever appears on the subprocess console, never in the
|
| 374 |
+
Python traceback."""
|
| 375 |
+
console = f"/tmp/console_{mode}.txt"
|
| 376 |
+
with open(console, "w") as cf:
|
| 377 |
+
proc = subprocess.Popen(
|
| 378 |
+
[sys.executable, "-m", "flash.engine.worker"],
|
| 379 |
+
cwd=code_dir,
|
| 380 |
+
env={**env, "RUN_MODE": mode},
|
| 381 |
+
stdout=subprocess.PIPE,
|
| 382 |
+
stderr=subprocess.STDOUT,
|
| 383 |
+
text=True,
|
| 384 |
+
)
|
| 385 |
+
for line in proc.stdout:
|
| 386 |
+
print(line, end="") # keep streaming to the platform console
|
| 387 |
+
cf.write(line)
|
| 388 |
+
proc.wait()
|
| 389 |
+
if proc.returncode != 0:
|
| 390 |
+
try:
|
| 391 |
+
from huggingface_hub import HfApi
|
| 392 |
+
|
| 393 |
+
spec = json.loads(input_data["job_spec_json"])
|
| 394 |
+
phase_ns = "rl" if spec.get("algorithm") == "grpo" else spec["algorithm"]
|
| 395 |
+
prefix = f"{phase_ns}/{spec['run_id']}/seed{input_data['seed']}"
|
| 396 |
+
with open(console) as f:
|
| 397 |
+
tail = f.read()[-64_000:]
|
| 398 |
+
with open(console + ".tail", "w") as f:
|
| 399 |
+
f.write(tail)
|
| 400 |
+
HfApi(token=env.get("HF_TOKEN")).upload_file(
|
| 401 |
+
path_or_fileobj=console + ".tail",
|
| 402 |
+
path_in_repo=f"{prefix}/console_{mode}.txt",
|
| 403 |
+
repo_id=input_data["hf_repo"],
|
| 404 |
+
repo_type="dataset",
|
| 405 |
+
)
|
| 406 |
+
except Exception as up_err:
|
| 407 |
+
print("console upload warn:", up_err)
|
| 408 |
+
if check:
|
| 409 |
+
raise RuntimeError(
|
| 410 |
+
f"worker mode '{mode}' exited {proc.returncode}; see console_{mode}.txt "
|
| 411 |
+
f"and error_{mode}.txt in the HF dataset repo"
|
| 412 |
+
)
|
| 413 |
+
return proc.returncode
|
| 414 |
+
|
| 415 |
+
# A warm worker can carry a previous seed's metrics files; a stale metrics.json
|
| 416 |
+
# would let a crashed train phase report the previous run's numbers. Clear before
|
| 417 |
+
# training.
|
| 418 |
+
for stale in ("/tmp/train_meta.json", "/tmp/metrics.json"):
|
| 419 |
+
with contextlib.suppress(FileNotFoundError):
|
| 420 |
+
os.remove(stale)
|
| 421 |
+
# Train. check=False — RL's colocated vLLM can segfault at interpreter exit AFTER
|
| 422 |
+
# the adapter + metrics.json + DONE are saved; don't treat that as a failure.
|
| 423 |
+
run_mode(input_data["phase"], check=False)
|
| 424 |
+
# The train phase writes metrics.json + the DONE sentinel itself (RunPod can also
|
| 425 |
+
# redeliver a completed job, whose worker restores metrics.json from DONE). If it
|
| 426 |
+
# is missing, the train phase crashed before finishing — fail fast with the real
|
| 427 |
+
# cause (full traceback in error_<phase>.txt / console_<phase>.txt in the HF repo).
|
| 428 |
+
if not os.path.exists("/tmp/metrics.json"):
|
| 429 |
+
phase = input_data["phase"]
|
| 430 |
+
raise RuntimeError(
|
| 431 |
+
f"train phase '{phase}' produced no /tmp/metrics.json (it crashed before "
|
| 432 |
+
f"finishing); see error_{phase}.txt and console_{phase}.txt in the HF "
|
| 433 |
+
f"dataset repo for the full traceback"
|
| 434 |
+
)
|
| 435 |
+
with open("/tmp/metrics.json") as f:
|
| 436 |
+
return json.load(f)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def isolate_flash_state(scope: str | None = None) -> None:
|
| 440 |
+
"""Point the Flash SDK's resource registry at a per-process/private directory.
|
| 441 |
+
|
| 442 |
+
The SDK persists its registry to ``./.flash/resources.pkl`` — shared, whole-dict,
|
| 443 |
+
last-writer-wins across every process in the CWD. Observed failure modes: stale
|
| 444 |
+
entries resurrecting long-dead endpoints on later syncs, and concurrent processes
|
| 445 |
+
clobbering each other's bookkeeping. Each Flash process gets its own registry
|
| 446 |
+
under ``~/.flash/flash-state/<scope>``; remote cleanup never relies on the
|
| 447 |
+
registry anyway (REST by id/name — see api.py).
|
| 448 |
+
"""
|
| 449 |
+
try:
|
| 450 |
+
from pathlib import Path
|
| 451 |
+
|
| 452 |
+
import runpod_flash.core.resources.resource_manager as rm
|
| 453 |
+
|
| 454 |
+
scope = scope or f"pid{os.getpid()}"
|
| 455 |
+
state_dir = Path.home() / ".flash" / "flash-state" / scope
|
| 456 |
+
state_dir.mkdir(parents=True, exist_ok=True)
|
| 457 |
+
rm.FLASH_STATE_DIR = state_dir
|
| 458 |
+
rm.RESOURCE_STATE_FILE = state_dir / "resources.pkl"
|
| 459 |
+
except Exception as exc: # never block a run on this
|
| 460 |
+
logger.warning("flash state isolation skipped: %s", exc)
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def _patch_runpod_backoff() -> None:
|
| 464 |
+
"""Work around a runpod_flash bug that aborts long-running jobs.
|
| 465 |
+
|
| 466 |
+
The SDK polls a synchronous job with exponential backoff computed as
|
| 467 |
+
``base * (2 ** attempt)`` and only clamps to ``max_seconds`` afterwards. On a long
|
| 468 |
+
run the poll ``attempt`` grows without bound, so ``2 ** attempt`` becomes a huge int
|
| 469 |
+
and the float multiply raises ``OverflowError: int too large to convert to float``
|
| 470 |
+
(observed ~80 min in), killing an otherwise-healthy job mid-run. We patch the symbol
|
| 471 |
+
to cap the exponent before the power so the delay still saturates at ``max_seconds``.
|
| 472 |
+
"""
|
| 473 |
+
try:
|
| 474 |
+
import math
|
| 475 |
+
import random
|
| 476 |
+
|
| 477 |
+
from runpod_flash.core.utils import backoff as _bo
|
| 478 |
+
|
| 479 |
+
if getattr(_bo, "_flash_backoff_patched", False):
|
| 480 |
+
return
|
| 481 |
+
|
| 482 |
+
def _safe_get_backoff_delay(
|
| 483 |
+
attempt,
|
| 484 |
+
base=0.1,
|
| 485 |
+
max_seconds=10.0,
|
| 486 |
+
jitter=0.2,
|
| 487 |
+
strategy=_bo.BackoffStrategy.EXPONENTIAL,
|
| 488 |
+
):
|
| 489 |
+
a = min(int(attempt), 30) # cap exponent: 2**30 is plenty; delay saturates anyway
|
| 490 |
+
if strategy == _bo.BackoffStrategy.EXPONENTIAL:
|
| 491 |
+
delay = base * (2**a)
|
| 492 |
+
elif strategy == _bo.BackoffStrategy.LINEAR:
|
| 493 |
+
delay = base + (attempt * base)
|
| 494 |
+
elif strategy == _bo.BackoffStrategy.LOGARITHMIC:
|
| 495 |
+
delay = base * math.log2(attempt + 2)
|
| 496 |
+
else:
|
| 497 |
+
raise ValueError(f"Unsupported backoff strategy: {strategy}")
|
| 498 |
+
delay = min(delay, max_seconds)
|
| 499 |
+
return delay * random.uniform(1 - jitter, 1 + jitter)
|
| 500 |
+
|
| 501 |
+
_bo.get_backoff_delay = _safe_get_backoff_delay
|
| 502 |
+
_bo._flash_backoff_patched = True
|
| 503 |
+
# serverless.py did `from ..utils.backoff import get_backoff_delay`, so patch its ref too.
|
| 504 |
+
try:
|
| 505 |
+
from runpod_flash.core.resources import serverless as _sl
|
| 506 |
+
|
| 507 |
+
_sl.get_backoff_delay = _safe_get_backoff_delay
|
| 508 |
+
except Exception:
|
| 509 |
+
# serverless.py may not import the symbol in this SDK version; the primary
|
| 510 |
+
# patch above still applies, so a missing alias is fine to ignore.
|
| 511 |
+
pass
|
| 512 |
+
except Exception as exc: # never let the patch break submission
|
| 513 |
+
logger.warning("runpod backoff patch skipped: %s", exc)
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
def min_cuda_for(friendly_gpu: str) -> str:
|
| 517 |
+
"""Minimum host CUDA (driver) version for this GPU class on the active stack.
|
| 518 |
+
|
| 519 |
+
Blackwell classes (sm_120 — RTX 5090, RTX Pro 6000): pypi wheels for
|
| 520 |
+
the modern stack (vllm 0.19) ship no Blackwell SASS, so every custom CUDA kernel
|
| 521 |
+
is PTX-JIT'd by the driver — and their PTX is built with a newer toolchain than
|
| 522 |
+
CUDA-12.8-era drivers can JIT (observed: "the provided PTX was compiled with an
|
| 523 |
+
unsupported toolchain" on driver 570.x). CUDA-13 drivers JIT it fine, so those
|
| 524 |
+
classes are pinned to >=13.0 on the modern stack (per-GPU ``min_cuda_modern`` in
|
| 525 |
+
providers.base.GPU_INFO). Ampere/Ada/Hopper have SASS in the wheels and run on 12.8.
|
| 526 |
+
Fully managed per-GPU (no override).
|
| 527 |
+
"""
|
| 528 |
+
from flash.providers.base import min_cuda_modern
|
| 529 |
+
|
| 530 |
+
return min_cuda_modern(friendly_gpu)
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def endpoint_name(friendly_gpu: str, suffix: str | None = None) -> str:
|
| 534 |
+
"""Flash endpoint/template name for a GPU class, optionally made unique per run.
|
| 535 |
+
|
| 536 |
+
A fixed name (``flash-5090``) collides across back-to-back runs: runpod_flash's
|
| 537 |
+
``get_or_deploy_resource`` finds the prior run's still-registered resource and tries to
|
| 538 |
+
*update* it, which fails with ``GraphQL errors: Template name must be unique`` (there is
|
| 539 |
+
no endpoint GC/reuse). A per-run ``suffix`` (the run id tail) gives each run its own
|
| 540 |
+
endpoint so it deploys fresh instead of colliding. RunPod scales each to zero when idle.
|
| 541 |
+
"""
|
| 542 |
+
base = f"flash-{gpu_short(friendly_gpu)}"
|
| 543 |
+
if not suffix:
|
| 544 |
+
return base
|
| 545 |
+
safe = "".join(c for c in str(suffix) if c.isalnum() or c == "-").strip("-")[:24]
|
| 546 |
+
return f"{base}-{safe}" if safe else base
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def get_train_endpoint(
|
| 550 |
+
friendly_gpu: str,
|
| 551 |
+
execution_timeout_ms: int | None = None,
|
| 552 |
+
name_suffix: str | None = None,
|
| 553 |
+
disk_gb: int | None = None,
|
| 554 |
+
spec=None,
|
| 555 |
+
):
|
| 556 |
+
"""Build (and cache) the live Flash endpoint handler for a GPU class."""
|
| 557 |
+
# Live ("ad-hoc") provisioning: provision on call, no separate `flash deploy`.
|
| 558 |
+
os.environ["FLASH_IS_LIVE_PROVISIONING"] = "true"
|
| 559 |
+
from runpod_flash import Endpoint
|
| 560 |
+
|
| 561 |
+
from flash.providers.runpod.auth import ensure_auth
|
| 562 |
+
from flash.providers.runpod.jobs import volume_endpoint_kwargs
|
| 563 |
+
|
| 564 |
+
ensure_auth()
|
| 565 |
+
_patch_runpod_backoff()
|
| 566 |
+
isolate_flash_state(name_suffix)
|
| 567 |
+
|
| 568 |
+
friendly = canonical_gpu(friendly_gpu)
|
| 569 |
+
name = endpoint_name(friendly, name_suffix)
|
| 570 |
+
if name in _ENDPOINT_CACHE:
|
| 571 |
+
return _ENDPOINT_CACHE[name]
|
| 572 |
+
kwargs = dict(
|
| 573 |
+
name=name,
|
| 574 |
+
gpu=flash_gpu(friendly),
|
| 575 |
+
gpu_count=1,
|
| 576 |
+
min_cuda_version=min_cuda_for(friendly),
|
| 577 |
+
execution_timeout_ms=execution_timeout_ms or DEFAULT_EXECUTION_TIMEOUT_MS,
|
| 578 |
+
workers=(0, 1), # one dedicated worker per run; scale to zero when idle
|
| 579 |
+
**volume_endpoint_kwargs(spec),
|
| 580 |
+
)
|
| 581 |
+
# RunPod Flash needs its serverless runtime baked into the worker image; the prebuilt
|
| 582 |
+
# WORKER_IMAGE is Vast's cold-start image (no Flash runtime) and leaves the worker unhealthy if
|
| 583 |
+
# forced. RunPod boot-installs WORKER_DEPS on Flash's default template instead (cached as a
|
| 584 |
+
# Flash artifact). Optional FLASH_WORKER_IMAGE override for a RunPod-serverless-compatible image.
|
| 585 |
+
image = os.environ.get("FLASH_WORKER_IMAGE")
|
| 586 |
+
if image:
|
| 587 |
+
kwargs["image"] = image
|
| 588 |
+
else:
|
| 589 |
+
kwargs["dependencies"] = resolve_worker_deps(friendly)
|
| 590 |
+
kwargs["system_dependencies"] = WORKER_SYSTEM_DEPS
|
| 591 |
+
ep = Endpoint(**kwargs)
|
| 592 |
+
handler = ep(_train_body) # register the queue-based handler; returns the callable
|
| 593 |
+
# The resource config is cached on the Endpoint, so raising the disk on it here
|
| 594 |
+
# carries through to the deploy that the first handler call triggers.
|
| 595 |
+
from flash.providers.runpod.jobs import apply_disk_gb
|
| 596 |
+
|
| 597 |
+
cfg = ep._build_resource_config()
|
| 598 |
+
apply_disk_gb(cfg, disk_gb)
|
| 599 |
+
_ENDPOINT_CACHE[name] = handler
|
| 600 |
+
return handler
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def _run_suffix(run_id: str | None) -> str | None:
|
| 604 |
+
"""Short, COLLISION-FREE per-run endpoint suffix.
|
| 605 |
+
|
| 606 |
+
Must be unique per run_id: the endpoint name is ``endpoint_name(friendly, suffix)`` and
|
| 607 |
+
RunPod reuses an endpoint by name -- two runs with the same suffix share one endpoint (and
|
| 608 |
+
its cached image/deps/registry-auth/template), so a later run silently reuses the earlier
|
| 609 |
+
one's config. The old ``run_id.split("-")[-1]`` only worked for hash-tailed default ids; a
|
| 610 |
+
descriptive run_id ending in e.g. the card name (``...-a100``) collided across every run.
|
| 611 |
+
Use a stable short hash of the WHOLE run_id, with a sanitized prefix for readability."""
|
| 612 |
+
if not run_id:
|
| 613 |
+
return None
|
| 614 |
+
import hashlib
|
| 615 |
+
import re
|
| 616 |
+
|
| 617 |
+
h = hashlib.sha1(run_id.encode()).hexdigest()[:8]
|
| 618 |
+
prefix = re.sub(r"[^a-z0-9]", "", run_id.lower())[-12:]
|
| 619 |
+
return f"{prefix}{h}" if prefix else h
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
def stop_endpoint(friendly_gpu: str, name: str | None = None) -> None:
|
| 623 |
+
"""Best-effort: scale cached endpoint(s) to zero / drop them.
|
| 624 |
+
|
| 625 |
+
With ``name`` only that run's cached endpoint is dropped; without it, every
|
| 626 |
+
cached endpoint of the GPU class is — so a per-run teardown passes ``name``
|
| 627 |
+
to avoid evicting a concurrent run's handler in the same process.
|
| 628 |
+
|
| 629 |
+
NOTE: this only touches THIS process's in-memory cache, so it does nothing in a fresh
|
| 630 |
+
``slm cancel`` process. Use ``terminate_endpoint`` to actually delete the remote endpoint.
|
| 631 |
+
"""
|
| 632 |
+
friendly = canonical_gpu(friendly_gpu)
|
| 633 |
+
prefix = f"flash-{gpu_short(friendly)}"
|
| 634 |
+
if name:
|
| 635 |
+
match = [k for k in _ENDPOINT_CACHE if k == name]
|
| 636 |
+
else:
|
| 637 |
+
match = [k for k in _ENDPOINT_CACHE if k.startswith(prefix)]
|
| 638 |
+
for key in match:
|
| 639 |
+
handler = _ENDPOINT_CACHE.pop(key, None)
|
| 640 |
+
ep = getattr(handler, "__self__", None) or getattr(handler, "endpoint", None)
|
| 641 |
+
for meth in ("scale_to_zero", "stop", "delete"):
|
| 642 |
+
fn = getattr(ep, meth, None)
|
| 643 |
+
if callable(fn):
|
| 644 |
+
try:
|
| 645 |
+
fn()
|
| 646 |
+
break
|
| 647 |
+
except Exception:
|
| 648 |
+
continue
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
def _select_endpoint_resources(resources: dict, target: str) -> list[str]:
|
| 652 |
+
"""Resource ids whose resource ``.name`` contains ``target``.
|
| 653 |
+
|
| 654 |
+
The live-provisioned resource is named ``live-<endpoint_name>``, so we match by substring
|
| 655 |
+
to catch the prefix. ``target`` is the endpoint name (``flash-<gpu>[-<run>]``).
|
| 656 |
+
"""
|
| 657 |
+
if not target:
|
| 658 |
+
return []
|
| 659 |
+
out = []
|
| 660 |
+
for uid, res in (resources or {}).items():
|
| 661 |
+
name = str(getattr(res, "name", "") or "")
|
| 662 |
+
if target in name:
|
| 663 |
+
out.append(uid)
|
| 664 |
+
return out
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
def terminate_endpoint(friendly_gpu: str, run_id: str | None = None) -> list[dict]:
|
| 668 |
+
"""Reliably tear down the remote Flash endpoint(s) for a run — cross-process.
|
| 669 |
+
|
| 670 |
+
Unlike ``stop_endpoint`` (which only touches this process's in-memory cache), this looks
|
| 671 |
+
the endpoint up by name in runpod_flash's *persisted* resource registry and deletes it via
|
| 672 |
+
the RunPod API (``ResourceManager.undeploy_resource`` -> ``delete_endpoint``), which stops
|
| 673 |
+
any running worker. Best-effort: never raises. Returns the per-resource undeploy results.
|
| 674 |
+
|
| 675 |
+
With ``run_id`` it targets exactly that run's uniquely-named endpoint; without it, the
|
| 676 |
+
bare ``flash-<gpu>`` prefix matches every endpoint of that GPU class.
|
| 677 |
+
"""
|
| 678 |
+
friendly = canonical_gpu(friendly_gpu)
|
| 679 |
+
target = endpoint_name(friendly, _run_suffix(run_id))
|
| 680 |
+
# Hold FLASH_SDK_LOCK across the ENTIRE Flash critical section, not just the undeploy.
|
| 681 |
+
# isolate_flash_state() swaps runpod_flash's process-wide registry globals and
|
| 682 |
+
# ResourceManager shares the SDK's asyncio singleton, so a concurrent deploy/undeploy on
|
| 683 |
+
# another thread could swap the registry scope between our lookup and our undeploy and tear
|
| 684 |
+
# down the wrong run's resources. Serialize isolation + lookup + undeploy together.
|
| 685 |
+
with FLASH_SDK_LOCK:
|
| 686 |
+
try:
|
| 687 |
+
from flash.providers.runpod.auth import ensure_auth
|
| 688 |
+
|
| 689 |
+
ensure_auth()
|
| 690 |
+
isolate_flash_state(_run_suffix(run_id))
|
| 691 |
+
from runpod_flash.core.resources.resource_manager import ResourceManager
|
| 692 |
+
except Exception as exc: # SDK/auth unavailable
|
| 693 |
+
return [{"success": False, "name": target, "message": f"flash unavailable: {exc}"}]
|
| 694 |
+
|
| 695 |
+
try:
|
| 696 |
+
rm = ResourceManager()
|
| 697 |
+
resources = rm.list_all_resources()
|
| 698 |
+
uids = _select_endpoint_resources(resources, target)
|
| 699 |
+
except Exception as exc:
|
| 700 |
+
return [{"success": False, "name": target, "message": f"resource lookup failed: {exc}"}]
|
| 701 |
+
|
| 702 |
+
async def _undeploy_all() -> list:
|
| 703 |
+
out = []
|
| 704 |
+
for uid in uids:
|
| 705 |
+
res = resources.get(uid)
|
| 706 |
+
name = getattr(res, "name", None)
|
| 707 |
+
try:
|
| 708 |
+
out.append(
|
| 709 |
+
await rm.undeploy_resource(uid, resource_name=name, force_remove=True)
|
| 710 |
+
)
|
| 711 |
+
except Exception as exc:
|
| 712 |
+
out.append({"success": False, "name": name, "message": str(exc)})
|
| 713 |
+
return out
|
| 714 |
+
|
| 715 |
+
try:
|
| 716 |
+
results = asyncio.run(_undeploy_all())
|
| 717 |
+
except Exception as exc:
|
| 718 |
+
results = [{"success": False, "name": target, "message": str(exc)}]
|
| 719 |
+
|
| 720 |
+
# Registry-less fallback: isolate_flash_state() keeps the Flash SDK's resource
|
| 721 |
+
# registry per-process under ~/.flash, so a recreated container (or a crash before
|
| 722 |
+
# on_handle() persisted the endpoint id) leaves the live endpoint invisible to the
|
| 723 |
+
# lookup above. Delete it via the RunPod REST API by its reconstructed name so it
|
| 724 |
+
# can't keep a paid worker alive.
|
| 725 |
+
if not uids:
|
| 726 |
+
with contextlib.suppress(Exception):
|
| 727 |
+
from flash.providers.runpod import api as runpod_api
|
| 728 |
+
|
| 729 |
+
for ep in runpod_api.find_endpoints_by_name(target):
|
| 730 |
+
if ep.get("name") == target and runpod_api.delete_endpoint(ep["id"]):
|
| 731 |
+
results.append(
|
| 732 |
+
{"success": True, "name": target, "message": "deleted via REST API"}
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
# also drop the in-process cached handler for THIS run only (a class-wide
|
| 736 |
+
# drop would evict a concurrent run's endpoint on the same GPU class).
|
| 737 |
+
with contextlib.suppress(Exception):
|
| 738 |
+
stop_endpoint(friendly, name=target)
|
| 739 |
+
return results
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
def build_worker_env(spec: JobSpec, seed: int) -> dict:
|
| 743 |
+
"""Per-run env passed to the worker (secrets + recipe overrides)."""
|
| 744 |
+
# CUDA allocator conf. Colocate (TRL trainer + vLLM on one GPU) fragments over a long run,
|
| 745 |
+
# so expandable_segments (which reclaims fragmentation) is the right default — EXCEPT under
|
| 746 |
+
# GRPO vLLM sleep mode, whose CuMemAllocator memory pool is incompatible with
|
| 747 |
+
# expandable_segments (vLLM asserts and the run crashes at engine init). So for RL with
|
| 748 |
+
# sleep mode ON (the default), default to a non-expandable conf instead; SFT and
|
| 749 |
+
# sleep-off RL keep expandable_segments. An explicit operator override always wins.
|
| 750 |
+
_is_rl = str(getattr(spec, "algorithm", "")).lower() not in ("sft",)
|
| 751 |
+
# RL_VLLM_SLEEP may be pinned per-run via [worker_env] (highest precedence, merged into the
|
| 752 |
+
# worker env later) OR via the control-plane process env. Resolve it from BOTH here — with
|
| 753 |
+
# worker_env winning — so a per-run explicit pin counts as explicit: otherwise _sleep_set stays
|
| 754 |
+
# false, FLASH_ALLOC_AUTO=1 is sent, and the worker can upgrade to expandable_segments while
|
| 755 |
+
# run_rl still enables vLLM sleep, hitting the CuMemAllocator incompatibility after provisioning.
|
| 756 |
+
_sleep_raw = (spec.worker_env or {}).get("RL_VLLM_SLEEP", os.environ.get("RL_VLLM_SLEEP"))
|
| 757 |
+
_sleep_set = _sleep_raw is not None
|
| 758 |
+
_sleep_on = (_sleep_raw if _sleep_raw is not None else "1") not in ("0", "false", "False")
|
| 759 |
+
_alloc_default = (
|
| 760 |
+
"garbage_collection_threshold:0.8,max_split_size_mb:256"
|
| 761 |
+
if (_is_rl and _sleep_on)
|
| 762 |
+
else "expandable_segments:True"
|
| 763 |
+
)
|
| 764 |
+
# torch >= 2.10 renamed the env to PYTORCH_ALLOC_CONF — set BOTH names for either stack.
|
| 765 |
+
# Resolve the override from [worker_env] AND the control-plane process env (worker_env wins,
|
| 766 |
+
# mirroring RL_VLLM_SLEEP above): a per-run [worker_env] PYTORCH_ALLOC_CONF is merged into the
|
| 767 |
+
# worker env later (and would win), but if it isn't counted as an explicit override HERE,
|
| 768 |
+
# _alloc_override stays falsy, FLASH_ALLOC_AUTO=1 is sent, and finalize_alloc_conf_for_sleep
|
| 769 |
+
# overwrites the operator's per-run pin.
|
| 770 |
+
_we = spec.worker_env or {}
|
| 771 |
+
_alloc_override = (
|
| 772 |
+
_we.get("PYTORCH_ALLOC_CONF")
|
| 773 |
+
or _we.get("PYTORCH_CUDA_ALLOC_CONF")
|
| 774 |
+
or os.environ.get("PYTORCH_ALLOC_CONF")
|
| 775 |
+
or os.environ.get("PYTORCH_CUDA_ALLOC_CONF")
|
| 776 |
+
)
|
| 777 |
+
_alloc_conf = _alloc_override or _alloc_default
|
| 778 |
+
env: dict[str, str] = {
|
| 779 |
+
"RUN_ID": spec.run_id,
|
| 780 |
+
# Compute substrate, read back by engine.worker for the RunMetrics record. Vast's
|
| 781 |
+
# on-instance bootstrap overrides this to "vast" (it reuses this same env builder).
|
| 782 |
+
"FLASH_ARM": "runpod",
|
| 783 |
+
"BENCH_HF_MODEL": spec.model,
|
| 784 |
+
"PYTORCH_CUDA_ALLOC_CONF": _alloc_conf,
|
| 785 |
+
"PYTORCH_ALLOC_CONF": _alloc_conf,
|
| 786 |
+
# We picked a DEFAULT alloc conf above without knowing the worker's resolved vLLM sleep
|
| 787 |
+
# decision (RL + RL_VLLM_SLEEP unset + no operator override). Cede the final choice to the
|
| 788 |
+
# worker, which resolves sleep from the model config and upgrades to expandable_segments
|
| 789 |
+
# when sleep is OFF (engine.worker.finalize_alloc_conf_for_sleep). Never set when the
|
| 790 |
+
# operator pinned an alloc conf or RL_VLLM_SLEEP explicitly — their choice is authoritative.
|
| 791 |
+
**(
|
| 792 |
+
{"FLASH_ALLOC_AUTO": "1"}
|
| 793 |
+
if (_is_rl and not _sleep_set and not _alloc_override)
|
| 794 |
+
else {}
|
| 795 |
+
),
|
| 796 |
+
# Escape hatch for torch.compile/inductor spikes (Qwen3.5 DeltaNet kernels
|
| 797 |
+
# compile at first forward and can OOM a tight colocate budget).
|
| 798 |
+
**(
|
| 799 |
+
{"TORCHDYNAMO_DISABLE": os.environ["TORCHDYNAMO_DISABLE"]}
|
| 800 |
+
if os.environ.get("TORCHDYNAMO_DISABLE")
|
| 801 |
+
else {}
|
| 802 |
+
),
|
| 803 |
+
}
|
| 804 |
+
# HF artifact creds + PRIME_API_KEY (the worker `prime env install`s the run's Hub
|
| 805 |
+
# env(s), public + private) + optional reward-judge creds: a verifiers env whose rubric
|
| 806 |
+
# calls an LLM judge (e.g. OpenRouter gpt-oss-120b) needs the API key ON THE WORKER,
|
| 807 |
+
# where the reward runs. FLASH_JUDGE_MODEL is the judge model id the optimizer-authored env
|
| 808 |
+
# reads (agents/common/prompt.py) to pick the JudgeRubric client model; forward the operator's
|
| 809 |
+
# control-plane override so SFT-eval/GRPO-reward/rejection-sampling judges don't silently fall
|
| 810 |
+
# back to the env's generated default. Forward any that the operator has set; absent ones are
|
| 811 |
+
# simply not passed (the env then uses its own default model).
|
| 812 |
+
for key in (
|
| 813 |
+
"HF_TOKEN",
|
| 814 |
+
"PRIME_API_KEY",
|
| 815 |
+
"OPENROUTER_API_KEY",
|
| 816 |
+
"OPENAI_API_KEY",
|
| 817 |
+
"FLASH_JUDGE_MODEL",
|
| 818 |
+
):
|
| 819 |
+
if os.environ.get(key):
|
| 820 |
+
env[key] = os.environ[key]
|
| 821 |
+
# Seed the worker's own HF_REPO env from the run's [train] hf_repo (adapter/checkpoint/
|
| 822 |
+
# code storage + heartbeats). The worker reads HF_REPO from its own process env; that env
|
| 823 |
+
# is now sourced from the spec, not the operator's HF_REPO.
|
| 824 |
+
env["HF_REPO"] = spec.train.hf_repo
|
| 825 |
+
# Opt-in network volume: point the whole HF cache at the persistent mount so
|
| 826 |
+
# model weights survive across runs (the download becomes a one-time cost per
|
| 827 |
+
# volume instead of per run).
|
| 828 |
+
if getattr(spec.gpu, "network_volume", None):
|
| 829 |
+
env["HF_HOME"] = "/runpod-volume/hf-cache"
|
| 830 |
+
if spec.train.steps is not None:
|
| 831 |
+
env["RL_STEPS"] = str(spec.train.steps)
|
| 832 |
+
if spec.train.epochs is not None:
|
| 833 |
+
env["SFT_EPOCHS"] = str(spec.train.epochs)
|
| 834 |
+
# Forward the documented worker-tuning knobs so they actually reach the GPU worker.
|
| 835 |
+
# RL_VLLM_GPU_UTIL / RL_PER_DEVICE_PROMPTS are the colocate-memory knobs the docs tell
|
| 836 |
+
# users to set to fix vLLM OOM/KV-cache errors; they were previously dropped here.
|
| 837 |
+
for k in (
|
| 838 |
+
"SFT_PER_DEVICE_BS",
|
| 839 |
+
"SFT_PACKING",
|
| 840 |
+
# Colocate-memory knobs the docs tell users to set to fix vLLM OOM / KV-cache errors.
|
| 841 |
+
"RL_VLLM_GPU_UTIL",
|
| 842 |
+
"RL_VLLM_SLEEP",
|
| 843 |
+
"RL_PER_DEVICE_PROMPTS",
|
| 844 |
+
"VLLM_USE_V1",
|
| 845 |
+
# Attention-backend escape hatch: vllm's bundled flash-attn PTX can be newer
|
| 846 |
+
# than the host driver's JIT (sm_120 + 12.8 drivers); TRITON_ATTN/FLASHINFER
|
| 847 |
+
# sidestep it without restricting the host pool to CUDA-13 drivers.
|
| 848 |
+
"VLLM_ATTENTION_BACKEND",
|
| 849 |
+
"FLASH_QUANT",
|
| 850 |
+
# W&B account routing: the API key AND the optional WANDB_ENTITY that routes runs into a
|
| 851 |
+
# team/service-account workspace. These are operator ACCOUNT config (where the dashboards
|
| 852 |
+
# land), not training tuning — without the entity, `wandb_report_to()` still enables W&B
|
| 853 |
+
# under the key's default (personal) entity, so team runs vanish from the configured
|
| 854 |
+
# workspace and service-account setups that require an explicit entity can fail. (Run TUNING
|
| 855 |
+
# is still NOT an operator env knob: flash is fully managed — every training setting uses the
|
| 856 |
+
# optimal default and the only per-run config is the spec's structured [train] fields. The
|
| 857 |
+
# worker also pins WANDB_PROJECT itself.)
|
| 858 |
+
"WANDB_API_KEY",
|
| 859 |
+
"WANDB_ENTITY",
|
| 860 |
+
"LORA_TARGETS",
|
| 861 |
+
# Periodic mid-run GRPO eval (engine/midrun_eval.eval_config): the cadence normally comes
|
| 862 |
+
# from the run's [train] eval_every_steps; FLASH_EVAL_EVERY_STEPS is an operator override
|
| 863 |
+
# (>0 enables), and FLASH_EVAL_NUM is a safety cap on held-out rows per eval. Everything
|
| 864 |
+
# else (eval set, grading, completion budget, threshold) comes from the environment/run.
|
| 865 |
+
"FLASH_EVAL_EVERY_STEPS",
|
| 866 |
+
"FLASH_EVAL_NUM",
|
| 867 |
+
# rl_step heartbeat-upload throttle (engine.worker._hb_min_interval_s). Operators raise this
|
| 868 |
+
# to stay under HuggingFace's 128 commits/hour-per-repo limit when several concurrent GRPO
|
| 869 |
+
# runs share one HF_REPO; the worker no-op's a non-positive/unparseable value back to 60s.
|
| 870 |
+
"FLASH_HEARTBEAT_MIN_S",
|
| 871 |
+
# FLASH_* chalk kernel-selection flags: chalk is install-on-call (reads NO env vars), so
|
| 872 |
+
# the WORKER decides which installers to run from these flags. install_chalk_kernels runs
|
| 873 |
+
# INSIDE the worker subprocess and reads them from its own process env, so a control-plane
|
| 874 |
+
# FLASH_* selection must be forwarded here or every chalk kernel silently no-ops on every
|
| 875 |
+
# remote run. FLASH_CHALK_SPEC is the install spec install_chalk_kernels points operators
|
| 876 |
+
# at (and is also consumed at submit time to add chalk to the worker's extra_pip).
|
| 877 |
+
"FLASH_MLP_KERNEL",
|
| 878 |
+
"FLASH_MLP_FP8",
|
| 879 |
+
"FLASH_MLP_FP8_DOWN",
|
| 880 |
+
"FLASH_FP8_BASE",
|
| 881 |
+
"FLASH_FP8_BASE_ATTN",
|
| 882 |
+
"FLASH_FP8_BASE_MLP",
|
| 883 |
+
"FLASH_FP8_BASE_MIN_K",
|
| 884 |
+
"FLASH_TRITON_LORA",
|
| 885 |
+
"FLASH_EMBED_KERNEL",
|
| 886 |
+
"FLASH_QKV_KERNEL",
|
| 887 |
+
"FLASH_ROPE_KERNEL",
|
| 888 |
+
# The chalk install spec itself — install_chalk_kernels warns pointing at it when a
|
| 889 |
+
# FLASH_* flag is set but chalk is absent.
|
| 890 |
+
"FLASH_CHALK_SPEC",
|
| 891 |
+
):
|
| 892 |
+
# Forward when SET, even if empty: an explicit "" is a meaningful override.
|
| 893 |
+
if os.environ.get(k) is not None:
|
| 894 |
+
env[k] = os.environ[k]
|
| 895 |
+
# Per-run worker_env overrides win over the global os.environ allowlist: this is what lets
|
| 896 |
+
# ONE run differ (e.g. a per-run optimizer or LoRA-init A/B) while every other concurrent run
|
| 897 |
+
# keeps the global default. Run-IDENTITY keys are control-plane-owned and excluded: the poller,
|
| 898 |
+
# deploy, and artifact paths all key off spec.run_id / spec.train.hf_repo, so letting a
|
| 899 |
+
# [worker_env] override RUN_ID/HF_REPO would make the worker upload under a different repo/prefix
|
| 900 |
+
# and orphan the artifacts (the poller would never find DONE/metrics, deploy can't locate the
|
| 901 |
+
# adapter). FLASH_ARM identifies the substrate (Vast rewrites it in its own bootstrap).
|
| 902 |
+
_RESERVED_WORKER_ENV = {"RUN_ID", "HF_REPO", "FLASH_ARM"}
|
| 903 |
+
for k, v in (getattr(spec, "worker_env", None) or {}).items():
|
| 904 |
+
if str(k).upper() in _RESERVED_WORKER_ENV:
|
| 905 |
+
continue # control plane owns run identity; a per-run override would orphan artifacts
|
| 906 |
+
env[str(k)] = str(v)
|
| 907 |
+
return env
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
def submit_train(spec: JobSpec, seed: int, log=None) -> dict:
|
| 911 |
+
"""Provision a dedicated GPU via Flash, run training, return the metrics dict."""
|
| 912 |
+
timeout_s = max(60, int(spec.gpu.max_wall_seconds))
|
| 913 |
+
from flash.envs.registry import worker_hub_env_ids, worker_pip_for_env
|
| 914 |
+
|
| 915 |
+
handler = get_train_endpoint(
|
| 916 |
+
spec.gpu.type,
|
| 917 |
+
execution_timeout_ms=timeout_s * 1000,
|
| 918 |
+
name_suffix=_run_suffix(spec.run_id),
|
| 919 |
+
disk_gb=spec.gpu.disk_gb,
|
| 920 |
+
spec=spec,
|
| 921 |
+
)
|
| 922 |
+
payload = {
|
| 923 |
+
"hf_repo": spec.train.hf_repo,
|
| 924 |
+
"job_spec_json": spec.to_json(),
|
| 925 |
+
"phase": spec.phase,
|
| 926 |
+
"seed": int(seed),
|
| 927 |
+
"env": build_worker_env(spec, seed),
|
| 928 |
+
# extra_pip is installed by the worker for EVERY job (baked-image RunPod _train_body and
|
| 929 |
+
# Vast bootstrap both pip-install it), so it's where the chalk spec must go to reach a
|
| 930 |
+
# default run — see chalk_extra_pip().
|
| 931 |
+
"extra_pip": (list(spec.environment.pip) or worker_pip_for_env(spec.environment.id))
|
| 932 |
+
+ chalk_extra_pip(spec),
|
| 933 |
+
"hub_env_ids": worker_hub_env_ids(spec.environment.id, spec.environment.params),
|
| 934 |
+
}
|
| 935 |
+
if log is not None:
|
| 936 |
+
print(
|
| 937 |
+
f"submitting Flash job: gpu={spec.gpu.type} phase={spec.phase} "
|
| 938 |
+
f"seed={seed} model={spec.model}",
|
| 939 |
+
file=log,
|
| 940 |
+
flush=True,
|
| 941 |
+
)
|
| 942 |
+
|
| 943 |
+
async def _call():
|
| 944 |
+
res = handler(payload)
|
| 945 |
+
if inspect.isawaitable(res):
|
| 946 |
+
res = await res
|
| 947 |
+
return res
|
| 948 |
+
|
| 949 |
+
out = asyncio.run(_call())
|
| 950 |
+
if not isinstance(out, dict):
|
| 951 |
+
raise RuntimeError(f"flash job returned no metrics: {out!r}")
|
| 952 |
+
return out
|
code/flash/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 flash.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 flash.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 FLASH_SKIP_NET (offline/CI) disables Vast
|
| 30 |
+
# entirely; offline allocation then degrades deterministically to RunPod's
|
| 31 |
+
# static catalog.
|
| 32 |
+
if os.environ.get("FLASH_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 flash.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 flash.providers.vast.gpus import gpu_classes
|
| 43 |
+
|
| 44 |
+
return gpu_classes()
|
| 45 |
+
|
| 46 |
+
def hourly_rate(self, gpu: str) -> float:
|
| 47 |
+
from flash.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 flash.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 flash.providers.runpod.jobs import make_hf_heartbeat_reader
|
| 76 |
+
from flash.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 flash.providers.vast.jobs import cancel
|
| 102 |
+
|
| 103 |
+
cancel(handle.to_dict())
|
| 104 |
+
|
| 105 |
+
def destroy(self, handle: JobHandle) -> None:
|
| 106 |
+
from flash.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 flash.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 flash.providers.vast.jobs import sweep_orphans
|
| 120 |
+
|
| 121 |
+
return sweep_orphans(active_labels=active_labels)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
PROVIDER: Provider = VastProvider()
|
code/flash/providers/vast/_bootstrap.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 flash package from the HF dataset repo, then run the
|
| 5 |
+
substrate-neutral worker (``flash.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 flash here.
|
| 14 |
+
It reads its payload from ``/root/flash/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/flash/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["FLASH_JOB_SPEC_PATH"] = "/tmp/job_spec.json"
|
| 66 |
+
env.pop("FLASH_JOB_SPEC_JSON", None)
|
| 67 |
+
else:
|
| 68 |
+
env["FLASH_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 FLASH_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["FLASH_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", "flash.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-flash-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 |
+
_wb = subprocess.run(
|
| 190 |
+
[sys.executable, "-m", "pip", "install", "wandb>=0.17"], check=False
|
| 191 |
+
)
|
| 192 |
+
if _wb.returncode == 0 and importlib.util.find_spec("wandb") is not None:
|
| 193 |
+
print("[wandb] installed wandb on-demand for W&B logging")
|
| 194 |
+
else:
|
| 195 |
+
print(
|
| 196 |
+
f"[wandb] on-demand wandb install FAILED (rc={_wb.returncode}); "
|
| 197 |
+
"W&B logging will be disabled"
|
| 198 |
+
)
|
| 199 |
+
except Exception as _e:
|
| 200 |
+
print("wandb setup skipped:", _e)
|
| 201 |
+
# NB: the Hopper fla guard lives in engine.worker._drop_fla_on_hopper (runs in the worker
|
| 202 |
+
# process after all installs, before any model import) — not here, where a later
|
| 203 |
+
# install could pull fla back in. The bootstrap just fetches code and runs the worker.
|
| 204 |
+
|
| 205 |
+
extra_pip = payload.get("extra_pip") or []
|
| 206 |
+
if extra_pip:
|
| 207 |
+
# check=True: a deterministic dependency failure (GRPO / Prime Hub
|
| 208 |
+
# / verifiers extras) must stop NOW with an actionable error, not proceed to
|
| 209 |
+
# a later import crash while the paid instance runs (matches the RunPod path).
|
| 210 |
+
subprocess.run([sys.executable, "-m", "pip", "install", *extra_pip], check=True)
|
| 211 |
+
_wenv = payload.get("env") or {}
|
| 212 |
+
# NB: fla is dropped on Hopper (sm90) automatically by engine.worker._drop_fla_on_hopper at
|
| 213 |
+
# worker startup (fla's GDN backward is miscomputed on sm90, #640) — no bootstrap uninstall
|
| 214 |
+
# or env toggle. fla only ever runs on the consumer archs where its Triton kernel is correct.
|
| 215 |
+
# Install the run's verifiers environment(s) from the Prime Hub via the
|
| 216 |
+
# authenticated `prime` CLI (mirrors runpod/train.py:_train_body). The public pip
|
| 217 |
+
# index does not serve PRIVATE env wheels; `prime env install` pulls/builds/installs
|
| 218 |
+
# public + private alike, authenticated by PRIME_API_KEY forwarded in the payload env.
|
| 219 |
+
hub_env_ids = payload.get("hub_env_ids") or []
|
| 220 |
+
if hub_env_ids:
|
| 221 |
+
worker_env = {k: str(v) for k, v in (payload.get("env") or {}).items()}
|
| 222 |
+
prime_key = worker_env.get("PRIME_API_KEY") or os.environ.get("PRIME_API_KEY")
|
| 223 |
+
if not prime_key:
|
| 224 |
+
raise RuntimeError(
|
| 225 |
+
"PRIME_API_KEY is required to install the Prime Hub environment on the worker"
|
| 226 |
+
)
|
| 227 |
+
# Only install `prime` when it isn't already present (it's often baked into the
|
| 228 |
+
# instance image) — an unconditional install adds latency and a per-run PyPI
|
| 229 |
+
# failure point every run.
|
| 230 |
+
if shutil.which("prime") is None:
|
| 231 |
+
subprocess.run([sys.executable, "-m", "pip", "install", "prime"], check=True)
|
| 232 |
+
# Resolve the prime binary (located path if present, else the bare name) so the env
|
| 233 |
+
# install runs through the actually-installed CLI.
|
| 234 |
+
prime_bin = shutil.which("prime") or "prime"
|
| 235 |
+
install_env = {
|
| 236 |
+
**os.environ,
|
| 237 |
+
"PRIME_API_KEY": prime_key,
|
| 238 |
+
"PRIME_DISABLE_VERSION_CHECK": "1",
|
| 239 |
+
"PIP_BREAK_SYSTEM_PACKAGES": "1",
|
| 240 |
+
}
|
| 241 |
+
# --with pip: install the env into THIS python via pip, not prime's isolated uv env
|
| 242 |
+
# (the default), so the trainer can import the env module at load_environment.
|
| 243 |
+
for env_id in hub_env_ids:
|
| 244 |
+
subprocess.run(
|
| 245 |
+
[prime_bin, "env", "install", env_id, "--with", "pip"],
|
| 246 |
+
check=True,
|
| 247 |
+
env=install_env,
|
| 248 |
+
)
|
| 249 |
+
fetch_code(payload)
|
| 250 |
+
env = build_worker_env(payload)
|
| 251 |
+
deadline = time.time() + float(payload.get("max_wall_s") or 24 * 3600)
|
| 252 |
+
phase = payload["phase"]
|
| 253 |
+
# A warm/retried Vast instance can carry a previous attempt's metrics file; a
|
| 254 |
+
# stale one would let a crashed train phase report the previous run's metrics.
|
| 255 |
+
# Clear before training (mirrors the RunPod Flash handler in runpod/train.py).
|
| 256 |
+
for stale in ("/tmp/train_meta.json", "/tmp/metrics.json"):
|
| 257 |
+
with contextlib.suppress(FileNotFoundError):
|
| 258 |
+
os.remove(stale)
|
| 259 |
+
# Train. Nonzero rc tolerated — RL's colocated vLLM can segfault at interpreter
|
| 260 |
+
# exit AFTER the adapter + metrics.json + DONE are saved. The train phase writes
|
| 261 |
+
# metrics.json + DONE itself (or restores them from an earlier attempt's DONE).
|
| 262 |
+
run_mode(payload, env, phase, deadline)
|
| 263 |
+
if not os.path.exists("/tmp/metrics.json"):
|
| 264 |
+
raise RuntimeError(
|
| 265 |
+
f"train phase '{phase}' produced no /tmp/metrics.json (it crashed before "
|
| 266 |
+
f"finishing); see error_{phase}.txt and console_{phase}.txt in the HF "
|
| 267 |
+
f"dataset repo"
|
| 268 |
+
)
|
| 269 |
+
ok = True
|
| 270 |
+
except Exception as exc:
|
| 271 |
+
# Record genuine failures in the attempt marker (written in `finally`). Don't catch
|
| 272 |
+
# BaseException — KeyboardInterrupt/SystemExit must propagate after the marker write
|
| 273 |
+
# rather than be swallowed into a `return 1`.
|
| 274 |
+
error = f"{type(exc).__name__}: {exc}"
|
| 275 |
+
print(f"bootstrap failed: {error}", flush=True)
|
| 276 |
+
finally:
|
| 277 |
+
write_attempt_marker(payload, ok, error)
|
| 278 |
+
return 0 if ok else 1
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
if __name__ == "__main__":
|
| 282 |
+
sys.exit(main())
|
code/flash/providers/vast/api.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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`` DATACENTER offers are searched (the
|
| 6 |
+
server-side ``datacenter`` hosting-type filter is applied, since run secrets ship to the
|
| 7 |
+
box); callers 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 flash.providers._http import RestClient
|
| 18 |
+
|
| 19 |
+
VAST_BASE = "https://console.vast.ai/api"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class VastApiError(RuntimeError):
|
| 23 |
+
pass
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# Shared urllib client (path form: callers pass paths joined onto VAST_BASE).
|
| 27 |
+
# Env-only by design, like RUNPOD_API_KEY: the operator sets VAST_API_KEY on the
|
| 28 |
+
# control-plane host; it is never written to config files or shipped to workers.
|
| 29 |
+
_CLIENT = RestClient(
|
| 30 |
+
env_var="VAST_API_KEY",
|
| 31 |
+
error_cls=VastApiError,
|
| 32 |
+
base_url=VAST_BASE,
|
| 33 |
+
missing_key_message=("VAST_API_KEY not configured on the control-plane host"),
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _api_key() -> str:
|
| 38 |
+
return _CLIENT.api_key()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _request(path: str, method: str = "GET", body: dict | None = None, timeout: float = 30.0):
|
| 42 |
+
return _CLIENT.request(path, method=method, body=body, timeout=timeout)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def request_with_retries(
|
| 46 |
+
path: str,
|
| 47 |
+
method: str = "GET",
|
| 48 |
+
body: dict | None = None,
|
| 49 |
+
retries: int = 4,
|
| 50 |
+
base_delay: float = 2.0,
|
| 51 |
+
) -> Any:
|
| 52 |
+
"""REST call hardened against transient network/5xx blips (jittered backoff)."""
|
| 53 |
+
return _CLIENT.request_with_retries(
|
| 54 |
+
path, method=method, body=body, retries=retries, base_delay=base_delay
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# ---------------------------------------------------------------------------
|
| 59 |
+
# Offer search
|
| 60 |
+
# ---------------------------------------------------------------------------
|
| 61 |
+
def search_offers(
|
| 62 |
+
min_vram_mb: int,
|
| 63 |
+
*,
|
| 64 |
+
min_disk_gb: float = 0,
|
| 65 |
+
min_reliability: float = 0.95,
|
| 66 |
+
limit: int = 64,
|
| 67 |
+
extra_q: dict | None = None,
|
| 68 |
+
) -> list[dict]:
|
| 69 |
+
"""Rentable single-GPU offers from verified DATACENTER hosts, cheapest first.
|
| 70 |
+
|
| 71 |
+
``datacenter`` here is Vast's hosting-type filter (professional datacenters vs
|
| 72 |
+
consumer/hobbyist machines); results additionally carry ``hosting_type`` which
|
| 73 |
+
callers re-check (``usable_offers``) — never trust one filter layer alone.
|
| 74 |
+
"""
|
| 75 |
+
# Apply Vast's server-side datacenter-only filter (hosting_type==1). usable_offers now rejects
|
| 76 |
+
# community/marketplace hosts unconditionally (run secrets ship to the box), so a mixed search
|
| 77 |
+
# would risk filling the price-sorted limit=64 page with community offers and reporting "no
|
| 78 |
+
# usable offers" even when verified-datacenter capacity exists just past the page. Filtering
|
| 79 |
+
# server-side keeps the page full of datacenter offers; usable_offers still re-checks
|
| 80 |
+
# hosting_type + verification + the reliability floor (belt and suspenders).
|
| 81 |
+
q: dict[str, Any] = {
|
| 82 |
+
"verified": {"eq": True},
|
| 83 |
+
"datacenter": {"eq": True},
|
| 84 |
+
"rentable": {"eq": True},
|
| 85 |
+
"num_gpus": {"eq": 1},
|
| 86 |
+
"gpu_ram": {"gte": int(min_vram_mb)},
|
| 87 |
+
"reliability2": {"gte": float(min_reliability)},
|
| 88 |
+
"type": "ask",
|
| 89 |
+
"order": [["dph_total", "asc"]],
|
| 90 |
+
"limit": int(limit),
|
| 91 |
+
}
|
| 92 |
+
if min_disk_gb:
|
| 93 |
+
q["disk_space"] = {"gte": float(min_disk_gb)}
|
| 94 |
+
if extra_q:
|
| 95 |
+
q.update(extra_q)
|
| 96 |
+
out = request_with_retries("/v0/search/asks/", method="PUT", body={"q": q})
|
| 97 |
+
offers = out.get("offers") if isinstance(out, dict) else None
|
| 98 |
+
return offers if isinstance(offers, list) else []
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# ---------------------------------------------------------------------------
|
| 102 |
+
# Instances
|
| 103 |
+
# ---------------------------------------------------------------------------
|
| 104 |
+
def create_instance(
|
| 105 |
+
offer_id: int,
|
| 106 |
+
*,
|
| 107 |
+
image: str,
|
| 108 |
+
disk_gb: float,
|
| 109 |
+
env: dict[str, str],
|
| 110 |
+
onstart: str,
|
| 111 |
+
label: str,
|
| 112 |
+
runtype: str = "args",
|
| 113 |
+
) -> int:
|
| 114 |
+
"""Rent an offer -> instance id. Raises VastApiError on rejection (offer taken).
|
| 115 |
+
|
| 116 |
+
Default ``args`` runtype (verified live): the script IS the container command
|
| 117 |
+
(``bash -c``), so the job needs no SSH key on the account, the container's
|
| 118 |
+
lifecycle is the job's lifecycle, and the Vast-injected CONTAINER_API_KEY /
|
| 119 |
+
CONTAINER_ID env vars are available for the self-destroy backstop. ``ssh``
|
| 120 |
+
runtype requires an SSH key attached to the Vast account.
|
| 121 |
+
"""
|
| 122 |
+
body = {
|
| 123 |
+
"client_id": "me",
|
| 124 |
+
"image": image,
|
| 125 |
+
"disk": float(disk_gb),
|
| 126 |
+
"env": dict(env),
|
| 127 |
+
"label": label,
|
| 128 |
+
"runtype": runtype,
|
| 129 |
+
}
|
| 130 |
+
# The worker image is PUBLIC, so Vast pulls it with no docker-login (no image_login / pull
|
| 131 |
+
# token is ever shipped to the untrusted host).
|
| 132 |
+
if runtype == "args":
|
| 133 |
+
body["args"] = ["bash", "-c", onstart]
|
| 134 |
+
else:
|
| 135 |
+
body["onstart"] = onstart
|
| 136 |
+
# NON-IDEMPOTENT: ``PUT /asks/{id}`` rents a NEW instance every time it succeeds.
|
| 137 |
+
# A blind retry on a timeout where Vast actually accepted the first request would
|
| 138 |
+
# double-provision (two billed instances, one invisible to our handle). So this
|
| 139 |
+
# call is NOT retried — a transient failure surfaces to deploy_and_submit, which
|
| 140 |
+
# walks to the next offer, and to the orchestrator, which consumes a run retry; a
|
| 141 |
+
# duplicate paid instance is the worse failure. (Idempotent calls — search,
|
| 142 |
+
# detail, destroy — keep their retries.)
|
| 143 |
+
out = request_with_retries(f"/v0/asks/{int(offer_id)}/", method="PUT", body=body, retries=0)
|
| 144 |
+
if not isinstance(out, dict) or not out.get("success"):
|
| 145 |
+
raise VastApiError(f"create_instance({offer_id}) rejected: {out}")
|
| 146 |
+
instance_id = out.get("new_contract")
|
| 147 |
+
if not instance_id:
|
| 148 |
+
raise VastApiError(f"create_instance({offer_id}): no instance id in response: {out}")
|
| 149 |
+
return int(instance_id)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def get_instance(instance_id: int) -> dict | None:
|
| 153 |
+
"""Instance detail dict, or None once it no longer exists (destroyed).
|
| 154 |
+
|
| 155 |
+
The v0 detail route answers 200 with ``{"instances": null}`` for unknown ids
|
| 156 |
+
(verified live) — that is the "gone" signal, not a 404.
|
| 157 |
+
"""
|
| 158 |
+
try:
|
| 159 |
+
out = request_with_retries(f"/v0/instances/{int(instance_id)}/")
|
| 160 |
+
except VastApiError as e:
|
| 161 |
+
if "404" in str(e):
|
| 162 |
+
return None
|
| 163 |
+
raise
|
| 164 |
+
if isinstance(out, dict):
|
| 165 |
+
if "instances" in out:
|
| 166 |
+
inst = out["instances"]
|
| 167 |
+
return inst if isinstance(inst, dict) else None
|
| 168 |
+
return out
|
| 169 |
+
return None
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def list_instances() -> list[dict]:
|
| 173 |
+
# The v0 list route is deprecated (410 "use /api/v1/instances/", verified live);
|
| 174 |
+
# detail/destroy remain on v0.
|
| 175 |
+
out = request_with_retries("/v1/instances/")
|
| 176 |
+
inst = out.get("instances") if isinstance(out, dict) else None
|
| 177 |
+
return inst if isinstance(inst, list) else []
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def instance_logs(instance_id: int, tail: int = 400, wait_s: float = 20.0) -> str | None:
|
| 181 |
+
"""Container log tail via the logs API (request -> poll the result URL).
|
| 182 |
+
|
| 183 |
+
The only place early-bootstrap failures (pip/env errors before the worker can
|
| 184 |
+
reach HF) are visible. Best-effort: returns None when logs are unavailable
|
| 185 |
+
(e.g. the instance is already destroyed); never raises.
|
| 186 |
+
"""
|
| 187 |
+
try:
|
| 188 |
+
out = request_with_retries(
|
| 189 |
+
f"/v0/instances/request_logs/{int(instance_id)}/",
|
| 190 |
+
method="PUT",
|
| 191 |
+
body={"tail": str(int(tail))},
|
| 192 |
+
retries=1,
|
| 193 |
+
)
|
| 194 |
+
url = out.get("result_url") if isinstance(out, dict) else None
|
| 195 |
+
if not url:
|
| 196 |
+
return None
|
| 197 |
+
deadline = time.time() + wait_s
|
| 198 |
+
while time.time() < deadline:
|
| 199 |
+
try:
|
| 200 |
+
with urllib.request.urlopen(url, timeout=15) as resp:
|
| 201 |
+
body = resp.read().decode(errors="replace")
|
| 202 |
+
if body.strip():
|
| 203 |
+
return body
|
| 204 |
+
except urllib.error.HTTPError as e:
|
| 205 |
+
if e.code != 404: # 404 = not materialized yet
|
| 206 |
+
return None
|
| 207 |
+
time.sleep(2.0)
|
| 208 |
+
except Exception:
|
| 209 |
+
return None
|
| 210 |
+
return None
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def destroy_instance(instance_id: int) -> bool:
|
| 214 |
+
"""Destroy (and stop billing for) an instance. Best-effort: never raises."""
|
| 215 |
+
try:
|
| 216 |
+
request_with_retries(f"/v0/instances/{int(instance_id)}/", method="DELETE", retries=2)
|
| 217 |
+
return True
|
| 218 |
+
except Exception:
|
| 219 |
+
return False
|
code/flash/providers/vast/auth.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from .._auth import ensure_provider_auth, load_provider_key
|
| 13 |
+
|
| 14 |
+
_ENV_VAR = "VAST_API_KEY"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def load_api_key() -> str | None:
|
| 18 |
+
"""API key from the environment (operator configuration)."""
|
| 19 |
+
return load_provider_key(_ENV_VAR)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def ensure_auth() -> str:
|
| 23 |
+
"""Ensure ``VAST_API_KEY`` is set; raise if unavailable."""
|
| 24 |
+
return ensure_provider_auth(_ENV_VAR, "no Vast API key found; set VAST_API_KEY on the control-plane host")
|
code/flash/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 flash.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 flash.providers.base import GPU_INFO
|
| 20 |
+
|
| 21 |
+
return [g for g in GPU_INFO.values() if g.vast_name]
|
code/flash/providers/vast/jobs.py
ADDED
|
@@ -0,0 +1,729 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 datacenter offer, 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 flash._logging import get_logger
|
| 28 |
+
from flash.providers._poll import PollErrorTracker, make_say, surface_heartbeat
|
| 29 |
+
from flash.providers.base import GPU_INFO, PollResult, min_cuda_modern, vast_gpu_for_offer
|
| 30 |
+
from flash.providers.runpod.jobs import make_hf_heartbeat_reader, make_hf_text_reader
|
| 31 |
+
from flash.providers.vast import api as vast_api
|
| 32 |
+
|
| 33 |
+
logger = get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
# Offer-quality floors (beyond verified+datacenter, which are non-negotiable). reliability2 is
|
| 36 |
+
# Vast's host-uptime/health score: 0.95 let ~1-in-20 long runs die mid-train ("worker terminated
|
| 37 |
+
# without a DONE sentinel" when the host went down); 0.995 (~1-in-200) keeps supply usable (the
|
| 38 |
+
# >=0.995 datacenter pool measured 67 offers) while nearly eliminating mid-run host deaths. These
|
| 39 |
+
# are fixed correctness floors, not operator-tunable.
|
| 40 |
+
RELIABILITY_FLOOR = 0.995
|
| 41 |
+
MIN_INET_MBPS = 200.0
|
| 42 |
+
# How long an instance may sit in a non-running state (image pull) before we give up.
|
| 43 |
+
LOAD_TIMEOUT_S = 900.0
|
| 44 |
+
# Boards under-report VRAM vs the class nominal (measured live: L4 23034 MB / 24 GB,
|
| 45 |
+
# A40 46068 MB / 48 GB = 0.938 of nominal); the server-side gpu_ram filter gets this
|
| 46 |
+
# slack, the class gate stays exact (vast_gpu_for_offer).
|
| 47 |
+
_SEARCH_VRAM_SLACK = 0.92
|
| 48 |
+
|
| 49 |
+
# Minimum disk Vast instances are provisioned with (the bootstrap + worker stack +
|
| 50 |
+
# weights need headroom regardless of the spec's request). The offer search MUST use
|
| 51 |
+
# this same floor so offers with <60 GB disk don't pass the search and then get
|
| 52 |
+
# rejected at create time (``create_instance`` enforces the same max).
|
| 53 |
+
MIN_DISK_GB = 60.0
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _effective_disk_gb(spec) -> float:
|
| 57 |
+
"""The disk size an instance is actually provisioned with (the create-time floor).
|
| 58 |
+
|
| 59 |
+
Both the offer search and ``create_instance`` must agree on this, or offers with a
|
| 60 |
+
disk between ``spec.gpu.disk_gb`` and the floor pass the search then fail to rent.
|
| 61 |
+
"""
|
| 62 |
+
return max(float(spec.gpu.disk_gb), MIN_DISK_GB)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@dataclass(frozen=True)
|
| 66 |
+
class VastOffer:
|
| 67 |
+
"""A normalized, fully-vetted offer (passed every ``usable_offers`` filter)."""
|
| 68 |
+
|
| 69 |
+
offer_id: int
|
| 70 |
+
machine_id: int
|
| 71 |
+
gpu: str # canonical class name (GPU_INFO key)
|
| 72 |
+
vram_gb: int
|
| 73 |
+
dph_total: float
|
| 74 |
+
cuda_max_good: float
|
| 75 |
+
disk_space: float
|
| 76 |
+
reliability: float
|
| 77 |
+
inet_down: float
|
| 78 |
+
geolocation: str
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def usable_offers(
|
| 82 |
+
min_vram_gb: int,
|
| 83 |
+
disk_gb: float,
|
| 84 |
+
exclude_machine_ids: set[int] | frozenset[int] = frozenset(),
|
| 85 |
+
) -> list[VastOffer]:
|
| 86 |
+
"""Verified datacenter offers able to run the job, cheapest first.
|
| 87 |
+
|
| 88 |
+
Server-side filters do the heavy lifting; everything load-bearing is re-checked
|
| 89 |
+
client-side (belt and suspenders — the result rows carry the proof fields).
|
| 90 |
+
"""
|
| 91 |
+
rows = vast_api.search_offers(
|
| 92 |
+
int(min_vram_gb * 1024 * _SEARCH_VRAM_SLACK),
|
| 93 |
+
min_disk_gb=disk_gb,
|
| 94 |
+
min_reliability=RELIABILITY_FLOOR,
|
| 95 |
+
)
|
| 96 |
+
# Host tier: ALWAYS datacenter-only (hosting_type==1). The onstart payload ships run secrets
|
| 97 |
+
# (HF_TOKEN, PRIME_API_KEY, OpenRouter/OpenAI/W&B creds) to the box, so verified-but-lower-trust
|
| 98 |
+
# community/marketplace hosts (hosting_type 0) are never used — even verified + reliability-
|
| 99 |
+
# floored, they're a lower trust tier we don't ship secrets to.
|
| 100 |
+
out: list[VastOffer] = []
|
| 101 |
+
for r in rows:
|
| 102 |
+
gpu = vast_gpu_for_offer(str(r.get("gpu_name") or ""), float(r.get("gpu_ram") or 0))
|
| 103 |
+
if gpu is None: # not a managed class (Ampere+ floor)
|
| 104 |
+
continue
|
| 105 |
+
info = GPU_INFO[gpu]
|
| 106 |
+
dph = float(r.get("dph_total") or 0)
|
| 107 |
+
cuda = float(r.get("cuda_max_good") or 0)
|
| 108 |
+
# Host tier: accept ONLY verified datacenter hosts (hosting_type==1); community/marketplace
|
| 109 |
+
# (hosting_type==0) and anything else is rejected (we ship run secrets to the box).
|
| 110 |
+
_bad_host = r.get("hosting_type") != 1
|
| 111 |
+
if (
|
| 112 |
+
_bad_host
|
| 113 |
+
or r.get("verification") != "verified"
|
| 114 |
+
# Exact class gate: guard against a board whose canonical class nominal VRAM
|
| 115 |
+
# is below the request (e.g. asking for 48 GB but the mapping landed on a
|
| 116 |
+
# 24 GB class) — the server-side gpu_ram filter only carries slack.
|
| 117 |
+
or info.vram_gb < min_vram_gb
|
| 118 |
+
or float(r.get("reliability2") or 0) < RELIABILITY_FLOOR
|
| 119 |
+
or float(r.get("disk_space") or 0) < float(disk_gb)
|
| 120 |
+
or float(r.get("inet_down") or 0) < MIN_INET_MBPS
|
| 121 |
+
or cuda < float(min_cuda_modern(gpu)) # Blackwell needs CUDA-13 drivers
|
| 122 |
+
or dph <= 0
|
| 123 |
+
or int(r.get("machine_id") or 0) in exclude_machine_ids
|
| 124 |
+
):
|
| 125 |
+
continue
|
| 126 |
+
out.append(
|
| 127 |
+
VastOffer(
|
| 128 |
+
offer_id=int(r["id"]),
|
| 129 |
+
machine_id=int(r.get("machine_id") or 0),
|
| 130 |
+
gpu=gpu,
|
| 131 |
+
vram_gb=info.vram_gb,
|
| 132 |
+
dph_total=dph,
|
| 133 |
+
cuda_max_good=cuda,
|
| 134 |
+
disk_space=float(r.get("disk_space") or 0),
|
| 135 |
+
reliability=float(r.get("reliability2") or 0),
|
| 136 |
+
inet_down=float(r.get("inet_down") or 0),
|
| 137 |
+
geolocation=str(r.get("geolocation") or ""),
|
| 138 |
+
)
|
| 139 |
+
)
|
| 140 |
+
return sorted(out, key=lambda o: (o.dph_total, o.vram_gb))
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def vast_image() -> str:
|
| 144 |
+
"""Docker image for the worker: the prebuilt, PUBLIC WORKER_IMAGE (full training stack baked
|
| 145 |
+
in). Used for every GPU class — the Blackwell driver floor lives in the ``cuda_max_good`` offer
|
| 146 |
+
filter, not the image. There is no generic fallback image; the worker image is always used."""
|
| 147 |
+
from flash.providers.runpod.train import WORKER_IMAGE
|
| 148 |
+
|
| 149 |
+
return WORKER_IMAGE
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@dataclass
|
| 153 |
+
class VastJobHandle:
|
| 154 |
+
"""Persisted in RunStatus.remote so any process can reattach/cancel (cf. JobHandle)."""
|
| 155 |
+
|
| 156 |
+
instance_id: int
|
| 157 |
+
offer_id: int
|
| 158 |
+
machine_id: int
|
| 159 |
+
label: str
|
| 160 |
+
gpu: str
|
| 161 |
+
hourly_usd: float
|
| 162 |
+
attempt: int
|
| 163 |
+
started_ts: float
|
| 164 |
+
|
| 165 |
+
def to_dict(self) -> dict:
|
| 166 |
+
return {
|
| 167 |
+
"provider": "vast",
|
| 168 |
+
"instance_id": self.instance_id,
|
| 169 |
+
"offer_id": self.offer_id,
|
| 170 |
+
"machine_id": self.machine_id,
|
| 171 |
+
"label": self.label,
|
| 172 |
+
"gpu": self.gpu,
|
| 173 |
+
"hourly_usd": self.hourly_usd,
|
| 174 |
+
"attempt": self.attempt,
|
| 175 |
+
"started_ts": self.started_ts,
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
@classmethod
|
| 179 |
+
def from_dict(cls, d: dict) -> VastJobHandle:
|
| 180 |
+
return cls(
|
| 181 |
+
instance_id=int(d["instance_id"]),
|
| 182 |
+
offer_id=int(d.get("offer_id") or 0),
|
| 183 |
+
machine_id=int(d.get("machine_id") or 0),
|
| 184 |
+
label=str(d.get("label") or ""),
|
| 185 |
+
gpu=str(d.get("gpu") or ""),
|
| 186 |
+
hourly_usd=float(d.get("hourly_usd") or 0),
|
| 187 |
+
attempt=int(d.get("attempt") or 0),
|
| 188 |
+
started_ts=float(d.get("started_ts") or 0),
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def run_label_prefix(run_id: str) -> str:
|
| 193 |
+
"""The prefix EVERY instance label for ``run_id`` starts with.
|
| 194 |
+
|
| 195 |
+
``instance_label`` forces the ``flash-`` prefix onto run ids that lack it, so the
|
| 196 |
+
orphan-sweep allowlist must apply the SAME transform: a raw run id (e.g. a
|
| 197 |
+
"fail-fast" test id) would otherwise never match its own ``flash-…`` labels and a
|
| 198 |
+
live run's instance could be swept (or fail to be protected)."""
|
| 199 |
+
return f"flash-{run_id}" if not run_id.startswith("flash-") else run_id
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def instance_label(run_id: str, seed: int, attempt: int) -> str:
|
| 203 |
+
"""Instance label: run-derived so ``sweep_orphans`` can tell ours from anything
|
| 204 |
+
else on the account. Platform run ids already start with ``flash-``; anything else
|
| 205 |
+
(direct-API callers, tests) gets the prefix forced — an instance we rented must NEVER
|
| 206 |
+
be invisible to the orphan sweep."""
|
| 207 |
+
return f"{run_label_prefix(run_id)}-s{seed}-a{attempt}"
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def build_payload(spec, seed: int, attempt: int) -> dict:
|
| 211 |
+
"""The bootstrap's input — field-compatible with _train_body's, plus the bits the
|
| 212 |
+
instance can't infer (HF prefix for markers, wall cap, attempt)."""
|
| 213 |
+
from flash.envs.registry import worker_hub_env_ids, worker_pip_for_env
|
| 214 |
+
from flash.providers.runpod.train import build_worker_env, chalk_extra_pip
|
| 215 |
+
|
| 216 |
+
return {
|
| 217 |
+
"hf_repo": spec.train.hf_repo,
|
| 218 |
+
"job_spec_json": spec.to_json(),
|
| 219 |
+
"phase": spec.phase,
|
| 220 |
+
"seed": int(seed),
|
| 221 |
+
"env": build_worker_env(spec, seed),
|
| 222 |
+
# The Vast bootstrap pip-installs extra_pip for every job (provider/vast/_bootstrap.py),
|
| 223 |
+
# so the opt-in chalk spec rides along here to reach default runs — see chalk_extra_pip().
|
| 224 |
+
"extra_pip": (list(spec.environment.pip) or worker_pip_for_env(spec.environment.id))
|
| 225 |
+
+ chalk_extra_pip(spec),
|
| 226 |
+
"hub_env_ids": worker_hub_env_ids(spec.environment.id, spec.environment.params),
|
| 227 |
+
"hf_prefix": f"{spec.phase}/{spec.run_id}/seed{seed}",
|
| 228 |
+
"max_wall_s": max(60, int(spec.gpu.max_wall_seconds)),
|
| 229 |
+
"attempt": int(attempt),
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def build_onstart(payload: dict, install_deps: bool = True) -> str:
|
| 234 |
+
"""The instance's onstart script: payload + bootstrap shipped as quoted heredocs.
|
| 235 |
+
|
| 236 |
+
Everything dynamic travels base64-encoded inside the script — never interpolated
|
| 237 |
+
into shell syntax and never through Vast's env plumbing — so the job-spec JSON
|
| 238 |
+
(quotes, spaces, anything) survives byte-exact. Secrets-wise the script carries
|
| 239 |
+
the same content as the worker env on RunPod (HF token; never provider keys).
|
| 240 |
+
|
| 241 |
+
The bootstrap source is the private ``_bootstrap.py`` sibling — an internal detail
|
| 242 |
+
of this provider, not a public module.
|
| 243 |
+
"""
|
| 244 |
+
from flash.providers.runpod.train import resolve_worker_deps
|
| 245 |
+
|
| 246 |
+
payload_b64 = base64.encodebytes(json.dumps(payload).encode()).decode()
|
| 247 |
+
bootstrap_src = (Path(__file__).parent / "_bootstrap.py").read_text()
|
| 248 |
+
if install_deps:
|
| 249 |
+
deps = " ".join(shlex.quote(d) for d in resolve_worker_deps())
|
| 250 |
+
# Vast cold-start is dominated by this dep install (torch/vllm/transformers cu128 stack) on
|
| 251 |
+
# fresh hosts — RunPod caches it as a Flash artifact, but Vast reinstalls per host, so use
|
| 252 |
+
# `uv pip` (validated in the worker image: resolves + installs the full pinned cu128 stack
|
| 253 |
+
# in ~12s, ~10x faster than pip). --break-system-packages: PYBIN is the image's
|
| 254 |
+
# externally-managed system python (newer pytorch images dropped /opt/conda); uv refuses it
|
| 255 |
+
# without this flag (and ignores pip's PIP_BREAK_SYSTEM_PACKAGES), which is what silently
|
| 256 |
+
# broke the earlier uv attempt. The flag is a no-op on a conda/venv python, so it's safe
|
| 257 |
+
# across image variants.
|
| 258 |
+
pip_line = (
|
| 259 |
+
'"$PYBIN" -m pip install --no-cache-dir uv '
|
| 260 |
+
f'&& "$PYBIN" -m uv pip install --python "$PYBIN" --break-system-packages --no-cache {deps}'
|
| 261 |
+
)
|
| 262 |
+
else:
|
| 263 |
+
pip_line = ": # deps baked into the image (WORKER_IMAGE)"
|
| 264 |
+
# Verified live: Vast's args-mode wrapper resets PATH, so `python3` resolves to
|
| 265 |
+
# the OS python (Ubuntu 24.04 = PEP 668 externally-managed -> pip refuses), not
|
| 266 |
+
# the image's conda env. Prefer the conda python when present (torch baked in),
|
| 267 |
+
# and let pip install into whichever interpreter won.
|
| 268 |
+
return f"""#!/bin/bash
|
| 269 |
+
# Flash vast worker (generated by flash.providers.vast.jobs.build_onstart)
|
| 270 |
+
set -x
|
| 271 |
+
export PIP_BREAK_SYSTEM_PACKAGES=1
|
| 272 |
+
PYBIN=/opt/conda/bin/python; [ -x "$PYBIN" ] || PYBIN=/usr/local/bin/python; [ -x "$PYBIN" ] || PYBIN=$(command -v python3)
|
| 273 |
+
mkdir -p /root/flash
|
| 274 |
+
cat > /root/flash/payload.b64 <<'FLASH_PAYLOAD_EOF'
|
| 275 |
+
{payload_b64}FLASH_PAYLOAD_EOF
|
| 276 |
+
base64 -d /root/flash/payload.b64 > /root/flash/payload.json
|
| 277 |
+
cat > /root/flash/bootstrap.py <<'FLASH_BOOTSTRAP_EOF'
|
| 278 |
+
{bootstrap_src}FLASH_BOOTSTRAP_EOF
|
| 279 |
+
# A base worker-stack install failure must STOP the script: continuing into
|
| 280 |
+
# bootstrap.py with a partially installed env turns a deterministic dependency
|
| 281 |
+
# failure into a later import/model crash (or a missing HF marker if
|
| 282 |
+
# huggingface_hub never installed). Hold the box first so the control plane can
|
| 283 |
+
# pull the log tail (mirrors the bootstrap-failure path below and the extra-pip
|
| 284 |
+
# check=True path). The no-deps branch (":") always succeeds, so this is a no-op there.
|
| 285 |
+
{pip_line} || {{ echo "FLASH: base worker dependency install failed" >&2; sleep 600; exit 1; }}
|
| 286 |
+
"$PYBIN" /root/flash/bootstrap.py
|
| 287 |
+
FLASH_RC=$?
|
| 288 |
+
# On failure, hold the box for 10 min so the control plane can pull the container
|
| 289 |
+
# log tail (the only home of early-bootstrap errors); it destroys us much sooner
|
| 290 |
+
# when alive. Success self-destroys immediately.
|
| 291 |
+
[ "$FLASH_RC" -ne 0 ] && sleep 600
|
| 292 |
+
# Self-destroy backstop (the control plane's destroy is primary). CONTAINER_API_KEY
|
| 293 |
+
# is the Vast-injected instance-scoped key — the operator key never ships here.
|
| 294 |
+
# python, not curl: the worker image is not guaranteed to carry curl.
|
| 295 |
+
"$PYBIN" - <<'FLASH_DESTROY_EOF'
|
| 296 |
+
import os, urllib.request
|
| 297 |
+
iid, key = os.environ.get("CONTAINER_ID"), os.environ.get("CONTAINER_API_KEY")
|
| 298 |
+
if iid and key:
|
| 299 |
+
req = urllib.request.Request(
|
| 300 |
+
f"https://console.vast.ai/api/v0/instances/{{iid}}/",
|
| 301 |
+
method="DELETE",
|
| 302 |
+
headers={{"Authorization": f"Bearer {{key}}"}},
|
| 303 |
+
)
|
| 304 |
+
try:
|
| 305 |
+
urllib.request.urlopen(req, timeout=30)
|
| 306 |
+
except Exception as exc:
|
| 307 |
+
print("self-destroy warn:", exc)
|
| 308 |
+
FLASH_DESTROY_EOF
|
| 309 |
+
exit $FLASH_RC
|
| 310 |
+
"""
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def deploy_and_submit(
|
| 314 |
+
spec,
|
| 315 |
+
seed: int,
|
| 316 |
+
offers: list[VastOffer],
|
| 317 |
+
attempt: int = 0,
|
| 318 |
+
log=None,
|
| 319 |
+
exclude_machine_ids: set[int] | frozenset[int] = frozenset(),
|
| 320 |
+
) -> VastJobHandle:
|
| 321 |
+
"""Rent the cheapest offer that will actually take the job; walk on rejection.
|
| 322 |
+
|
| 323 |
+
Offers are a live market — between search and rent the cheapest one is often
|
| 324 |
+
gone. We walk up to 5 ranked offers, then refresh the search once.
|
| 325 |
+
|
| 326 |
+
``exclude_machine_ids`` is the run's blacklist (machines that stalled/failed this
|
| 327 |
+
run earlier). The refresh re-search MUST keep them excluded — otherwise a sick
|
| 328 |
+
machine the orchestrator just blacklisted gets re-selected from the fresh market.
|
| 329 |
+
"""
|
| 330 |
+
|
| 331 |
+
def say(msg: str):
|
| 332 |
+
if log is not None:
|
| 333 |
+
print(f"[{time.strftime('%H:%M:%S')}] {msg}", file=log, flush=True)
|
| 334 |
+
|
| 335 |
+
if not offers:
|
| 336 |
+
raise vast_api.VastApiError("no usable vast offers (verified datacenter pool empty)")
|
| 337 |
+
payload = build_payload(spec, seed, attempt)
|
| 338 |
+
label = instance_label(spec.run_id, seed, attempt)
|
| 339 |
+
from flash.providers.runpod.train import WORKER_IMAGE
|
| 340 |
+
|
| 341 |
+
install_deps = not WORKER_IMAGE
|
| 342 |
+
tried: list[VastOffer] = []
|
| 343 |
+
candidates = list(offers[:5])
|
| 344 |
+
refreshed = False
|
| 345 |
+
last_err: Exception | None = None
|
| 346 |
+
while candidates:
|
| 347 |
+
offer = candidates.pop(0)
|
| 348 |
+
tried.append(offer)
|
| 349 |
+
onstart = build_onstart(payload, install_deps=install_deps)
|
| 350 |
+
try:
|
| 351 |
+
instance_id = vast_api.create_instance(
|
| 352 |
+
offer.offer_id,
|
| 353 |
+
image=vast_image(),
|
| 354 |
+
disk_gb=_effective_disk_gb(spec),
|
| 355 |
+
env={},
|
| 356 |
+
onstart=onstart,
|
| 357 |
+
label=label,
|
| 358 |
+
runtype="args",
|
| 359 |
+
)
|
| 360 |
+
except vast_api.VastApiError as e:
|
| 361 |
+
last_err = e
|
| 362 |
+
say(f"offer {offer.offer_id} ({offer.gpu} ${offer.dph_total:.2f}/hr) rejected: {e}")
|
| 363 |
+
if not candidates and not refreshed:
|
| 364 |
+
refreshed = True
|
| 365 |
+
# Exclude both the machines we just tried this attempt AND the run's
|
| 366 |
+
# standing blacklist (machines that stalled/failed earlier attempts) —
|
| 367 |
+
# otherwise the fresh search can re-select a sick machine the
|
| 368 |
+
# orchestrator deliberately excluded.
|
| 369 |
+
taken = {o.machine_id for o in tried} | set(exclude_machine_ids)
|
| 370 |
+
# Stay within the allocator-approved class pool: the original `offers`
|
| 371 |
+
# are already filtered to the allocated/pinned + validated classes, so
|
| 372 |
+
# the refresh must not widen to any usable offer (which could rent a
|
| 373 |
+
# different or unvalidated GPU than the run spec assumes).
|
| 374 |
+
allowed = {o.gpu for o in offers}
|
| 375 |
+
candidates = [
|
| 376 |
+
o
|
| 377 |
+
for o in usable_offers(
|
| 378 |
+
min(o.vram_gb for o in offers),
|
| 379 |
+
_effective_disk_gb(spec),
|
| 380 |
+
exclude_machine_ids=taken,
|
| 381 |
+
)
|
| 382 |
+
if o.gpu in allowed
|
| 383 |
+
][:5]
|
| 384 |
+
continue
|
| 385 |
+
say(
|
| 386 |
+
f"rented vast instance {instance_id}: {offer.gpu} ${offer.dph_total:.2f}/hr "
|
| 387 |
+
f"(offer {offer.offer_id}, {offer.geolocation}, reliability "
|
| 388 |
+
f"{offer.reliability:.3f}) attempt={attempt} seed={seed}"
|
| 389 |
+
)
|
| 390 |
+
return VastJobHandle(
|
| 391 |
+
instance_id=instance_id,
|
| 392 |
+
offer_id=offer.offer_id,
|
| 393 |
+
machine_id=offer.machine_id,
|
| 394 |
+
label=label,
|
| 395 |
+
gpu=offer.gpu,
|
| 396 |
+
hourly_usd=offer.dph_total,
|
| 397 |
+
attempt=attempt,
|
| 398 |
+
started_ts=time.time(),
|
| 399 |
+
)
|
| 400 |
+
raise vast_api.VastApiError(f"all {len(tried)} vast offers rejected the job: {last_err}")
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
# Rate-limited reader for one HF artifact's text content (None until it exists). Shared
|
| 404 |
+
# with runpod's poller via make_hf_text_reader; kept under this module-local name because
|
| 405 |
+
# tests monkeypatch ``vast.jobs._make_hf_file_reader`` and the poll/failure paths below
|
| 406 |
+
# resolve it as a module global (so a monkeypatch still takes effect).
|
| 407 |
+
_make_hf_file_reader = make_hf_text_reader
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def _failure_detail(
|
| 411 |
+
hf_repo: str, prefix: str, phase: str, marker: dict | None, instance_id: int | None = None
|
| 412 |
+
) -> str:
|
| 413 |
+
"""Best root-cause detail we can assemble from the HF artifacts."""
|
| 414 |
+
parts = []
|
| 415 |
+
if marker and marker.get("error"):
|
| 416 |
+
parts.append(str(marker["error"]))
|
| 417 |
+
content = _make_hf_file_reader(hf_repo, f"{prefix}/error_{phase}.txt")(force=True)
|
| 418 |
+
if content:
|
| 419 |
+
parts.append(f"--- error_{phase}.txt ---\n{content[-2000:]}")
|
| 420 |
+
if instance_id:
|
| 421 |
+
# Early-bootstrap failures (pip/env errors before the worker can reach HF)
|
| 422 |
+
# only ever appear on the container console.
|
| 423 |
+
logs = vast_api.instance_logs(int(instance_id))
|
| 424 |
+
if logs:
|
| 425 |
+
parts.append(f"--- instance log tail ---\n{logs[-3000:]}")
|
| 426 |
+
return "\n".join(parts) or "vast worker terminated without a DONE sentinel"
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
# Vast instance states that mean "the container is gone / will not progress".
|
| 430 |
+
_DEAD_STATES = {"exited", "stopped", "offline", "deleted"}
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def poll_vast_job(
|
| 434 |
+
handle: VastJobHandle,
|
| 435 |
+
spec,
|
| 436 |
+
seed: int,
|
| 437 |
+
log=None,
|
| 438 |
+
interval_s: float = 15.0,
|
| 439 |
+
heartbeat_reader=None,
|
| 440 |
+
stall_after_s: float = 1500.0,
|
| 441 |
+
deadline_s: float | None = None,
|
| 442 |
+
) -> PollResult:
|
| 443 |
+
"""Poll instance status + HF artifacts to a terminal state (cf. jobs.poll_job).
|
| 444 |
+
|
| 445 |
+
COMPLETED fresh DONE sentinel on HF -> metrics.json (cost stamped from the
|
| 446 |
+
offer's real $/hr).
|
| 447 |
+
FAILED attempt marker with ok=false, or instance dead without DONE.
|
| 448 |
+
STALLED never left loading within LOAD_TIMEOUT_S, heartbeat frozen for
|
| 449 |
+
stall_after_s, or the client-side deadline passed.
|
| 450 |
+
"""
|
| 451 |
+
|
| 452 |
+
say = make_say(log)
|
| 453 |
+
|
| 454 |
+
hf_repo = spec.train.hf_repo
|
| 455 |
+
prefix = f"{spec.phase}/{spec.run_id}/seed{seed}"
|
| 456 |
+
done_reader = _make_hf_file_reader(hf_repo, f"{prefix}/DONE")
|
| 457 |
+
marker_reader = _make_hf_file_reader(
|
| 458 |
+
hf_repo, f"{prefix}/vast_attempt{handle.attempt}.json", min_interval_s=60.0
|
| 459 |
+
)
|
| 460 |
+
metrics_reader = _make_hf_file_reader(hf_repo, f"{prefix}/metrics.json")
|
| 461 |
+
|
| 462 |
+
def finish_ok(done_content: str | None = None) -> PollResult:
|
| 463 |
+
raw = metrics_reader(force=True)
|
| 464 |
+
if raw is None:
|
| 465 |
+
return PollResult(False, failure="job_failed", detail="DONE without metrics.json")
|
| 466 |
+
metrics = json.loads(raw)
|
| 467 |
+
# Prefer the worker's DONE timestamp when present and sane; fall back to now.
|
| 468 |
+
# On delayed recovery the control plane may call this hours after the instance
|
| 469 |
+
# wrote DONE and self-destroyed, so billing to now would over-bill by the
|
| 470 |
+
# downtime — accepted because a missing/garbled DONE timestamp is rare. DONE
|
| 471 |
+
# carries the worker's time.time().
|
| 472 |
+
end_ts = time.time()
|
| 473 |
+
if done_content:
|
| 474 |
+
try:
|
| 475 |
+
done_ts = float(done_content.strip())
|
| 476 |
+
if handle.started_ts <= done_ts <= end_ts:
|
| 477 |
+
end_ts = done_ts
|
| 478 |
+
except ValueError:
|
| 479 |
+
# Malformed DONE timestamp: keep end_ts = now rather than trusting garbage.
|
| 480 |
+
pass
|
| 481 |
+
wall_h = (end_ts - handle.started_ts) / 3600.0
|
| 482 |
+
metrics["cost_usd"] = round(wall_h * handle.hourly_usd, 6)
|
| 483 |
+
notes = metrics.get("notes") if isinstance(metrics.get("notes"), dict) else {}
|
| 484 |
+
notes.update(
|
| 485 |
+
{
|
| 486 |
+
"provider": "vast",
|
| 487 |
+
"vast_rate_usd_hr": handle.hourly_usd,
|
| 488 |
+
"vast_gpu": handle.gpu,
|
| 489 |
+
"vast_offer_id": handle.offer_id,
|
| 490 |
+
}
|
| 491 |
+
)
|
| 492 |
+
metrics["notes"] = notes
|
| 493 |
+
return PollResult(True, metrics=metrics)
|
| 494 |
+
|
| 495 |
+
def done_is_fresh(content: str) -> bool:
|
| 496 |
+
# DONE carries the worker's time.time(); 120 s of clock-skew grace. Anything
|
| 497 |
+
# older predates this attempt (leftover from a prior attempt's resume).
|
| 498 |
+
try:
|
| 499 |
+
return float(content.strip()) > handle.started_ts - 120.0
|
| 500 |
+
except ValueError:
|
| 501 |
+
return False
|
| 502 |
+
|
| 503 |
+
poll_errors = PollErrorTracker(say, interval_s)
|
| 504 |
+
|
| 505 |
+
start = time.time()
|
| 506 |
+
last_status = None
|
| 507 |
+
last_hb_key = None
|
| 508 |
+
last_progress = time.time()
|
| 509 |
+
became_running = False
|
| 510 |
+
missing_streak = 0
|
| 511 |
+
while True:
|
| 512 |
+
if deadline_s is not None and time.time() - start > deadline_s:
|
| 513 |
+
return PollResult(False, failure="stalled", detail="client-side deadline exceeded")
|
| 514 |
+
try:
|
| 515 |
+
inst = vast_api.get_instance(handle.instance_id)
|
| 516 |
+
poll_errors.reset()
|
| 517 |
+
except vast_api.VastApiError as e:
|
| 518 |
+
if poll_errors.record(e):
|
| 519 |
+
return PollResult(False, failure="poll_error", detail=str(e))
|
| 520 |
+
continue
|
| 521 |
+
# Verified live: the instance-detail route TRANSIENTLY answers
|
| 522 |
+
# {"instances": null} for perfectly healthy instances (and for brand-new ones
|
| 523 |
+
# before they materialize). A single missing read means nothing — only a
|
| 524 |
+
# sustained streak is a real disappearance.
|
| 525 |
+
missing_streak = missing_streak + 1 if inst is None else 0
|
| 526 |
+
|
| 527 |
+
status = (inst or {}).get("actual_status") or ("missing" if inst is None else "unknown")
|
| 528 |
+
if status != last_status:
|
| 529 |
+
say(f"instance {handle.instance_id}: {status}")
|
| 530 |
+
last_status = status
|
| 531 |
+
last_progress = time.time()
|
| 532 |
+
if status == "running":
|
| 533 |
+
became_running = True
|
| 534 |
+
|
| 535 |
+
done = done_reader()
|
| 536 |
+
if done is not None and done_is_fresh(done):
|
| 537 |
+
return finish_ok(done)
|
| 538 |
+
|
| 539 |
+
if missing_streak >= 4 or status in _DEAD_STATES:
|
| 540 |
+
# One forced final read: the worker may have finished right before the
|
| 541 |
+
# instance self-destroyed (the normal success order on this substrate).
|
| 542 |
+
done = done_reader(force=True)
|
| 543 |
+
if done is not None and done_is_fresh(done):
|
| 544 |
+
return finish_ok(done)
|
| 545 |
+
raw_marker = marker_reader(force=True)
|
| 546 |
+
marker = None
|
| 547 |
+
if raw_marker:
|
| 548 |
+
with contextlib.suppress(ValueError):
|
| 549 |
+
marker = json.loads(raw_marker)
|
| 550 |
+
return PollResult(
|
| 551 |
+
False,
|
| 552 |
+
failure="job_failed",
|
| 553 |
+
detail=_failure_detail(hf_repo, prefix, spec.phase, marker, handle.instance_id),
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
raw_marker = marker_reader()
|
| 557 |
+
if raw_marker:
|
| 558 |
+
try:
|
| 559 |
+
marker = json.loads(raw_marker)
|
| 560 |
+
except ValueError:
|
| 561 |
+
marker = None
|
| 562 |
+
if marker and not marker.get("ok"):
|
| 563 |
+
return PollResult(
|
| 564 |
+
False,
|
| 565 |
+
failure="job_failed",
|
| 566 |
+
detail=_failure_detail(hf_repo, prefix, spec.phase, marker, handle.instance_id),
|
| 567 |
+
)
|
| 568 |
+
if marker and marker.get("ok"):
|
| 569 |
+
done = done_reader(force=True)
|
| 570 |
+
if done is not None and done_is_fresh(done):
|
| 571 |
+
return finish_ok(done)
|
| 572 |
+
|
| 573 |
+
if not became_running and time.time() - start > LOAD_TIMEOUT_S:
|
| 574 |
+
return PollResult(
|
| 575 |
+
False,
|
| 576 |
+
failure="stalled",
|
| 577 |
+
detail=f"instance stuck in '{status}' for {int(time.time() - start)}s "
|
| 578 |
+
f"(image pull / host issue)",
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
new_key, _stage = surface_heartbeat(heartbeat_reader, last_hb_key, say)
|
| 582 |
+
if new_key != last_hb_key:
|
| 583 |
+
last_hb_key = new_key
|
| 584 |
+
last_progress = time.time()
|
| 585 |
+
if became_running and time.time() - last_progress > stall_after_s:
|
| 586 |
+
return PollResult(
|
| 587 |
+
False,
|
| 588 |
+
failure="stalled",
|
| 589 |
+
detail=f"no worker progress for {int(time.time() - last_progress)}s "
|
| 590 |
+
f"(instance status {status})",
|
| 591 |
+
)
|
| 592 |
+
time.sleep(interval_s)
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def submit_run_vast(
|
| 596 |
+
spec,
|
| 597 |
+
seed: int,
|
| 598 |
+
log=None,
|
| 599 |
+
on_handle=None,
|
| 600 |
+
attempt: int = 0,
|
| 601 |
+
offers: list[VastOffer] | None = None,
|
| 602 |
+
exclude_machine_ids: set[int] | frozenset[int] = frozenset(),
|
| 603 |
+
) -> PollResult:
|
| 604 |
+
"""Vast equivalent of ``runpod.jobs.submit_run``: rent, persist, poll.
|
| 605 |
+
|
| 606 |
+
The ``finally`` destroy is the cost-safety primary: every exit path — success,
|
| 607 |
+
failure, stall, exception, KeyboardInterrupt — tears the paid instance down.
|
| 608 |
+
"""
|
| 609 |
+
if offers is None:
|
| 610 |
+
# GPU_INFO is keyed by concrete GPU class; a policy word ("cheapest"/"auto") would
|
| 611 |
+
# KeyError opaquely here. The allocator resolves policy words to a concrete class
|
| 612 |
+
# upstream, so reaching this fallback with one is a caller bug — name it clearly.
|
| 613 |
+
if spec.gpu.type not in GPU_INFO:
|
| 614 |
+
raise vast_api.VastApiError(
|
| 615 |
+
f"submit_run_vast needs a concrete gpu class, got {spec.gpu.type!r}"
|
| 616 |
+
)
|
| 617 |
+
info = GPU_INFO[spec.gpu.type]
|
| 618 |
+
offers = [
|
| 619 |
+
o
|
| 620 |
+
for o in usable_offers(
|
| 621 |
+
info.vram_gb,
|
| 622 |
+
_effective_disk_gb(spec),
|
| 623 |
+
exclude_machine_ids=exclude_machine_ids,
|
| 624 |
+
)
|
| 625 |
+
if o.gpu == spec.gpu.type
|
| 626 |
+
]
|
| 627 |
+
handle = deploy_and_submit(
|
| 628 |
+
spec, seed, offers, attempt=attempt, log=log, exclude_machine_ids=exclude_machine_ids
|
| 629 |
+
)
|
| 630 |
+
# The instance is rented and billing the MOMENT deploy_and_submit returns; the
|
| 631 |
+
# teardown ``finally`` must guard EVERYTHING after that point — including
|
| 632 |
+
# ``on_handle`` (persisting the remote handle can itself raise). Entering the try
|
| 633 |
+
# before on_handle guarantees the paid instance is destroyed even if the handle is
|
| 634 |
+
# never persisted, closing the rent->persist crash window's billing leak.
|
| 635 |
+
try:
|
| 636 |
+
if on_handle is not None:
|
| 637 |
+
on_handle(handle.to_dict())
|
| 638 |
+
hf_repo = spec.train.hf_repo
|
| 639 |
+
prefix = f"{spec.phase}/{spec.run_id}/seed{seed}"
|
| 640 |
+
reader = make_hf_heartbeat_reader(hf_repo, prefix) if hf_repo else None
|
| 641 |
+
stall = 1500.0
|
| 642 |
+
# Wall cap + provision/install grace; Vast has no server-side execution
|
| 643 |
+
# timeout, so the client deadline (and the bootstrap's own cap) bound spend.
|
| 644 |
+
deadline = max(60, int(spec.gpu.max_wall_seconds)) + 1800
|
| 645 |
+
return poll_vast_job(
|
| 646 |
+
handle,
|
| 647 |
+
spec,
|
| 648 |
+
seed,
|
| 649 |
+
log=log,
|
| 650 |
+
heartbeat_reader=reader,
|
| 651 |
+
stall_after_s=stall,
|
| 652 |
+
deadline_s=deadline,
|
| 653 |
+
)
|
| 654 |
+
finally:
|
| 655 |
+
vast_api.destroy_instance(handle.instance_id)
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
def cancel(remote: dict) -> None:
|
| 659 |
+
"""Cross-process cancel: destroy the persisted instance (stops billing)."""
|
| 660 |
+
instance_id = remote.get("instance_id")
|
| 661 |
+
if instance_id:
|
| 662 |
+
vast_api.destroy_instance(int(instance_id))
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
def destroy_run_instances(run_id: str) -> list[int]:
|
| 666 |
+
"""Destroy every instance belonging to ONE run (labels start with its run id).
|
| 667 |
+
|
| 668 |
+
Cancel/GC path: unlike ``sweep_orphans`` this never looks at other runs, so it
|
| 669 |
+
is safe to call while they are in flight. Best-effort: never raises.
|
| 670 |
+
"""
|
| 671 |
+
destroyed: list[int] = []
|
| 672 |
+
if not run_id:
|
| 673 |
+
return destroyed
|
| 674 |
+
try:
|
| 675 |
+
instances = vast_api.list_instances()
|
| 676 |
+
except Exception:
|
| 677 |
+
return destroyed
|
| 678 |
+
prefixes = (run_id, f"flash-{run_id}") # instance_label may force the prefix
|
| 679 |
+
for inst in instances:
|
| 680 |
+
iid = inst.get("id")
|
| 681 |
+
label = str(inst.get("label") or "")
|
| 682 |
+
# Match on the label boundary, not a raw string prefix (see ``sweep_orphans``):
|
| 683 |
+
# an instance label is ``f"{run_label_prefix(run_id)}-s{seed}-a{attempt}"``, so a
|
| 684 |
+
# run's prefix must equal the label or be followed by the ``-s`` seed boundary.
|
| 685 |
+
# A bare ``startswith`` would let run ``100`` also destroy run ``1000``'s instances.
|
| 686 |
+
if (
|
| 687 |
+
iid
|
| 688 |
+
and any(label == p or label.startswith(p + "-s") for p in prefixes)
|
| 689 |
+
and vast_api.destroy_instance(int(iid))
|
| 690 |
+
):
|
| 691 |
+
destroyed.append(int(iid))
|
| 692 |
+
return destroyed
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
def sweep_orphans(active_labels: set[str] | None = None) -> list[int]:
|
| 696 |
+
"""Destroy Flash-labeled instances that no live run owns; return destroyed ids.
|
| 697 |
+
|
| 698 |
+
Run at server startup (crash recovery) and after runs (belt and suspenders).
|
| 699 |
+
Only labels carrying the run-id prefix are ever touched — nothing else on the
|
| 700 |
+
account is ours to destroy. Best-effort: never raises.
|
| 701 |
+
|
| 702 |
+
``active_labels`` may be RAW run ids (what the server tracks) — each is passed
|
| 703 |
+
through ``run_label_prefix`` so it matches the SAME forced-``flash-`` prefix the
|
| 704 |
+
instance labels carry. Passing an already-prefixed label is fine (idempotent), so a
|
| 705 |
+
live run whose id lacks the prefix is still correctly protected.
|
| 706 |
+
"""
|
| 707 |
+
destroyed: list[int] = []
|
| 708 |
+
try:
|
| 709 |
+
instances = vast_api.list_instances()
|
| 710 |
+
except Exception as exc:
|
| 711 |
+
logger.warning("vast orphan sweep skipped: %s", exc)
|
| 712 |
+
return destroyed
|
| 713 |
+
active = {run_label_prefix(a) for a in (active_labels or set())}
|
| 714 |
+
for inst in instances:
|
| 715 |
+
label = str(inst.get("label") or "")
|
| 716 |
+
if not label.startswith("flash-"):
|
| 717 |
+
continue
|
| 718 |
+
# Match on the label boundary, not a raw string prefix: an instance label is
|
| 719 |
+
# ``f"{run_label_prefix(run_id)}-s{seed}-a{attempt}"`` (see ``instance_label``),
|
| 720 |
+
# so a live run's prefix must equal the label or be followed by the ``-s`` seed
|
| 721 |
+
# boundary. A bare ``startswith`` would let one run's prefix (e.g. ``flash-100``)
|
| 722 |
+
# shield another run's orphan (``flash-1000-...``) from the sweep.
|
| 723 |
+
if any(label == a or label.startswith(a + "-s") for a in active):
|
| 724 |
+
continue
|
| 725 |
+
iid = inst.get("id")
|
| 726 |
+
if iid and vast_api.destroy_instance(int(iid)):
|
| 727 |
+
destroyed.append(int(iid))
|
| 728 |
+
logger.warning("destroyed orphaned vast instance %s (label %s)", iid, label)
|
| 729 |
+
return destroyed
|
code/flash/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 flash.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/flash/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: FLASH_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 flash._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 flash.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: FLASH_SKIP_NET (or any fetch failure) returns the static rates.
|
| 30 |
+
"""
|
| 31 |
+
static = _static_rates()
|
| 32 |
+
if os.environ.get("FLASH_SKIP_NET") or not os.environ.get("VAST_API_KEY"):
|
| 33 |
+
return static
|
| 34 |
+
try:
|
| 35 |
+
from flash.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 flash.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/flash/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 flash.providers.runpod.train import (
|
| 13 |
+
WORKER_DEPS,
|
| 14 |
+
WORKER_SYSTEM_DEPS,
|
| 15 |
+
build_worker_env,
|
| 16 |
+
resolve_worker_deps,
|
| 17 |
+
)
|
| 18 |
+
from flash.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/flash/py.typed
ADDED
|
File without changes
|
code/flash/runner.py
ADDED
|
@@ -0,0 +1,994 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Platform runner: drives managed GPUs across providers (RunPod Flash + Vast), one allocation per seed."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import contextlib
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
import tempfile
|
| 10 |
+
import threading
|
| 11 |
+
import time
|
| 12 |
+
import uuid
|
| 13 |
+
from dataclasses import asdict, dataclass, field
|
| 14 |
+
|
| 15 |
+
from .catalog import ModelInfo, resolve_model
|
| 16 |
+
from .spec import JobSpec
|
| 17 |
+
|
| 18 |
+
# Fixed local storage roots (not operator-configurable): run-state JSON + result artifacts,
|
| 19 |
+
# both under the ~/.flash 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 ~/.flash to persist it.
|
| 21 |
+
# Tests redirect them via monkeypatch.setattr(runner, "RUNS_DIR"/"RESULTS_DIR").
|
| 22 |
+
_STATE_DIR = os.path.join(os.path.expanduser("~"), ".flash")
|
| 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 flash.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 = "flash") -> str:
|
| 85 |
+
return f"{prefix}-{int(time.time())}-{uuid.uuid4().hex[:8]}"
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
_RUN_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def require_safe_run_id(run_id: str) -> str:
|
| 92 |
+
"""Reject run ids that could traverse outside the runs directory.
|
| 93 |
+
|
| 94 |
+
Run ids flow from API path params into filesystem paths (status json,
|
| 95 |
+
log files); restrict them to a conservative filename alphabet.
|
| 96 |
+
"""
|
| 97 |
+
if not _RUN_ID_RE.match(run_id or ""):
|
| 98 |
+
raise ValueError(f"invalid run_id: {run_id!r}")
|
| 99 |
+
return run_id
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def runs_file_path(run_id: str, suffix: str) -> str:
|
| 103 |
+
"""Containment-checked path for a run's file under RUNS_DIR.
|
| 104 |
+
|
| 105 |
+
Belt and braces with require_safe_run_id: the resolved path must stay
|
| 106 |
+
inside the runs directory even if the alphabet check ever regresses.
|
| 107 |
+
"""
|
| 108 |
+
base = os.path.abspath(RUNS_DIR)
|
| 109 |
+
path = os.path.normpath(os.path.join(base, f"{require_safe_run_id(run_id)}{suffix}"))
|
| 110 |
+
if not path.startswith(base + os.sep):
|
| 111 |
+
raise ValueError(f"invalid run_id: {run_id!r}")
|
| 112 |
+
return path
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _with_model_disk(spec: JobSpec, info: ModelInfo) -> dict:
|
| 116 |
+
"""Spec dict with gpu.disk_gb raised to the model's min_disk_gb (catalog).
|
| 117 |
+
|
| 118 |
+
Big-checkpoint models (whose weights alone exceed the default) need more container
|
| 119 |
+
disk than the platform's 64 GB default; this makes them work without users having
|
| 120 |
+
to know the right ``gpu.disk_gb``.
|
| 121 |
+
"""
|
| 122 |
+
d = spec.to_dict()
|
| 123 |
+
need = int(getattr(info, "min_disk_gb", 0) or 0)
|
| 124 |
+
if need > int(d["gpu"].get("disk_gb") or 0):
|
| 125 |
+
d["gpu"] = {**d["gpu"], "disk_gb": need}
|
| 126 |
+
return d
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def submit_job(spec: JobSpec, dry_run: bool = False, background: bool = False) -> RunStatus:
|
| 130 |
+
"""Submit a job. In real mode this allocates and provisions the cheapest validated GPU class
|
| 131 |
+
across the configured providers (RunPod Flash or Vast); dry-run only records state."""
|
| 132 |
+
info = resolve_model(spec.model, spec.algorithm, policy=spec.model_policy, gpu=spec.gpu.type)
|
| 133 |
+
spec = JobSpec.from_dict(
|
| 134 |
+
{**_with_model_disk(spec, info), "run_id": spec.run_id or new_run_id()}
|
| 135 |
+
)
|
| 136 |
+
status = RunStatus(run_id=spec.run_id, state="queued", spec=spec.to_dict())
|
| 137 |
+
_save_status(status)
|
| 138 |
+
if dry_run:
|
| 139 |
+
status.state = "dry_run"
|
| 140 |
+
_save_status(status)
|
| 141 |
+
return status
|
| 142 |
+
if background:
|
| 143 |
+
threading.Thread(target=_run_job, args=(spec,), daemon=True).start()
|
| 144 |
+
return get_status(spec.run_id)
|
| 145 |
+
_run_job(spec)
|
| 146 |
+
return get_status(spec.run_id)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def get_status(run_id: str) -> RunStatus:
|
| 150 |
+
path = runs_file_path(run_id, ".json")
|
| 151 |
+
if not os.path.exists(path):
|
| 152 |
+
raise FileNotFoundError(f"unknown run_id: {run_id}")
|
| 153 |
+
with open(path) as f:
|
| 154 |
+
return RunStatus(**json.load(f))
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def list_runs() -> list[RunStatus]:
|
| 158 |
+
os.makedirs(RUNS_DIR, exist_ok=True)
|
| 159 |
+
runs = []
|
| 160 |
+
for name in sorted(os.listdir(RUNS_DIR)):
|
| 161 |
+
if name.endswith(".json"):
|
| 162 |
+
with open(os.path.join(RUNS_DIR, name)) as f:
|
| 163 |
+
runs.append(RunStatus(**json.load(f)))
|
| 164 |
+
return runs
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def get_logs(run_id: str) -> str:
|
| 168 |
+
log_path = runs_file_path(run_id, ".log")
|
| 169 |
+
if not os.path.exists(log_path):
|
| 170 |
+
return ""
|
| 171 |
+
with open(log_path) as f:
|
| 172 |
+
return f.read()
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def cancel_run(run_id: str) -> RunStatus:
|
| 176 |
+
"""Cancel a run: delete its remote Flash endpoint (stopping the worker), then mark it
|
| 177 |
+
cancelled.
|
| 178 |
+
|
| 179 |
+
Uses ``terminate_endpoint`` (reconstructs the run's uniquely-named endpoint and deletes it
|
| 180 |
+
via the RunPod API) so the cancel works **cross-process** — a fresh ``slm cancel`` actually
|
| 181 |
+
stops the GPU worker, instead of leaving it running until the wall cap. Best-effort: any
|
| 182 |
+
teardown error is recorded but still flips the run to ``cancelled``.
|
| 183 |
+
"""
|
| 184 |
+
status = get_status(run_id)
|
| 185 |
+
if status.state in TERMINAL_STATES:
|
| 186 |
+
return status
|
| 187 |
+
# Whether the run was a live `deployed` serving run at cancel entry. This scopes the
|
| 188 |
+
# final `cancelled` transition's terminal override below: only a `deployed` run can have
|
| 189 |
+
# a concurrent undeploy (`mark_undeployed`) race this teardown and write a non-completion
|
| 190 |
+
# terminal `done`. A non-deployed run (running/provisioning/queued) has an in-flight
|
| 191 |
+
# TRAINING thread whose only terminal `done` is a GENUINE completion — which cancel must
|
| 192 |
+
# never clobber. See the final _update call for how this gates the override.
|
| 193 |
+
entered_deployed = status.state == "deployed"
|
| 194 |
+
spec = JobSpec.from_dict(status.spec)
|
| 195 |
+
remote = status.remote or {}
|
| 196 |
+
# A deployed run also owns a serving endpoint (flash-serve-*) that the
|
| 197 |
+
# training-endpoint GC below does not touch; tear it down too so a
|
| 198 |
+
# cancelled run can't leave a billable deployment registered. Serving is
|
| 199 |
+
# RunPod-only, so use the class actually deployed (a Vast-only training class
|
| 200 |
+
# falls back to a RunPod class at deploy time).
|
| 201 |
+
if status.state == "deployed":
|
| 202 |
+
try:
|
| 203 |
+
from flash.serve.deploy import undeploy_adapter
|
| 204 |
+
|
| 205 |
+
deployed_gpu = (status.deployment or {}).get("gpu") or spec.gpu.type
|
| 206 |
+
deleted = undeploy_adapter(run_id, gpu_name=deployed_gpu)
|
| 207 |
+
# Mark the deployment inactive so /v1/deployments and /chat (which gate only
|
| 208 |
+
# on the deployment record's state) stop treating the cancelled run as
|
| 209 |
+
# active. dev mode is scale-to-zero: a never-chatted dev deployment has no
|
| 210 |
+
# endpoint yet, so an empty deletion is still a clean teardown — don't leave
|
| 211 |
+
# it "ready". always-on provisions at deploy time, so only mark it inactive
|
| 212 |
+
# once a deletion is confirmed (an empty deletion there is suspicious).
|
| 213 |
+
dev_mode = (status.deployment or {}).get("mode", "dev") == "dev"
|
| 214 |
+
if status.deployment and (deleted or dev_mode):
|
| 215 |
+
# Mark the deployment inactive through the lock-guarded path so this write
|
| 216 |
+
# participates in the same _STATUS_LOCK as the rest of the runner. A bare
|
| 217 |
+
# _save_status here would persist a stale pre-teardown snapshot OUTSIDE the
|
| 218 |
+
# lock, bypassing serialization and potentially clobbering a concurrent field
|
| 219 |
+
# update. We mark ONLY the deployment field and leave the run's state alone
|
| 220 |
+
# (no state re-assert): a concurrent mark_undeployed can move the run to
|
| 221 |
+
# terminal `done` between our get_status read and this write, and _update's
|
| 222 |
+
# compare-and-set rejects ANY transition off a terminal state (even a
|
| 223 |
+
# same-field re-assert of the stale `deployed`), which would silently leave
|
| 224 |
+
# the deployment advertised as `ready`. mark_deployment_undeployed flips the
|
| 225 |
+
# deployment regardless of (and without disturbing) the current state.
|
| 226 |
+
mark_deployment_undeployed(run_id)
|
| 227 |
+
except Exception:
|
| 228 |
+
# Best-effort serving teardown: a failure here must not block the cancel
|
| 229 |
+
# below (the run still flips to cancelled and the training endpoint is GC'd).
|
| 230 |
+
pass
|
| 231 |
+
# Durable path first: stop the exact remote worker via the handle's provider
|
| 232 |
+
# (works from any process); endpoint/instance teardown is shared with the GC.
|
| 233 |
+
# Dispatched generically through the registry — never a hardcoded per-provider branch.
|
| 234 |
+
if remote:
|
| 235 |
+
try:
|
| 236 |
+
from flash.providers import get_provider
|
| 237 |
+
from flash.providers.base import JobHandle
|
| 238 |
+
|
| 239 |
+
handle = JobHandle.from_dict(remote)
|
| 240 |
+
provider = get_provider(handle.provider)
|
| 241 |
+
provider.cancel(handle)
|
| 242 |
+
# Vast bills until destroyed, so also belt-and-suspenders destroy the
|
| 243 |
+
# instance (a no-op cost-wise for runpod, whose endpoint GC follows).
|
| 244 |
+
provider.destroy(handle)
|
| 245 |
+
except Exception:
|
| 246 |
+
# Best-effort remote stop; _gc_run_endpoints below still tears the endpoint down.
|
| 247 |
+
pass
|
| 248 |
+
_gc_run_endpoints(spec)
|
| 249 |
+
# Final transition to `cancelled`. The run was NON-terminal at entry, but teardown takes
|
| 250 |
+
# time and a terminal state can race in mid-teardown. We must distinguish two cases:
|
| 251 |
+
#
|
| 252 |
+
# - A concurrent mark_undeployed() (an external `DELETE /v1/runs/{id}/deploy`) flipped a
|
| 253 |
+
# `deployed` run to terminal `done`. That `done` is NOT a fresh result — it just
|
| 254 |
+
# restored the run's pre-deploy completion marker while retiring serving. The user
|
| 255 |
+
# explicitly asked to cancel, so this must be OVERRIDDEN to `cancelled`.
|
| 256 |
+
# - A genuine training-COMPLETION `done` from the run's own training thread
|
| 257 |
+
# (_run_job_inner / attach_run), which persisted real metrics+cost+artifacts. Cancel
|
| 258 |
+
# must NEVER clobber that — the run finished, so the real result is preserved.
|
| 259 |
+
#
|
| 260 |
+
# These two races are mutually exclusive on the entry state: only a `deployed` run owns a
|
| 261 |
+
# deployment that mark_undeployed can race, and only a non-deployed (running/provisioning/
|
| 262 |
+
# queued) run has an in-flight training thread that can complete mid-teardown. So scope the
|
| 263 |
+
# terminal override to runs that were `deployed` at entry — there a racing `done` is always
|
| 264 |
+
# an undeploy artifact (cancel wins); elsewhere a racing `done` is a genuine completion that
|
| 265 |
+
# _update's CAS correctly protects (cancel loses to a real finish).
|
| 266 |
+
_update(run_id, "cancelled", allow_from_terminal=entered_deployed)
|
| 267 |
+
return get_status(run_id)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def attach_run(run_id: str, log_stream=None) -> RunStatus:
|
| 271 |
+
"""Re-attach to a run's remote job from ANY process (after a client crash/restart).
|
| 272 |
+
|
| 273 |
+
Uses the persisted {endpoint_id, job_id} handle to resume polling; on completion,
|
| 274 |
+
persists metrics exactly like the original client would have, flips the state, and
|
| 275 |
+
GCs the endpoint. Raises if the run has no persisted handle (it failed or was
|
| 276 |
+
cancelled before a worker was provisioned).
|
| 277 |
+
"""
|
| 278 |
+
import sys
|
| 279 |
+
|
| 280 |
+
status = get_status(run_id)
|
| 281 |
+
if status.state in TERMINAL_STATES:
|
| 282 |
+
return status
|
| 283 |
+
if not status.remote:
|
| 284 |
+
raise ValueError(f"run {run_id} has no persisted job handle; cannot reattach")
|
| 285 |
+
|
| 286 |
+
spec = JobSpec.from_dict(status.spec)
|
| 287 |
+
remote = dict(status.remote)
|
| 288 |
+
seed = int(remote.pop("seed", spec.train.seeds[0]))
|
| 289 |
+
# The class the run actually provisioned (a policy retry may have walked past the
|
| 290 |
+
# provisional spec.gpu.type). The in-process success path stamps this into metrics;
|
| 291 |
+
# on recovery the worker output carries no such field, so recover it from the handle
|
| 292 |
+
# to cost the right card.
|
| 293 |
+
allocated_gpu = remote.pop("allocated_gpu", None)
|
| 294 |
+
log = log_stream or sys.stderr
|
| 295 |
+
# Dispatch the poll generically via the handle's provider (the provider owns its
|
| 296 |
+
# heartbeat reader + poll loop); the orchestrator stays provider-agnostic.
|
| 297 |
+
from flash.providers import get_provider
|
| 298 |
+
from flash.providers.base import JobHandle
|
| 299 |
+
|
| 300 |
+
handle = JobHandle.from_dict(remote)
|
| 301 |
+
print(f"attaching to {run_id}: provider={handle.provider} {handle.data}", file=log)
|
| 302 |
+
res = get_provider(handle.provider).poll(handle, spec, seed, log=log)
|
| 303 |
+
try:
|
| 304 |
+
# A best-effort cancel deletes the job/instance, which the poller reports as a
|
| 305 |
+
# failure (or a late worker may still succeed) — either way, re-read the state
|
| 306 |
+
# first so a recovery thread can't overwrite the user's terminal `cancelled`.
|
| 307 |
+
if get_status(run_id).state == "cancelled":
|
| 308 |
+
return get_status(run_id)
|
| 309 |
+
if not res.ok:
|
| 310 |
+
_update(run_id, "failed", error=f"{res.failure}: {res.detail}")
|
| 311 |
+
return get_status(run_id)
|
| 312 |
+
# Carry the provisioned class into metrics so _persist_metrics costs the card the
|
| 313 |
+
# run actually used (the in-process path stamps this; recovery must restore it).
|
| 314 |
+
if allocated_gpu and isinstance(res.metrics, dict):
|
| 315 |
+
res.metrics.setdefault("allocated_gpu", allocated_gpu)
|
| 316 |
+
# Earlier seeds of a multi-seed run already persisted their cost into
|
| 317 |
+
# status.cost_usd; add this seed's so recovery doesn't underreport spend.
|
| 318 |
+
total = float(status.cost_usd or 0.0) + _persist_metrics(spec, seed, res.metrics)
|
| 319 |
+
# A cancel can land while this thread persists the recovered seed's metrics
|
| 320 |
+
# (after the late-cancel check above). Re-read before the post-seed writes so
|
| 321 |
+
# the "running" update and the terminal "done" below can't resurrect a
|
| 322 |
+
# user-cancelled run (mirrors the fresh seed loop). _RunCancelled is caught
|
| 323 |
+
# below, leaving the cancellation intact.
|
| 324 |
+
if get_status(run_id).state == "cancelled":
|
| 325 |
+
raise _RunCancelled(f"run {run_id} was cancelled")
|
| 326 |
+
# The remote handle only identifies the seed that was in flight. For a
|
| 327 |
+
# multi-seed run, resume the remaining seeds instead of terminally
|
| 328 |
+
# completing the whole run after just this one.
|
| 329 |
+
try:
|
| 330 |
+
resumed_index = list(spec.train.seeds).index(seed) + 1
|
| 331 |
+
except ValueError:
|
| 332 |
+
resumed_index = len(spec.train.seeds)
|
| 333 |
+
more_seeds = resumed_index < len(spec.train.seeds)
|
| 334 |
+
# Clear the now-stale completed handle before resuming. In the
|
| 335 |
+
# allocation/provisioning gap before the next seed's on_handle() persists a
|
| 336 |
+
# fresh handle, a server restart must not reattach recovery to this finished
|
| 337 |
+
# job — that would double-count its cost and replay the wrong seed. Record the
|
| 338 |
+
# next seed index so a restart in that gap resumes the remaining seeds rather
|
| 339 |
+
# than failing the run. (The last seed keeps its handle for post-run
|
| 340 |
+
# observability, mirroring the fresh-submit seed loop.)
|
| 341 |
+
_update(
|
| 342 |
+
run_id,
|
| 343 |
+
"running",
|
| 344 |
+
cost_usd=total,
|
| 345 |
+
artifacts_dir=artifacts_dir(spec),
|
| 346 |
+
**({"remote": None, "resume_seed_index": resumed_index} if more_seeds else {}),
|
| 347 |
+
)
|
| 348 |
+
if more_seeds:
|
| 349 |
+
_run_seed_loop(spec, log, start_index=resumed_index, prior_cost=total)
|
| 350 |
+
else:
|
| 351 |
+
_update(run_id, "done", cost_usd=total, artifacts_dir=artifacts_dir(spec))
|
| 352 |
+
except _RunCancelled:
|
| 353 |
+
# Intentional: cancel_run already wrote the terminal `cancelled` state; leave it.
|
| 354 |
+
pass
|
| 355 |
+
except Exception as exc:
|
| 356 |
+
if get_status(run_id).state != "cancelled":
|
| 357 |
+
_update(run_id, "failed", error=str(exc))
|
| 358 |
+
finally:
|
| 359 |
+
_gc_run_endpoints(spec)
|
| 360 |
+
return get_status(run_id)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def resume_run(run_id: str, log_stream=None) -> RunStatus:
|
| 364 |
+
"""Resume the remaining seeds of a multi-seed run after a restart in the inter-seed gap.
|
| 365 |
+
|
| 366 |
+
Between two seeds the completed seed's handle is cleared and ``resume_seed_index`` is
|
| 367 |
+
recorded (see ``_run_seed_loop``). A control-plane restart in that handle-less window
|
| 368 |
+
must RESUME from that index rather than fail the run and discard the finished seeds.
|
| 369 |
+
Unlike ``attach_run`` there is no live job to poll — the prior process already tore the
|
| 370 |
+
seed's endpoint down — so we start a fresh seed loop from the recorded index. The slm
|
| 371 |
+
package was uploaded to HF on the original submit, so the worker can still fetch it; no
|
| 372 |
+
re-upload is needed.
|
| 373 |
+
"""
|
| 374 |
+
import sys
|
| 375 |
+
|
| 376 |
+
status = get_status(run_id)
|
| 377 |
+
if status.state in TERMINAL_STATES:
|
| 378 |
+
return status
|
| 379 |
+
if status.resume_seed_index is None:
|
| 380 |
+
raise ValueError(f"run {run_id} has no resume_seed_index; cannot resume")
|
| 381 |
+
spec = JobSpec.from_dict(status.spec)
|
| 382 |
+
log = log_stream or sys.stderr
|
| 383 |
+
print(f"resuming {run_id}: remaining seeds from index {status.resume_seed_index}", file=log)
|
| 384 |
+
try:
|
| 385 |
+
_run_seed_loop(
|
| 386 |
+
spec,
|
| 387 |
+
log,
|
| 388 |
+
start_index=status.resume_seed_index,
|
| 389 |
+
prior_cost=float(status.cost_usd or 0.0),
|
| 390 |
+
)
|
| 391 |
+
except _RunCancelled:
|
| 392 |
+
pass # cancel_run already set the terminal state
|
| 393 |
+
except Exception as exc:
|
| 394 |
+
if get_status(run_id).state != "cancelled":
|
| 395 |
+
_update(run_id, "failed", error=str(exc))
|
| 396 |
+
finally:
|
| 397 |
+
# Mirror _run_job: GC any endpoint a transient destroy left behind rather than
|
| 398 |
+
# leaking a billable RunPod endpoint.
|
| 399 |
+
_gc_run_endpoints(spec)
|
| 400 |
+
return get_status(run_id)
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def mark_deployed(run_id: str, deployment: dict, expect_state: str | None = None) -> RunStatus:
|
| 404 |
+
# Atomic + terminal-respecting (same guard as _update): a /cancel landing during
|
| 405 |
+
# always-on provisioning/warmup writes `cancelled`; this must NOT overwrite it with
|
| 406 |
+
# `deployed` and resurrect the run as an active deployment. `done` is deployable
|
| 407 |
+
# though (the common case: deploy a finished run), so only the non-`done` terminal
|
| 408 |
+
# states block here — otherwise a freshly finished run could never be deployed.
|
| 409 |
+
#
|
| 410 |
+
# expect_state is a compare-and-set: the deploy flow passes the state it expects the
|
| 411 |
+
# run to still be in (the pre-deploy snapshot, or "deployed" after the provisional
|
| 412 |
+
# mark). If an undeploy raced finalization — deleting the endpoint and writing `done`
|
| 413 |
+
# with deployment.state="undeployed" mid-warmup — the state no longer matches and we
|
| 414 |
+
# refuse to re-advertise the just-deleted endpoint.
|
| 415 |
+
with _STATUS_LOCK:
|
| 416 |
+
status = get_status(run_id)
|
| 417 |
+
if status.state in _UNDEPLOYABLE_STATES:
|
| 418 |
+
return status
|
| 419 |
+
if expect_state is not None and status.state != expect_state:
|
| 420 |
+
return status
|
| 421 |
+
status.deployment = deployment
|
| 422 |
+
status.state = "deployed"
|
| 423 |
+
status.updated_at = time.time()
|
| 424 |
+
_save_status(status)
|
| 425 |
+
return status
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def mark_undeployed(run_id: str) -> RunStatus:
|
| 429 |
+
"""Record an explicit undeploy (endpoint torn down -> run back to `done`).
|
| 430 |
+
|
| 431 |
+
Lock-guarded so it serializes with a racing deploy finalization: the raw read +
|
| 432 |
+
_save_status the endpoint used to do could interleave with mark_deployed and be
|
| 433 |
+
clobbered. With this under the same lock, mark_deployed's expect_state CAS then sees
|
| 434 |
+
the `done`/undeployed write and won't re-advertise the deleted endpoint.
|
| 435 |
+
"""
|
| 436 |
+
with _STATUS_LOCK:
|
| 437 |
+
status = get_status(run_id)
|
| 438 |
+
if status.deployment:
|
| 439 |
+
status.deployment = {**status.deployment, "state": "undeployed"}
|
| 440 |
+
# Record the teardown but don't resurrect a terminal run: undeploying a
|
| 441 |
+
# cancelled/failed run keeps its terminal state (only a live `deployed` run goes
|
| 442 |
+
# back to `done`). `done` is terminal too, so this naturally no-ops the state.
|
| 443 |
+
if status.state not in TERMINAL_STATES:
|
| 444 |
+
status.state = "done"
|
| 445 |
+
status.updated_at = time.time()
|
| 446 |
+
_save_status(status)
|
| 447 |
+
return status
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def mark_deployment_undeployed(run_id: str) -> RunStatus:
|
| 451 |
+
"""Flip ONLY the deployment field to ``undeployed``, leaving the run's state untouched.
|
| 452 |
+
|
| 453 |
+
Used by ``cancel_run`` to retire a deployed run's serving record. Unlike
|
| 454 |
+
``mark_undeployed`` (which is a state transition: a live `deployed` run goes back to
|
| 455 |
+
`done`), this never asserts or changes the run state. That matters under the cancel
|
| 456 |
+
race: a concurrent ``mark_undeployed`` may have already moved the run to terminal
|
| 457 |
+
`done`, and ``_update``'s compare-and-set rejects any transition off a terminal state —
|
| 458 |
+
even re-asserting `deployed` to carry the deployment field — which would leave the
|
| 459 |
+
deployment advertised as `ready`. Marking the field directly (lock-guarded for
|
| 460 |
+
serialization) sidesteps the CAS so the deployment reliably ends `undeployed`, while the
|
| 461 |
+
trailing ``cancelled`` transition is left to ``_update``.
|
| 462 |
+
"""
|
| 463 |
+
with _STATUS_LOCK:
|
| 464 |
+
status = get_status(run_id)
|
| 465 |
+
if status.deployment:
|
| 466 |
+
status.deployment = {**status.deployment, "state": "undeployed"}
|
| 467 |
+
status.updated_at = time.time()
|
| 468 |
+
_save_status(status)
|
| 469 |
+
return status
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def rollback_deploy(run_id: str, snapshot: RunStatus) -> None:
|
| 473 |
+
"""Restore the pre-deploy state/deployment after always-on provisioning fails.
|
| 474 |
+
|
| 475 |
+
Lock-guarded + terminal-respecting (same guard as _update/mark_deployed): a /cancel
|
| 476 |
+
that landed during provisioning/warmup already persisted `cancelled`; restoring the
|
| 477 |
+
pre-deploy snapshot must NOT overwrite it and resurrect the run as `done`/`deployed`.
|
| 478 |
+
"""
|
| 479 |
+
with _STATUS_LOCK:
|
| 480 |
+
status = get_status(run_id)
|
| 481 |
+
if status.state in TERMINAL_STATES:
|
| 482 |
+
return
|
| 483 |
+
status.state = snapshot.state
|
| 484 |
+
status.deployment = snapshot.deployment
|
| 485 |
+
status.updated_at = time.time()
|
| 486 |
+
_save_status(status)
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def _run_job(spec: JobSpec) -> None:
|
| 490 |
+
# Lazy import so dry-run / unit tests never construct a Flash endpoint.
|
| 491 |
+
from flash.providers.runpod.train import upload_code
|
| 492 |
+
|
| 493 |
+
# A cancel can land between the queued status being returned to the client and
|
| 494 |
+
# this background thread starting; don't overwrite a terminal state (cancelled)
|
| 495 |
+
# with provisioning and then launch a paid seed as if the cancel never happened.
|
| 496 |
+
if get_status(spec.run_id).state in TERMINAL_STATES:
|
| 497 |
+
return
|
| 498 |
+
_update(spec.run_id, "provisioning")
|
| 499 |
+
log_path = os.path.join(RUNS_DIR, f"{spec.run_id}.log")
|
| 500 |
+
try:
|
| 501 |
+
_run_job_inner(spec, log_path, upload_code)
|
| 502 |
+
finally:
|
| 503 |
+
# Endpoint GC: every run leaves its uniquely-named endpoint registered, and the
|
| 504 |
+
# account-wide *max workers quota* (5 by default) counts registered endpoints —
|
| 505 |
+
# after a handful of runs, ALL new submissions fail with "Max workers across all
|
| 506 |
+
# endpoints must not exceed your workers quota". Tear ours down on any terminal
|
| 507 |
+
# state (best-effort; never raises).
|
| 508 |
+
_gc_run_endpoints(spec)
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def _spec_with_gpu(spec: JobSpec, gpu_type: str) -> JobSpec:
|
| 512 |
+
"""The spec the workers/loggers see for THIS attempt's allocated class."""
|
| 513 |
+
if spec.gpu.type == gpu_type:
|
| 514 |
+
return spec
|
| 515 |
+
d = spec.to_dict()
|
| 516 |
+
d["gpu"] = {**d["gpu"], "type": gpu_type}
|
| 517 |
+
return JobSpec.from_dict(d)
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def _submit_seed_supervised(spec: JobSpec, seed: int, log) -> dict:
|
| 521 |
+
"""Run one seed with the job submit/poll path + bounded auto-retry.
|
| 522 |
+
|
| 523 |
+
Each attempt first ALLOCATES the GPU: the cheapest class across providers (RunPod
|
| 524 |
+
live pricing + Vast verified-datacenter offers) that fits the model — re-resolved
|
| 525 |
+
fresh per attempt because offers are a live market. A policy ``gpu.requested``
|
| 526 |
+
("cheapest"/"auto") lets the allocator pick the class; a concrete ``gpu.requested``
|
| 527 |
+
pins the class (the allocator then only picks the provider); ``gpu.provider`` pins
|
| 528 |
+
the substrate.
|
| 529 |
+
|
| 530 |
+
Retries (fresh job on a fresh host; worker resumes from the latest HF
|
| 531 |
+
checkpoint) when the failure looks infra-shaped: a stall (heartbeat frozen), a
|
| 532 |
+
client polling breakdown, or a platform TIMED_OUT/worker-loss. Sick Vast machines
|
| 533 |
+
are blacklisted for the run; failover naturally crosses providers.
|
| 534 |
+
Genuine worker errors (the run's code crashed; traceback persisted to HF) fail
|
| 535 |
+
immediately. The offline test/CI marker FLASH_SKIP_NET takes the blocking
|
| 536 |
+
in-process submit instead (the job poll path is network-only).
|
| 537 |
+
"""
|
| 538 |
+
from flash.providers.base import PollResult
|
| 539 |
+
from flash.providers.runpod.train import submit_train
|
| 540 |
+
|
| 541 |
+
if os.environ.get("FLASH_SKIP_NET"):
|
| 542 |
+
return submit_train(spec, seed, log=log)
|
| 543 |
+
|
| 544 |
+
from flash.providers import get_provider
|
| 545 |
+
from flash.providers.allocator import allocate, allocation_summary
|
| 546 |
+
from flash.providers.base import POLICY_NAMES
|
| 547 |
+
|
| 548 |
+
last_handle: dict = {}
|
| 549 |
+
# The friendly GPU class the CURRENT attempt provisioned (set right before each submit),
|
| 550 |
+
# so on_handle persists it into the run handle and a recovery via attach_run costs the
|
| 551 |
+
# class actually used rather than the parse-time provisional spec.gpu.type.
|
| 552 |
+
current_gpu: dict = {}
|
| 553 |
+
# Every RunPod endpoint id this run registered across attempts. Retries run on
|
| 554 |
+
# rN-suffixed endpoints whose names _gc_run_endpoints cannot reconstruct, and a
|
| 555 |
+
# failed delete during the next attempt's teardown would otherwise lose the id;
|
| 556 |
+
# GC the whole set at exit so no retry endpoint leaks against the worker quota.
|
| 557 |
+
seen_endpoints: set[str] = set()
|
| 558 |
+
|
| 559 |
+
def on_handle(handle: dict):
|
| 560 |
+
last_handle.clear()
|
| 561 |
+
last_handle.update(handle)
|
| 562 |
+
if handle.get("endpoint_id"):
|
| 563 |
+
seen_endpoints.add(handle["endpoint_id"])
|
| 564 |
+
_update(
|
| 565 |
+
spec.run_id,
|
| 566 |
+
"running",
|
| 567 |
+
remote={**handle, "seed": int(seed), "allocated_gpu": current_gpu.get("name")},
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
def _gc_seen_endpoints() -> None:
|
| 571 |
+
if not seen_endpoints:
|
| 572 |
+
return
|
| 573 |
+
from flash.providers.runpod import api as runpod_api
|
| 574 |
+
|
| 575 |
+
for eid in seen_endpoints:
|
| 576 |
+
with contextlib.suppress(Exception):
|
| 577 |
+
runpod_api.delete_endpoint(eid)
|
| 578 |
+
|
| 579 |
+
max_retries = int(spec.gpu.max_retries)
|
| 580 |
+
last_detail = None
|
| 581 |
+
bad_machines: set[int] = set()
|
| 582 |
+
# Re-allocate freely for policy requests ("cheapest"/"auto"); honor a concrete
|
| 583 |
+
# user pin by passing it through as the only candidate class.
|
| 584 |
+
requested = (spec.gpu.requested or "").strip().lower()
|
| 585 |
+
pinned_gpu = None if requested in POLICY_NAMES else spec.gpu.type
|
| 586 |
+
# Index into the ranked candidate list. It advances only after an attempt that
|
| 587 |
+
# actually provisioned a class lost it to an infra failure (see the retry tail), so a
|
| 588 |
+
# failed allocation — which never tried a card — can't skip past the cheapest class.
|
| 589 |
+
gpu_walk_offset = 0
|
| 590 |
+
for attempt in range(max_retries + 1):
|
| 591 |
+
if attempt > 0 and last_handle:
|
| 592 |
+
# A stalled/timed-out attempt often means the worker is pinned to a
|
| 593 |
+
# throttled/sick host; tear it down so the fresh deploy lands elsewhere.
|
| 594 |
+
# Dispatched generically via the handle's provider.
|
| 595 |
+
if last_handle.get("provider") == "vast":
|
| 596 |
+
with contextlib.suppress(Exception):
|
| 597 |
+
from flash.providers import get_provider
|
| 598 |
+
from flash.providers.base import JobHandle
|
| 599 |
+
|
| 600 |
+
get_provider("vast").destroy(JobHandle.from_dict(last_handle))
|
| 601 |
+
if last_handle.get("machine_id"):
|
| 602 |
+
bad_machines.add(int(last_handle["machine_id"]))
|
| 603 |
+
print(
|
| 604 |
+
f"retry {attempt}: destroyed vast instance "
|
| 605 |
+
f"{last_handle.get('instance_id')} (machine "
|
| 606 |
+
f"{last_handle.get('machine_id')} blacklisted for this run)",
|
| 607 |
+
file=log,
|
| 608 |
+
flush=True,
|
| 609 |
+
)
|
| 610 |
+
elif last_handle.get("endpoint_id"):
|
| 611 |
+
try:
|
| 612 |
+
from flash.providers.runpod import api as runpod_api
|
| 613 |
+
|
| 614 |
+
runpod_api.cancel_job(last_handle["endpoint_id"], last_handle["job_id"])
|
| 615 |
+
runpod_api.delete_endpoint(last_handle["endpoint_id"])
|
| 616 |
+
print(
|
| 617 |
+
f"retry {attempt}: deleted endpoint {last_handle['endpoint_id']} "
|
| 618 |
+
"(escaping throttled/sick host)",
|
| 619 |
+
file=log,
|
| 620 |
+
flush=True,
|
| 621 |
+
)
|
| 622 |
+
except Exception:
|
| 623 |
+
# Logging the host-escape note is cosmetic; never let it abort the retry.
|
| 624 |
+
pass
|
| 625 |
+
# The previous endpoint is now deleted; clear the persisted handle so a cancel
|
| 626 |
+
# or control-plane restart during the fresh deploy doesn't operate on (or get
|
| 627 |
+
# shielded by) the dead handle. The next on_handle() records the new one.
|
| 628 |
+
with contextlib.suppress(FileNotFoundError):
|
| 629 |
+
st = get_status(spec.run_id)
|
| 630 |
+
if st.state not in TERMINAL_STATES and st.remote is not None:
|
| 631 |
+
_update(spec.run_id, st.state, remote=None)
|
| 632 |
+
res = None
|
| 633 |
+
alloc = None
|
| 634 |
+
chosen = None
|
| 635 |
+
# A cancel can land after _run_seed_loop's pre-submit check but while
|
| 636 |
+
# allocation/pricing runs, when no handle exists yet for cancel_run() to
|
| 637 |
+
# delete. Re-read state right before paid provisioning so a cancelled run
|
| 638 |
+
# never launches a worker (the later checks only stop the final-state
|
| 639 |
+
# overwrite, after the GPU has already run and billed).
|
| 640 |
+
with contextlib.suppress(FileNotFoundError):
|
| 641 |
+
if get_status(spec.run_id).state == "cancelled":
|
| 642 |
+
raise _RunCancelled(f"run {spec.run_id} was cancelled")
|
| 643 |
+
try:
|
| 644 |
+
alloc = allocate(
|
| 645 |
+
spec.model,
|
| 646 |
+
spec.algorithm,
|
| 647 |
+
gpu=pinned_gpu,
|
| 648 |
+
provider=spec.gpu.provider,
|
| 649 |
+
disk_gb=spec.gpu.disk_gb,
|
| 650 |
+
allow_unvalidated=spec.gpu.allow_unvalidated,
|
| 651 |
+
exclude_machine_ids=frozenset(bad_machines),
|
| 652 |
+
# Pass the run's train knobs + thinking so the VRAM estimate reflects THIS job's
|
| 653 |
+
# max_length / group_size / batch_size / lora_rank (and the seq escalation) instead
|
| 654 |
+
# of the generic defaults — else a long-context / big-group run is sized at seq=1024
|
| 655 |
+
# and OOMs the card it picks.
|
| 656 |
+
train=spec.train,
|
| 657 |
+
thinking=spec.thinking,
|
| 658 |
+
)
|
| 659 |
+
except Exception as exc:
|
| 660 |
+
from flash.providers.base import UnsupportedGpuError
|
| 661 |
+
|
| 662 |
+
if isinstance(exc, UnsupportedGpuError):
|
| 663 |
+
raise # config-shaped: no GPU anywhere can run this job
|
| 664 |
+
res = PollResult(False, failure="poll_error", detail=f"allocation: {exc}")
|
| 665 |
+
if alloc is not None:
|
| 666 |
+
# allocate() above ran a live-market price walk; re-check cancellation
|
| 667 |
+
# right before provisioning so a cancel during allocation doesn't still
|
| 668 |
+
# launch a paid worker.
|
| 669 |
+
with contextlib.suppress(FileNotFoundError):
|
| 670 |
+
if get_status(spec.run_id).state == "cancelled":
|
| 671 |
+
raise _RunCancelled(f"run {spec.run_id} was cancelled")
|
| 672 |
+
# Walk down the ranked candidates by the walk offset (clamped to the last): the
|
| 673 |
+
# first attempt takes the cheapest; each retry that provisioned a class and lost
|
| 674 |
+
# it to an infra failure steps to the next-cheapest, so a capacity-starved class
|
| 675 |
+
# can't burn the whole budget. A concrete pin yields a single candidate, so the
|
| 676 |
+
# clamp keeps a pinned run on its class.
|
| 677 |
+
chosen = alloc.candidates[min(gpu_walk_offset, len(alloc.candidates) - 1)]
|
| 678 |
+
print(allocation_summary(alloc), file=log, flush=True)
|
| 679 |
+
if chosen.gpu != alloc.gpu:
|
| 680 |
+
print(
|
| 681 |
+
f"retry {attempt}: walking past the cheapest class to {chosen.gpu} "
|
| 682 |
+
f"@ ${chosen.hourly_usd:.2f}/hr",
|
| 683 |
+
file=log,
|
| 684 |
+
flush=True,
|
| 685 |
+
)
|
| 686 |
+
run_spec = _spec_with_gpu(spec, chosen.gpu)
|
| 687 |
+
current_gpu["name"] = chosen.gpu
|
| 688 |
+
provider = get_provider(chosen.provider)
|
| 689 |
+
# Vast needs the live-market offer book for the chosen class first, then the
|
| 690 |
+
# other allocator-approved classes by price; RunPod ignores ``offers``.
|
| 691 |
+
offers = None
|
| 692 |
+
if chosen.provider == "vast":
|
| 693 |
+
ok_classes = {c.gpu for c in alloc.candidates if c.provider == "vast"}
|
| 694 |
+
offers = sorted(
|
| 695 |
+
(o for o in alloc.provider_offers if o.gpu in ok_classes),
|
| 696 |
+
key=lambda o: (o.gpu != chosen.gpu, o.dph_total),
|
| 697 |
+
)
|
| 698 |
+
try:
|
| 699 |
+
res = provider.submit_run(
|
| 700 |
+
run_spec,
|
| 701 |
+
seed,
|
| 702 |
+
log=log,
|
| 703 |
+
on_handle=on_handle,
|
| 704 |
+
attempt=attempt,
|
| 705 |
+
offers=offers,
|
| 706 |
+
# The run's machine blacklist must reach the provider so an in-provider
|
| 707 |
+
# offer REFRESH (Vast) keeps stalled/sick machines excluded.
|
| 708 |
+
exclude_machine_ids=frozenset(bad_machines),
|
| 709 |
+
)
|
| 710 |
+
except Exception as exc:
|
| 711 |
+
# Deploy/submit themselves can fail transiently (observed: RunPod
|
| 712 |
+
# GraphQL "Something went wrong" x3 during a retry deploy; a vast offer
|
| 713 |
+
# pool emptying between search and rent). That must consume a retry, not
|
| 714 |
+
# kill the run — the budget exists precisely for flakes.
|
| 715 |
+
res = PollResult(False, failure="poll_error", detail=f"deploy/submit: {exc}")
|
| 716 |
+
if attempt < max_retries:
|
| 717 |
+
time.sleep(10 * (attempt + 1)) # let the transient clear
|
| 718 |
+
if res.ok:
|
| 719 |
+
# A best-effort cancel may fail to stop the worker, which then completes
|
| 720 |
+
# successfully after cancel_run() persisted `cancelled`. Don't let a late
|
| 721 |
+
# worker success resurrect the run into running/done.
|
| 722 |
+
try:
|
| 723 |
+
if get_status(spec.run_id).state == "cancelled":
|
| 724 |
+
raise _RunCancelled(f"run {spec.run_id} was cancelled")
|
| 725 |
+
except FileNotFoundError:
|
| 726 |
+
# Status file not yet written (early race): treat as not-cancelled, proceed.
|
| 727 |
+
pass
|
| 728 |
+
# Worker is done (DONE sentinel seen); GC every endpoint this seed used,
|
| 729 |
+
# including intermediate rN retries _gc_run_endpoints can't name.
|
| 730 |
+
_gc_seen_endpoints()
|
| 731 |
+
# Record the class actually allocated so _persist_metrics rates the right
|
| 732 |
+
# RunPod card when a policy GPU was re-allocated away from the provisional.
|
| 733 |
+
if chosen is not None and isinstance(res.metrics, dict):
|
| 734 |
+
res.metrics.setdefault("allocated_gpu", chosen.gpu)
|
| 735 |
+
return res.metrics
|
| 736 |
+
last_detail = f"{res.failure}: {res.detail}"
|
| 737 |
+
# Infra-shaped failures are retried on a FRESH endpoint/host; genuine worker
|
| 738 |
+
# code errors are not. Detail markers cover the observed flake classes:
|
| 739 |
+
# platform timeouts, worker pip-install network timeouts, and sick-GPU hosts.
|
| 740 |
+
_infra_markers = (
|
| 741 |
+
"TIMED_OUT",
|
| 742 |
+
"Failed to fetch",
|
| 743 |
+
"operation timed out",
|
| 744 |
+
"python_dependencies failed",
|
| 745 |
+
"Connection reset",
|
| 746 |
+
"cuda not available",
|
| 747 |
+
"GPU never became ready",
|
| 748 |
+
# Host vanished mid-run: the instance went "missing"/dead and NOTHING was captured
|
| 749 |
+
# (no marker error, no error_<phase>.txt, no console log) so _failure_detail falls back
|
| 750 |
+
# to this bare sentinel. A genuine worker code crash instead yields a RICHER detail
|
| 751 |
+
# (the captured traceback), so this exact phrase only ever marks a dead host -> retry it
|
| 752 |
+
# on a fresh one. Without this, a single ~1-in-200 host death killed the whole run.
|
| 753 |
+
"terminated without a DONE sentinel",
|
| 754 |
+
)
|
| 755 |
+
infra_shaped = res.failure in ("stalled", "poll_error") or any(
|
| 756 |
+
m in (res.detail or "") for m in _infra_markers
|
| 757 |
+
)
|
| 758 |
+
# A cancel deletes the endpoint, which the poller sees as an
|
| 759 |
+
# infra-shaped failure; retrying would resurrect the run and keep
|
| 760 |
+
# billing. The user's cancel wins over the retry budget.
|
| 761 |
+
try:
|
| 762 |
+
if get_status(spec.run_id).state == "cancelled":
|
| 763 |
+
raise _RunCancelled(f"run {spec.run_id} was cancelled")
|
| 764 |
+
except FileNotFoundError:
|
| 765 |
+
# Status file not yet written (early race): treat as not-cancelled and proceed.
|
| 766 |
+
pass
|
| 767 |
+
print(
|
| 768 |
+
f"seed={seed} attempt={attempt} failed ({res.failure}); "
|
| 769 |
+
f"{'retrying (resume from last checkpoint)' if infra_shaped and attempt < max_retries else 'not retrying'}"
|
| 770 |
+
f"\n--- failure detail ---\n{(res.detail or '')[:2000]}\n---",
|
| 771 |
+
file=log,
|
| 772 |
+
flush=True,
|
| 773 |
+
)
|
| 774 |
+
if not infra_shaped or attempt >= max_retries:
|
| 775 |
+
break
|
| 776 |
+
# Step to the next-cheapest class only when THIS attempt actually provisioned one
|
| 777 |
+
# and it failed infra-shaped. An allocation/pricing failure (chosen is None) never
|
| 778 |
+
# tried a card, so the next attempt must retry from the cheapest, not walk past it.
|
| 779 |
+
if chosen is not None:
|
| 780 |
+
gpu_walk_offset += 1
|
| 781 |
+
# Retry budget exhausted: GC every endpoint this seed registered (the final
|
| 782 |
+
# attempt's is in status.remote for _gc_run_endpoints, but intermediate rN ones
|
| 783 |
+
# are only known here).
|
| 784 |
+
_gc_seen_endpoints()
|
| 785 |
+
raise RuntimeError(f"seed {seed} failed after retries: {last_detail}")
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
def _run_job_inner(spec: JobSpec, log_path: str, upload_code) -> None:
|
| 789 |
+
try:
|
| 790 |
+
# Ship the slm package to the run's HF repo (the per-run [train] hf_repo) so the GPU
|
| 791 |
+
# worker — which fetches code/** from that same repo — can run it.
|
| 792 |
+
upload_code(spec.train.hf_repo)
|
| 793 |
+
with open(log_path, "a") as log:
|
| 794 |
+
_run_seed_loop(spec, log, start_index=0, prior_cost=0.0)
|
| 795 |
+
except _RunCancelled:
|
| 796 |
+
return # cancel_run already set the terminal state
|
| 797 |
+
except Exception as exc:
|
| 798 |
+
if get_status(spec.run_id).state != "cancelled":
|
| 799 |
+
_update(spec.run_id, "failed", error=str(exc))
|
| 800 |
+
raise
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
def _run_seed_loop(spec: JobSpec, log, *, start_index: int, prior_cost: float) -> None:
|
| 804 |
+
"""Run spec.train.seeds[start_index:] under supervision; finalize the run.
|
| 805 |
+
|
| 806 |
+
Shared by a fresh submit (start_index=0) and post-restart recovery, which
|
| 807 |
+
resumes the remaining seeds after the in-flight one completes."""
|
| 808 |
+
total_cost = prior_cost
|
| 809 |
+
seeds = spec.train.seeds
|
| 810 |
+
for i in range(start_index, len(seeds)):
|
| 811 |
+
seed = seeds[i]
|
| 812 |
+
# An early cancel (before any remote handle existed) sets `cancelled`;
|
| 813 |
+
# do not overwrite it with `running` and submit the GPU job anyway.
|
| 814 |
+
if get_status(spec.run_id).state == "cancelled":
|
| 815 |
+
raise _RunCancelled(f"run {spec.run_id} was cancelled")
|
| 816 |
+
_update(spec.run_id, "running")
|
| 817 |
+
print(
|
| 818 |
+
f"starting seed={seed} phase={spec.phase} model={spec.model} gpu={spec.gpu.type}",
|
| 819 |
+
file=log,
|
| 820 |
+
flush=True,
|
| 821 |
+
)
|
| 822 |
+
metrics = _submit_seed_supervised(spec, seed, log)
|
| 823 |
+
total_cost += _persist_metrics(spec, seed, metrics)
|
| 824 |
+
# A cancel can land while this thread writes metrics — after the supervised
|
| 825 |
+
# late-cancel check. Re-read before the post-seed status writes so a late
|
| 826 |
+
# worker success doesn't resurrect a user-cancelled run via this "running"
|
| 827 |
+
# update (or the final "done" below).
|
| 828 |
+
with contextlib.suppress(FileNotFoundError):
|
| 829 |
+
if get_status(spec.run_id).state == "cancelled":
|
| 830 |
+
raise _RunCancelled(f"run {spec.run_id} was cancelled")
|
| 831 |
+
# If more seeds follow, this seed's endpoint/instance is already torn down, so
|
| 832 |
+
# clear the now-stale remote handle: a restart in the gap before the next
|
| 833 |
+
# seed's on_handle must not make recover_runs reattach to a deleted handle and
|
| 834 |
+
# fail the run. Record the next seed index so a restart in that handle-less gap
|
| 835 |
+
# RESUMES the remaining seeds (recover_runs) instead of discarding the completed
|
| 836 |
+
# ones. The last seed keeps its handle for post-run observability (the run is
|
| 837 |
+
# about to go terminal, which recover_runs never reattaches).
|
| 838 |
+
more_seeds = (i + 1) < len(seeds)
|
| 839 |
+
_update(
|
| 840 |
+
spec.run_id,
|
| 841 |
+
"running",
|
| 842 |
+
cost_usd=total_cost,
|
| 843 |
+
**({"remote": None, "resume_seed_index": i + 1} if more_seeds else {}),
|
| 844 |
+
)
|
| 845 |
+
print(
|
| 846 |
+
f"seed={seed} done: train_wall={metrics.get('wall_seconds')} cost_usd={total_cost:.4f}",
|
| 847 |
+
file=log,
|
| 848 |
+
flush=True,
|
| 849 |
+
)
|
| 850 |
+
# Final guard: a cancel landing after the last seed's check must not be overwritten
|
| 851 |
+
# by the terminal "done".
|
| 852 |
+
with contextlib.suppress(FileNotFoundError):
|
| 853 |
+
if get_status(spec.run_id).state == "cancelled":
|
| 854 |
+
raise _RunCancelled(f"run {spec.run_id} was cancelled")
|
| 855 |
+
_update(
|
| 856 |
+
spec.run_id,
|
| 857 |
+
"done",
|
| 858 |
+
cost_usd=total_cost,
|
| 859 |
+
artifacts_dir=artifacts_dir(spec),
|
| 860 |
+
resume_seed_index=None,
|
| 861 |
+
)
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
def _gc_run_endpoints(spec: JobSpec) -> None:
|
| 865 |
+
"""Best-effort teardown of every endpoint a run may have registered.
|
| 866 |
+
|
| 867 |
+
Retried attempts run on rN-suffixed endpoints whose runpod_flash state is
|
| 868 |
+
isolated per-suffix, so the name-based terminate_endpoint cannot see them;
|
| 869 |
+
the persisted remote handle's endpoint id covers whichever attempt ran
|
| 870 |
+
last via the plain REST API."""
|
| 871 |
+
status = None
|
| 872 |
+
with contextlib.suppress(Exception):
|
| 873 |
+
status = get_status(spec.run_id)
|
| 874 |
+
if status is not None and status.remote:
|
| 875 |
+
try:
|
| 876 |
+
from flash.providers import get_provider
|
| 877 |
+
from flash.providers.base import JobHandle
|
| 878 |
+
|
| 879 |
+
handle = JobHandle.from_dict(status.remote)
|
| 880 |
+
get_provider(handle.provider).destroy(handle)
|
| 881 |
+
except Exception:
|
| 882 |
+
# Best-effort GC; the name-reconstructed RunPod gc below is the backstop.
|
| 883 |
+
pass
|
| 884 |
+
try:
|
| 885 |
+
# RunPod's gc reaps rN-suffixed endpoints the persisted handle can't name.
|
| 886 |
+
from flash.providers import get_provider
|
| 887 |
+
|
| 888 |
+
get_provider("runpod").gc(spec)
|
| 889 |
+
except Exception:
|
| 890 |
+
# Best-effort GC; an undeleted endpoint only holds worker quota, never blocks the run.
|
| 891 |
+
pass
|
| 892 |
+
# Vast instances bill until destroyed: the runner's per-attempt `finally` already
|
| 893 |
+
# destroys them, but a crashed supervisor thread can leave one behind. Reap any
|
| 894 |
+
# instance still labeled for this run via the provider's gc (best-effort).
|
| 895 |
+
from flash.providers import available_providers, get_provider
|
| 896 |
+
|
| 897 |
+
if "vast" in available_providers():
|
| 898 |
+
with contextlib.suppress(Exception):
|
| 899 |
+
get_provider("vast").gc(spec)
|
| 900 |
+
|
| 901 |
+
|
| 902 |
+
def _persist_metrics(spec: JobSpec, seed: int, metrics: dict) -> float:
|
| 903 |
+
"""Write metrics to results/runpod/<phase>/<run_id>/seedN and return the cost.
|
| 904 |
+
|
| 905 |
+
The run id keeps concurrent/sequential runs of the same phase+seed from
|
| 906 |
+
overwriting each other's artifacts. Vast runs arrive with ``cost_usd`` already
|
| 907 |
+
stamped from the offer's real $/hr (plus provider notes) and short-circuit the
|
| 908 |
+
rate fallback below (the RunPod projection)."""
|
| 909 |
+
dest = os.path.join(artifacts_dir(spec), f"seed{seed}")
|
| 910 |
+
os.makedirs(dest, exist_ok=True)
|
| 911 |
+
# Rate the actually-allocated class, not the parse-time provisional spec.gpu.type:
|
| 912 |
+
# a policy GPU can be re-allocated to a different RunPod class at submit time, so
|
| 913 |
+
# the worker stamps "allocated_gpu" into metrics for the cost fallback below.
|
| 914 |
+
gpu_type = metrics.get("allocated_gpu") or spec.gpu.type
|
| 915 |
+
rate = _gpu_rate(gpu_type)
|
| 916 |
+
# A non-runpod provider (e.g. Vast) stamps the real cost_usd from its offer's $/hr
|
| 917 |
+
# AND tags notes["provider"] with its own name — and a near-zero-duration run can
|
| 918 |
+
# legitimately stamp cost_usd == 0.0. The RunPod arm, by contrast, never stamps a real
|
| 919 |
+
# cost: it arrives with cost_usd absent (or a 0.0 placeholder) and no provider note, so
|
| 920 |
+
# the wall-based projection below must run. A bare `cost or 0.0` would treat the Vast
|
| 921 |
+
# 0.0 as "absent" and re-rate it against RunPod pricing while overwriting the provider
|
| 922 |
+
# notes, mis-attributing the run to 'runpod'. So fall back only when the cost is
|
| 923 |
+
# missing/zero AND it has NOT already been attributed to a non-runpod provider.
|
| 924 |
+
_notes = metrics.get("notes")
|
| 925 |
+
_stamped_provider = _notes.get("provider") if isinstance(_notes, dict) else None
|
| 926 |
+
_non_runpod = bool(_stamped_provider) and _stamped_provider != "runpod"
|
| 927 |
+
cost = metrics.get("cost_usd")
|
| 928 |
+
if cost or _non_runpod:
|
| 929 |
+
cost = float(cost or 0.0)
|
| 930 |
+
else:
|
| 931 |
+
wall = float(metrics.get("wall_seconds") or 0.0)
|
| 932 |
+
cost = wall / 3600.0 * rate
|
| 933 |
+
metrics = {**metrics, "cost_usd": cost}
|
| 934 |
+
metrics.setdefault("notes", {})
|
| 935 |
+
if isinstance(metrics["notes"], dict):
|
| 936 |
+
metrics["notes"]["provider"] = "runpod"
|
| 937 |
+
metrics["notes"]["runpod_rate_usd_hr"] = rate
|
| 938 |
+
metrics["notes"]["runpod_gpu"] = gpu_type
|
| 939 |
+
with open(os.path.join(dest, "metrics.json"), "w") as f:
|
| 940 |
+
json.dump(metrics, f, indent=2)
|
| 941 |
+
return float(cost)
|
| 942 |
+
|
| 943 |
+
|
| 944 |
+
def _update(run_id: str, state: str, *, allow_from_terminal: bool = False, **updates) -> None:
|
| 945 |
+
# The read-check-write below must be atomic: a concurrent `slm cancel` (also via
|
| 946 |
+
# _update) landing between the get_status read and the _save_status write could
|
| 947 |
+
# otherwise be clobbered by this stale background update, resurrecting a cancelled
|
| 948 |
+
# run. The control plane is single-instance with per-run threads, so a process-wide
|
| 949 |
+
# lock serializes all status transitions into a compare-and-set.
|
| 950 |
+
with _STATUS_LOCK:
|
| 951 |
+
status = get_status(run_id)
|
| 952 |
+
# Terminal states are STICKY: once a run is done/failed/cancelled/dry_run, no
|
| 953 |
+
# other state may overwrite it. This closes the whole cancel-race class at the
|
| 954 |
+
# source — a cancel landing between a caller's check and a later write
|
| 955 |
+
# (provisioning/running, or even a late terminal done/failed from a worker that
|
| 956 |
+
# finished as the cancel arrived) can no longer resurrect the run. Same-state
|
| 957 |
+
# writes still pass so terminal field updates (cost_usd, error, artifacts_dir)
|
| 958 |
+
# are preserved.
|
| 959 |
+
#
|
| 960 |
+
# allow_from_terminal is the NARROW escape hatch used ONLY by cancel_run's final
|
| 961 |
+
# `cancelled` transition, and ONLY when the run was `deployed` at cancel entry (see
|
| 962 |
+
# cancel_run). In that case an explicit user cancel must WIN over a racing
|
| 963 |
+
# mark_undeployed() that flipped the `deployed` run to terminal `done` mid-teardown —
|
| 964 |
+
# that `done` is an undeploy artifact (restoring the pre-deploy completion marker while
|
| 965 |
+
# retiring serving), not a fresh result. Without the override the `cancelled` write
|
| 966 |
+
# no-ops against the freshly-written `done` and the run wrongly ends `done` despite the
|
| 967 |
+
# user asking to cancel. cancel_run passes allow_from_terminal=False for a non-deployed
|
| 968 |
+
# run, so a GENUINE training-completion `done` racing in from the run's own training
|
| 969 |
+
# thread is protected by the CAS below — cancel correctly loses to a real finish.
|
| 970 |
+
if status.state in TERMINAL_STATES and state != status.state and not allow_from_terminal:
|
| 971 |
+
return
|
| 972 |
+
status.state = state
|
| 973 |
+
status.updated_at = time.time()
|
| 974 |
+
for key, value in updates.items():
|
| 975 |
+
setattr(status, key, value)
|
| 976 |
+
_save_status(status)
|
| 977 |
+
|
| 978 |
+
|
| 979 |
+
def _save_status(status: RunStatus) -> None:
|
| 980 |
+
os.makedirs(RUNS_DIR, exist_ok=True)
|
| 981 |
+
# Write-then-rename: a concurrent reader (poll on /v1/runs or /logs) must
|
| 982 |
+
# never observe a half-written/truncated file and 500 on JSONDecodeError.
|
| 983 |
+
# The temp name is UNIQUE per write (mkstemp) so two threads updating the same
|
| 984 |
+
# run (e.g. a cancel racing the background seed update) can't clobber each
|
| 985 |
+
# other's temp file mid-dump — each os.replace is atomic and independent.
|
| 986 |
+
path = runs_file_path(status.run_id, ".json")
|
| 987 |
+
fd, tmp = tempfile.mkstemp(dir=RUNS_DIR, prefix=f"{status.run_id}.", suffix=".tmp")
|
| 988 |
+
try:
|
| 989 |
+
with os.fdopen(fd, "w") as f:
|
| 990 |
+
json.dump(status.to_dict(), f, indent=2, sort_keys=True)
|
| 991 |
+
os.replace(tmp, path)
|
| 992 |
+
finally:
|
| 993 |
+
with contextlib.suppress(FileNotFoundError):
|
| 994 |
+
os.unlink(tmp)
|