| """RunPod Flash fine-tuning endpoints (queue-based, one dedicated GPU per run). |
| |
| Flash provisions a dedicated RunPod GPU (RTX 4090 / 5090, no Docker), installs |
| ``WORKER_DEPS``, runs the handler, returns the metrics dict, and scales to zero. |
| |
| Flash's live ("ad-hoc") provisioning does not bundle local project code, so the |
| handler fetches the ``flash`` package from the HF dataset repo (uploaded by |
| ``upload_code`` before submit), adds it to ``PYTHONPATH``, and runs |
| ``flash.engine.worker`` to train. The worker streams the adapter + checkpoints to |
| the same HF repo for serving and preemption-resilient resume. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import asyncio |
| import contextlib |
| import inspect |
| import os |
| import threading |
| from typing import Any |
|
|
| from flash._logging import get_logger |
| from flash.providers.base import canonical_gpu, gpu_short |
| from flash.providers.runpod.gpus import flash_gpu |
| from flash.spec import JobSpec |
|
|
| logger = get_logger(__name__) |
|
|
| |
| |
| |
| |
| |
| |
| FLASH_SDK_LOCK = threading.Lock() |
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| WORKER_DEPS = [ |
| "torch==2.10.0", |
| "transformers>=5.6,<5.13", |
| "trl>=1.6,<1.7", |
| "peft>=0.19", |
| "vllm==0.19.1", |
| "bitsandbytes>=0.49", |
| "datasets>=4.7,<6", |
| "huggingface_hub>=0.25", |
| "accelerate>=1.4", |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| "wandb>=0.17", |
| "liger-kernel>=0.5", |
| |
| |
| |
| "flash-linear-attention==0.5.0", |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| ] |
| |
| |
| |
| |
| |
| WORKER_SYSTEM_DEPS = ["build-essential"] |
|
|
| |
| |
| |
| |
| WORKER_IMAGE = "ghcr.io/freesolo-co/flash-worker:cu128" |
|
|
|
|
| def resolve_worker_deps(friendly_gpu: str | None = None) -> list[str]: |
| """The dependency list Flash installs on the GPU worker for this run. |
| |
| Precedence: FLASH_WORKER_DEPS (explicit list) > the pinned ``WORKER_DEPS``. |
| |
| GPU-specific: on HOPPER (sm90, H100), DROP flash-linear-attention — its gated |
| chunk_bwd Triton kernel is miscomputed there (Triton>=3.4, fla #640). Without fla, |
| transformers uses the correct pure-PyTorch delta rule (slower but correct). |
| Ampere/Ada/Blackwell keep fla for the speedup. |
| """ |
| explicit = os.environ.get("FLASH_WORKER_DEPS") |
| if explicit: |
| |
| |
| if explicit.strip().startswith("["): |
| import json as _json |
|
|
| deps = [str(d).strip() for d in _json.loads(explicit) if str(d).strip()] |
| else: |
| |
| |
| import shlex |
|
|
| deps = [d for d in shlex.split(explicit) if d.strip()] |
| if deps: |
| return deps |
| deps = list(WORKER_DEPS) |
| |
| |
| |
| |
| if friendly_gpu: |
| try: |
| from flash.providers.base import get_gpu_info |
|
|
| if get_gpu_info(friendly_gpu).sm == "sm90": |
| deps = [d for d in deps if not d.startswith("flash-linear-attention")] |
| except Exception: |
| pass |
| |
| |
| extra = os.environ.get("FLASH_WORKER_EXTRA_DEPS") |
| if extra: |
| import shlex |
|
|
| deps = deps + [d for d in shlex.split(extra) if d.strip()] |
| return deps |
|
|
|
|
| |
| |
| _CHALK_KERNEL_FLAGS = ( |
| "FLASH_MLP_KERNEL", |
| "FLASH_MLP_FP8", |
| "FLASH_FP8_BASE", |
| "FLASH_TRITON_LORA", |
| "FLASH_EMBED_KERNEL", |
| "FLASH_QKV_KERNEL", |
| "FLASH_ROPE_KERNEL", |
| ) |
|
|
|
|
| def _effective_worker_env(spec=None) -> dict[str, str]: |
| """The env the WORKER process will actually see, for chalk-selection decisions. |
| |
| chalk install-on-call is selected by ``FLASH_*`` flags read on the worker from its own process |
| env, which ``build_worker_env`` builds as the control-plane ``os.environ`` allowlist with the |
| run's ``[worker_env]`` overrides merged ON TOP (per-run ``spec.worker_env`` wins). A run that |
| opts into chalk via its ``[worker_env]`` block therefore sets the flag the worker reads — so the |
| SAME merge must decide whether chalk is selected and whether its spec is added to ``extra_pip``; |
| reading bare ``os.environ`` here would miss a per-run ``[worker_env]`` opt-in and the kernels |
| would never install for that run. |
| |
| Returns ``os.environ`` overlaid with ``spec.worker_env`` (string-coerced). ``spec=None`` (no |
| per-run env) collapses to plain ``os.environ``. |
| """ |
| eff: dict[str, str] = dict(os.environ) |
| for k, v in (getattr(spec, "worker_env", None) or {}).items(): |
| eff[str(k)] = str(v) |
| return eff |
|
|
|
|
| def _chalk_selected(spec=None) -> bool: |
| """True if any FLASH_* chalk kernel-selection flag is truthy in the EFFECTIVE worker env. |
| |
| Reads the per-run ``[worker_env]`` (``spec.worker_env``) merged over ``os.environ`` so a chalk |
| opt-in set only in the run's ``[worker_env]`` block is detected (see ``_effective_worker_env``). |
| """ |
| env = _effective_worker_env(spec) |
| for name in _CHALK_KERNEL_FLAGS: |
| v = env.get(name) |
| if v is not None and v.strip().lower() not in ("", "0", "false", "no", "off"): |
| return True |
| return False |
|
|
|
|
| def chalk_extra_pip(spec=None) -> list[str]: |
| """Chalk pip spec(s) to ADD to the worker's ``extra_pip`` when a chalk kernel is selected. |
| |
| This is the install hook that runs for DEFAULT remote jobs: the baked-image RunPod path |
| (``_train_body`` -> ``pip install *extra_pip``) and the Vast bootstrap both consume the |
| payload's ``extra_pip`` regardless of ``WORKER_IMAGE`` — unlike ``FLASH_WORKER_EXTRA_DEPS`` |
| / ``resolve_worker_deps``, which the durable ``build_function_input`` baked-image path skips. |
| |
| Selection (and the ``FLASH_CHALK_SPEC`` lookup) is resolved against the EFFECTIVE worker env — |
| the run's ``[worker_env]`` merged over ``os.environ`` — so it matches exactly what the worker |
| process will see (``build_worker_env``) and a per-run ``[worker_env]`` opt-in installs chalk. |
| |
| freesolo-chalk is unpublished, so there is no auto-installable default: the operator MUST set |
| ``FLASH_CHALK_SPEC`` to an installable spec (a git URL with access, or a wheel/path). When a |
| chalk kernel flag is set but ``FLASH_CHALK_SPEC`` is empty we log a warning and add nothing — |
| ``install_chalk_kernels`` then finds no chalk on the worker and safely no-ops. |
| """ |
| if not _chalk_selected(spec): |
| return [] |
| spec_str = _effective_worker_env(spec).get("FLASH_CHALK_SPEC", "").strip() |
| if not spec_str: |
| logger.warning( |
| "a FLASH_* chalk kernel is selected but FLASH_CHALK_SPEC is unset; freesolo-chalk is " |
| "unpublished so it can't be auto-installed — set FLASH_CHALK_SPEC to an installable " |
| "spec (git URL or wheel) or the chalk kernels will no-op on the worker." |
| ) |
| return [] |
| import shlex |
|
|
| return [d for d in shlex.split(spec_str) if d.strip()] |
|
|
|
|
| DEFAULT_EXECUTION_TIMEOUT_MS = 6 * 3600 * 1000 |
|
|
| _ENDPOINT_CACHE: dict[str, Any] = {} |
|
|
|
|
| def upload_code(repo: str | None = None) -> str: |
| """Upload the ``flash`` package to the run's HF artifact repo. |
| |
| ``repo`` is the per-run artifact repo (``spec.train.hf_repo``); the worker fetches |
| ``code/**`` from the same repo it is given in the submit payload, so the code must land in |
| that per-run repo. |
| |
| The worker downloads ``code/**`` to ``/runcode``. Verifiers-only: there are no built-in |
| example environments to ship — Hub/installed envs are pip-installed on the worker (see |
| ``registry.worker_pip_for_env``). |
| |
| Only the ``flash`` package is uploaded, NOT the client's project tree. Managed runs must |
| reference a published Hub env by ``id`` (``slm env push`` to publish a local env first); the |
| worker pip-installs the env wheel. |
| """ |
| from huggingface_hub import HfApi |
|
|
| import flash |
|
|
| if not repo: |
| raise RuntimeError( |
| "hf_repo must be set (the run's [train] hf_repo: HF dataset repo for code + artifacts)" |
| ) |
| token = os.environ.get("HF_TOKEN") |
| pkg_dir = os.path.dirname(os.path.abspath(flash.__file__)) |
| api = HfApi(token=token) |
| |
| |
| |
| _priv = os.environ.get("FLASH_HF_REPO_PRIVATE", "1").strip().lower() not in ("0", "false", "no") |
| api.create_repo(repo, repo_type="dataset", exist_ok=True, private=_priv) |
| api.update_repo_settings(repo_id=repo, repo_type="dataset", private=_priv) |
| api.upload_folder( |
| folder_path=pkg_dir, |
| path_in_repo="code/flash", |
| repo_id=repo, |
| repo_type="dataset", |
| ignore_patterns=["__pycache__/*", "*.pyc"], |
| ) |
| return repo |
|
|
|
|
| def _train_body(input_data: dict) -> dict: |
| """Runs ON the RunPod GPU worker: fetch code, train (phase), return metrics. |
| |
| NOTE: Flash serializes this handler and runs it standalone, so every name it uses |
| must be imported INSIDE the function body (module-level imports are not in scope). |
| """ |
| import contextlib |
| import json |
| import os |
| import shutil |
| import subprocess |
| import sys |
|
|
| from huggingface_hub import snapshot_download |
|
|
| |
| |
| |
|
|
| |
| extra_pip = input_data.get("extra_pip") or [] |
| if extra_pip: |
| |
| |
| subprocess.run([sys.executable, "-m", "pip", "install", *extra_pip], check=True) |
|
|
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| hub_env_ids = input_data.get("hub_env_ids") or [] |
| if hub_env_ids: |
| worker_env = {k: str(v) for k, v in (input_data.get("env") or {}).items()} |
| prime_key = worker_env.get("PRIME_API_KEY") or os.environ.get("PRIME_API_KEY") |
| if not prime_key: |
| raise RuntimeError( |
| "PRIME_API_KEY is required to install the Prime Hub environment on the worker" |
| ) |
| |
| |
| |
| if shutil.which("prime") is None: |
| subprocess.run([sys.executable, "-m", "pip", "install", "prime"], check=True) |
| |
| |
| |
| |
| install_env = { |
| **os.environ, |
| "PRIME_API_KEY": prime_key, |
| "PRIME_DISABLE_VERSION_CHECK": "1", |
| "PIP_BREAK_SYSTEM_PACKAGES": "1", |
| } |
| for env_id in hub_env_ids: |
| subprocess.run( |
| ["prime", "env", "install", env_id, "--with", "pip"], check=True, env=install_env |
| ) |
|
|
| overrides = {k: str(v) for k, v in (input_data.get("env") or {}).items()} |
| snapshot_download( |
| repo_id=input_data["hf_repo"], |
| repo_type="dataset", |
| allow_patterns=["code/**"], |
| local_dir="/runcode", |
| token=overrides.get("HF_TOKEN"), |
| ) |
| code_dir = "/runcode/code" |
|
|
| env = dict(os.environ) |
| env.update(overrides) |
| |
| |
| |
| spec_path = "/tmp/job_spec.json" |
| with open(spec_path, "w") as sf: |
| sf.write(input_data["job_spec_json"]) |
| env["FLASH_JOB_SPEC_PATH"] = spec_path |
| env.pop("FLASH_JOB_SPEC_JSON", None) |
| env["PHASE"] = input_data["phase"] |
| env["SEED"] = str(input_data["seed"]) |
| env["PYTHONPATH"] = code_dir + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "") |
|
|
| def run_mode(mode: str, check: bool) -> int: |
| """Run one worker process, tee its console to a file, and on failure upload the |
| tail to HF as console_<mode>.txt — the engine-core root cause of crashes like |
| vLLM EngineDeadError only ever appears on the subprocess console, never in the |
| Python traceback.""" |
| console = f"/tmp/console_{mode}.txt" |
| with open(console, "w") as cf: |
| proc = subprocess.Popen( |
| [sys.executable, "-m", "flash.engine.worker"], |
| cwd=code_dir, |
| env={**env, "RUN_MODE": mode}, |
| stdout=subprocess.PIPE, |
| stderr=subprocess.STDOUT, |
| text=True, |
| ) |
| for line in proc.stdout: |
| print(line, end="") |
| cf.write(line) |
| proc.wait() |
| if proc.returncode != 0: |
| try: |
| from huggingface_hub import HfApi |
|
|
| spec = json.loads(input_data["job_spec_json"]) |
| phase_ns = "rl" if spec.get("algorithm") == "grpo" else spec["algorithm"] |
| prefix = f"{phase_ns}/{spec['run_id']}/seed{input_data['seed']}" |
| with open(console) as f: |
| tail = f.read()[-64_000:] |
| with open(console + ".tail", "w") as f: |
| f.write(tail) |
| HfApi(token=env.get("HF_TOKEN")).upload_file( |
| path_or_fileobj=console + ".tail", |
| path_in_repo=f"{prefix}/console_{mode}.txt", |
| repo_id=input_data["hf_repo"], |
| repo_type="dataset", |
| ) |
| except Exception as up_err: |
| print("console upload warn:", up_err) |
| if check: |
| raise RuntimeError( |
| f"worker mode '{mode}' exited {proc.returncode}; see console_{mode}.txt " |
| f"and error_{mode}.txt in the HF dataset repo" |
| ) |
| return proc.returncode |
|
|
| |
| |
| |
| for stale in ("/tmp/train_meta.json", "/tmp/metrics.json"): |
| with contextlib.suppress(FileNotFoundError): |
| os.remove(stale) |
| |
| |
| run_mode(input_data["phase"], check=False) |
| |
| |
| |
| |
| if not os.path.exists("/tmp/metrics.json"): |
| phase = input_data["phase"] |
| raise RuntimeError( |
| f"train phase '{phase}' produced no /tmp/metrics.json (it crashed before " |
| f"finishing); see error_{phase}.txt and console_{phase}.txt in the HF " |
| f"dataset repo for the full traceback" |
| ) |
| with open("/tmp/metrics.json") as f: |
| return json.load(f) |
|
|
|
|
| def isolate_flash_state(scope: str | None = None) -> None: |
| """Point the Flash SDK's resource registry at a per-process/private directory. |
| |
| The SDK persists its registry to ``./.flash/resources.pkl`` — shared, whole-dict, |
| last-writer-wins across every process in the CWD. Observed failure modes: stale |
| entries resurrecting long-dead endpoints on later syncs, and concurrent processes |
| clobbering each other's bookkeeping. Each Flash process gets its own registry |
| under ``~/.flash/flash-state/<scope>``; remote cleanup never relies on the |
| registry anyway (REST by id/name — see api.py). |
| """ |
| try: |
| from pathlib import Path |
|
|
| import runpod_flash.core.resources.resource_manager as rm |
|
|
| scope = scope or f"pid{os.getpid()}" |
| state_dir = Path.home() / ".flash" / "flash-state" / scope |
| state_dir.mkdir(parents=True, exist_ok=True) |
| rm.FLASH_STATE_DIR = state_dir |
| rm.RESOURCE_STATE_FILE = state_dir / "resources.pkl" |
| except Exception as exc: |
| logger.warning("flash state isolation skipped: %s", exc) |
|
|
|
|
| def _patch_runpod_backoff() -> None: |
| """Work around a runpod_flash bug that aborts long-running jobs. |
| |
| The SDK polls a synchronous job with exponential backoff computed as |
| ``base * (2 ** attempt)`` and only clamps to ``max_seconds`` afterwards. On a long |
| run the poll ``attempt`` grows without bound, so ``2 ** attempt`` becomes a huge int |
| and the float multiply raises ``OverflowError: int too large to convert to float`` |
| (observed ~80 min in), killing an otherwise-healthy job mid-run. We patch the symbol |
| to cap the exponent before the power so the delay still saturates at ``max_seconds``. |
| """ |
| try: |
| import math |
| import random |
|
|
| from runpod_flash.core.utils import backoff as _bo |
|
|
| if getattr(_bo, "_flash_backoff_patched", False): |
| return |
|
|
| def _safe_get_backoff_delay( |
| attempt, |
| base=0.1, |
| max_seconds=10.0, |
| jitter=0.2, |
| strategy=_bo.BackoffStrategy.EXPONENTIAL, |
| ): |
| a = min(int(attempt), 30) |
| if strategy == _bo.BackoffStrategy.EXPONENTIAL: |
| delay = base * (2**a) |
| elif strategy == _bo.BackoffStrategy.LINEAR: |
| delay = base + (attempt * base) |
| elif strategy == _bo.BackoffStrategy.LOGARITHMIC: |
| delay = base * math.log2(attempt + 2) |
| else: |
| raise ValueError(f"Unsupported backoff strategy: {strategy}") |
| delay = min(delay, max_seconds) |
| return delay * random.uniform(1 - jitter, 1 + jitter) |
|
|
| _bo.get_backoff_delay = _safe_get_backoff_delay |
| _bo._flash_backoff_patched = True |
| |
| try: |
| from runpod_flash.core.resources import serverless as _sl |
|
|
| _sl.get_backoff_delay = _safe_get_backoff_delay |
| except Exception: |
| |
| |
| pass |
| except Exception as exc: |
| logger.warning("runpod backoff patch skipped: %s", exc) |
|
|
|
|
| def min_cuda_for(friendly_gpu: str) -> str: |
| """Minimum host CUDA (driver) version for this GPU class on the active stack. |
| |
| Blackwell classes (sm_120 — RTX 5090, RTX Pro 6000): pypi wheels for |
| the modern stack (vllm 0.19) ship no Blackwell SASS, so every custom CUDA kernel |
| is PTX-JIT'd by the driver — and their PTX is built with a newer toolchain than |
| CUDA-12.8-era drivers can JIT (observed: "the provided PTX was compiled with an |
| unsupported toolchain" on driver 570.x). CUDA-13 drivers JIT it fine, so those |
| classes are pinned to >=13.0 on the modern stack (per-GPU ``min_cuda_modern`` in |
| providers.base.GPU_INFO). Ampere/Ada/Hopper have SASS in the wheels and run on 12.8. |
| Fully managed per-GPU (no override). |
| """ |
| from flash.providers.base import min_cuda_modern |
|
|
| return min_cuda_modern(friendly_gpu) |
|
|
|
|
| def endpoint_name(friendly_gpu: str, suffix: str | None = None) -> str: |
| """Flash endpoint/template name for a GPU class, optionally made unique per run. |
| |
| A fixed name (``flash-5090``) collides across back-to-back runs: runpod_flash's |
| ``get_or_deploy_resource`` finds the prior run's still-registered resource and tries to |
| *update* it, which fails with ``GraphQL errors: Template name must be unique`` (there is |
| no endpoint GC/reuse). A per-run ``suffix`` (the run id tail) gives each run its own |
| endpoint so it deploys fresh instead of colliding. RunPod scales each to zero when idle. |
| """ |
| base = f"flash-{gpu_short(friendly_gpu)}" |
| if not suffix: |
| return base |
| safe = "".join(c for c in str(suffix) if c.isalnum() or c == "-").strip("-")[:24] |
| return f"{base}-{safe}" if safe else base |
|
|
|
|
| def get_train_endpoint( |
| friendly_gpu: str, |
| execution_timeout_ms: int | None = None, |
| name_suffix: str | None = None, |
| disk_gb: int | None = None, |
| spec=None, |
| ): |
| """Build (and cache) the live Flash endpoint handler for a GPU class.""" |
| |
| os.environ["FLASH_IS_LIVE_PROVISIONING"] = "true" |
| from runpod_flash import Endpoint |
|
|
| from flash.providers.runpod.auth import ensure_auth |
| from flash.providers.runpod.jobs import volume_endpoint_kwargs |
|
|
| ensure_auth() |
| _patch_runpod_backoff() |
| isolate_flash_state(name_suffix) |
|
|
| friendly = canonical_gpu(friendly_gpu) |
| name = endpoint_name(friendly, name_suffix) |
| if name in _ENDPOINT_CACHE: |
| return _ENDPOINT_CACHE[name] |
| kwargs = dict( |
| name=name, |
| gpu=flash_gpu(friendly), |
| gpu_count=1, |
| min_cuda_version=min_cuda_for(friendly), |
| execution_timeout_ms=execution_timeout_ms or DEFAULT_EXECUTION_TIMEOUT_MS, |
| workers=(0, 1), |
| **volume_endpoint_kwargs(spec), |
| ) |
| |
| |
| |
| |
| image = os.environ.get("FLASH_WORKER_IMAGE") |
| if image: |
| kwargs["image"] = image |
| else: |
| kwargs["dependencies"] = resolve_worker_deps(friendly) |
| kwargs["system_dependencies"] = WORKER_SYSTEM_DEPS |
| ep = Endpoint(**kwargs) |
| handler = ep(_train_body) |
| |
| |
| from flash.providers.runpod.jobs import apply_disk_gb |
|
|
| cfg = ep._build_resource_config() |
| apply_disk_gb(cfg, disk_gb) |
| _ENDPOINT_CACHE[name] = handler |
| return handler |
|
|
|
|
| def _run_suffix(run_id: str | None) -> str | None: |
| """Short, COLLISION-FREE per-run endpoint suffix. |
| |
| Must be unique per run_id: the endpoint name is ``endpoint_name(friendly, suffix)`` and |
| RunPod reuses an endpoint by name -- two runs with the same suffix share one endpoint (and |
| its cached image/deps/registry-auth/template), so a later run silently reuses the earlier |
| one's config. The old ``run_id.split("-")[-1]`` only worked for hash-tailed default ids; a |
| descriptive run_id ending in e.g. the card name (``...-a100``) collided across every run. |
| Use a stable short hash of the WHOLE run_id, with a sanitized prefix for readability.""" |
| if not run_id: |
| return None |
| import hashlib |
| import re |
|
|
| h = hashlib.sha1(run_id.encode()).hexdigest()[:8] |
| prefix = re.sub(r"[^a-z0-9]", "", run_id.lower())[-12:] |
| return f"{prefix}{h}" if prefix else h |
|
|
|
|
| def stop_endpoint(friendly_gpu: str, name: str | None = None) -> None: |
| """Best-effort: scale cached endpoint(s) to zero / drop them. |
| |
| With ``name`` only that run's cached endpoint is dropped; without it, every |
| cached endpoint of the GPU class is — so a per-run teardown passes ``name`` |
| to avoid evicting a concurrent run's handler in the same process. |
| |
| NOTE: this only touches THIS process's in-memory cache, so it does nothing in a fresh |
| ``slm cancel`` process. Use ``terminate_endpoint`` to actually delete the remote endpoint. |
| """ |
| friendly = canonical_gpu(friendly_gpu) |
| prefix = f"flash-{gpu_short(friendly)}" |
| if name: |
| match = [k for k in _ENDPOINT_CACHE if k == name] |
| else: |
| match = [k for k in _ENDPOINT_CACHE if k.startswith(prefix)] |
| for key in match: |
| handler = _ENDPOINT_CACHE.pop(key, None) |
| ep = getattr(handler, "__self__", None) or getattr(handler, "endpoint", None) |
| for meth in ("scale_to_zero", "stop", "delete"): |
| fn = getattr(ep, meth, None) |
| if callable(fn): |
| try: |
| fn() |
| break |
| except Exception: |
| continue |
|
|
|
|
| def _select_endpoint_resources(resources: dict, target: str) -> list[str]: |
| """Resource ids whose resource ``.name`` contains ``target``. |
| |
| The live-provisioned resource is named ``live-<endpoint_name>``, so we match by substring |
| to catch the prefix. ``target`` is the endpoint name (``flash-<gpu>[-<run>]``). |
| """ |
| if not target: |
| return [] |
| out = [] |
| for uid, res in (resources or {}).items(): |
| name = str(getattr(res, "name", "") or "") |
| if target in name: |
| out.append(uid) |
| return out |
|
|
|
|
| def terminate_endpoint(friendly_gpu: str, run_id: str | None = None) -> list[dict]: |
| """Reliably tear down the remote Flash endpoint(s) for a run — cross-process. |
| |
| Unlike ``stop_endpoint`` (which only touches this process's in-memory cache), this looks |
| the endpoint up by name in runpod_flash's *persisted* resource registry and deletes it via |
| the RunPod API (``ResourceManager.undeploy_resource`` -> ``delete_endpoint``), which stops |
| any running worker. Best-effort: never raises. Returns the per-resource undeploy results. |
| |
| With ``run_id`` it targets exactly that run's uniquely-named endpoint; without it, the |
| bare ``flash-<gpu>`` prefix matches every endpoint of that GPU class. |
| """ |
| friendly = canonical_gpu(friendly_gpu) |
| target = endpoint_name(friendly, _run_suffix(run_id)) |
| |
| |
| |
| |
| |
| with FLASH_SDK_LOCK: |
| try: |
| from flash.providers.runpod.auth import ensure_auth |
|
|
| ensure_auth() |
| isolate_flash_state(_run_suffix(run_id)) |
| from runpod_flash.core.resources.resource_manager import ResourceManager |
| except Exception as exc: |
| return [{"success": False, "name": target, "message": f"flash unavailable: {exc}"}] |
|
|
| try: |
| rm = ResourceManager() |
| resources = rm.list_all_resources() |
| uids = _select_endpoint_resources(resources, target) |
| except Exception as exc: |
| return [{"success": False, "name": target, "message": f"resource lookup failed: {exc}"}] |
|
|
| async def _undeploy_all() -> list: |
| out = [] |
| for uid in uids: |
| res = resources.get(uid) |
| name = getattr(res, "name", None) |
| try: |
| out.append( |
| await rm.undeploy_resource(uid, resource_name=name, force_remove=True) |
| ) |
| except Exception as exc: |
| out.append({"success": False, "name": name, "message": str(exc)}) |
| return out |
|
|
| try: |
| results = asyncio.run(_undeploy_all()) |
| except Exception as exc: |
| results = [{"success": False, "name": target, "message": str(exc)}] |
|
|
| |
| |
| |
| |
| |
| if not uids: |
| with contextlib.suppress(Exception): |
| from flash.providers.runpod import api as runpod_api |
|
|
| for ep in runpod_api.find_endpoints_by_name(target): |
| if ep.get("name") == target and runpod_api.delete_endpoint(ep["id"]): |
| results.append( |
| {"success": True, "name": target, "message": "deleted via REST API"} |
| ) |
|
|
| |
| |
| with contextlib.suppress(Exception): |
| stop_endpoint(friendly, name=target) |
| return results |
|
|
|
|
| def build_worker_env(spec: JobSpec, seed: int) -> dict: |
| """Per-run env passed to the worker (secrets + recipe overrides).""" |
| |
| |
| |
| |
| |
| |
| _is_rl = str(getattr(spec, "algorithm", "")).lower() not in ("sft",) |
| |
| |
| |
| |
| |
| _sleep_raw = (spec.worker_env or {}).get("RL_VLLM_SLEEP", os.environ.get("RL_VLLM_SLEEP")) |
| _sleep_set = _sleep_raw is not None |
| _sleep_on = (_sleep_raw if _sleep_raw is not None else "1") not in ("0", "false", "False") |
| _alloc_default = ( |
| "garbage_collection_threshold:0.8,max_split_size_mb:256" |
| if (_is_rl and _sleep_on) |
| else "expandable_segments:True" |
| ) |
| |
| |
| |
| |
| |
| |
| _we = spec.worker_env or {} |
| _alloc_override = ( |
| _we.get("PYTORCH_ALLOC_CONF") |
| or _we.get("PYTORCH_CUDA_ALLOC_CONF") |
| or os.environ.get("PYTORCH_ALLOC_CONF") |
| or os.environ.get("PYTORCH_CUDA_ALLOC_CONF") |
| ) |
| _alloc_conf = _alloc_override or _alloc_default |
| env: dict[str, str] = { |
| "RUN_ID": spec.run_id, |
| |
| |
| "FLASH_ARM": "runpod", |
| "BENCH_HF_MODEL": spec.model, |
| "PYTORCH_CUDA_ALLOC_CONF": _alloc_conf, |
| "PYTORCH_ALLOC_CONF": _alloc_conf, |
| |
| |
| |
| |
| |
| **( |
| {"FLASH_ALLOC_AUTO": "1"} |
| if (_is_rl and not _sleep_set and not _alloc_override) |
| else {} |
| ), |
| |
| |
| **( |
| {"TORCHDYNAMO_DISABLE": os.environ["TORCHDYNAMO_DISABLE"]} |
| if os.environ.get("TORCHDYNAMO_DISABLE") |
| else {} |
| ), |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| for key in ( |
| "HF_TOKEN", |
| "PRIME_API_KEY", |
| "OPENROUTER_API_KEY", |
| "OPENAI_API_KEY", |
| "FLASH_JUDGE_MODEL", |
| ): |
| if os.environ.get(key): |
| env[key] = os.environ[key] |
| |
| |
| |
| env["HF_REPO"] = spec.train.hf_repo |
| |
| |
| |
| if getattr(spec.gpu, "network_volume", None): |
| env["HF_HOME"] = "/runpod-volume/hf-cache" |
| if spec.train.steps is not None: |
| env["RL_STEPS"] = str(spec.train.steps) |
| if spec.train.epochs is not None: |
| env["SFT_EPOCHS"] = str(spec.train.epochs) |
| |
| |
| |
| for k in ( |
| "SFT_PER_DEVICE_BS", |
| "SFT_PACKING", |
| |
| "RL_VLLM_GPU_UTIL", |
| "RL_VLLM_SLEEP", |
| "RL_PER_DEVICE_PROMPTS", |
| "VLLM_USE_V1", |
| |
| |
| |
| "VLLM_ATTENTION_BACKEND", |
| "FLASH_QUANT", |
| |
| |
| |
| |
| |
| |
| |
| |
| "WANDB_API_KEY", |
| "WANDB_ENTITY", |
| "LORA_TARGETS", |
| |
| |
| |
| |
| "FLASH_EVAL_EVERY_STEPS", |
| "FLASH_EVAL_NUM", |
| |
| |
| |
| "FLASH_HEARTBEAT_MIN_S", |
| |
| |
| |
| |
| |
| |
| "FLASH_MLP_KERNEL", |
| "FLASH_MLP_FP8", |
| "FLASH_MLP_FP8_DOWN", |
| "FLASH_FP8_BASE", |
| "FLASH_FP8_BASE_ATTN", |
| "FLASH_FP8_BASE_MLP", |
| "FLASH_FP8_BASE_MIN_K", |
| "FLASH_TRITON_LORA", |
| "FLASH_EMBED_KERNEL", |
| "FLASH_QKV_KERNEL", |
| "FLASH_ROPE_KERNEL", |
| |
| |
| "FLASH_CHALK_SPEC", |
| ): |
| |
| if os.environ.get(k) is not None: |
| env[k] = os.environ[k] |
| |
| |
| |
| |
| |
| |
| |
| _RESERVED_WORKER_ENV = {"RUN_ID", "HF_REPO", "FLASH_ARM"} |
| for k, v in (getattr(spec, "worker_env", None) or {}).items(): |
| if str(k).upper() in _RESERVED_WORKER_ENV: |
| continue |
| env[str(k)] = str(v) |
| return env |
|
|
|
|
| def submit_train(spec: JobSpec, seed: int, log=None) -> dict: |
| """Provision a dedicated GPU via Flash, run training, return the metrics dict.""" |
| timeout_s = max(60, int(spec.gpu.max_wall_seconds)) |
| from flash.envs.registry import worker_hub_env_ids, worker_pip_for_env |
|
|
| handler = get_train_endpoint( |
| spec.gpu.type, |
| execution_timeout_ms=timeout_s * 1000, |
| name_suffix=_run_suffix(spec.run_id), |
| disk_gb=spec.gpu.disk_gb, |
| spec=spec, |
| ) |
| payload = { |
| "hf_repo": spec.train.hf_repo, |
| "job_spec_json": spec.to_json(), |
| "phase": spec.phase, |
| "seed": int(seed), |
| "env": build_worker_env(spec, seed), |
| |
| |
| |
| "extra_pip": (list(spec.environment.pip) or worker_pip_for_env(spec.environment.id)) |
| + chalk_extra_pip(spec), |
| "hub_env_ids": worker_hub_env_ids(spec.environment.id, spec.environment.params), |
| } |
| if log is not None: |
| print( |
| f"submitting Flash job: gpu={spec.gpu.type} phase={spec.phase} " |
| f"seed={seed} model={spec.model}", |
| file=log, |
| flush=True, |
| ) |
|
|
| async def _call(): |
| res = handler(payload) |
| if inspect.isawaitable(res): |
| res = await res |
| return res |
|
|
| out = asyncio.run(_call()) |
| if not isinstance(out, dict): |
| raise RuntimeError(f"flash job returned no metrics: {out!r}") |
| return out |
|
|