Skip to content

Add Multi-Tensor LAMB Optimizer challenge (medium #165) - #394

Open
claude[bot] wants to merge 1 commit into
mainfrom
add-challenge-165-multi-tensor-lamb
Open

claude[bot] wants to merge 1 commit into
mainfrom
add-challenge-165-multi-tensor-lamb

Conversation

@claude

@claude claude Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

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 offsets marks where each of the T tensors starts. Every element computes an Adam step u (with bias correction, plus weight_decay * theta). Each tensor is then scaled by its own trust ratio r_k = ||theta_k|| / ||u_k||, falling back to 1 when either norm is zero, and updated with theta -= lr * r_k * u. params, m and v are updated in place.

What the solver learns

  • Segmented (per-tensor) reductions over ragged, heavily skewed segments. The perf case is the real BERT-base parameter list: 199 tensors ranging from a 23.4M-element embedding down to 768-element LayerNorm vectors.
  • Load balancing through a chunked work list (the multi_tensor_apply pattern). Work is split into fixed-size chunks, a chunk never spans two tensors, and block partials are combined per tensor.
  • A global dependency inside a fused update. No parameter can be written until its tensor's norms are complete, so the solver must structure the step as two passes or use a grid-wide sync, without materializing intermediates.

Novelty vs. closest existing challenges

Naive vs. optimized

  • Naive but correct: loop over tensors on the host. For each tensor, launch elementwise kernels for m/v/u (with u materialized), 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-reading u, 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.
  • Optimized: build a chunk table once (e.g. 8K-element chunks tagged with their tensor id) so every block does equal work, whatever the tensor sizes. Pass 1 reads θ, g, m, v, writes m and v, and computes u in registers. It block-reduces θ² and u², then does one atomic per chunk per tensor. Pass 2 reads θ, m, v, recomputes u, and writes θ. That's 2 launches total, ~40 B/element, and u never 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.

  • Size skew. The single embedding tensor is 21% of all elements. Per-tensor blocking serializes it.
  • Many tensors. 185 of the 199 tensors have ≤ 3,072 elements, so per-tensor launches spend most of their time on launch latency.
  • Extra DRAM passes. A materialized u plus 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.

Mistake Caught by
One global norm instead of per-tensor norms [1,2,1] tensors with norms differing by 10⁴; mixed-scale cases; 11 of 13 tests overall
Off-by-one segment bounds (boundary element in the wrong tensor) adjacent tiny tensors; [1023, 1, 1025, 2049] (sizes straddle chunk sizes, with a size-1 tensor between two tails); T = 100 random sizes
Missing zero-norm fallback (NaN from 0/0, or r = 0) zero-initialized bias tensor (‖θ‖ = 0) and a tensor with zero grad + zero state + wd = 0 (‖u‖ = 0)
Weight decay dropped from u, or applied AdamW-style outside the trust ratio weight_decay = 0.5 on large-norm params (r ≫ 1)
Bias correction skipped / betas hardcoded t = 2 with beta1 = 0.8, beta2 = 0.95 on warm state
Overwriting block partials instead of accumulating, or dropping the last chunk [3, 70000, 5, 1] (one large tensor split across many blocks)
Writing θ before the norms are complete every test (norms must use the pre-update θ)

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 about lr·|θ|·δ. 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.py on T4: --action run passed, and --action submit passed 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-files passes, and scripts/validate_challenges.py reports 0 errors.
  • Went through the CLAUDE.md checklist: the HTML has an SVG (dark theme, #222) and the performance bullet; the reference uses only standard PyTorch ops (no CUDA-specific APIs) and allocates everything with device=self.device; each starter has exactly one parameter comment.

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 shxjames left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 on m, 0.00397 on v. Every test dict includes params, m and v.
  • 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); m share 4.6e-5; v share 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 uses max|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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant