|
| 1 | +"""V8-R04: ``architectures.auto_fit`` — given a preset, pick the best |
| 2 | +``(hidden_size, num_layers)`` AND a sharding proposal for the detected |
| 3 | +(or supplied) devbox in one shot. |
| 4 | +
|
| 5 | +Strategy: |
| 6 | + 1. Resolve the target topology — either ``host_info.topology`` from |
| 7 | + the caller, or pick the first ``available_topologies`` entry from |
| 8 | + ``platform.get_info``. |
| 9 | + 2. Compute ``target_bytes = total_hbm × headroom`` and run |
| 10 | + :func:`architectures.scale_down.scale_down` to land a model that |
| 11 | + fits the device. |
| 12 | + 3. Call :func:`suggest_sharding` against the scaled spec with a |
| 13 | + minimal default ``loss=cross_entropy`` + ``optim=adamw`` so the |
| 14 | + planner has enough to produce ranked proposals. |
| 15 | + 4. Return the bundle: scaled / sharding / fits / reason. |
| 16 | +""" |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +from typing import Any |
| 21 | + |
| 22 | +from pydantic import BaseModel, ConfigDict |
| 23 | + |
| 24 | +from cppmega_v4.architectures.scale_down import scale_down as _scale_down |
| 25 | +from cppmega_v4.jsonrpc.cache import LRUCache |
| 26 | +from cppmega_v4.jsonrpc.methods import ( |
| 27 | + _cache_lookup, _cache_store, suggest_sharding, |
| 28 | +) |
| 29 | +from cppmega_v4.jsonrpc.schema import ( |
| 30 | + ScaleDownFromCanonical, ScaleDownResultModel, |
| 31 | + SuggestShardingParams, SuggestShardingResult, |
| 32 | +) |
| 33 | +from cppmega_v4.parallelism import topology as _topo |
| 34 | + |
| 35 | + |
| 36 | +__all__ = [ |
| 37 | + "AutoFitParams", |
| 38 | + "AutoFitHostInfo", |
| 39 | + "AutoFitResult", |
| 40 | + "auto_fit", |
| 41 | + "TOPOLOGY_BUILDERS", |
| 42 | +] |
| 43 | + |
| 44 | + |
| 45 | +# Same table as memory_matrix_method but kept local to avoid a cycle. |
| 46 | +TOPOLOGY_BUILDERS: dict[str, Any] = { |
| 47 | + "h100_8x": lambda: _topo.h100_8x(), |
| 48 | + "h200_8x": lambda: _topo.h200_8x(), |
| 49 | + "a100_8x": lambda: _topo.a100_8x(), |
| 50 | + "b100_8x": lambda: _topo.b100_8x(), |
| 51 | + "gb10_quarter": lambda: _topo.gb10_quarter(), |
| 52 | + "tpu_v6e_8": lambda: _topo.tpu_v6e_8(), |
| 53 | + "tpu_v5p_4": lambda: _topo.tpu_v5p_4(), |
| 54 | + "m3_ultra_solo": lambda: _topo.m3_ultra_solo(), |
| 55 | +} |
| 56 | + |
| 57 | + |
| 58 | +class AutoFitHostInfo(BaseModel): |
| 59 | + """When supplied, overrides the server-side platform probe.""" |
| 60 | + |
| 61 | + model_config = ConfigDict(extra="forbid") |
| 62 | + |
| 63 | + topology: str |
| 64 | + headroom: float = 0.9 |
| 65 | + |
| 66 | + |
| 67 | +class AutoFitParams(BaseModel): |
| 68 | + """Input — preset name + optional host overrides.""" |
| 69 | + |
| 70 | + model_config = ConfigDict(extra="forbid") |
| 71 | + |
| 72 | + preset: str |
| 73 | + host_info: AutoFitHostInfo | None = None |
| 74 | + |
| 75 | + |
| 76 | +class AutoFitResult(BaseModel): |
| 77 | + """Output — scale-down result + sharding proposals + fits verdict.""" |
| 78 | + |
| 79 | + model_config = ConfigDict(extra="forbid") |
| 80 | + |
| 81 | + scaled: ScaleDownResultModel |
| 82 | + sharding: SuggestShardingResult |
| 83 | + fits: bool |
| 84 | + reason: str |
| 85 | + topology: str |
| 86 | + headroom: float |
| 87 | + |
| 88 | + |
| 89 | +def _resolve_topology(params: AutoFitParams) -> tuple[str, float]: |
| 90 | + """Pick (topology_name, headroom) from host_info or platform probe.""" |
| 91 | + if params.host_info is not None: |
| 92 | + if params.host_info.topology not in TOPOLOGY_BUILDERS: |
| 93 | + raise ValueError( |
| 94 | + f"unknown topology {params.host_info.topology!r}; " |
| 95 | + f"choose from {sorted(TOPOLOGY_BUILDERS)}") |
| 96 | + return params.host_info.topology, params.host_info.headroom |
| 97 | + from cppmega_v4.runtime.platform_probe import probe_platform |
| 98 | + info = probe_platform() |
| 99 | + available = info.get("available_topologies") or [] |
| 100 | + for t in available: |
| 101 | + if t in TOPOLOGY_BUILDERS: |
| 102 | + return t, 0.9 |
| 103 | + return "m3_ultra_solo", 0.9 # final fallback |
| 104 | + |
| 105 | + |
| 106 | +def auto_fit( |
| 107 | + params: AutoFitParams, *, cache: LRUCache | None = None, |
| 108 | +) -> AutoFitResult: |
| 109 | + """Chain scale_down + suggest_sharding for the detected/given devbox.""" |
| 110 | + key, hit = _cache_lookup(cache, "architectures.auto_fit", params) |
| 111 | + if hit is not None: |
| 112 | + return hit |
| 113 | + |
| 114 | + topo_name, headroom = _resolve_topology(params) |
| 115 | + topo = TOPOLOGY_BUILDERS[topo_name]() |
| 116 | + total_hbm = topo.total_hbm_bytes |
| 117 | + target_bytes = int(total_hbm * headroom) |
| 118 | + scaled = _scale_down(params.preset, target_bytes) |
| 119 | + |
| 120 | + # Build minimal sharding query payload — use the scaled specs + |
| 121 | + # cross_entropy + adamw defaults. We feed the scaled hidden_size |
| 122 | + # so the suggester sees the right model size, and head_outputs to |
| 123 | + # the last brick so verify_build_spec accepts the request. |
| 124 | + graph_nodes = [] |
| 125 | + graph_edges = [] |
| 126 | + prev_name: str | None = None |
| 127 | + for spec in scaled.specs: |
| 128 | + if "parallel" in spec: |
| 129 | + # Each branch becomes a leaf for the suggester. |
| 130 | + for leaf in spec["parallel"]: |
| 131 | + name = leaf.get("name") or leaf.get("kind") |
| 132 | + graph_nodes.append({ |
| 133 | + "id": name, "kind": leaf["kind"], |
| 134 | + "params": leaf.get("params", {}), |
| 135 | + }) |
| 136 | + if prev_name is not None: |
| 137 | + graph_edges.append({"src": prev_name, "dst": name}) |
| 138 | + prev_name = name |
| 139 | + continue |
| 140 | + name = spec.get("name") or spec.get("kind") |
| 141 | + graph_nodes.append({ |
| 142 | + "id": name, "kind": spec["kind"], |
| 143 | + "params": spec.get("params", {}), |
| 144 | + }) |
| 145 | + if prev_name is not None: |
| 146 | + graph_edges.append({"src": prev_name, "dst": name}) |
| 147 | + prev_name = name |
| 148 | + |
| 149 | + last = graph_nodes[-1]["id"] if graph_nodes else "out" |
| 150 | + sharding_params = SuggestShardingParams.model_validate({ |
| 151 | + "graph": {"nodes": graph_nodes, "edges": graph_edges}, |
| 152 | + "dim_env": {"H": scaled.hidden_size, "B": 1, "S": 256}, |
| 153 | + "loss": {"kind": "cross_entropy", "head_outputs": [last]}, |
| 154 | + "optim": {"kind": "adamw", "groups": [ |
| 155 | + {"matcher": "all", "lr": 3e-4, "weight_decay": 0.01, |
| 156 | + "betas": [0.9, 0.95]}, |
| 157 | + ], "gradient_clip_norm": 1.0, "mixed_precision": True}, |
| 158 | + "topology": {"factory": topo_name, "kwargs": {}}, |
| 159 | + }) |
| 160 | + sharding = suggest_sharding(sharding_params, cache=cache) |
| 161 | + |
| 162 | + best_proposal = ( |
| 163 | + sharding.proposals[0] if sharding.proposals else None) |
| 164 | + fits = bool(scaled.fits and ( |
| 165 | + best_proposal is None or best_proposal.fits)) |
| 166 | + axis_desc = ( |
| 167 | + ",".join(f"{a.axis_name}×{a.degree}" |
| 168 | + for a in best_proposal.sharding.axis_assignments) |
| 169 | + if best_proposal else "<no proposal>") |
| 170 | + reason = ( |
| 171 | + f"hidden={scaled.hidden_size}, layers={scaled.num_layers}, " |
| 172 | + f"axis={axis_desc}, peak={scaled.estimated_bytes / 1e9:.2f} GB / " |
| 173 | + f"{total_hbm / 1e9:.0f} GB") |
| 174 | + out = AutoFitResult( |
| 175 | + scaled=ScaleDownResultModel( |
| 176 | + hidden_size=scaled.hidden_size, |
| 177 | + num_layers=scaled.num_layers, |
| 178 | + estimated_bytes=scaled.estimated_bytes, |
| 179 | + target_bytes=scaled.target_bytes, |
| 180 | + fits=scaled.fits, |
| 181 | + scaled_down_from=ScaleDownFromCanonical( |
| 182 | + hidden_size=scaled.scaled_down_from[0], |
| 183 | + num_layers=scaled.scaled_down_from[1], |
| 184 | + ), |
| 185 | + specs=scaled.specs, |
| 186 | + ), |
| 187 | + sharding=sharding, |
| 188 | + fits=fits, |
| 189 | + reason=reason, |
| 190 | + topology=topo_name, |
| 191 | + headroom=headroom, |
| 192 | + ) |
| 193 | + _cache_store(cache, key, out) |
| 194 | + return out |
0 commit comments