forked from tile-ai/TileOPs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbench_binary_arith.py
More file actions
506 lines (397 loc) · 16.5 KB
/
Copy pathbench_binary_arith.py
File metadata and controls
506 lines (397 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
from tileops.utils import get_backend_name
DEVICE = get_backend_name()
"""Benchmarks for binary arithmetic ops covering risk points R1, R2, R4.
Risk points covered:
- R1: Stride-based load vectorization (add x explicit_parallel x fp16 x
{1D same-shape, 2D bias-add, 3D interleaved})
- R2: Divmod overhead on small tensors (add same-shape/3D-broadcast x fp16 x 4K)
- R4: DEFAULT_STRATEGY confirmation (add x 2 strategies x 3 dtypes x 3 sizes x
{same-shape, 2D bias-add, 3D interleaved})
Profiles both binary strategies (direct, explicit_parallel) and compares
against PyTorch baseline.
"""
from math import prod
from typing import Optional, Protocol
import pytest
import torch
from benchmarks.benchmark_base import BenchmarkBase, BenchmarkReport
from tileops.ops.elementwise import AddFwdOp, LerpTensorFwdOp, WhereFwdOp
from workloads.binary_arith import AddSameShapeTest
from workloads.workload_base import FixtureBase
# ---------------------------------------------------------------------------
# LLM-realistic shapes (LLaMA-family defaults)
# ---------------------------------------------------------------------------
# Per-strategy/broadcast matrix sizes. Each label maps to a 2D shape that
# both the same-shape and broadcast patterns can derive from. The third
# entry is non-pow2 in the hidden dim to exercise tail handling.
_SHAPE_BY_LABEL: dict[str, tuple[int, int]] = {
"4K": (1, 4096),
"1M": (1024, 1024),
"11M": (1024, 11008),
}
_DTYPES = (torch.float16, torch.bfloat16, torch.float32)
_BINARY_STRATEGIES = ("direct", "explicit_parallel")
def _make_interleaved_3d(n: int) -> tuple[tuple, tuple]:
"""Build (A,1,C) + (1,B,1) -> (A,B,C) with A*B*C == n exactly.
Uses A=8 (or 1 for very small n). Finds the largest B <= sqrt(n/A)
that divides n/A evenly, then C = n/(A*B).
"""
if n < 8:
return (1, 1, n), (1, n, 1)
a_dim = 8
remainder = n // a_dim
b_dim = int(remainder ** 0.5)
while b_dim > 1 and remainder % b_dim != 0:
b_dim -= 1
c_dim = remainder // b_dim
return (a_dim, 1, c_dim), (1, b_dim, 1)
# Broadcast patterns for binary ops. Each pattern derives a (a_shape,
# b_shape) pair from a 2D output shape (M, N), preserving model geometry.
_BROADCAST_PATTERNS = {
"same_shape": lambda mn: (mn, mn),
"bias_add_2d": lambda mn: (mn, (1, mn[1])),
"interleaved_3d": lambda mn: _make_interleaved_3d(mn[0] * mn[1]),
}
# ---------------------------------------------------------------------------
# Benchmark harness
# ---------------------------------------------------------------------------
class BinaryWorkload(Protocol):
"""Structural type for binary benchmark workloads.
Requires ``n_total``, ``dtype``, and ``gen_inputs``. Attributes
``a_shape`` / ``b_shape`` are optional — ``BinaryBenchmark`` falls
back to ``n_total`` when they are absent.
"""
n_total: int
dtype: torch.dtype
def gen_inputs(self) -> tuple[torch.Tensor, ...]: ...
class BinaryBenchCase:
"""Minimal test harness for binary benchmarks."""
def __init__(
self, a_shape: tuple, b_shape: tuple, dtype: torch.dtype,
):
self.a_shape = a_shape
self.b_shape = b_shape
self.dtype = dtype
self.n_total = prod(torch.broadcast_shapes(a_shape, b_shape))
def gen_inputs(self) -> tuple[torch.Tensor, torch.Tensor]:
a = torch.randn(self.a_shape, device=DEVICE, dtype=self.dtype)
b = torch.randn(self.b_shape, device=DEVICE, dtype=self.dtype)
return a, b
class BinaryBenchmark(BenchmarkBase[BinaryWorkload]):
"""Bandwidth-oriented benchmark for binary elementwise ops."""
def calculate_flops(self) -> Optional[float]:
return self.workload.n_total
def calculate_memory(self) -> Optional[float]:
t = self.workload
elem_bytes = t.dtype.itemsize
# Read a + read b + write output
a_elems = prod(getattr(t, "a_shape", (t.n_total,)))
b_elems = prod(getattr(t, "b_shape", (t.n_total,)))
return (a_elems + b_elems + t.n_total) * elem_bytes
class WhereBenchCase:
"""Test harness for where op benchmarks."""
def __init__(self, shape: tuple[int, ...], dtype: torch.dtype):
self.shape = shape
self.n_total = prod(shape)
self.dtype = dtype
def gen_inputs(self) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
cond = torch.randint(0, 2, self.shape, device=DEVICE, dtype=torch.bool)
x = torch.randn(*self.shape, device=DEVICE, dtype=self.dtype)
y = torch.randn(*self.shape, device=DEVICE, dtype=self.dtype)
return cond, x, y
class WhereBenchmark(BenchmarkBase[WhereBenchCase]):
"""Benchmark for where op."""
def calculate_flops(self) -> Optional[float]:
return self.workload.n_total
def calculate_memory(self) -> Optional[float]:
t = self.workload
elem_bytes = t.dtype.itemsize
# Read cond (1 byte) + read x + read y + write output
return t.n_total * (1 + 3 * elem_bytes)
# ---------------------------------------------------------------------------
# R1: Stride-based load vectorization
# ---------------------------------------------------------------------------
_R1_PATTERNS = [
("same_shape_1d", (1_000_000,), (1_000_000,)),
# bias-add: (1000, 1000) + (1, 1000) -> 1,000,000 output elements
("bias_add_2d", (1000, 1000), (1, 1000)),
# interleaved: (8,1,1024) + (1,128,1) -> (8,128,1024) = 1,048,576 output
("interleaved_3d", (8, 1, 1024), (1, 128, 1)),
]
class R1VectorizationFixture(FixtureBase):
PARAMS = [
("pattern_name, a_shape, b_shape", [
pytest.param(name, a, b, marks=pytest.mark.smoke if name == "same_shape_1d"
else pytest.mark.full)
for name, a, b in _R1_PATTERNS
]),
]
@R1VectorizationFixture
def test_r1_vectorization(
pattern_name: str,
a_shape: tuple,
b_shape: tuple,
) -> None:
"""R1: Benchmark stride-based load vectorization.
Binary divmod offset may prevent uint4 vectorized loads.
Compares same-shape (no divmod) vs broadcast patterns (divmod required).
"""
dtype = torch.float16
test = BinaryBenchCase(a_shape, b_shape, dtype)
bm = BinaryBenchmark(test)
inputs = test.gen_inputs()
op = AddFwdOp(
a_shape=a_shape, b_shape=b_shape, dtype=dtype,
strategy="explicit_parallel",
)
result = bm.profile(op, *inputs)
BenchmarkReport.record(
"r1_vectorization",
{"pattern_name": pattern_name, "a_shape": a_shape, "b_shape": b_shape},
result,
tag=f"add_{pattern_name}",
)
# Baseline: PyTorch add with broadcast
a, b = inputs
def baseline_fn(a, b):
return a + b
result_bl = bm.profile(baseline_fn, a, b)
BenchmarkReport.record(
"r1_vectorization",
{"pattern_name": pattern_name, "a_shape": a_shape, "b_shape": b_shape},
result_bl,
tag=f"torch-{pattern_name}",
)
# ---------------------------------------------------------------------------
# R2: Divmod overhead on small tensors (binary)
# ---------------------------------------------------------------------------
class R2BinaryFixture(FixtureBase):
PARAMS = [
("pattern_name, a_shape, b_shape", [
pytest.param("same_shape", (4096,), (4096,), marks=pytest.mark.smoke),
pytest.param(
"broadcast_3d", (4, 1, 32), (1, 32, 1),
marks=pytest.mark.full,
),
]),
]
@R2BinaryFixture
def test_r2_small_tensor_binary(
pattern_name: str,
a_shape: tuple,
b_shape: tuple,
) -> None:
"""R2: Benchmark divmod overhead on small tensors (binary add, 4K)."""
dtype = torch.float16
test = BinaryBenchCase(a_shape, b_shape, dtype)
bm = BinaryBenchmark(test)
inputs = test.gen_inputs()
op = AddFwdOp(a_shape=a_shape, b_shape=b_shape, dtype=dtype)
result = bm.profile(op, *inputs)
BenchmarkReport.record(
"r2_small_tensor_binary",
{"pattern_name": pattern_name, "a_shape": a_shape, "b_shape": b_shape},
result,
tag=f"add_{pattern_name}",
)
a, b = inputs
def baseline_fn(a, b):
return a + b
result_bl = bm.profile(baseline_fn, a, b)
BenchmarkReport.record(
"r2_small_tensor_binary",
{"pattern_name": pattern_name, "a_shape": a_shape, "b_shape": b_shape},
result_bl,
tag=f"torch-{pattern_name}",
)
# ---------------------------------------------------------------------------
# R4: DEFAULT_STRATEGY confirmation (binary full matrix)
# ---------------------------------------------------------------------------
_R4_BINARY_PARAMS = []
for size_label, _shape_2d in _SHAPE_BY_LABEL.items():
for dt in _DTYPES:
for strategy in _BINARY_STRATEGIES:
for pat_name, pat_fn in _BROADCAST_PATTERNS.items():
a_shape, b_shape = pat_fn(_shape_2d)
mark = pytest.mark.smoke if (
size_label == "1M" and dt == torch.float16
and strategy == "explicit_parallel"
and pat_name == "same_shape"
) else pytest.mark.full
_R4_BINARY_PARAMS.append(
pytest.param(
a_shape, b_shape, dt, strategy, size_label, pat_name,
id=f"{size_label}-{dt}-{strategy}-{pat_name}",
marks=mark,
)
)
class R4BinaryStrategyFixture(FixtureBase):
PARAMS = [
("a_shape, b_shape, dtype, strategy, size_label, pattern_name",
_R4_BINARY_PARAMS),
]
@R4BinaryStrategyFixture
def test_r4_default_strategy_binary(
a_shape: tuple,
b_shape: tuple,
dtype: torch.dtype,
strategy: str,
size_label: str,
pattern_name: str,
) -> None:
"""R4: Benchmark both binary strategies across full matrix.
Covers: add x {direct, explicit_parallel} x {fp32, fp16, bf16}
x {4K, 1M, 16M} x {same-shape, bias-add, interleaved-3D}
"""
test = BinaryBenchCase(a_shape, b_shape, dtype)
bm = BinaryBenchmark(test)
inputs = test.gen_inputs()
op = AddFwdOp(
a_shape=a_shape, b_shape=b_shape, dtype=dtype, strategy=strategy,
)
result = bm.profile(op, *inputs)
BenchmarkReport.record(
"r4_strategy_binary",
{
"size_label": size_label,
"pattern_name": pattern_name,
"a_shape": a_shape,
"b_shape": b_shape,
"dtype": dtype,
"strategy": strategy,
},
result,
tag=f"add_{strategy}_{pattern_name}",
)
# ---------------------------------------------------------------------------
# R4: Where op strategy comparison (3-input op)
# ---------------------------------------------------------------------------
_R4_WHERE_PARAMS = []
for size_label, _shape_2d in _SHAPE_BY_LABEL.items():
_R4_WHERE_PARAMS.append(
pytest.param(
_shape_2d, size_label, torch.float16,
id=f"where-{size_label}-fp16",
marks=pytest.mark.full,
)
)
class R4WhereFixture(FixtureBase):
PARAMS = [
("shape, size_label, dtype", _R4_WHERE_PARAMS),
]
@R4WhereFixture
def test_r4_where_bench(
shape: tuple[int, ...],
size_label: str,
dtype: torch.dtype,
) -> None:
"""R4: Benchmark where op across sizes."""
test = WhereBenchCase(shape, dtype)
bm = WhereBenchmark(test)
inputs = test.gen_inputs()
op = WhereFwdOp(condition=shape, input=shape, other=shape, dtype=dtype)
result = bm.profile(op, *inputs)
BenchmarkReport.record(
"r4_where",
{"shape": shape, "size_label": size_label, "dtype": dtype},
result,
tag="tileops-where",
)
cond, x, y = inputs
def baseline_fn(cond, x, y):
return torch.where(cond, x, y)
result_bl = bm.profile(baseline_fn, cond, x, y)
BenchmarkReport.record(
"r4_where",
{"shape": shape, "size_label": size_label, "dtype": dtype},
result_bl,
tag="torch",
)
# ---------------------------------------------------------------------------
# Baseline throughput benchmarks (existing, refined with LLaMA shapes)
# ---------------------------------------------------------------------------
_ADD_BENCH_PARAMS = [
pytest.param((1024, 4096), torch.float16, id="throughput-fp16"),
pytest.param((1024, 4096), torch.bfloat16, id="throughput-bf16"),
pytest.param((1024, 4096), torch.float32, id="baseline-fp32"),
]
@pytest.mark.parametrize("shape, dtype", _ADD_BENCH_PARAMS)
def test_add_bench(shape: tuple[int, ...], dtype: torch.dtype) -> None:
n_total = prod(shape)
# ``AddSameShapeTest`` (workloads) accepts a flat element count; the
# bench harness still records the original shape tuple via
# ``record(...)`` so the report carries the input geometry verbatim.
test = AddSameShapeTest(n_total, dtype)
bm = BinaryBenchmark(test)
inputs = test.gen_inputs()
op = AddFwdOp(a_shape=shape, b_shape=shape, dtype=dtype)
result = bm.profile(op, *inputs)
BenchmarkReport.record(op, locals(), result, tag="tileops")
def baseline_fn(a, b):
return a + b
result_bl = bm.profile(baseline_fn, *inputs)
BenchmarkReport.record(op, locals(), result_bl, tag="torch")
# ---------------------------------------------------------------------------
# LerpTensorFwdOp — Tensor-weight torch.lerp benchmark.
#
# Per output element: 3 flops (sub + mul + add); 3 reads + 1 write at
# post-broadcast ``N_total`` (matches
# ``tileops.perf.formulas.lerp_tensor_fwd_roofline``). Same-shape inputs
# only here; the broadcast contract is exercised by the test suite.
# ---------------------------------------------------------------------------
class LerpTensorBenchCase:
"""Same-shape input/end/weight; output broadcast equals the shape."""
def __init__(self, shape: tuple[int, ...], dtype: torch.dtype):
self.shape = shape
self.n_total = prod(shape)
self.dtype = dtype
def gen_inputs(self) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
a = torch.randn(self.shape, device=DEVICE, dtype=self.dtype)
b = torch.randn(self.shape, device=DEVICE, dtype=self.dtype)
# Keep weight in [0, 1] to stay close to typical lerp usage.
w = torch.rand(self.shape, device=DEVICE, dtype=self.dtype)
return a, b, w
class LerpTensorBenchmark(BenchmarkBase[LerpTensorBenchCase]):
"""Bandwidth-oriented benchmark for ``LerpTensorFwdOp``."""
def calculate_flops(self) -> Optional[float]:
return 3 * self.workload.n_total
def calculate_memory(self) -> Optional[float]:
t = self.workload
return 4 * t.n_total * t.dtype.itemsize
_LERP_TENSOR_BENCH_PARAMS = [
pytest.param((1024, 4096), torch.float16,
id="lerp-tensor-fp16-1024x4096", marks=pytest.mark.smoke),
pytest.param((1024, 4096), torch.bfloat16,
id="lerp-tensor-bf16-1024x4096", marks=pytest.mark.full),
pytest.param((1024, 4096), torch.float32,
id="lerp-tensor-fp32-1024x4096", marks=pytest.mark.full),
pytest.param((1024, 10240), torch.float16,
id="lerp-tensor-fp16-1024x10240", marks=pytest.mark.full),
pytest.param((1024, 11008), torch.float16,
id="lerp-tensor-fp16-1024x11008", marks=pytest.mark.full),
]
@pytest.mark.parametrize("shape, dtype", _LERP_TENSOR_BENCH_PARAMS)
def test_lerp_tensor_bench(shape: tuple[int, ...], dtype: torch.dtype) -> None:
from tileops.perf.formulas import lerp_tensor_fwd_roofline
test = LerpTensorBenchCase(shape, dtype)
bm = LerpTensorBenchmark(test)
a, b, w = test.gen_inputs()
op = LerpTensorFwdOp(
input=tuple(shape), end=tuple(shape), weight=tuple(shape), dtype=dtype,
)
# Cross-check the bench harness' inline flop/byte counts against the
# manifest-bound roofline formula so a drift in either direction
# surfaces as a bench failure rather than silent perf misreporting.
formula_flops, formula_bytes = lerp_tensor_fwd_roofline(op)
assert formula_flops == bm.calculate_flops(), (
f"flop mismatch: formula={formula_flops}, bench={bm.calculate_flops()}"
)
assert formula_bytes == bm.calculate_memory(), (
f"byte mismatch: formula={formula_bytes}, bench={bm.calculate_memory()}"
)
result = bm.profile(op, a, b, w)
BenchmarkReport.record(op, locals(), result, tag="tileops")
result_bl = bm.profile(torch.lerp, a, b, w)
BenchmarkReport.record(op, locals(), result_bl, tag="torch")
if __name__ == "__main__":
pytest.main([__file__, "-vvs"])