File size: 16,160 Bytes
2baeb41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16631e7
2baeb41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16631e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2baeb41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16631e7
2baeb41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
"""Cross-provider GPU allocation: the cheapest class that comfortably fits the run.

Given a base model (+ algorithm), compute the VRAM the FULL run needs β€” sized for the
heavier phase, GRPO, since the typical pipeline is SFT followed by GRPO β€” then rank
every provisionable candidate across ALL registered providers by live $/hr and pick the
cheapest:

  runpod  every Flash-provisionable class (live pricing, cached; static fallback)
  vast    live verified-datacenter offers (usable_offers' quality floors applied)

Allocation happens at SUBMIT time in the runner (offers are a volatile market);
the parse-time resolution in schema is a RunPod-static provisional for
validation/dry-run display. Offline (AUTOSLM_SKIP_NET) the allocator degrades to exactly
``cheapest_gpu``'s deterministic static-rate answer (RunPod only β€” Vast is offline-off).

Provider-agnostic by construction: it walks the registered providers and asks each for
its ``gpu_classes()`` + ``hourly_rate()``; the only provider-specific knowledge is that
Vast classes come from a live offer book (collected through the provider's
``usable_offers`` and carried opaquely on ``Candidate.offer``).
"""

from __future__ import annotations

from autoslm._logging import get_logger
from autoslm.providers import PROVIDER_NAMES, available_providers, get_provider
from autoslm.providers.base import (
    Allocation,
    Candidate,
    UnsupportedGpuError,
    canonical_gpu,
    unvalidated_allowed,
)

logger = get_logger(__name__)

# "Comfortably" = the open-model VRAM estimate plus headroom, so a full SFT+GRPO run
# never lands in check_fit's "tight" band by construction. Curated catalog entries
# already carry measured minimums and are used as-is. The headroom (default 1.1 ==
# model_required_vram_gb's own default) is read at call time via vram_headroom() so allocate()
# and resolve_gpu_policy size identically and pick up a value exported after import.


def vram_headroom() -> float:
    """The sizing headroom multiplier, honored by both the submit-time allocator and the
    parse-time resolve_gpu_policy so they never disagree (PR #176 review). A validated constant."""
    return 1.1


def required_vram_gb(
    model_id: str,
    algorithm: str,
    *,
    train=None,
    thinking: bool = False,
    gpu_count: int = 1,
) -> int:
    """VRAM the full run needs, sized to the run's actual knobs (context length, LoRA
    rank, batch / group size, thinking) via the shared ``model_required_vram_gb`` matrix.

    Catalog GRPO floors stay hard floors (never under-provision a validated model); the
    matrix sizes up from there for big contexts/groups and down to a cheaper card for
    small runs. Unlisted open models size from HF metadata, falling back to the 24 GB tier
    when unreadable (handled inside model_required_vram_gb)."""
    from autoslm.engine.vram import model_required_vram_gb

    colocate = model_required_vram_gb(
        model_id,
        algorithm,
        train=train,
        thinking=thinking,
        headroom=vram_headroom(),
    )
    # Disaggregated GRPO ([train].inference_gpus>0) splits memory across the node's GPUs: the
    # inference server (full bf16 weights + KV) and the trainer (quant weights + LoRA optimizer +
    # activations) live on SEPARATE cards, so no single GPU needs the colocate total. The binding
    # per-GPU need is max(server bf16 weights + KV/overhead, the trainer's share ~= colocate minus
    # the vLLM engine/KV). Sizing to that lets a big model fit a per-role card (e.g. Qwen3.6-35B-A3B
    # served bf16 on a 94GB H100 NVL, 4-bit trainer on the other) instead of demanding the colocate
    # floor (~96GB) β€” which no available 2-GPU node meets β€” while staying FLOORED by the bf16 weights
    # so the server can never be under-provisioned into an OOM. Also unblocks 4B 1:2 on a 5090 (the
    # disaggregated server/trainer each fit 32GB though colocate 4B needs ~35GB).
    if train is not None and int(getattr(train, "inference_gpus", 0) or 0) > 0:
        pb = _params_b_for_vram(model_id)
        if pb:
            infer = max(1, int(getattr(train, "inference_gpus", 1) or 1))
            # Total GPUs on the node (rollout + trainer). The trainer pool is everything that
            # isn't a rollout GPU; default to a single trainer when the caller didn't pass a count
            # (the colocate cap below still protects that degenerate case).
            total = max(infer + 1, int(gpu_count or (infer + 1)))
            n_trainer = max(1, total - infer)
            base = 2.0 * pb  # frozen base model, bf16, ALL params resident (MoE: every expert loaded)

            # ROLLOUT card. The baked verl default is DATA-PARALLEL (TP=1) β€” each replica holds the
            # FULL base + KV. A base too large to fit one 80GB card as a DP replica is served
            # TENSOR-PARALLEL across the inference GPUs instead (verl_runner auto-bumps
            # AUTOSLM_VERL_ROLLOUT_TP to match), so size per shard. Floors the per-card need so the
            # inference GPU is never under-provisioned into a KV/weights OOM.
            rollout_tp = infer if (base * 1.35 + 4) > 78 else 1
            rollout_need = int(base * 1.35 / rollout_tp) + 4  # weights/shard + KV / CUDA-graph / overhead

            # TRAINER card. FSDP2 shards the frozen base (+ tiny LoRA grads/optim) across the
            # n_trainer trainer GPUs; activations and the one_step_off *bucketed* weight-transfer
            # staging do NOT shard, so floor each card at base/n_trainer + a bounded transfer buffer +
            # fixed overhead. n_trainer==1 keeps the whole base on one card (matches the observed 4B
            # one-trainer OOM on a 24GB card β€” needed ~26GB, fits 40GB β€” while 4B sharded across two
            # trainers fits 24GB). The bucketed sync stages only a few layers, NOT a full second copy,
            # so 35B-A3B (70GB base) trains across 2 trainers at ~58GB/card and fits an 80GB H100/A100.
            transfer_buf = min(0.5 * base, 10.0)
            trainer_need = int(base / n_trainer + transfer_buf + 13)

            # Per-card requirement is the heavier role on a homogeneous node. This is already a true
            # per-card figure (both roles divided by their parallel degree), so no colocate cap β€” a
            # multi-GPU FSDP/TP split legitimately needs LESS per card than the whole colocated total.
            return max(rollout_need, trainer_need)
    return colocate


def _params_b_for_vram(model_id: str) -> float | None:
    """Param count (billions) for disaggregated VRAM sizing: catalog first, then HF metadata."""
    from autoslm.engine.vram import fetch_hf_params_b, params_b_from_str

    try:
        from autoslm.catalog import get_model

        pb = params_b_from_str(getattr(get_model(model_id), "params", None))
        if pb:
            return pb
    except Exception:
        pass
    try:
        return fetch_hf_params_b(model_id)
    except Exception:
        return None


def _runpod_candidates(need: int, pinned_gpu: str | None, allow_unval: bool) -> list[Candidate]:
    """RunPod's fitting classes priced live (static fallback)."""
    provider = get_provider("runpod")
    out: list[Candidate] = []
    for g in provider.gpu_classes():
        if g.vram_gb < need:
            continue
        if pinned_gpu and g.name != pinned_gpu:
            continue
        if "runpod" not in g.validated_on and not allow_unval:
            continue
        out.append(
            Candidate(
                "runpod",
                g.name,
                provider.hourly_rate(g.name),
                g.vram_gb,
                "runpod" in g.validated_on,
            )
        )
    return out


def _vast_candidates(
    need: int,
    pinned_gpu: str | None,
    allow_unval: bool,
    disk_gb: int,
    exclude_machine_ids,
    *,
    required: bool,
    num_gpus: int = 1,
) -> tuple[list[Candidate], tuple]:
    """Vast's fitting classes from the live offer book (cheapest per class).

    Returns (candidates, full_offer_book). ``required`` (a hard ``provider="vast"``
    pin) re-raises a search failure; otherwise it degrades to RunPod-only.
    """
    from autoslm.providers.base import GPU_INFO
    from autoslm.providers.vast.jobs import MIN_DISK_GB, usable_offers

    # When a larger class is pinned for a small model, search at the PINNED class's VRAM,
    # not the (smaller) model requirement: the offer search returns the cheapest ``limit``
    # offers from a VRAM floor, so a search at ``need`` can fill that window entirely with
    # small cheap cards and never surface the pinned larger class. ``need`` is still the
    # validity floor (allocate() rejects an undersized pin before we get here).
    search_vram = max(need, GPU_INFO[pinned_gpu].vram_gb) if pinned_gpu else need
    book: list = []
    try:
        # The offer search must use the SAME disk floor instances are actually
        # provisioned with (``create_instance``/``_effective_disk_gb``); searching at a
        # smaller requested ``disk_gb`` would surface offers that then fail to rent.
        book = usable_offers(
            search_vram, max(float(disk_gb), MIN_DISK_GB),
            exclude_machine_ids=exclude_machine_ids, num_gpus=num_gpus,
        )
    except Exception as exc:
        if required:
            raise UnsupportedGpuError(f"vast offer search failed: {exc}") from exc
        logger.warning("vast offer search failed (%s); allocating on runpod only", exc)
    out: list[Candidate] = []
    seen: set[str] = set()
    for o in book:
        if pinned_gpu and o.gpu != pinned_gpu:
            continue
        info = GPU_INFO[o.gpu]
        if "vast" not in info.validated_on and not allow_unval:
            continue
        if o.gpu in seen:  # offers are price-sorted; keep the cheapest per class
            continue
        seen.add(o.gpu)
        out.append(
            Candidate(
                "vast", o.gpu, o.dph_total, info.vram_gb, "vast" in info.validated_on, offer=o
            )
        )
    return out, tuple(book)


def allocate(
    model_id: str,
    algorithm: str,
    *,
    gpu: str | None = None,
    provider: str = "auto",
    disk_gb: int = 60,
    allow_unvalidated: bool | None = None,
    exclude_machine_ids: set[int] | frozenset[int] = frozenset(),
    exclude_gpu_classes: set[str] | frozenset[str] = frozenset(),
    gpu_count: int = 1,
    train=None,
    thinking: bool = False,
) -> Allocation:
    """Pick the cheapest (provider, GPU class) able to run the job across providers.

    ``gpu`` pins the class (the allocator then only picks the provider); ``provider``
    pins the substrate ("auto"/"runpod"/"vast"). Both default to fully automatic.
    ``train``/``thinking`` size the requirement to the run's actual knobs (context, group,
    rank, batch) via the matrix β€” long context / large group route up, small runs down.
    ``exclude_gpu_classes`` drops whole GPU classes (any provider) from the candidate pool β€”
    the orchestrator adds a class here after it failed ``no_capacity`` (capacity-starved /
    throttled) so re-allocation walks to the next-cheapest AVAILABLE class instead of retrying
    the same starved one on another provider.
    """
    _excluded_classes = {canonical_gpu(c) for c in exclude_gpu_classes}
    if provider not in ("auto", *PROVIDER_NAMES):
        raise UnsupportedGpuError(
            f"unknown provider {provider!r} (auto, {', '.join(PROVIDER_NAMES)})"
        )
    pinned_gpu = canonical_gpu(gpu) if gpu else None
    # The model's requirement is the floor regardless of a pin: an undersized concrete
    # pin (e.g. Qwen3-8B on a 24 GB card) must drop out of the candidate filter and
    # raise here, not provision a paid worker that OOMs. The pin only narrows WHICH
    # fitting class is chosen, never lowers the VRAM bar.
    need = required_vram_gb(model_id, algorithm, train=train, thinking=thinking, gpu_count=gpu_count)
    allow_unval = unvalidated_allowed(allow_unvalidated)
    live = available_providers()
    if provider != "auto" and provider not in live:
        raise UnsupportedGpuError(
            f"provider {provider!r} requested but not available on this control plane "
            f"(available: {', '.join(live) or '(none)'}; vast needs VAST_API_KEY)"
        )

    def _gather(pin: str | None) -> tuple[list[Candidate], tuple]:
        cands: list[Candidate] = []
        book: tuple = ()
        if provider in ("auto", "runpod") and "runpod" in live:
            cands += _runpod_candidates(need, pin, allow_unval)
        if provider in ("auto", "vast") and "vast" in live:
            vcands, book = _vast_candidates(
                need, pin, allow_unval, disk_gb, exclude_machine_ids,
                required=(provider == "vast"), num_gpus=gpu_count,
            )
            cands += vcands
        if _excluded_classes:
            cands = [c for c in cands if c.gpu not in _excluded_classes]
        return cands, book

    candidates, offer_book = _gather(pinned_gpu)
    # NEVER hard-fail on availability: a pin that no live provider can serve (the class isn't
    # offered right now, or is below ``need`` so it's filtered out) escalates to the cheapest
    # FITTING class across providers instead of raising -- "one spot larger, and so on". The
    # ``need`` floor is still absolute (we never drop below it -> no OOM), and the pin is only a
    # preference. We only raise when NOTHING >= need is available anywhere (truly unsatisfiable).
    escalated_from = None
    if not candidates and pinned_gpu is not None:
        escalated_from = pinned_gpu
        candidates, offer_book = _gather(None)
    if not candidates:
        raise UnsupportedGpuError(
            f"no allocatable GPU (>= {need} GB VRAM for {model_id}, provider={provider}, "
            f"validated_only={not allow_unval}); widen with gpu.allow_unvalidated = true, add a "
            f"provider (VAST_API_KEY), or the run genuinely exceeds every available GPU class"
        )
    if escalated_from is not None:
        order0 = {n: i for i, n in enumerate(PROVIDER_NAMES)}
        _cheapest = sorted(candidates, key=lambda c: (c.hourly_usd, c.vram_gb, order0.get(c.provider, 99)))[0]
        # WARNING level so it surfaces at default `slm train` verbosity (configure_logging is
        # WARNING) β€” a silently-escalated pin changes cost/hardware and operators must see it;
        # still routed through the logger (stderr), so machine-readable stdout stays clean.
        logger.warning(
            "pinned GPU %r unavailable or below need (%s GB) on provider=%s; "
            "escalated to cheapest fitting class %s (%s GB, %s)",
            escalated_from,
            need,
            provider,
            _cheapest.gpu,
            _cheapest.vram_gb,
            _cheapest.provider,
        )
    # Cheapest first; equal rates prefer less VRAM (don't burn a big card on a small
    # job), then registry order (runpod is the longest-validated substrate).
    order = {n: i for i, n in enumerate(PROVIDER_NAMES)}
    ranked = sorted(candidates, key=lambda c: (c.hourly_usd, c.vram_gb, order.get(c.provider, 99)))
    best = ranked[0]
    return Allocation(
        provider=best.provider,
        gpu=best.gpu,
        hourly_usd=best.hourly_usd,
        min_vram_gb=need,
        candidates=tuple(ranked),
        offer=best.offer,
        provider_offers=offer_book,
    )


def allocation_summary(a: Allocation) -> str:
    head = (
        f"allocated {a.gpu} on {a.provider} at ${a.hourly_usd:.2f}/hr "
        f"(need >= {a.min_vram_gb} GB VRAM"
    )
    # ``a.offer`` is an OPAQUE per-provider provisioning hint, not necessarily a Vast
    # offer β€” only format Vast specifics when the chosen provider is vast, so a future
    # provider's hint never misformats or raises on a missing attribute.
    if a.provider == "vast" and a.offer is not None:
        head += f", vast offer {a.offer.offer_id} in {a.offer.geolocation}"
    head += ")"
    if len(a.candidates) > 1:
        nxt = a.candidates[1]
        head += f"; next-best: {nxt.gpu}@{nxt.provider} ${nxt.hourly_usd:.2f}/hr"
    return head