|
| 1 | +"""H23: fp16 dtype option alongside bf16/fp32.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +from cppmega_v4.jsonrpc.schema import VerifyParams |
| 8 | +from cppmega_v4.runner import Pipeline, run_pipeline |
| 9 | + |
| 10 | + |
| 11 | +def _spec() -> VerifyParams: |
| 12 | + return VerifyParams.model_validate({ |
| 13 | + "graph": { |
| 14 | + "nodes": [ |
| 15 | + {"id": "attn", "kind": "attention", |
| 16 | + "params": {"num_heads": 4, "head_dim": 64}}, |
| 17 | + {"id": "mlp", "kind": "mlp", "params": {}}, |
| 18 | + ], |
| 19 | + "edges": [{"src": "attn", "dst": "mlp"}], |
| 20 | + }, |
| 21 | + "dim_env": {"B": 1, "S": 8, "H": 128, |
| 22 | + "nh": 2, "nkv": 1, "head_dim": 64}, |
| 23 | + "loss": {"kind": "cross_entropy", "head_outputs": ["mlp"]}, |
| 24 | + "optim": {"kind": "adamw", |
| 25 | + "groups": [{"matcher": "all", "lr": 1e-3, |
| 26 | + "weight_decay": 0.01, |
| 27 | + "betas": [0.9, 0.95]}]}, |
| 28 | + }) |
| 29 | + |
| 30 | + |
| 31 | +def _train(**opts) -> dict: |
| 32 | + rep = run_pipeline(_spec(), Pipeline.from_dict({ |
| 33 | + "stages": ["parse", "verify_build_spec", "build_model", "train"], |
| 34 | + "stage_options": {"train": {"num_steps": 2, **opts}}, |
| 35 | + })) |
| 36 | + tr = next(s for s in rep.stages if s.name == "train") |
| 37 | + assert tr.status == "ok" |
| 38 | + return tr.extras |
| 39 | + |
| 40 | + |
| 41 | +def test_h23_fp16_option_accepted_and_reported(): |
| 42 | + e = _train(master_dtype="fp16") |
| 43 | + assert e["master_dtype"] == "fp16" |
| 44 | + assert e["train_dtype"] == "fp16" |
| 45 | + assert "float16" in e["dtype_actual"]["master_dtype_actual"] |
| 46 | + |
| 47 | + |
| 48 | +def test_h23_fp16_losses_finite_and_close_to_bf16(): |
| 49 | + bf16 = _train(master_dtype="bf16")["losses"] |
| 50 | + fp16 = _train(master_dtype="fp16")["losses"] |
| 51 | + assert all(x == x and -1e10 < x < 1e10 for x in fp16) |
| 52 | + # fp16 and bf16 share the same exponent range; loss should be in |
| 53 | + # the same ballpark for a 2-step run (within 50%). |
| 54 | + for a, b in zip(bf16, fp16): |
| 55 | + assert abs(a - b) / max(abs(a), abs(b), 1e-9) < 0.5 |
| 56 | + |
| 57 | + |
| 58 | +def test_h23_fp16_weight_delta_smaller_than_fp32(): |
| 59 | + """fp16 has fewer mantissa bits → tiny updates round to zero → |
| 60 | + expected smaller weight_delta_norm than fp32.""" |
| 61 | + fp32 = _train(master_dtype="fp32")["weight_delta_norm"] |
| 62 | + fp16 = _train(master_dtype="fp16")["weight_delta_norm"] |
| 63 | + # On a 2-step run noise is large; allow generous gate that fp16 |
| 64 | + # weight delta is no MORE than 1.5x fp32 (precision loss caps it). |
| 65 | + assert fp16 <= fp32 * 1.5 + 1e-6, ( |
| 66 | + f"fp16 delta {fp16} > 1.5×fp32 {fp32}") |
0 commit comments