AbstractPhil commited on
Commit
b1087f8
·
verified ·
1 Parent(s): ab05909

mirror 0.7.3: hub scan restructure (attention.py; AlephLLM@60ee496)

Browse files
Files changed (1) hide show
  1. attention.py +84 -43
attention.py CHANGED
@@ -136,36 +136,80 @@ class CausalSplatHUB(nn.Module):
136
  self._mask_cache[key] = m
137
  return m
138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  # ------------------------------------------------ constellation access
140
- def _books_cat(self, x, which: str):
141
- """All books' oriented codes in one batched pass: stack the frame
142
- weights (H, D, d) and codebooks (H, K, D) — a few-MB copy — then a
143
- single projection einsum, one address einsum, and the per-book 2K
144
- softmax batched over the H axis. Returns (B, n, H*2K)."""
145
- # AUTOCAST TRAP (measured, Blackwell 2026-08-26): torch.einsum is in
146
- # autocast's PROMOTE category — one fp32 operand (F.normalize output,
147
- # raw fp32 params) drags every einsum here AND the whole downstream
148
- # scan to fp32 (half the TC rate, double the traffic; the 4-6%-util
149
- # smoking gun). Cast the operands to the autocast dtype explicitly.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  dt = (torch.get_autocast_dtype("cuda")
151
  if torch.is_autocast_enabled() and x.is_cuda else x.dtype)
152
- W = torch.stack([(c.q if which == "q" else c.k).weight
153
- for c in self.consts]).to(dt) # (H, D, d)
154
- A = torch.stack([F.normalize(c.addr.codebook, dim=-1)
155
- for c in self.consts]).to(dt) # (H, K, D)
156
- tau = self.consts[0].addr.tau
157
- xh = torch.einsum("bnd,hkd->bnhk", x.to(dt), W) # (B, n, H, D)
158
- u = torch.einsum("bnhd,hkd->bnhk",
159
- F.normalize(xh, dim=-1).to(dt), A) / tau
160
- m = u.abs().amax(dim=-1, keepdim=True)
161
- e = torch.exp(torch.cat([u - m, -u - m], dim=-1)) # (B, n, H, 2K)
162
- e = e / e.sum(dim=-1, keepdim=True) # per-book softmax
 
 
 
 
 
 
 
163
  B, n = x.shape[:2]
164
- # torch.exp is ALSO on autocast's fp32 list (bf16 in -> fp32 out), so
165
- # the softmax tail runs fp32 regardless — standard attention practice
166
- # (fp32 softmax, low-precision output). Cast the CODE to dt so the
167
- # whole downstream scan + backward runs bf16.
168
- return e.reshape(B, n, -1).to(dt)
 
 
 
 
 
 
 
169
 
170
  def _units(self):
171
  """Uniform view: [(addr, q, k)] whether single- or multi-book."""
@@ -188,9 +232,10 @@ class CausalSplatHUB(nn.Module):
188
  qc = qc.view(B, nc, C, K2)
189
  kc = kc.view(B, nc, C, K2)
190
  S = torch.einsum("bick,bicd->bikd", kc, v) # per-chunk 2KxD sums
191
- P = torch.cumsum(S, dim=1) - S # exclusive prefix
 
192
  zS = kc.sum(dim=2) # (B, nc, 2K)
193
- zP = torch.cumsum(zS, dim=1) - zS
194
  att = torch.einsum("bick,bijk->bicj", qc, kc) * mask # (B,nc,C,C)
195
  num = torch.einsum("bick,bikd->bicd", qc, P) + att @ v
196
  den = torch.einsum("bick,bik->bic", qc, zP).unsqueeze(-1) \
@@ -215,21 +260,17 @@ class CausalSplatHUB(nn.Module):
215
  nc = (n + pad) // C
216
  vc = vp.view(B, nc, C, d)
217
  mask = self._mask(C, x.device, v.dtype)
218
- if self.n_const == 1:
219
- qc = self.addr.oriented_cat(self.q(x)) # (B, n, 2K)
220
- kc = self.addr.oriented_cat(self.k(x))
221
- else:
222
- # BATCHED multi-book path (2026-08-26 Blackwell verdict: the
223
- # per-book Python loop was 512 sequential little scans per
224
- # forward — launch-bound). Budget composition is algebraically
225
- # ONE scan over the concatenated code: num and den are sums of
226
- # per-book bilinear forms, so scanning cat_h(qc_h) against
227
- # cat_h(kc_h) equals summing 16 separate scans (fp reorder).
228
- qc = self._books_cat(x, "q") # (B, n, H*2K)
229
- kc = self._books_cat(x, "k")
230
- if qc.dtype != v.dtype: # the einsum-promote trap, single-book
231
- qc = qc.to(v.dtype) # path included (oriented_cat's exp
232
- kc = kc.to(v.dtype) # chain runs fp32 under autocast)
233
  if pad:
234
  qc = F.pad(qc, (0, 0, 0, pad))
235
  kc = F.pad(kc, (0, 0, 0, pad))
 
136
  self._mask_cache[key] = m
137
  return m
138
 
139
+ def _prefix(self, nc: int, device, dtype):
140
+ """Strictly-lower-triangular ones (nc, nc): the exclusive prefix sum
141
+ as ONE tensor-core GEMM. The cumsum scan kernel ran ~6x off its
142
+ memory roofline on the (B, nc, 2K·H, d) layout (C2d, Blackwell
143
+ 2026-08-26) and its backward is flip+cumsum+flip; matmul accumulates
144
+ fp32 inside the GEMM — strictly MORE precise than a bf16 cumsum."""
145
+ key = ("prefix", nc, device, dtype)
146
+ m = self._mask_cache.get(key)
147
+ if m is None:
148
+ m = torch.tril(torch.ones(nc, nc, device=device, dtype=dtype),
149
+ diagonal=-1)
150
+ self._mask_cache[key] = m
151
+ return m
152
+
153
  # ------------------------------------------------ constellation access
154
+ def _code_cat_qk(self, x):
155
+ """BOTH oriented codes (q and k, every book) in one batched pass.
156
+
157
+ Stack all 2H frame weights, one projection einsum, one address
158
+ einsum, ONE fused softmax. The oriented address IS softmax over the
159
+ 2K half-axes — exp(cat[u−m, −u−m])/Σ with m = max|u| is bit-the-same
160
+ quantity as F.softmax(cat[u, −u]) (softmax subtracts its own max,
161
+ which is exactly m). This is a KERNEL substitution, not a mechanism
162
+ change: no softmax over positions, no softmax across books —
163
+ composition stays budget. The old chain was ~8 unfused GB-scale
164
+ elementwise passes per call, twice per forward (C2d: 24.6 ms).
165
+
166
+ AUTOCAST TRAP (measured, Blackwell 2026-08-26): torch.einsum is in
167
+ autocast's PROMOTE category, and F.normalize / exp / softmax are on
168
+ its fp32 list — one fp32 operand drags the whole downstream scan to
169
+ fp32. Operands are cast to the autocast dtype explicitly; the
170
+ softmax accumulates fp32 inside the kernel (standard attention
171
+ practice) and the returned CODE is in the compute dtype so the
172
+ num/S/P scan and its backward run bf16. DELIBERATE exception: den's
173
+ reductions (kc.sum, att.sum) stay fp32 by autocast policy — the
174
+ agreement mass keeps v1's fp32 dtype_floor semantics at ~5% of
175
+ scan traffic (dtype audit 2026-08-26).
176
+
177
+ Returns (qc, kc), each (B, n, H*2K), per-book layout [K pos | K neg]
178
+ matching oriented()/forward_naive."""
179
+ units = self._units()
180
  dt = (torch.get_autocast_dtype("cuda")
181
  if torch.is_autocast_enabled() and x.is_cuda else x.dtype)
182
+ W = torch.stack([q.weight for _, q, _ in units]
183
+ + [k.weight for _, _, k in units]).to(dt) # (2H, D, d)
184
+ tau = units[0][0].tau
185
+ # tau folds into the codebook (a few-MB fp32 tensor op, MORE precise
186
+ # than dividing bf16 u afterwards), and the query-side row
187
+ # normalization folds into ONE post-GEMM scale: a per-row scalar
188
+ # commutes through the linear map, so (xh/||xh||) @ A^T / tau ==
189
+ # (xh @ (A/tau)^T) * (1/||xh||) exactly (fp reorder). Kills the
190
+ # fp32 normalize-div + cast + separate tau-div passes (perf audit
191
+ # 2026-08-26). Same 1e-12 floor as F.normalize.
192
+ A = (F.normalize(torch.stack([a.codebook for a, _, _ in units]),
193
+ dim=-1) / tau).to(dt) # (H, K, D)
194
+ A = torch.cat([A, A]) # (2H, K, D)
195
+ xh = torch.einsum("bnd,hkd->bnhk", x.to(dt), W) # (B,n,2H,D)
196
+ inv = torch.linalg.vector_norm( # fp32 by autocast
197
+ xh, dim=-1, keepdim=True).clamp_min(1e-12) \
198
+ .reciprocal().to(dt) # policy; cast back
199
+ u = torch.einsum("bnhd,hkd->bnhk", xh, A) * inv # (B,n,2H,K)
200
  B, n = x.shape[:2]
201
+ H = len(units)
202
+ # Split-axis-first WITHOUT a copy: the permute is a view, and the
203
+ # cat (which must write a fresh tensor anyway) absorbs it — so the
204
+ # q/k split below is a pure view instead of two GB-scale reshape
205
+ # copies. Layout per book stays [K pos | K neg], book-major.
206
+ u = u.view(B, n, 2, H, -1).permute(2, 0, 1, 3, 4)
207
+ # softmax: the explicit dtype arg opts out of autocast's fp32
208
+ # override (fp32_set_opt_dtype policy) while the CUDA kernel still
209
+ # accumulates fp32 internally — bf16-in/bf16-out, no fp32 e pass,
210
+ # and the softmax BACKWARD chain halves too.
211
+ e = F.softmax(torch.cat([u, -u], dim=-1), dim=-1, dtype=dt)
212
+ return e[0].reshape(B, n, -1), e[1].reshape(B, n, -1)
213
 
214
  def _units(self):
215
  """Uniform view: [(addr, q, k)] whether single- or multi-book."""
 
232
  qc = qc.view(B, nc, C, K2)
233
  kc = kc.view(B, nc, C, K2)
234
  S = torch.einsum("bick,bicd->bikd", kc, v) # per-chunk 2KxD sums
235
+ L = self._prefix(nc, qc.device, qc.dtype)
236
+ P = torch.matmul(L, S.reshape(B, nc, -1)).view_as(S) # excl. prefix
237
  zS = kc.sum(dim=2) # (B, nc, 2K)
238
+ zP = torch.matmul(L, zS)
239
  att = torch.einsum("bick,bijk->bicj", qc, kc) * mask # (B,nc,C,C)
240
  num = torch.einsum("bick,bikd->bicd", qc, P) + att @ v
241
  den = torch.einsum("bick,bik->bic", qc, zP).unsqueeze(-1) \
 
260
  nc = (n + pad) // C
261
  vc = vp.view(B, nc, C, d)
262
  mask = self._mask(C, x.device, v.dtype)
263
+ # BATCHED path, both n_const cases (2026-08-26 Blackwell verdicts:
264
+ # the per-book Python loop was 512 sequential little scans —
265
+ # launch-bound; then the split q/k exp chains were ~8 unfused
266
+ # GB-scale passes each). Budget composition is algebraically ONE
267
+ # scan over the concatenated code: num and den are sums of per-book
268
+ # bilinear forms, so scanning cat_h(qc_h) against cat_h(kc_h)
269
+ # equals summing H separate scans (fp reorder).
270
+ qc, kc = self._code_cat_qk(x) # (B, n, H*2K)
271
+ if qc.dtype != v.dtype: # einsum-promote guard (belt-and-braces;
272
+ qc = qc.to(v.dtype) # _code_cat_qk already returns the
273
+ kc = kc.to(v.dtype) # compute dtype)
 
 
 
 
274
  if pad:
275
  qc = F.pad(qc, (0, 0, 0, pad))
276
  kc = F.pad(kc, (0, 0, 0, pad))