|
| 1 | +"""V7-D06: dtype.cost_estimate RPC. |
| 2 | +
|
| 3 | +Honest-closure: scripts/bench_dtype_cast_cost.py produced a static |
| 4 | +CSV/HTML report of cast_overhead_ms + fwd_ms + fwdbwd_ms per dtype, |
| 5 | +but the UI dtype dropdown showed no numbers and the user could not |
| 6 | +see the real cost of fp32 vs bf16 vs fp16 before clicking Train. |
| 7 | +
|
| 8 | +This method runs an inline tiny-model probe (n_iter=5 by default, |
| 9 | +B=1 S=8 H=128) so the UI can fetch fresh numbers on mount and render |
| 10 | +ms/token alongside each option in the dropdown. |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +import time |
| 16 | +from typing import Literal |
| 17 | + |
| 18 | +from pydantic import BaseModel, ConfigDict, Field |
| 19 | + |
| 20 | +import mlx.core as mx |
| 21 | +import mlx.nn as nn |
| 22 | + |
| 23 | +from cppmega_v4.jsonrpc.cache import LRUCache |
| 24 | + |
| 25 | +DtypeName = Literal["fp32", "bf16", "fp16"] |
| 26 | + |
| 27 | + |
| 28 | +class DtypeCostParams(BaseModel): |
| 29 | + model_config = ConfigDict(extra="forbid") |
| 30 | + |
| 31 | + n_iter: int = Field(5, ge=1, le=200) |
| 32 | + hidden: int = Field(128, ge=16, le=4096) |
| 33 | + batch: int = Field(1, ge=1, le=32) |
| 34 | + seq: int = Field(8, ge=1, le=2048) |
| 35 | + |
| 36 | + |
| 37 | +class DtypeCostRow(BaseModel): |
| 38 | + model_config = ConfigDict(extra="allow") |
| 39 | + |
| 40 | + dtype: DtypeName |
| 41 | + supported: bool |
| 42 | + cast_overhead_ms: float | None = None |
| 43 | + fwd_ms: float | None = None |
| 44 | + fwdbwd_ms: float | None = None |
| 45 | + fwd_ms_per_token: float | None = None |
| 46 | + fwdbwd_ms_per_token: float | None = None |
| 47 | + error: str | None = None |
| 48 | + |
| 49 | + |
| 50 | +class DtypeCostResult(BaseModel): |
| 51 | + model_config = ConfigDict(extra="forbid") |
| 52 | + |
| 53 | + rows: list[DtypeCostRow] = Field(default_factory=list) |
| 54 | + n_iter: int |
| 55 | + shape: list[int] |
| 56 | + |
| 57 | + |
| 58 | +def _build_tiny(hidden: int) -> nn.Module: |
| 59 | + class _Block(nn.Module): |
| 60 | + def __init__(self) -> None: |
| 61 | + super().__init__() |
| 62 | + self.q = nn.Linear(hidden, hidden, bias=False) |
| 63 | + self.up = nn.Linear(hidden, 4 * hidden, bias=False) |
| 64 | + self.down = nn.Linear(4 * hidden, hidden, bias=False) |
| 65 | + |
| 66 | + def __call__(self, x: mx.array) -> mx.array: |
| 67 | + return self.down(nn.silu(self.up(self.q(x)))) |
| 68 | + |
| 69 | + return _Block() |
| 70 | + |
| 71 | + |
| 72 | +def _bench_one(dtype: DtypeName, *, n_iter: int, hidden: int, |
| 73 | + batch: int, seq: int) -> DtypeCostRow: |
| 74 | + dtype_map = {"fp32": mx.float32, "bf16": mx.bfloat16, |
| 75 | + "fp16": mx.float16} |
| 76 | + if dtype not in dtype_map: |
| 77 | + return DtypeCostRow(dtype=dtype, supported=False, |
| 78 | + error=f"unknown dtype {dtype}") |
| 79 | + target = dtype_map[dtype] |
| 80 | + try: |
| 81 | + model = _build_tiny(hidden) |
| 82 | + t0 = time.perf_counter() |
| 83 | + model.set_dtype(target) |
| 84 | + mx.eval(model.parameters()) |
| 85 | + cast_ms = (time.perf_counter() - t0) * 1000.0 |
| 86 | + |
| 87 | + x = mx.random.normal(shape=(batch, seq, hidden), |
| 88 | + key=mx.random.key(0)).astype(target) |
| 89 | + # Warm. |
| 90 | + warm = model(x) |
| 91 | + mx.eval(warm) |
| 92 | + t0 = time.perf_counter() |
| 93 | + for _ in range(n_iter): |
| 94 | + out = model(x) |
| 95 | + mx.eval(out) |
| 96 | + fwd_ms = (time.perf_counter() - t0) * 1000.0 / n_iter |
| 97 | + |
| 98 | + def _loss(m, _x): |
| 99 | + return mx.mean(m(_x).astype(mx.float32) ** 2) |
| 100 | + |
| 101 | + lvg = nn.value_and_grad(model, _loss) |
| 102 | + warm_lvg = lvg(model, x) |
| 103 | + mx.eval(warm_lvg) |
| 104 | + t0 = time.perf_counter() |
| 105 | + for _ in range(n_iter): |
| 106 | + loss, grads = lvg(model, x) |
| 107 | + mx.eval(loss, grads) |
| 108 | + fwdbwd_ms = (time.perf_counter() - t0) * 1000.0 / n_iter |
| 109 | + |
| 110 | + tokens = batch * seq |
| 111 | + return DtypeCostRow( |
| 112 | + dtype=dtype, supported=True, |
| 113 | + cast_overhead_ms=round(cast_ms, 4), |
| 114 | + fwd_ms=round(fwd_ms, 4), |
| 115 | + fwdbwd_ms=round(fwdbwd_ms, 4), |
| 116 | + fwd_ms_per_token=round(fwd_ms / tokens, 6), |
| 117 | + fwdbwd_ms_per_token=round(fwdbwd_ms / tokens, 6), |
| 118 | + ) |
| 119 | + except Exception as exc: |
| 120 | + return DtypeCostRow(dtype=dtype, supported=False, error=str(exc)) |
| 121 | + |
| 122 | + |
| 123 | +def dtype_cost_estimate( |
| 124 | + params: DtypeCostParams, *, cache: LRUCache | None = None, |
| 125 | +) -> DtypeCostResult: |
| 126 | + dtype_names: tuple[DtypeName, ...] = ("fp32", "bf16", "fp16") |
| 127 | + rows = [ |
| 128 | + _bench_one(dt, n_iter=params.n_iter, hidden=params.hidden, |
| 129 | + batch=params.batch, seq=params.seq) |
| 130 | + for dt in dtype_names |
| 131 | + ] |
| 132 | + return DtypeCostResult( |
| 133 | + rows=rows, n_iter=params.n_iter, |
| 134 | + shape=[params.batch, params.seq, params.hidden], |
| 135 | + ) |
| 136 | + |
| 137 | + |
| 138 | +__all__ = ["DtypeCostParams", "DtypeCostResult", "DtypeCostRow", |
| 139 | + "dtype_cost_estimate"] |
0 commit comments