File size: 9,170 Bytes
83a559d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reproduction of Table 2, arXiv 2506.14038v2 ("Load Balancing MoE with Similarity
Preserving Routers", Omi/Sen/Farhadi).

Claim under test: 100 loss-based router updates (bf16) yield lower post-cast
Gram-matrix error than (a) the fp32 direct orthogonal parameterization
(Lezcano-Casado 2019 = torch.nn.utils.parametrizations.orthogonal) and (b)
orthogonal initialization (Saxe et al. 2014 = torch.nn.init.orthogonal_),
both cast fp32 -> bfloat16.

Protocol (paper Sec 4.1, Table 2, Fig 6):
  - Router stored as nn.Linear weight, shape (E, D) = (32, 1536) (transposed
    convention); Gram = W W^T == R^T R.
  - Trained: AdamW, no weight decay, LR cosine-decayed 1e-4 -> 1e-5 over 100
    steps, matrix kept in bfloat16 ("trains the matrix directly in bfloat16").
  - Loss: simbal_loss from paper Fig 6, verbatim: torch.norm(w @ w.T - I, p=1)
    (entrywise L1 sum; the /E^2 normalized version is the reported "L1 Dist").
  - Metrics computed in float32 on the bf16 matrix (a bf16-output Gram matmul
    has ulp ~3.9e-3 at 1.0 and cannot produce the paper's ~1e-5 values, so the
    post-cast evaluation must upcast; noted as an interpretation).
  - 100 trials, seeds 0..99; report mean +- SD of Max Dev and mean |G - I|.

Declared ambiguities handled as explicit variants (paper does not state them):
  A1: trained-arm init: orthogonal_ (primary) vs PyTorch default Linear init.
  A2: loss matmul dtype during training: bf16 (verbatim Fig 6) vs float32.
  A3: Param arm trained for the same 100 steps (budget parity) vs no training.
"""

import argparse
import json
import statistics
import sys
import time

import torch

D, E, STEPS = 1536, 32, 100
LR0, LR1 = 1e-4, 1e-5

PAPER = {
    "trained": {"max": (1.03e-5, 2.76e-6), "mean": (8.52e-7, 5.84e-8)},
    "param": {"max": (2.00e-4, 2.31e-5), "mean": (4.80e-5, 1.60e-6)},
    "ortho_init": {"max": (1.93e-4, 1.88e-5), "mean": (4.62e-5, 1.79e-6)},
}


def gram_metrics(w_bf16: torch.Tensor, eye32: torch.Tensor):
    """Post-cast evaluation in float32: W W^T vs I (E x E)."""
    g = w_bf16.float() @ w_bf16.float().T
    d = (g - eye32).abs()
    return d.max().item(), d.mean().item()


def simbal_loss(w: torch.Tensor, eye: torch.Tensor, normalized: bool = False):
    """Verbatim paper Fig. 6 (SimBal), dtype follows w. normalized=True divides
    the entrywise L1 sum by E^2 (the mean form the Table 2 column reports)."""
    w_ortho = torch.matmul(w, w.T)
    loss = torch.norm(w_ortho - eye, p=1)
    return loss / (E * E) if normalized else loss


def make_ortho(seed: int):
    torch.manual_seed(seed)
    w = torch.empty(E, D, device=DEVICE)
    torch.nn.init.orthogonal_(w)  # Saxe et al. 2014, float32
    return w


def run_trained(seed: int, init: str = "ortho", loss_fp32: bool = False, normalized: bool = False):
    """Trained arm: optimize simbal_loss for STEPS AdamW steps in bf16."""
    if init == "ortho":
        w = make_ortho(seed).to(torch.bfloat16)
    elif init == "linear_default":
        torch.manual_seed(seed)
        lin = torch.nn.Linear(D, E, bias=False, device=DEVICE)  # default kaiming-uniform
        w = lin.weight.detach().to(torch.bfloat16)
    else:
        raise ValueError(init)
    w = w.requires_grad_(True)
    opt = torch.optim.AdamW([w], lr=LR0, weight_decay=0.0)
    sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=STEPS, eta_min=LR1)
    eye = torch.eye(E, device=DEVICE, dtype=torch.bfloat16)
    loss_val = None
    for _ in range(STEPS):
        opt.zero_grad(set_to_none=True)
        loss = simbal_loss(w.float() if loss_fp32 else w, eye.float() if loss_fp32 else eye, normalized=normalized)
        loss.backward()
        opt.step()
        sched.step()
        loss_val = loss.item()
    md, ml1 = gram_metrics(w.detach(), EYE32)
    return md, ml1, loss_val


def run_trained_const(seed: int):
    """Variant: same as fp32-loss trained but constant LR 1e-4 (no cosine)."""
    w = make_ortho(seed).to(torch.bfloat16).requires_grad_(True)
    opt = torch.optim.AdamW([w], lr=LR0, weight_decay=0.0)
    eye = torch.eye(E, device=DEVICE, dtype=torch.float32)
    loss_val = None
    for _ in range(STEPS):
        opt.zero_grad(set_to_none=True)
        loss = simbal_loss(w.float(), eye)
        loss.backward()
        opt.step()
        loss_val = loss.item()
    md, ml1 = gram_metrics(w.detach(), EYE32)
    return md, ml1, loss_val


def run_param(seed: int, train: bool = True):
    """Param arm: fp32 orthogonal parametrization (Lezcano-Casado 2019), cast to bf16."""
    torch.manual_seed(seed)
    lin = torch.nn.Linear(D, E, bias=False, dtype=torch.float32, device=DEVICE)
    torch.nn.init.orthogonal_(lin.weight)
    lin = torch.nn.utils.parametrizations.orthogonal(lin, "weight", use_trivialization=False)
    if train:
        opt = torch.optim.AdamW(lin.parameters(), lr=LR0, weight_decay=0.0)
        sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=STEPS, eta_min=LR1)
        eye32f = torch.eye(E, device=DEVICE, dtype=torch.float32)
        for _ in range(STEPS):
            opt.zero_grad(set_to_none=True)
            loss = simbal_loss(lin.weight, eye32f)
            loss.backward()
            opt.step()
            sched.step()
    w_f32 = lin.weight.detach()
    pre_cast = gram_metrics(w_f32, EYE32)
    md, ml1 = gram_metrics(w_f32.to(torch.bfloat16), EYE32)
    return md, ml1, pre_cast


def run_ortho_init(seed: int):
    """OrthoInit arm: orthogonal_ in fp32, cast to bf16, no training."""
    w_f32 = make_ortho(seed)
    pre_cast = gram_metrics(w_f32, EYE32)
    md, ml1 = gram_metrics(w_f32.to(torch.bfloat16), EYE32)
    return md, ml1, pre_cast


def summarize(vals_max, vals_mean):
    return {
        "max_dev_mean": statistics.fmean(vals_max),
        "max_dev_sd": statistics.pstdev(vals_max),
        "l1_dist_mean": statistics.fmean(vals_mean),
        "l1_dist_sd": statistics.pstdev(vals_mean),
    }


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--trials", type=int, default=100)
    ap.add_argument("--seed0", type=int, default=0)
    ap.add_argument("--out", type=str, default="results.json")
    ap.add_argument("--arms", type=str, default="",
                    help="comma-separated arm names to run; empty = all")
    args = ap.parse_args()

    print(f"torch {torch.__version__} | device {DEVICE} | {torch.cuda.get_device_name(0) if DEVICE=='cuda' else 'cpu'}", flush=True)

    arms = {
        "trained_bf16loss_orthoinit": lambda s: run_trained(s, init="ortho", loss_fp32=False),
        "trained_fp32loss_orthoinit": lambda s: run_trained(s, init="ortho", loss_fp32=True),
        "trained_bf16loss_linear_default": lambda s: run_trained(s, init="linear_default", loss_fp32=False),
        "param_trained100": lambda s: run_param(s, train=True),
        "param_notrained": lambda s: run_param(s, train=False),
        "ortho_init": lambda s: run_ortho_init(s),
        "trained_fp32loss_normalized": lambda s: run_trained(s, init="ortho", loss_fp32=True, normalized=True),
        "trained_fp32loss_nosched": lambda s: run_trained_const(s),
    }

    if args.arms:
        keep = [a.strip() for a in args.arms.split(",") if a.strip()]
        arms = {k: v for k, v in arms.items() if k in keep}
    results = {name: {"max_dev": [], "l1_dist": []} for name in arms}
    t0 = time.time()
    for i in range(args.trials):
        seed = args.seed0 + i
        for name, fn in arms.items():
            out = fn(seed)
            results[name]["max_dev"].append(out[0])
            results[name]["l1_dist"].append(out[1])
        if (i + 1) % 10 == 0:
            print(f"trial {i+1}/{args.trials} elapsed {time.time()-t0:.1f}s", flush=True)

    summary = {name: summarize(r["max_dev"], r["l1_dist"]) for name, r in results.items()}
    payload = {
        "config": {"D": D, "E": E, "steps": STEPS, "trials": args.trials, "lr0": LR0, "lr1": LR1,
                   "torch": torch.__version__, "device": str(DEVICE)},
        "paper": PAPER,
        "summary": summary,
        "per_trial": {name: {"max_dev": r["max_dev"], "l1_dist": r["l1_dist"]} for name, r in results.items()},
    }
    with open(args.out, "w") as f:
        json.dump(payload, f, indent=2)

    print("\n=== Table 2 reproduction (mean +- SD over %d trials) ===" % args.trials, flush=True)
    hdr = f"{'arm':<34}{'Max Dev':>24}{'L1 Dist':>24}"
    print(hdr)
    def fmt(m, s):
        return f"{m:.3e} +- {s:.2e}"
    print(f"{'PAPER Trained':<34}{fmt(*PAPER['trained']['max']):>24}{fmt(*PAPER['trained']['mean']):>24}")
    print(f"{'PAPER Param':<34}{fmt(*PAPER['param']['max']):>24}{fmt(*PAPER['param']['mean']):>24}")
    print(f"{'PAPER OrthoInit':<34}{fmt(*PAPER['ortho_init']['max']):>24}{fmt(*PAPER['ortho_init']['mean']):>24}")
    print("-" * len(hdr))
    for name in arms:
        s = summary[name]
        print(f"{name:<34}{fmt(s['max_dev_mean'], s['max_dev_sd']):>24}{fmt(s['l1_dist_mean'], s['l1_dist_sd']):>24}")
    print(f"\ntotal elapsed {time.time()-t0:.1f}s; wrote {args.out}", flush=True)


if __name__ == "__main__":
    DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
    EYE32 = torch.eye(E, device=DEVICE, dtype=torch.float32)
    main()