kharki commited on
Commit
37ec00d
·
verified ·
1 Parent(s): 6f3cb01

stacked grouped MoE (batched counter update)

Browse files
Files changed (1) hide show
  1. src/memory_native/moe_ffn.py +106 -38
src/memory_native/moe_ffn.py CHANGED
@@ -35,7 +35,7 @@ import torch
35
  import torch.nn as nn
36
  import torch.nn.functional as F
37
 
38
- from .counter import RMSCounterLinear
39
  from .packed import PackedRMSCounterLinear
40
 
41
  __all__ = ["CounterMoEFFN"]
@@ -48,47 +48,106 @@ def _gelu_grad(x: torch.Tensor) -> torch.Tensor:
48
  return cdf + x * pdf
49
 
50
 
51
- class _GroupedExperts(torch.autograd.Function):
52
- """Run ALL experts' two counter MLPs as grouped GEMMs (one launch each via torch._grouped_mm)
53
- instead of a python loop over E experts, then self-update each expert's counter state from its
54
- grouped weight-gradient. Tokens arrive already SORTED by expert; `offs` are the cumulative
55
- per-expert row ends. Routing, the convex-combination weighting, and the scatter stay in ordinary
56
- autograd OUTSIDE this Function (so the router gets its gradient for free); the Function owns only
57
- x->grad_x and the counter update -- the counter-specific part autograd can't express. `tap`
58
- forces backward to run even when x needs no gradient (so the experts always self-update)."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
  @staticmethod
61
- def forward(ctx, x_sorted, offs, tap, moe):
62
- E, d, h = moe.E, moe.d, moe.h
63
- W1 = torch.empty(E, h, d, device=x_sorted.device, dtype=torch.float32) # scale1*T1 [out,in]
64
- W2 = torch.empty(E, d, h, device=x_sorted.device, dtype=torch.float32)
65
- for e, ex in enumerate(moe.experts):
66
- t1, _ = ex.fc1._decode_rows(0, h); W1[e] = ex.fc1.scale * t1.float()
67
- t2, _ = ex.fc2._decode_rows(0, d); W2[e] = ex.fc2.scale * t2.float()
68
  xs = x_sorted.float()
69
  y1 = torch._grouped_mm(xs, W1.transpose(1, 2).contiguous(), offs=offs) # [M,h]
70
  a = F.gelu(y1)
71
  y2 = torch._grouped_mm(a, W2.transpose(1, 2).contiguous(), offs=offs) # [M,d]
72
- ctx.moe = moe; ctx.offs = offs
73
  ctx.save_for_backward(xs, y1, a, W1, W2)
74
  return y2.to(x_sorted.dtype)
75
 
76
  @staticmethod
77
  def backward(ctx, grad_y2):
78
  xs, y1, a, W1, W2 = ctx.saved_tensors
79
- offs = ctx.offs; moe = ctx.moe
80
  gy2 = grad_y2.float()
81
- grad_a = torch._grouped_mm(gy2, W2.contiguous(), offs=offs) # [M,h]
82
  grad_y1 = grad_a * _gelu_grad(y1)
83
- grad_x = torch._grouped_mm(grad_y1, W1.contiguous(), offs=offs) # [M,d]
84
- # per-expert counter update from the grouped weight-gradients (the cheap ~9% part).
 
 
85
  bounds = [0] + offs.tolist()
86
- for e, ex in enumerate(moe.experts):
 
87
  s, t = bounds[e], bounds[e + 1]
88
  if t <= s:
89
  continue
90
- ex.fc1.apply_update_from_grad_w(grad_y1[s:t].t() @ xs[s:t]) # [h,d]
91
- ex.fc2.apply_update_from_grad_w(gy2[s:t].t() @ a[s:t]) # [d,h]
 
 
92
  return grad_x.to(grad_y2.dtype), None, None, None
93
 
94
 
@@ -143,21 +202,27 @@ class CounterMoEFFN(nn.Module):
143
  # h = 4d / top_k -> top_k experts cost ~ the dense FFN's 2*d*4d active MACs/token.
144
  self.h = int(expert_hidden) if expert_hidden is not None else max(1, (4 * self.d) // self.k)
145
  self.aux_loss_weight = float(aux_loss_weight)
146
- # grouped=True replaces the python per-expert loop with grouped GEMMs (torch._grouped_mm):
147
- # all experts' fc1/fc2 run in one launch each, the per-expert update reads its grouped
148
- # weight-gradient. Same math as the loop (fp32, up to reduction order). Needs torch._grouped_mm.
 
149
  self.grouped = bool(grouped) and hasattr(torch, "_grouped_mm")
150
 
151
  # The ONLY fp Parameter: the router (a tiny d->E linear). AdamW owns it.
152
  self.router = nn.Linear(self.d, self.E, bias=False)
153
  nn.init.normal_(self.router.weight, std=0.02)
154
 
155
- # packed_experts=True (default): experts are PackedRMSCounterLinear -> fused Triton update
156
- # on CUDA + 0.75 B/weight. Identical dynamics on CPU.
157
- self.experts = nn.ModuleList(
158
- _CounterExpert(self.d, self.h, C=C, lr=lr, lr_scale=lr_scale, packed=packed_experts)
159
- for _ in range(self.E)
160
- )
 
 
 
 
 
161
 
162
  # Diagnostics (not optimizer state): O(E) scalars.
163
  self.register_buffer("token_count", torch.zeros(self.E, dtype=torch.float64),
@@ -228,7 +293,7 @@ class CounterMoEFFN(nn.Module):
228
  x_sorted = h[sorted_tok] # [M, d] (autograd-tracked)
229
  tap = (torch.zeros((), device=h.device, dtype=h.dtype, requires_grad=True)
230
  if torch.is_grad_enabled() else h.new_zeros(())) # forces experts to update
231
- y2 = _GroupedExperts.apply(x_sorted, offs, tap, self) # [M, d] unweighted outputs
232
  weighted = y2 * sorted_w.unsqueeze(-1) # router grad flows here
233
  y = torch.zeros_like(h).index_add(0, sorted_tok, weighted)
234
  return y.reshape(sh)
@@ -240,10 +305,13 @@ class CounterMoEFFN(nn.Module):
240
 
241
  def persistent_bytes(self) -> int:
242
  """Counter experts (the bulk: ~0.75 B/weight visible + per-row scale/v) + fp router."""
243
- b = 0
244
- for expert in self.experts:
245
- for m in (expert.fc1, expert.fc2):
246
- b += m.state.numel() + m.scale.numel() * 4 + m.v.numel() * 4
 
 
 
247
  b += self.router.weight.numel() * 4 # fp router
248
  return b
249
 
 
35
  import torch.nn as nn
36
  import torch.nn.functional as F
37
 
38
+ from .counter import RMSCounterLinear, decode_state, encode_state, stochastic_round
39
  from .packed import PackedRMSCounterLinear
40
 
41
  __all__ = ["CounterMoEFFN"]
 
48
  return cdf + x * pdf
49
 
50
 
51
+ @torch.no_grad()
52
+ def _batched_rms_update(state, scale, v, grad_w, active, *, C, lr, lr_scale, beta, eps):
53
+ """RMS + stochastic-rounding counter update over a STACK of experts at once: state/grad_w are
54
+ [E,out,in], scale/v are [E,out,1]. Identical math to RMSCounterLinear._update_tile (exact/eager,
55
+ pulse=direct), just vectorized over the E axis -- so all experts update in ONE set of ops, no
56
+ per-expert decode/SR/encode loop. `active` [E] masks experts that got no tokens this step (they
57
+ keep their state/scale/v unchanged, matching the loop path which never calls them). Bit-identical
58
+ to looping the same update per expert with the same SR draw order (verified)."""
59
+ t, c = decode_state(state, C); t = t.float(); c = c.float()
60
+ g_sq = grad_w.pow(2).mean(dim=-1, keepdim=True)
61
+ v_new = beta * v + (1.0 - beta) * g_sq
62
+ denom = v_new.sqrt().clamp_min(eps)
63
+ grad_eff = grad_w / denom
64
+ grad_s = (grad_w * t).sum(dim=-1, keepdim=True) / math.sqrt(grad_w.shape[-1])
65
+ s_new = (scale - lr_scale * grad_s).clamp(1e-5, 10.0)
66
+ cc = stochastic_round(c * (scale / s_new) + (-lr * grad_eff) * (C / s_new))
67
+ carry = torch.trunc(cc / C)
68
+ rem = cc - carry * C
69
+ nt = (t + carry).clamp(-1, 1)
70
+ rem = torch.where((t + carry) != nt, torch.sign(cc) * (C - 1), rem).clamp(-(C - 1), C - 1)
71
+ new_state = encode_state(nt, rem, C)
72
+ m = active.view(-1, *([1] * (state.dim() - 1))) # [E,1,1] broadcast mask
73
+ state.copy_(torch.where(m, new_state, state))
74
+ scale.copy_(torch.where(m, s_new, scale))
75
+ v.copy_(torch.where(m, v_new, v))
76
+
77
+
78
+ class StackedCounterExperts(nn.Module):
79
+ """All E experts' two counter MLPs in STACKED buffers ([E,out,in]) instead of a ModuleList, so
80
+ the weight decode (forward) and the RMS+SR update (backward) are each ONE vectorized op over the
81
+ whole expert axis -- no python per-expert loop. Combined with the grouped GEMMs, the only
82
+ remaining per-expert step is forming each segment's weight-gradient. Same counter math as
83
+ RMSCounterLinear (exact/eager); state is 1 byte/weight here (unpacked codes, the stack is small)."""
84
+
85
+ def __init__(self, E, d, h, *, C, lr, lr_scale, init_gain=1.0, rms_beta=0.9, rms_eps=1e-3):
86
+ super().__init__()
87
+ self.E, self.d, self.h, self.C = E, d, h, C
88
+ self.lr, self.lr_scale = lr, lr_scale
89
+ self.beta, self.eps = rms_beta, rms_eps
90
+ for name, out, in_ in (("1", h, d), ("2", d, h)):
91
+ t0 = torch.randint(-1, 2, (E, out, in_), dtype=torch.int16)
92
+ self.register_buffer(f"s{name}", encode_state(t0, torch.zeros_like(t0), C))
93
+ s0 = init_gain * math.sqrt(3.0 / (2.0 * in_))
94
+ self.register_buffer(f"sc{name}", torch.full((E, out, 1), s0, dtype=torch.float32))
95
+ self.register_buffer(f"v{name}", torch.zeros((E, out, 1), dtype=torch.float32))
96
+
97
+ def weights(self):
98
+ """Decode both stacked states to usable ternary*scale weights, in ONE decode each."""
99
+ W1 = self.sc1 * decode_state(self.s1, self.C)[0].float() # [E,h,d]
100
+ W2 = self.sc2 * decode_state(self.s2, self.C)[0].float() # [E,d,h]
101
+ return W1, W2
102
+
103
+ @torch.no_grad()
104
+ def update(self, grad_w1, grad_w2, active):
105
+ kw = dict(C=self.C, lr=self.lr, lr_scale=self.lr_scale, beta=self.beta, eps=self.eps)
106
+ _batched_rms_update(self.s1, self.sc1, self.v1, grad_w1, active, **kw)
107
+ _batched_rms_update(self.s2, self.sc2, self.v2, grad_w2, active, **kw)
108
+
109
+ def persistent_bytes(self):
110
+ return (self.s1.numel() + self.s2.numel()
111
+ + (self.sc1.numel() + self.sc2.numel() + self.v1.numel() + self.v2.numel()) * 4)
112
+
113
+
114
+ class _StackedGroupedFn(torch.autograd.Function):
115
+ """Grouped forward + grad_x via torch._grouped_mm over the stacked experts, then ONE batched
116
+ counter update. The only per-expert step left is the segment weight-gradient matmul (cheap GEMM);
117
+ the heavy decode/SR/encode is vectorized over E. tap forces backward so experts always update."""
118
 
119
  @staticmethod
120
+ def forward(ctx, x_sorted, offs, tap, stk):
121
+ W1, W2 = stk.weights() # [E,h,d], [E,d,h]
 
 
 
 
 
122
  xs = x_sorted.float()
123
  y1 = torch._grouped_mm(xs, W1.transpose(1, 2).contiguous(), offs=offs) # [M,h]
124
  a = F.gelu(y1)
125
  y2 = torch._grouped_mm(a, W2.transpose(1, 2).contiguous(), offs=offs) # [M,d]
126
+ ctx.stk = stk; ctx.offs = offs
127
  ctx.save_for_backward(xs, y1, a, W1, W2)
128
  return y2.to(x_sorted.dtype)
129
 
130
  @staticmethod
131
  def backward(ctx, grad_y2):
132
  xs, y1, a, W1, W2 = ctx.saved_tensors
133
+ offs = ctx.offs; stk = ctx.stk; E = stk.E
134
  gy2 = grad_y2.float()
135
+ grad_a = torch._grouped_mm(gy2, W2.contiguous(), offs=offs) # [M,h]
136
  grad_y1 = grad_a * _gelu_grad(y1)
137
+ grad_x = torch._grouped_mm(grad_y1, W1.contiguous(), offs=offs) # [M,d]
138
+ # per-segment weight gradients, stacked (the only remaining per-expert step; cheap GEMMs).
139
+ gw1 = xs.new_zeros(E, stk.h, stk.d)
140
+ gw2 = xs.new_zeros(E, stk.d, stk.h)
141
  bounds = [0] + offs.tolist()
142
+ active = torch.zeros(E, dtype=torch.bool, device=xs.device)
143
+ for e in range(E):
144
  s, t = bounds[e], bounds[e + 1]
145
  if t <= s:
146
  continue
147
+ active[e] = True
148
+ gw1[e] = grad_y1[s:t].t() @ xs[s:t] # [h,d]
149
+ gw2[e] = gy2[s:t].t() @ a[s:t] # [d,h]
150
+ stk.update(gw1, gw2, active) # ONE batched update
151
  return grad_x.to(grad_y2.dtype), None, None, None
152
 
153
 
 
202
  # h = 4d / top_k -> top_k experts cost ~ the dense FFN's 2*d*4d active MACs/token.
203
  self.h = int(expert_hidden) if expert_hidden is not None else max(1, (4 * self.d) // self.k)
204
  self.aux_loss_weight = float(aux_loss_weight)
205
+ # grouped=True replaces the python per-expert loop with grouped GEMMs (torch._grouped_mm) +
206
+ # stacked experts: all experts' fc1/fc2 run in one launch each AND the counter update is one
207
+ # vectorized op over the expert axis (StackedCounterExperts). Same math as the loop (fp32, up
208
+ # to reduction order + batched-vs-per-expert SR ordering). Needs torch._grouped_mm.
209
  self.grouped = bool(grouped) and hasattr(torch, "_grouped_mm")
210
 
211
  # The ONLY fp Parameter: the router (a tiny d->E linear). AdamW owns it.
212
  self.router = nn.Linear(self.d, self.E, bias=False)
213
  nn.init.normal_(self.router.weight, std=0.02)
214
 
215
+ # grouped -> stacked storage (one shared buffer, vectorized decode+update); else a ModuleList
216
+ # of per-expert counter MLPs. packed_experts=True: PackedRMSCounterLinear (fused update + 0.75
217
+ # B/weight) on the loop path. Identical dynamics on CPU.
218
+ if self.grouped:
219
+ self.stacked = StackedCounterExperts(self.E, self.d, self.h, C=C, lr=lr, lr_scale=lr_scale)
220
+ self.experts = nn.ModuleList()
221
+ else:
222
+ self.experts = nn.ModuleList(
223
+ _CounterExpert(self.d, self.h, C=C, lr=lr, lr_scale=lr_scale, packed=packed_experts)
224
+ for _ in range(self.E)
225
+ )
226
 
227
  # Diagnostics (not optimizer state): O(E) scalars.
228
  self.register_buffer("token_count", torch.zeros(self.E, dtype=torch.float64),
 
293
  x_sorted = h[sorted_tok] # [M, d] (autograd-tracked)
294
  tap = (torch.zeros((), device=h.device, dtype=h.dtype, requires_grad=True)
295
  if torch.is_grad_enabled() else h.new_zeros(())) # forces experts to update
296
+ y2 = _StackedGroupedFn.apply(x_sorted, offs, tap, self.stacked) # [M, d] unweighted outputs
297
  weighted = y2 * sorted_w.unsqueeze(-1) # router grad flows here
298
  y = torch.zeros_like(h).index_add(0, sorted_tok, weighted)
299
  return y.reshape(sh)
 
305
 
306
  def persistent_bytes(self) -> int:
307
  """Counter experts (the bulk: ~0.75 B/weight visible + per-row scale/v) + fp router."""
308
+ if self.grouped:
309
+ b = self.stacked.persistent_bytes()
310
+ else:
311
+ b = 0
312
+ for expert in self.experts:
313
+ for m in (expert.fc1, expert.fc2):
314
+ b += m.state.numel() + m.scale.numel() * 4 + m.v.numel() * 4
315
  b += self.router.weight.numel() * 4 # fp router
316
  return b
317