File size: 9,750 Bytes
c5eb42c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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

import os

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.
VRAM_HEADROOM = float(os.environ.get("AUTOSLM_VRAM_HEADROOM", "1.1"))


def required_vram_gb(
    model_id: str,
    algorithm: str,
    *,
    train=None,
    thinking: bool = False,
    quant_repo: str | None = None,
) -> 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 and the 4-bit MoE 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."""
    from autoslm.engine.vram import model_required_vram_gb

    return model_required_vram_gb(
        model_id,
        algorithm,
        train=train,
        thinking=thinking,
        headroom=VRAM_HEADROOM,
        quant_repo=quant_repo,
    )


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,
) -> 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
        )
    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(),
    train=None,
    thinking: bool = False,
    quant_repo: str | None = None,
) -> 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.
    ``quant_repo`` (the run's pre-quantized export) sizes the AWQ'd footprint so a
    prequant MoE allocates onto the cheaper card it actually fits, not the bf16 tier.
    """
    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, quant_repo=quant_repo
    )
    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)"
        )

    candidates: list[Candidate] = []
    offer_book: tuple = ()
    if provider in ("auto", "runpod") and "runpod" in live:
        candidates += _runpod_candidates(need, pinned_gpu, allow_unval)
    if provider in ("auto", "vast") and "vast" in live:
        vast_cands, offer_book = _vast_candidates(
            need,
            pinned_gpu,
            allow_unval,
            disk_gb,
            exclude_machine_ids,
            required=(provider == "vast"),
        )
        candidates += vast_cands

    if not candidates:
        constraint = (
            f"gpu pinned to {pinned_gpu}" if pinned_gpu else f">= {need} GB VRAM for {model_id}"
        )
        raise UnsupportedGpuError(
            f"no allocatable GPU ({constraint}, provider={provider}, "
            f"validated_only={not allow_unval}); widen with gpu.allow_unvalidated = true "
            f"or a different gpu.type/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