diff --git a/challenges/medium/165_multi_tensor_lamb/challenge.html b/challenges/medium/165_multi_tensor_lamb/challenge.html
new file mode 100644
index 00000000..155b5a42
--- /dev/null
+++ b/challenges/medium/165_multi_tensor_lamb/challenge.html
@@ -0,0 +1,122 @@
+
+ Implement one step of the LAMB optimizer (Layer-wise Adaptive Moments,
+ used to pretrain BERT with batch sizes of 32K and more) over a whole model's parameters
+ at once. All T parameter tensors are packed back to back in one flat
+ float32 buffer params of length N; tensor
+ k occupies the elements offsets[k] ≤ i <
+ offsets[k+1]. grad, m and v use the
+ same layout. LAMB takes an Adam step but rescales it separately for each tensor by a
+ trust ratio, the norm of that tensor's parameters divided by the norm of its
+ update. Update params, m and v in place.
+
+
+
+
+
+ For step t (1-indexed), every element computes
+
+
+ \[
+ \begin{align}
+ m &\leftarrow \beta_1 m + (1 - \beta_1) g \\
+ v &\leftarrow \beta_2 v + (1 - \beta_2) g^2 \\
+ u &= \frac{m / (1 - \beta_1^{t})}{\sqrt{v / (1 - \beta_2^{t})} + \epsilon} + \lambda \theta
+ \end{align}
+ \]
+
+
+ where θ is the parameter value before this step, g
+ is grad, and β1, β2,
+ ε, λ are beta1, beta2,
+ eps, weight_decay. Then, for each tensor k, using the
+ L2 norms over that tensor's elements only:
+
+ with η = lr. Note that the weight decay term is part of
+ u, so it is scaled by the trust ratio too, and that rk is
+ not clipped.
+
+
+
Implementation Requirements
+
+
Do not change the function signature.
+
Do not use external libraries beyond what is available in the starter.
+
params, m and v are updated in place; there is
+ no separate output buffer.
+
Both norms of tensor k use the values before this step's parameter update:
+ θ is the old parameter value and u is computed from the
+ updated m and v. No element of params may be
+ overwritten before the norms that depend on it are complete.
+
When either norm of a tensor is exactly zero (for example a zero-initialized bias, or a
+ tensor whose gradient, optimizer state and weight decay term are all zero), its trust ratio
+ is 1.
Performance is measured with N = 109,482,240, T = 199,
+ t = 1,000 (the full BERT-base parameter list, from the 23,440,896-element word
+ embedding down to 768-element LayerNorm vectors)
+
diff --git a/challenges/medium/165_multi_tensor_lamb/challenge.py b/challenges/medium/165_multi_tensor_lamb/challenge.py
new file mode 100644
index 00000000..65bc1d7b
--- /dev/null
+++ b/challenges/medium/165_multi_tensor_lamb/challenge.py
@@ -0,0 +1,306 @@
+import ctypes
+from typing import Any, Dict, List
+
+import torch
+from core.challenge_base import ChallengeBase
+
+
+class Challenge(ChallengeBase):
+ name = "Multi-Tensor LAMB Optimizer"
+ # The new parameters are theta - lr * r * u with r = ||theta|| / ||u||, so a relative error
+ # delta in a per-tensor norm moves theta by only ~lr * |theta| * delta. Correct float32
+ # solutions (any reduction order: tree, block partials + atomics, two-pass) agree with a
+ # float64 recomputation to < 1% of the atol + rtol * |ref| budget on the performance case.
+ # The plausible mistakes each fail several targeted tests: one global norm instead of
+ # per-tensor norms, attributing a boundary element to the neighbouring tensor, dropping
+ # weight decay from u, applying weight decay AdamW-style (outside the trust ratio), and
+ # skipping bias correction.
+ atol = 1e-05
+ rtol = 1e-05
+ num_gpus = 1
+ access_tier = "free"
+
+ def reference_impl(
+ self,
+ params: torch.Tensor,
+ grad: torch.Tensor,
+ m: torch.Tensor,
+ v: torch.Tensor,
+ offsets: torch.Tensor,
+ N: int,
+ T: int,
+ lr: float,
+ beta1: float,
+ beta2: float,
+ eps: float,
+ weight_decay: float,
+ t: int,
+ ):
+ assert params.shape == (N,)
+ assert grad.shape == (N,)
+ assert m.shape == (N,)
+ assert v.shape == (N,)
+ assert offsets.shape == (T + 1,)
+ assert params.dtype == grad.dtype == m.dtype == v.dtype == torch.float32
+ assert offsets.dtype == torch.int32
+ assert t >= 1
+
+ # Adam moment updates and bias correction (elementwise, all tensors at once).
+ m.copy_(beta1 * m + (1.0 - beta1) * grad)
+ v.copy_(beta2 * v + (1.0 - beta2) * grad * grad)
+ m_hat = m / (1.0 - beta1**t)
+ v_hat = v / (1.0 - beta2**t)
+ # LAMB update direction: Adam step plus weight decay on the pre-update parameters.
+ u = m_hat / (v_hat.sqrt() + eps) + weight_decay * params
+
+ # Per-tensor trust ratio. torch.linalg.vector_norm uses a tree reduction, which stays
+ # accurate in float32 even for tensors with tens of millions of elements.
+ bounds = offsets.tolist()
+ assert bounds[0] == 0 and bounds[-1] == N
+ new_params = torch.empty_like(params)
+ for k in range(T):
+ s, e = bounds[k], bounds[k + 1]
+ assert e > s, "every tensor must have at least one element"
+ w_norm = torch.linalg.vector_norm(params[s:e])
+ u_norm = torch.linalg.vector_norm(u[s:e])
+ ratio = torch.where(
+ (w_norm > 0) & (u_norm > 0), w_norm / u_norm, torch.ones_like(w_norm)
+ )
+ new_params[s:e] = params[s:e] - lr * ratio * u[s:e]
+ params.copy_(new_params)
+
+ def get_solve_signature(self) -> Dict[str, tuple]:
+ return {
+ "params": (ctypes.POINTER(ctypes.c_float), "inout"),
+ "grad": (ctypes.POINTER(ctypes.c_float), "in"),
+ "m": (ctypes.POINTER(ctypes.c_float), "inout"),
+ "v": (ctypes.POINTER(ctypes.c_float), "inout"),
+ "offsets": (ctypes.POINTER(ctypes.c_int), "in"),
+ "N": (ctypes.c_int, "in"),
+ "T": (ctypes.c_int, "in"),
+ "lr": (ctypes.c_float, "in"),
+ "beta1": (ctypes.c_float, "in"),
+ "beta2": (ctypes.c_float, "in"),
+ "eps": (ctypes.c_float, "in"),
+ "weight_decay": (ctypes.c_float, "in"),
+ "t": (ctypes.c_int, "in"),
+ }
+
+ def _build(
+ self,
+ sizes: List[int],
+ param_scales=None,
+ lr=0.05,
+ beta1=0.9,
+ beta2=0.999,
+ eps=1e-6,
+ weight_decay=0.01,
+ t=1,
+ warm_state=False,
+ grad_scale=1.0,
+ param_offsets=None,
+ seed=0,
+ ) -> Dict[str, Any]:
+ dev, f32 = self.device, torch.float32
+ torch.manual_seed(seed)
+ T = len(sizes)
+ N = sum(sizes)
+ if param_scales is None:
+ param_scales = [1.0] * T
+ if param_offsets is None:
+ param_offsets = [0.0] * T
+ # Per-tensor parameter scale and offset, so different tensors have very different
+ # norms (as embeddings, projection weights, LayerNorm gains and biases do).
+ params = torch.cat(
+ [
+ torch.randn(n, device=dev, dtype=f32) * sc + off
+ for n, sc, off in zip(sizes, param_scales, param_offsets)
+ ]
+ )
+ grad = torch.empty(N, device=dev, dtype=f32).uniform_(-grad_scale, grad_scale)
+ if warm_state:
+ # An optimizer that has already taken steps: m carries gradient-like signs and v is
+ # a positive magnitude bounded away from zero (as when v tracks g^2), which keeps
+ # m_hat / sqrt(v_hat) well conditioned.
+ m = torch.empty(N, device=dev, dtype=f32).uniform_(-0.5, 0.5) * grad_scale
+ v = torch.empty(N, device=dev, dtype=f32).uniform_(0.01, 0.5) * grad_scale**2
+ else:
+ m = torch.zeros(N, device=dev, dtype=f32)
+ v = torch.zeros(N, device=dev, dtype=f32)
+ offs = [0]
+ for s in sizes:
+ offs.append(offs[-1] + s)
+ return {
+ "params": params,
+ "grad": grad,
+ "m": m,
+ "v": v,
+ "offsets": torch.tensor(offs, device=dev, dtype=torch.int32),
+ "N": N,
+ "T": T,
+ "lr": lr,
+ "beta1": beta1,
+ "beta2": beta2,
+ "eps": eps,
+ "weight_decay": weight_decay,
+ "t": t,
+ }
+
+ def generate_example_test(self) -> Dict[str, Any]:
+ dev, f32 = self.device, torch.float32
+ return {
+ "params": torch.tensor([3.0, 4.0, 0.0], device=dev, dtype=f32),
+ "grad": torch.tensor([0.5, -0.5, 2.0], device=dev, dtype=f32),
+ "m": torch.zeros(3, device=dev, dtype=f32),
+ "v": torch.zeros(3, device=dev, dtype=f32),
+ "offsets": torch.tensor([0, 2, 3], device=dev, dtype=torch.int32),
+ "N": 3,
+ "T": 2,
+ "lr": 0.1,
+ "beta1": 0.9,
+ "beta2": 0.999,
+ "eps": 1e-6,
+ "weight_decay": 0.0,
+ "t": 1,
+ }
+
+ def generate_functional_test(self) -> List[Dict[str, Any]]:
+ tests = []
+
+ # Hand-computed example (see challenge.html): tensor 0 has ||theta|| = 5, u = [1, -1]
+ # (up to eps), so r = 5 / sqrt(2) and theta -> [2.646447, 4.353553]; tensor 1 is a zero
+ # bias, so ||theta|| = 0 and r must fall back to 1 (theta -> -0.1, not NaN or 0).
+ tests.append(self.generate_example_test())
+
+ # Minimal: one tensor with one element. r = |theta| / |u|, so theta moves by exactly
+ # lr * |theta| (relative step lr) regardless of the gradient magnitude.
+ tests.append(self._build([1], param_scales=[2.0], seed=1))
+
+ # Three tiny adjacent tensors with norms differing by 10^4: catches computing a single
+ # global ||theta|| / ||u|| instead of per-tensor norms, and off-by-one segment bounds
+ # (a boundary element counted in the wrong tensor swings that tensor's norm by orders
+ # of magnitude).
+ tests.append(self._build([1, 2, 1], param_scales=[100.0, 0.01, 3.0], t=3, seed=2))
+
+ # Zero-norm fallbacks. Tensor 1 is a zero-initialized bias (||theta|| = 0, r must be 1).
+ # Tensor 2 has zero gradient and zero optimizer state with weight_decay = 0, so u = 0
+ # and ||u|| = 0: r must be 1 and theta must stay unchanged (catches 0/0 = NaN and
+ # r = 0 * inf). Tensor 0 is a normal tensor so the case is not degenerate overall.
+ zero = self._build([4, 3, 4], weight_decay=0.0, seed=3)
+ zero["params"][4:7] = 0.0
+ zero["grad"][7:11] = 0.0
+ tests.append(zero)
+
+ # All-zero gradients with warm state: no new signal, momentum still drives the step.
+ warm_zero = self._build([16, 16], param_scales=[1.0, 0.1], warm_state=True, t=20, seed=4)
+ warm_zero["grad"].zero_()
+ tests.append(warm_zero)
+
+ # Large weight decay on large-norm parameters (r >> 1): catches omitting
+ # weight_decay * theta from u (r and the step direction change) and applying weight
+ # decay AdamW-style as theta *= (1 - lr * wd) outside the trust ratio.
+ tests.append(
+ self._build(
+ [32, 64], param_scales=[10.0, 0.5], weight_decay=0.5, warm_state=True, seed=5
+ )
+ )
+
+ # All-negative parameters and gradients.
+ neg = self._build([100], param_scales=[0.5], param_offsets=[-2.0], seed=6)
+ neg["grad"].copy_(-neg["grad"].abs() - 0.1)
+ tests.append(neg)
+
+ # Small t with non-default betas on warm state: bias corrections 1 - beta^t are far
+ # from 1, so skipping them (or hardcoding beta1 = 0.9 / beta2 = 0.999) changes u.
+ tests.append(
+ self._build(
+ [30, 100, 255],
+ param_scales=[1.0, 0.02, 5.0],
+ beta1=0.8,
+ beta2=0.95,
+ t=2,
+ warm_state=True,
+ seed=7,
+ )
+ )
+
+ # Power-of-2 sizes with a larger eps (eps matters in the denominator).
+ tests.append(self._build([256, 1024, 512], param_scales=[0.02, 1.0, 0.1], eps=1e-2, seed=8))
+
+ # Sizes straddling common block / chunk sizes (1023, 1, 1025, 2049): a chunked solution
+ # whose chunk spans a tensor boundary must split its partial sums between tensors, and
+ # a size-1 tensor sits between two tails.
+ tests.append(
+ self._build(
+ [1023, 1, 1025, 2049],
+ param_scales=[1.0, 7.0, 0.05, 2.0],
+ warm_state=True,
+ t=100,
+ seed=9,
+ )
+ )
+
+ # Many small tensors (T = 100, sizes 1..40) with varied scales: catches per-tensor
+ # indexing errors and fixed-size per-tensor bookkeeping.
+ gen = torch.Generator().manual_seed(10)
+ sizes = torch.randint(1, 41, (100,), generator=gen).tolist()
+ scales = (10.0 ** torch.empty(100).uniform_(-2, 1, generator=gen)).tolist()
+ tests.append(self._build(sizes, param_scales=scales, warm_state=True, t=7, seed=11))
+
+ # Skewed sizes: one large tensor beside tiny ones. Splitting the large tensor's
+ # reduction across many blocks is required for speed; overwriting instead of
+ # accumulating block partials, or dropping the last partial chunk, fails here.
+ tests.append(
+ self._build(
+ [3, 70000, 5, 1],
+ param_scales=[0.5, 0.02, 3.0, 1.0],
+ warm_state=True,
+ t=1000,
+ seed=12,
+ )
+ )
+
+ # Realistic: one encoder layer of a hidden-128 transformer (Q, K, V, O, LayerNorm,
+ # FFN weights and biases) with LayerNorm gains around 1 and small biases.
+ tests.append(self._build_model(hidden=128, layers=1, vocab=0, max_pos=0, seed=13))
+
+ return tests
+
+ def _model_tensors(self, hidden, layers, vocab, max_pos):
+ """(size, scale, offset) for each parameter tensor of a BERT-style encoder."""
+ h, ff = hidden, 4 * hidden
+ weight = lambda n: (n, 0.02, 0.0) # noqa: E731
+ bias = lambda n: (n, 0.02, 0.0) # noqa: E731
+ ln = [(h, 0.05, 1.0), (h, 0.02, 0.0)]
+ tensors = []
+ if vocab > 0:
+ tensors += [weight(vocab * h), weight(max_pos * h), weight(2 * h)] + ln
+ for _ in range(layers):
+ for _ in range(4): # query, key, value, attention output
+ tensors += [weight(h * h), bias(h)]
+ tensors += ln
+ tensors += [weight(h * ff), bias(ff), weight(ff * h), bias(h)]
+ tensors += ln
+ if vocab > 0:
+ tensors += [weight(h * h), bias(h)] # pooler
+ return tensors
+
+ def _build_model(self, hidden, layers, vocab, max_pos, seed, lr=0.002, t=1000):
+ tensors = self._model_tensors(hidden, layers, vocab, max_pos)
+ return self._build(
+ [s for s, _, _ in tensors],
+ param_scales=[sc for _, sc, _ in tensors],
+ param_offsets=[o for _, _, o in tensors],
+ lr=lr,
+ weight_decay=0.01,
+ t=t,
+ warm_state=True,
+ grad_scale=1e-2,
+ seed=seed,
+ )
+
+ def generate_performance_test(self) -> Dict[str, Any]:
+ # One LAMB step over the full parameter list of BERT-base (the model LAMB was designed
+ # to pretrain at large batch): 199 tensors, 109,482,240 parameters. Sizes are extremely
+ # skewed, from the 23.4M-element word embedding down to 768-element LayerNorm vectors.
+ return self._build_model(hidden=768, layers=12, vocab=30522, max_pos=512, seed=165)
diff --git a/challenges/medium/165_multi_tensor_lamb/starter/starter.cu b/challenges/medium/165_multi_tensor_lamb/starter/starter.cu
new file mode 100644
index 00000000..bf6f4f4d
--- /dev/null
+++ b/challenges/medium/165_multi_tensor_lamb/starter/starter.cu
@@ -0,0 +1,6 @@
+#include
+
+// params, grad, m, v, offsets are device pointers
+extern "C" void solve(float* params, const float* grad, float* m, float* v, const int* offsets,
+ int N, int T, float lr, float beta1, float beta2, float eps,
+ float weight_decay, int t) {}
diff --git a/challenges/medium/165_multi_tensor_lamb/starter/starter.cute.py b/challenges/medium/165_multi_tensor_lamb/starter/starter.cute.py
new file mode 100644
index 00000000..534a5587
--- /dev/null
+++ b/challenges/medium/165_multi_tensor_lamb/starter/starter.cute.py
@@ -0,0 +1,22 @@
+import cutlass
+import cutlass.cute as cute
+
+
+# params, grad, m, v, offsets are tensors on the GPU
+@cute.jit
+def solve(
+ params: cute.Tensor,
+ grad: cute.Tensor,
+ m: cute.Tensor,
+ v: cute.Tensor,
+ offsets: cute.Tensor,
+ N: cute.Int32,
+ T: cute.Int32,
+ lr: cute.Float32,
+ beta1: cute.Float32,
+ beta2: cute.Float32,
+ eps: cute.Float32,
+ weight_decay: cute.Float32,
+ t: cute.Int32,
+):
+ pass
diff --git a/challenges/medium/165_multi_tensor_lamb/starter/starter.jax.py b/challenges/medium/165_multi_tensor_lamb/starter/starter.jax.py
new file mode 100644
index 00000000..25126977
--- /dev/null
+++ b/challenges/medium/165_multi_tensor_lamb/starter/starter.jax.py
@@ -0,0 +1,23 @@
+import jax
+import jax.numpy as jnp
+
+
+# params, grad, m, v, offsets are tensors on device
+@jax.jit
+def solve(
+ params: jax.Array,
+ grad: jax.Array,
+ m: jax.Array,
+ v: jax.Array,
+ offsets: jax.Array,
+ N: int,
+ T: int,
+ lr: float,
+ beta1: float,
+ beta2: float,
+ eps: float,
+ weight_decay: float,
+ t: int,
+) -> tuple[jax.Array, jax.Array, jax.Array]:
+ # return output tensor directly
+ pass
diff --git a/challenges/medium/165_multi_tensor_lamb/starter/starter.mojo b/challenges/medium/165_multi_tensor_lamb/starter/starter.mojo
new file mode 100644
index 00000000..d09d0e06
--- /dev/null
+++ b/challenges/medium/165_multi_tensor_lamb/starter/starter.mojo
@@ -0,0 +1,24 @@
+from max.gpu.host import DeviceContext
+from max.gpu import block_dim, block_idx, thread_idx
+from std.memory import UnsafePointer
+from std.math import ceildiv
+
+
+# params, grad, m, v, offsets are device pointers
+@export
+def solve(
+ params: UnsafePointer[Float32, MutAnyOrigin],
+ grad: UnsafePointer[Float32, MutAnyOrigin],
+ m: UnsafePointer[Float32, MutAnyOrigin],
+ v: UnsafePointer[Float32, MutAnyOrigin],
+ offsets: UnsafePointer[Int32, MutAnyOrigin],
+ N: Int32,
+ T: Int32,
+ lr: Float32,
+ beta1: Float32,
+ beta2: Float32,
+ eps: Float32,
+ weight_decay: Float32,
+ t: Int32,
+) raises:
+ pass
diff --git a/challenges/medium/165_multi_tensor_lamb/starter/starter.pytorch.py b/challenges/medium/165_multi_tensor_lamb/starter/starter.pytorch.py
new file mode 100644
index 00000000..93d49f1a
--- /dev/null
+++ b/challenges/medium/165_multi_tensor_lamb/starter/starter.pytorch.py
@@ -0,0 +1,20 @@
+import torch
+
+
+# params, grad, m, v, offsets are tensors on the GPU
+def solve(
+ params: torch.Tensor,
+ grad: torch.Tensor,
+ m: torch.Tensor,
+ v: torch.Tensor,
+ offsets: torch.Tensor,
+ N: int,
+ T: int,
+ lr: float,
+ beta1: float,
+ beta2: float,
+ eps: float,
+ weight_decay: float,
+ t: int,
+):
+ pass
diff --git a/challenges/medium/165_multi_tensor_lamb/starter/starter.triton.py b/challenges/medium/165_multi_tensor_lamb/starter/starter.triton.py
new file mode 100644
index 00000000..f0cf111f
--- /dev/null
+++ b/challenges/medium/165_multi_tensor_lamb/starter/starter.triton.py
@@ -0,0 +1,22 @@
+import torch
+import triton
+import triton.language as tl
+
+
+# params, grad, m, v, offsets are tensors on the GPU
+def solve(
+ params: torch.Tensor,
+ grad: torch.Tensor,
+ m: torch.Tensor,
+ v: torch.Tensor,
+ offsets: torch.Tensor,
+ N: int,
+ T: int,
+ lr: float,
+ beta1: float,
+ beta2: float,
+ eps: float,
+ weight_decay: float,
+ t: int,
+):
+ pass