Repository navigation
Add Multi-Tensor LAMB Optimizer challenge (medium #165) - #394
claude[bot] wants to merge 1 commit into
Conversation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
✅ Review bot: low risk, safe to merge. Lint and structure checks passed; no sensitive paths or grader edits; 306 lines changed.
- The ID prefix 165 is unused, and no existing challenge covers a segmented per-tensor trust-ratio reduction fused with an update. #127 Fused AdamW is purely elementwise and #151 Muon works on a single matrix.
- challenge.py has the 5 required methods, no init, and name/atol/rtol/num_gpus/access_tier set. The extra underscore-prefixed helpers only build test data.
- The imports are only ctypes, typing, torch and the challenge base. There is no network, file, subprocess or import-time code.
- reference_impl asserts shapes and dtypes, uses standard PyTorch ops, and has no device checks. It updates params, m and v in place as the signature says.
- Every tensor allocation in generate_* uses device=self.device. The only CPU tensors are a host-side Generator and torch.empty(100) used for sizes and scales, converted to lists, which is a minor deviation.
- The functional tests are thorough and several of them are tied to specific mistakes. They cover a single-element tensor, zero-norm fallbacks, boundary-straddling sizes, skewed sizes, many tiny tensors, bias correction, weight decay, and a realistic mini-encoder.
- The 1e-5 tolerances are sensible for float32, since a norm error is scaled by lr * |theta|.
- The performance test uses the BERT-base layout with N=109M and T=199. The four float32 buffers are about 1.75 GB, under the 3.2 GB limit.
- The starters are empty stubs with only the parameter comment, and the Mojo starter uses max.gpu imports and MutAnyOrigin. The HTML signature, constraints and worked example match challenge.py.
- The PR body is cut off mid-sentence, but the diff itself looks complete and contains no reviewer-directed text.
shxjames
left a comment
There was a problem hiding this comment.
Spec matches the code: Adam moments with bias correction, u = m_hat / (sqrt(v_hat) + eps) + weight_decay * theta (decay is inside u, so it is scaled by the trust ratio; this is not AdamW), and a per-tensor trust ratio r_k = ||theta_k|| / ||u_k|| that falls back to 1 when either L2 norm is zero. Norms use the pre-update theta and the u from the updated m/v. Layout is offsets[k] <= i < offsets[k+1], with params, m and v updated in place. r_k is not clipped.
Example 1 matches a closed-form calculation: params -> [2.646446609, 4.353553391, -0.099999950], m -> [0.05, -0.05, 0.2], v -> [0.00025, 0.00025, 0.004]. The HTML rounding [2.646447, 4.353553, -0.100000] is correct (max rounding error 3.9e-7). The reference matches the closed form to 1e-7. The zero-bias tensor correctly uses r = 1 (not NaN). The dedicated zero-norm case (f3) is also exact: the zero-initialized tensor moves with r = 1, and the u = 0 tensor is left unchanged and finite.
Correctness (independent fp64 LAMB in /workspace/kr, norms via sqrt(sum sq) rather than vector_norm):
- Example + all 13 functional cases: worst prod-grader share (
atol + rtol * max|ref|per output tensor, atol=rtol=1e-5) is 0.00696 on params (f5, large weight decay, ~144x headroom), 0.00387 onm, 0.00397 onv. Every test dict includesparams,mandv. - Perf BERT-base list (N=109,482,240, T=199, t=1000, seed 165): params max abs 1.19e-7, max|y| 1.216, share 0.00538 (~186x);
mshare 4.6e-5;vshare 3.6e-7. Word-embedding size 23,440,896 matches. 124 of 199 tensors have <= 3072 elements (the PR body says 185; the HTML is fine).
Bugs / low-prec (prod grader, all three outputs). Every intended mutant is caught on at least one functional case: global norm 11 (not the two single-tensor cases, correctly), off-by-one bounds 11, missing zero-norm fallback 2 (f0, f3), r = 0 fallback 2, dropped decay 9 (all wd > 0 cases except those too small to exceed the budget), AdamW-style decay outside r 11, missing bias correction 10 (including the t=2 / non-default-beta case), eps inside the sqrt 2 (the targeted eps=1e-2 case plus f12), not writing m/v 13, updating theta before the norms 12.
TF32 / FP16 / BF16 are rejected on params for f1-f12 and on perf (shares 44 / 24 / 177). They also fail m and v on the warm-state functional cases (f4, f5, f7, f9-f11). They slip past m/v on the perf case (TF32/FP16 m shares 0.42 / 0.21; v all pass) and on a few cold-start functional cases, but those paths are still rejected overall. No need to tighten the tolerance.
Perf / T4. Four buffers are 1.63 GiB; the reference's u + new_params add 0.82 GiB; peak is well under 16 GB. Two-pass traffic is 4.38 GB, T4 bandwidth floor ~15 ms. Memory-bound, with a 21% embedding tensor and many tiny LayerNorm/bias tensors. Medium is the right difficulty.
Starters. All 6 match the signature (params, m, v in/out; JAX returns (params, m, v)). Coverage includes N=1, adjacent tiny tensors with norms 10^4 apart, both zero-norm fallbacks, warm state with zero grad, large decay, all-negative values, non-default betas, power-of-two and non-power-of-two sizes, chunk-straddling sizes with a size-1 hole, T=100 random sizes, a 70k skewed tensor, and a hidden-128 encoder layer.
Nits, not blockers:
- PR description says 185 of 199 tensors have <= 3072 elements; the generated list has 124 (75 are the large embeddings / projections). The HTML does not make that claim.
- The comment describes the tolerance as
atol + rtol * |ref|; the prod grader usesmax|ref|per output tensor. Headroom is unchanged. - The JAX starter comment says "return output tensor directly" but the function returns a 3-tuple.
CI on 3ccebef0db64afc6958bad415ff8fec5bcd27e8f is green (review, checks, Lint Python Files, Check Mojo Files, Lint C++/CUDA Files, check-index). Merge is blocked only on a code-owner approval. LGTM, no blockers.
Summary
Adds medium #165: Multi-Tensor LAMB Optimizer. It is one step of LAMB (Layer-wise Adaptive Moments, the optimizer used for large-batch BERT pretraining) over a whole model's parameter list. The model's parameters are packed into one flat buffer, and
offsetsmarks where each of theTtensors starts. Every element computes an Adam stepu(with bias correction, plusweight_decay * theta). Each tensor is then scaled by its own trust ratior_k = ||theta_k|| / ||u_k||, falling back to 1 when either norm is zero, and updated withtheta -= lr * r_k * u.params,mandvare updated in place.What the solver learns
multi_tensor_applypattern). Work is split into fixed-size chunks, a chunk never spans two tensors, and block partials are combined per tensor.Novelty vs. closest existing challenges
Naive vs. optimized
umaterialized), two norm reductions, and an update. That's roughly 5 launches × 199 tensors ≈ 1,000 launches, and most of them process a few hundred elements. The ~185 tiny LayerNorm/bias tensors are pure launch overhead. Each element also takes several extra trips through DRAM (writing and re-readingu, re-reading θ for the norm). Another naive option is one block per tensor, which leaves the 23.4M-element embedding on a single SM while the other 39 sit idle.uin registers. It block-reduces θ² and u², then does one atomic per chunk per tensor. Pass 2 reads θ, m, v, recomputesu, and writes θ. That's 2 launches total, ~40 B/element, andunever touches memory. The result is the same: only the floating-point reduction order changes.How the benchmark exposes it
The perf test is the exact BERT-base list: N = 109,482,240 and T = 199 (1.63 GiB of θ/g/m/v, which fits 5× in 16 GB). The kernel is memory-bound: ~4.4 GB of minimum traffic is ~15 ms on a T4.
uplus separate norm passes adds ~2× DRAM traffic over the two-pass fused version.Targeted tests and the mistakes they catch
I checked these offline: an independent float64 implementation that injects each mistake fails the tests marked below.
[1,2,1]tensors with norms differing by 10⁴; mixed-scale cases; 11 of 13 tests overall[1023, 1, 1025, 2049](sizes straddle chunk sizes, with a size-1 tensor between two tails); T = 100 random sizesu, or applied AdamW-style outside the trust ratioweight_decay = 0.5on large-norm params (r ≫ 1)[3, 70000, 5, 1](one large tensor split across many blocks)Coverage also includes N = 1, power-of-2 sizes (256/1024/512, with a larger eps), non-power-of-2 sizes (30/100/255), all-negative values, zero gradients with warm momentum, and a realistic hidden-128 encoder layer (16 tensors). For the example (two tensors), I hand-computed the expected values independently:
[2.646447, 4.353553, -0.1]. They match the reference.Tolerance (atol = rtol = 1e-5): θ moves by
lr * r * u, so a relative error δ in a norm shifts θ by only aboutlr·|θ|·δ. On the perf case, a float32 two-pass solution's worst error is 0.5% of the atol + rtol·|ref| budget against float64. Each mistake above misses by orders of magnitude more.Validation
scripts/run_challenge.pyon T4:--action runpassed, and--action submitpassed all tests twice (the second run was after a data-generation change), using a two-pass chunked CUDA solution. The solution file is not committed.pre-commit run --all-filespasses, andscripts/validate_challenges.pyreports 0 errors.#222) and the performance bullet; the reference uses only standard PyTorch ops (no CUDA-specific APIs) and allocates everything withdevice=self.device; each starter has exactly one parameter comment.🤖 Generated with Claude Code