theapemachine commited on
Commit
514b330
Β·
verified Β·
1 Parent(s): 2f36ac4

Upload triton_v2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. triton_v2.py +419 -0
triton_v2.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Triton-fused Chunked Sparse Backward Pass β€” v2.
4
+
5
+ Fixes from review:
6
+ 1. Bias folded into dW kernel (kills the uncoalesced column-striding bias kernel)
7
+ 2. block_ptr / TMA for dW and dX loads (hardware-accelerated 2D tile fetch)
8
+ 3. No autotune (fixed config to eliminate compilation overhead + divergence risk)
9
+
10
+ Benchmarks v1 (manual ptrs + separate bias) vs v2 (block_ptr + fused bias)
11
+ vs Python-loop baseline vs Dense.
12
+ """
13
+
14
+ import math, os, time
15
+ import torch, torch.nn as nn, torch.nn.functional as F
16
+ import triton, triton.language as tl
17
+
18
+ # ═══════════════════════════════════════════════════════════════════
19
+ # V2 KERNELS β€” block_ptr + fused bias
20
+ # ═══════════════════════════════════════════════════════════════════
21
+
22
+ # Fixed tile sizes β€” no autotune. CS=64 means one N-block covers the whole chunk.
23
+ # BM=64: token tile for the M-reduction loop
24
+ # BK=64: tile along d_in
25
+ # BN=64: tile along chunk (== CS for chunk_size=64, so 1 block per chunk)
26
+
27
+ @triton.jit
28
+ def _v2_sparse_bwd_dW_kernel(
29
+ X_ptr, dY_ptr, dW_ptr, dB_ptr, chunk_ids_ptr,
30
+ M, d_in, d_out, num_active,
31
+ stride_xm, stride_xk,
32
+ stride_dym, stride_dyn,
33
+ stride_dwn, stride_dwk,
34
+ HAS_BIAS: tl.constexpr,
35
+ CS: tl.constexpr,
36
+ BK: tl.constexpr,
37
+ BM: tl.constexpr,
38
+ ):
39
+ """
40
+ Each program computes one [CS, BK] tile of dW for one active chunk,
41
+ plus the [CS] bias slice if HAS_BIAS.
42
+
43
+ Grid: (num_active, ceil(d_in / BK))
44
+ Since CS fits in one tile (CS==64, BN==CS), pid0 == chunk index directly.
45
+ """
46
+ chunk_linear_id = tl.program_id(0)
47
+ k_block_id = tl.program_id(1)
48
+
49
+ if chunk_linear_id >= num_active:
50
+ return
51
+
52
+ chunk_idx = tl.load(chunk_ids_ptr + chunk_linear_id)
53
+ chunk_start = chunk_idx * CS
54
+
55
+ k_offset = k_block_id * BK
56
+
57
+ # Block pointer for dY transposed: we want dY.T[chunk_cols, :] = shape (CS, M)
58
+ # dY is (M, d_out) row-major. Transposed view: shape=(d_out, M), strides=(stride_dyn, stride_dym)
59
+ dy_block_ptr = tl.make_block_ptr(
60
+ base=dY_ptr,
61
+ shape=(d_out, M),
62
+ strides=(stride_dyn, stride_dym),
63
+ offsets=(chunk_start, 0),
64
+ block_shape=(CS, BM),
65
+ order=(1, 0),
66
+ )
67
+
68
+ # Block pointer for X: shape (M, d_in), reading (BM, BK) tiles
69
+ x_block_ptr = tl.make_block_ptr(
70
+ base=X_ptr,
71
+ shape=(M, d_in),
72
+ strides=(stride_xm, stride_xk),
73
+ offsets=(0, k_offset),
74
+ block_shape=(BM, BK),
75
+ order=(1, 0),
76
+ )
77
+
78
+ # Accumulators
79
+ acc_dw = tl.zeros((CS, BK), dtype=tl.float32)
80
+ # Bias accumulator: only on the first k-block to avoid redundant work
81
+ compute_bias = HAS_BIAS and (k_block_id == 0)
82
+ acc_db = tl.zeros((CS,), dtype=tl.float32)
83
+
84
+ # Reduction over M
85
+ for m_start in range(0, M, BM):
86
+ dy_t = tl.load(dy_block_ptr, boundary_check=(0, 1)) # (CS, BM)
87
+ x = tl.load(x_block_ptr, boundary_check=(0, 1)) # (BM, BK)
88
+
89
+ # dW += dY.T @ X -> (CS, BM) @ (BM, BK) = (CS, BK)
90
+ acc_dw = tl.dot(dy_t, x, acc=acc_dw)
91
+
92
+ # Bias: sum over M dimension of dY chunk columns
93
+ # dy_t is (CS, BM) = transposed chunk. Sum along dim=1 = sum over tokens.
94
+ if compute_bias:
95
+ acc_db += tl.sum(dy_t, axis=1)
96
+
97
+ dy_block_ptr = tl.advance(dy_block_ptr, (0, BM))
98
+ x_block_ptr = tl.advance(x_block_ptr, (BM, 0))
99
+
100
+ # Store dW tile: dW[chunk_start:chunk_start+CS, k_offset:k_offset+BK]
101
+ dw_block_ptr = tl.make_block_ptr(
102
+ base=dW_ptr,
103
+ shape=(d_out, d_in),
104
+ strides=(stride_dwn, stride_dwk),
105
+ offsets=(chunk_start, k_offset),
106
+ block_shape=(CS, BK),
107
+ order=(1, 0),
108
+ )
109
+ tl.store(dw_block_ptr, acc_dw.to(dW_ptr.dtype.element_ty), boundary_check=(0, 1))
110
+
111
+ # Store bias (only from k_block_id == 0)
112
+ if compute_bias:
113
+ rn = chunk_start + tl.arange(0, CS)
114
+ n_mask = rn < d_out
115
+ tl.store(dB_ptr + rn, acc_db.to(dB_ptr.dtype.element_ty), mask=n_mask)
116
+
117
+
118
+ def v2_sparse_bwd_dW(X, dY, active_chunks, chunk_size, d_out, bias=True):
119
+ """Fused dW + dBias via block_ptr kernel."""
120
+ M, d_in = X.shape
121
+ num_active = active_chunks.shape[0]
122
+ CS = chunk_size
123
+
124
+ dW = torch.zeros(d_out, d_in, device=X.device, dtype=X.dtype)
125
+ dB = torch.zeros(d_out, device=X.device, dtype=X.dtype) if bias else None
126
+
127
+ if num_active == 0:
128
+ return dW, dB
129
+
130
+ chunk_ids = active_chunks.to(torch.int32).contiguous()
131
+
132
+ BK = 64
133
+ BM = 64
134
+
135
+ grid = (num_active, triton.cdiv(d_in, BK))
136
+
137
+ _v2_sparse_bwd_dW_kernel[grid](
138
+ X, dY, dW, dB if bias else X, # dummy ptr if no bias
139
+ chunk_ids,
140
+ M, d_in, d_out, num_active,
141
+ X.stride(0), X.stride(1),
142
+ dY.stride(0), dY.stride(1),
143
+ dW.stride(0), dW.stride(1),
144
+ HAS_BIAS=bias,
145
+ CS=CS, BK=BK, BM=BM,
146
+ )
147
+ return dW, dB
148
+
149
+
150
+ # ── V2 dX kernel with block_ptr ──
151
+
152
+ @triton.jit
153
+ def _v2_sparse_bwd_dX_kernel(
154
+ dY_ptr, W_ptr, dX_ptr, chunk_ids_ptr,
155
+ M, d_in, d_out, num_active,
156
+ stride_dym, stride_dyn,
157
+ stride_wn, stride_wk,
158
+ stride_dxm, stride_dxk,
159
+ CS: tl.constexpr,
160
+ BM: tl.constexpr,
161
+ BK: tl.constexpr,
162
+ ):
163
+ """
164
+ Each program computes one [BM, BK] tile of dX by accumulating over active chunks.
165
+ Grid: (ceil(M/BM), ceil(d_in/BK))
166
+ """
167
+ pid_m = tl.program_id(0)
168
+ pid_k = tl.program_id(1)
169
+
170
+ m_offset = pid_m * BM
171
+ k_offset = pid_k * BK
172
+
173
+ acc = tl.zeros((BM, BK), dtype=tl.float32)
174
+
175
+ for i in range(num_active):
176
+ chunk_idx = tl.load(chunk_ids_ptr + i)
177
+ chunk_start = chunk_idx * CS
178
+
179
+ # dY tile: (BM, CS) at [m_offset, chunk_start]
180
+ dy_block_ptr = tl.make_block_ptr(
181
+ base=dY_ptr,
182
+ shape=(M, d_out),
183
+ strides=(stride_dym, stride_dyn),
184
+ offsets=(m_offset, chunk_start),
185
+ block_shape=(BM, CS),
186
+ order=(1, 0),
187
+ )
188
+
189
+ # W tile: (CS, BK) at [chunk_start, k_offset]
190
+ w_block_ptr = tl.make_block_ptr(
191
+ base=W_ptr,
192
+ shape=(d_out, d_in),
193
+ strides=(stride_wn, stride_wk),
194
+ offsets=(chunk_start, k_offset),
195
+ block_shape=(CS, BK),
196
+ order=(1, 0),
197
+ )
198
+
199
+ dy = tl.load(dy_block_ptr, boundary_check=(0, 1)) # (BM, CS)
200
+ w = tl.load(w_block_ptr, boundary_check=(0, 1)) # (CS, BK)
201
+
202
+ # dY @ W -> (BM, BK)
203
+ acc = tl.dot(dy, w, acc=acc)
204
+
205
+ # Store dX tile
206
+ dx_block_ptr = tl.make_block_ptr(
207
+ base=dX_ptr,
208
+ shape=(M, d_in),
209
+ strides=(stride_dxm, stride_dxk),
210
+ offsets=(m_offset, k_offset),
211
+ block_shape=(BM, BK),
212
+ order=(1, 0),
213
+ )
214
+ tl.store(dx_block_ptr, acc.to(dX_ptr.dtype.element_ty), boundary_check=(0, 1))
215
+
216
+
217
+ def v2_sparse_bwd_dX(dY, W, active_chunks, chunk_size, M, d_in):
218
+ """Fused dX via block_ptr kernel."""
219
+ num_active = active_chunks.shape[0]
220
+ d_out = dY.shape[1]
221
+ CS = chunk_size
222
+
223
+ dX = torch.zeros(M, d_in, device=dY.device, dtype=dY.dtype)
224
+ if num_active == 0:
225
+ return dX
226
+
227
+ chunk_ids = active_chunks.to(torch.int32).contiguous()
228
+
229
+ BM = 64
230
+ BK = 64
231
+
232
+ grid = (triton.cdiv(M, BM), triton.cdiv(d_in, BK))
233
+
234
+ _v2_sparse_bwd_dX_kernel[grid](
235
+ dY, W, dX, chunk_ids,
236
+ M, d_in, d_out, num_active,
237
+ dY.stride(0), dY.stride(1),
238
+ W.stride(0), W.stride(1),
239
+ dX.stride(0), dX.stride(1),
240
+ CS=CS, BM=BM, BK=BK,
241
+ )
242
+ return dX
243
+
244
+
245
+ # ═══════════════════════════════════════════════════════════════════
246
+ # V1 KERNELS (old, for comparison) β€” import from triton_sparse.py
247
+ # ═══════════════════════════════════════════════════════════════════
248
+
249
+ from triton_sparse import (
250
+ sparse_bwd_dW as v1_sparse_bwd_dW,
251
+ sparse_bwd_dX as v1_sparse_bwd_dX,
252
+ sparse_bwd_dbias as v1_sparse_bwd_dbias,
253
+ )
254
+
255
+
256
+ # ═══════════════════════════════════════════════════════════════════
257
+ # CORRECTNESS TEST
258
+ # ═══════════════════════════════════════════════════════════════════
259
+
260
+ def test_correctness():
261
+ print("V2 Correctness Tests")
262
+ print("=" * 60)
263
+ device = "cuda"
264
+ torch.manual_seed(42)
265
+
266
+ for d_in, d_out, cs in [(512, 2048, 64), (1024, 4096, 64), (256, 1024, 64)]:
267
+ M = 2048
268
+ n_chunks = d_out // cs
269
+ n_active = max(1, int(0.1 * n_chunks))
270
+ active = torch.randperm(n_chunks, device=device)[:n_active].sort().values
271
+
272
+ x = torch.randn(M, d_in, device=device)
273
+ w = torch.randn(d_out, d_in, device=device)
274
+ gy = torch.randn(M, d_out, device=device)
275
+
276
+ # Reference
277
+ ref_dw = torch.zeros_like(w)
278
+ ref_db = torch.zeros(d_out, device=device)
279
+ for c in active.tolist():
280
+ s, e = c * cs, (c + 1) * cs
281
+ ref_dw[s:e] = gy[:, s:e].t() @ x
282
+ ref_db[s:e] = gy[:, s:e].sum(0)
283
+
284
+ ref_dx = torch.zeros_like(x)
285
+ for c in active.tolist():
286
+ s, e = c * cs, (c + 1) * cs
287
+ ref_dx += gy[:, s:e] @ w[s:e]
288
+
289
+ # V2
290
+ v2_dw, v2_db = v2_sparse_bwd_dW(x, gy, active, cs, d_out, bias=True)
291
+ v2_dx = v2_sparse_bwd_dX(gy, w, active, cs, M, d_in)
292
+
293
+ dw_err = (v2_dw - ref_dw).abs().max().item()
294
+ db_err = (v2_db - ref_db).abs().max().item()
295
+ dx_err = (v2_dx - ref_dx).abs().max().item()
296
+
297
+ ok = dw_err < 0.01 and db_err < 0.01 and dx_err < 0.01
298
+ print(f" {'βœ“' if ok else 'βœ—'} d_in={d_in} d_out={d_out} cs={cs}: dW={dw_err:.6f} dB={db_err:.6f} dX={dx_err:.6f}")
299
+
300
+ print()
301
+
302
+
303
+ # ═══════════════════════════════════════════════════════════════════
304
+ # BENCHMARK
305
+ # ═══════════════════════════════════════════════════════════════════
306
+
307
+ def benchmark():
308
+ print("=" * 100)
309
+ print("BENCHMARK: Dense vs PyLoop vs V1-Triton vs V2-Triton (block_ptr + fused bias)")
310
+ print("=" * 100)
311
+ device = "cuda"
312
+ B, T = 8, 256
313
+ M = B * T
314
+ cs = 64
315
+ af = 0.10
316
+ warmup = 20
317
+ iters = 100
318
+
319
+ print(f"\nM={M}, chunk_size={cs}, active_frac={af}, {iters} iters after {warmup} warmup")
320
+ print(f"{'d':>5} | {'ffn':>5} | {'act':>3} | {'Dense':>9} | {'PyLoop':>9} | {'V1-Tri':>9} | {'V2-Tri':>9} | {'V2/Dense':>9} | {'V2/PyLoop':>9} | {'V2/V1':>9}")
321
+ print("-" * 105)
322
+
323
+ for d_in in [256, 512, 768, 1024, 1536, 2048]:
324
+ d_out = 4 * d_in
325
+ nc = d_out // cs
326
+ na = max(1, int(af * nc))
327
+ active = torch.randperm(nc, device=device)[:na].sort().values
328
+
329
+ x = torch.randn(M, d_in, device=device)
330
+ w = torch.randn(d_out, d_in, device=device)
331
+ gy = torch.randn(M, d_out, device=device)
332
+
333
+ def dense():
334
+ return gy.t() @ x, gy @ w, gy.sum(0)
335
+
336
+ def pyloop():
337
+ dw = torch.zeros_like(w); db = torch.zeros(d_out, device=device)
338
+ dx = gy @ w
339
+ for c in active.tolist():
340
+ s, e = c*cs, (c+1)*cs
341
+ dw[s:e] = gy[:, s:e].t() @ x
342
+ db[s:e] = gy[:, s:e].sum(0)
343
+ return dw, dx, db
344
+
345
+ def v1_tri():
346
+ dw = v1_sparse_bwd_dW(x, gy, active, cs, d_out)
347
+ dx = gy @ w
348
+ db = v1_sparse_bwd_dbias(gy, active, cs, d_out)
349
+ return dw, dx, db
350
+
351
+ def v2_tri():
352
+ dw, db = v2_sparse_bwd_dW(x, gy, active, cs, d_out, bias=True)
353
+ dx = gy @ w
354
+ return dw, dx, db
355
+
356
+ # Warmup all
357
+ for _ in range(warmup):
358
+ dense(); pyloop(); v1_tri(); v2_tri()
359
+ torch.cuda.synchronize()
360
+
361
+ times = {}
362
+ for name, fn in [("dense", dense), ("pyloop", pyloop), ("v1", v1_tri), ("v2", v2_tri)]:
363
+ torch.cuda.synchronize(); t0 = time.perf_counter()
364
+ for _ in range(iters): fn()
365
+ torch.cuda.synchronize()
366
+ times[name] = (time.perf_counter() - t0) / iters
367
+
368
+ td, tp, t1, t2 = times["dense"], times["pyloop"], times["v1"], times["v2"]
369
+ print(f"{d_in:>5} | {d_out:>5} | {na:>3} | {td*1000:>8.2f}ms | {tp*1000:>8.2f}ms | {t1*1000:>8.2f}ms | {t2*1000:>8.2f}ms | {td/t2:>8.2f}x | {tp/t2:>8.2f}x | {t1/t2:>8.2f}x")
370
+
371
+ # Sparse dX comparison: V1 vs V2
372
+ print(f"\n{'='*80}")
373
+ print("Sparse dX (both dW+dX sparse): V1 vs V2")
374
+ print(f"{'d':>5} | {'Dense':>9} | {'V1-all':>9} | {'V2-all':>9} | {'V2/Dense':>9}")
375
+ print("-" * 55)
376
+
377
+ for d_in in [512, 1024, 2048]:
378
+ d_out = 4 * d_in; nc = d_out // cs; na = max(1, int(af * nc))
379
+ active = torch.randperm(nc, device=device)[:na].sort().values
380
+ x = torch.randn(M, d_in, device=device)
381
+ w = torch.randn(d_out, d_in, device=device)
382
+ gy = torch.randn(M, d_out, device=device)
383
+
384
+ def dense_all():
385
+ return gy.t() @ x, gy @ w
386
+ def v1_all():
387
+ return v1_sparse_bwd_dW(x, gy, active, cs, d_out), v1_sparse_bwd_dX(gy, w, active, cs, M, d_in)
388
+ def v2_all():
389
+ dw, _ = v2_sparse_bwd_dW(x, gy, active, cs, d_out, bias=False)
390
+ return dw, v2_sparse_bwd_dX(gy, w, active, cs, M, d_in)
391
+
392
+ for _ in range(warmup): dense_all(); v1_all(); v2_all()
393
+ torch.cuda.synchronize()
394
+
395
+ for name, fn, store in [("dense", dense_all, "td"), ("v1", v1_all, "t1"), ("v2", v2_all, "t2")]:
396
+ torch.cuda.synchronize(); t0 = time.perf_counter()
397
+ for _ in range(iters): fn()
398
+ torch.cuda.synchronize()
399
+ locals()[store] = (time.perf_counter() - t0) / iters
400
+
401
+ # Need to read them back since locals() trick doesn't work cleanly
402
+ torch.cuda.synchronize(); t0 = time.perf_counter()
403
+ for _ in range(iters): dense_all()
404
+ torch.cuda.synchronize(); td = (time.perf_counter() - t0) / iters
405
+
406
+ torch.cuda.synchronize(); t0 = time.perf_counter()
407
+ for _ in range(iters): v1_all()
408
+ torch.cuda.synchronize(); t1 = (time.perf_counter() - t0) / iters
409
+
410
+ torch.cuda.synchronize(); t0 = time.perf_counter()
411
+ for _ in range(iters): v2_all()
412
+ torch.cuda.synchronize(); t2 = (time.perf_counter() - t0) / iters
413
+
414
+ print(f"{d_in:>5} | {td*1000:>8.2f}ms | {t1*1000:>8.2f}ms | {t2*1000:>8.2f}ms | {td/t2:>8.2f}x")
415
+
416
+
417
+ if __name__ == "__main__":
418
+ test_correctness()
419
+ benchmark()