Matching Every Model to the Same Budget
The H-Net paper compares models that spend the same compute on the same bytes. Its Appendix B lists the formulas, and each model's main network depth is then chosen to hit the baseline's budget. Implement both. Every count below is a forward pass.
attention_flops(L, D, F, h) is one Transformer layer over L positions, with a=h⋅⌊D/h⌋ (heads times head dimension). Sum these terms and return an int:
- QKV projections: 2⋅3⋅L⋅D⋅a
- Attention logits: 2L2a, softmax: 3hL2, scores at the query: 2L2a
- Output projection: 2LaD
- Gated MLP projections: 2L⋅3DF, and gating: 5LD
mamba_flops(L, D, expand=2, d_state=128, head_dim=64, window=4) is one Mamba-2 layer, with n=⌊expand⋅D/head_dim⌋ heads. Sum and return an int:
- XZ projections: 2LD(2⋅expand⋅D)
- BC and step-size projections: 2LD(2dstate+n)
- SSD: 2⋅3⋅L(expand⋅D)dstate
- Depthwise convolution: 2LD⋅window, gating: 5LD, output projection: 2LD2
gflops_per_byte(stages, vocab, n_bytes, train=False)
stages is a list of dicts with keys L, D, F, h, m, t, outermost first: positions, width, MLP size, heads, Mamba-2 layers and Transformer layers at that stage. F and h are only read when t > 0.
- Add each stage's layers, plus the embedding and the prediction head, each costing 2LVD with L and D taken from
stages[0] and V = vocab.
- Divide by
n_bytes and by 1e9, and return a float. With train=True, multiply by 3 (the backward pass is taken as twice the forward pass).
match_main_layers(target, stages, vocab, n_bytes)
- Return the largest integer number of Transformer layers in
stages[-1] whose forward gflops_per_byte does not exceed target. Ignore the t given in stages[-1], and do not modify the input. Raise ValueError if even zero layers exceed target.
Hints
- Keep everything in Python integers until the final division, so large sequence lengths do not lose precision.
- The cost is linear in the number of main layers.