Neptune-T commited on
Commit
be12f65
·
verified ·
1 Parent(s): e57a3b5

Add files using upload-large-folder tool

Browse files
upstream/CoDA/coda.egg-info/PKG-INFO ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: coda
3
+ Version: 1.0.0
4
+ Summary: ['CoDA training and inference']
5
+ Home-page: https://github.com/phj128/CoDA
6
+ Author: Huaijin Pi
7
+ Dynamic: author
8
+ Dynamic: home-page
9
+ Dynamic: summary
upstream/CoDA/coda.egg-info/SOURCES.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ README.md
2
+ setup.py
3
+ coda/__init__.py
4
+ coda.egg-info/PKG-INFO
5
+ coda.egg-info/SOURCES.txt
6
+ coda.egg-info/dependency_links.txt
7
+ coda.egg-info/top_level.txt
8
+ coda/configs/__init__.py
9
+ coda/configs/store_coda.py
upstream/CoDA/coda.egg-info/dependency_links.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
upstream/CoDA/coda.egg-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ coda
upstream/CoDA/coda/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+
4
+ PROJ_ROOT = Path(__file__).resolve().parents[1]
5
+
6
+
7
+ def os_chdir_to_proj_root():
8
+ """useful for running notebooks in different directories."""
9
+ os.chdir(PROJ_ROOT)
upstream/CoDA/outputs/test_arctic/diffusionwholebody/.hydra/overrides.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ - exp=wholebody/obj_arctic
2
+ - global/task=wholebody/test_arctic
3
+ - +pl_trainer.limit_test_batches=1
4
+ - seed=43
upstream/CoDA/outputs/wis3d/debug_arctic_wholebodypose_000/00190/meshes/gt-righthand.ply ADDED
Binary file (4.82 kB). View file
 
upstream/CoDA/outputs/wis3d/debug_arctic_wholebodypose_000/00190/meshes/pred-ours-righthand.ply ADDED
Binary file (4.82 kB). View file
 
upstream/flash-linear-attention/benchmarks/ops/benchmark.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023, Tri Dao.
2
+ """ Useful functions for writing test code. """
3
+
4
+ import torch
5
+ import torch.utils.benchmark as benchmark
6
+
7
+
8
+ def benchmark_forward(
9
+ fn, *inputs, repeats=10, desc="", verbose=True, amp=False, amp_dtype=torch.float16, **kwinputs
10
+ ):
11
+ """Use Pytorch Benchmark on the forward pass of an arbitrary function."""
12
+ if verbose:
13
+ print(desc, "- Forward pass")
14
+
15
+ def amp_wrapper(*inputs, **kwinputs):
16
+ with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp):
17
+ fn(*inputs, **kwinputs)
18
+
19
+ t = benchmark.Timer(
20
+ stmt="fn_amp(*inputs, **kwinputs)",
21
+ globals={"fn_amp": amp_wrapper, "inputs": inputs, "kwinputs": kwinputs},
22
+ num_threads=torch.get_num_threads(),
23
+ )
24
+ m = t.timeit(repeats)
25
+ if verbose:
26
+ print(m)
27
+ return t, m
28
+
29
+
30
+ def benchmark_backward(
31
+ fn,
32
+ *inputs,
33
+ grad=None,
34
+ repeats=10,
35
+ desc="",
36
+ verbose=True,
37
+ amp=False,
38
+ amp_dtype=torch.float16,
39
+ **kwinputs,
40
+ ):
41
+ """Use Pytorch Benchmark on the backward pass of an arbitrary function."""
42
+ if verbose:
43
+ print(desc, "- Backward pass")
44
+ with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp):
45
+ y = fn(*inputs, **kwinputs)
46
+ if type(y) is tuple:
47
+ y = y[0]
48
+ if grad is None:
49
+ grad = torch.randn_like(y)
50
+ else:
51
+ if grad.shape != y.shape:
52
+ raise RuntimeError("Grad shape does not match output shape")
53
+
54
+ def f(*inputs, y, grad):
55
+ # Set .grad to None to avoid extra operation of gradient accumulation
56
+ for x in inputs:
57
+ if isinstance(x, torch.Tensor):
58
+ x.grad = None
59
+ y.backward(grad, retain_graph=True)
60
+
61
+ t = benchmark.Timer(
62
+ stmt="f(*inputs, y=y, grad=grad)",
63
+ globals={"f": f, "inputs": inputs, "y": y, "grad": grad},
64
+ num_threads=torch.get_num_threads(),
65
+ )
66
+ m = t.timeit(repeats)
67
+ if verbose:
68
+ print(m)
69
+ return t, m
70
+
71
+
72
+ def benchmark_combined(
73
+ fn,
74
+ *inputs,
75
+ grad=None,
76
+ repeats=10,
77
+ desc="",
78
+ verbose=True,
79
+ amp=False,
80
+ amp_dtype=torch.float16,
81
+ **kwinputs,
82
+ ):
83
+ """Use Pytorch Benchmark on the forward+backward pass of an arbitrary function."""
84
+ if verbose:
85
+ print(desc, "- Forward + Backward pass")
86
+ with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp):
87
+ y = fn(*inputs, **kwinputs)
88
+ if type(y) is tuple:
89
+ y = y[0]
90
+ if grad is None:
91
+ grad = torch.randn_like(y)
92
+ else:
93
+ if grad.shape != y.shape:
94
+ raise RuntimeError("Grad shape does not match output shape")
95
+
96
+ def f(grad, *inputs, **kwinputs):
97
+ for x in inputs:
98
+ if isinstance(x, torch.Tensor):
99
+ x.grad = None
100
+ with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp):
101
+ y = fn(*inputs, **kwinputs)
102
+ if type(y) is tuple:
103
+ y = y[0]
104
+ y.backward(grad, retain_graph=True)
105
+
106
+ t = benchmark.Timer(
107
+ stmt="f(grad, *inputs, **kwinputs)",
108
+ globals={"f": f, "fn": fn, "inputs": inputs, "grad": grad, "kwinputs": kwinputs},
109
+ num_threads=torch.get_num_threads(),
110
+ )
111
+ m = t.timeit(repeats)
112
+ if verbose:
113
+ print(m)
114
+ return t, m
115
+
116
+
117
+ def benchmark_fwd_bwd(
118
+ fn,
119
+ *inputs,
120
+ grad=None,
121
+ repeats=10,
122
+ desc="",
123
+ verbose=True,
124
+ amp=False,
125
+ amp_dtype=torch.float16,
126
+ **kwinputs,
127
+ ):
128
+ """Use Pytorch Benchmark on the forward+backward pass of an arbitrary function."""
129
+ return (
130
+ benchmark_forward(
131
+ fn,
132
+ *inputs,
133
+ repeats=repeats,
134
+ desc=desc,
135
+ verbose=verbose,
136
+ amp=amp,
137
+ amp_dtype=amp_dtype,
138
+ **kwinputs,
139
+ ),
140
+ benchmark_backward(
141
+ fn,
142
+ *inputs,
143
+ grad=grad,
144
+ repeats=repeats,
145
+ desc=desc,
146
+ verbose=verbose,
147
+ amp=amp,
148
+ amp_dtype=amp_dtype,
149
+ **kwinputs,
150
+ ),
151
+ )
152
+
153
+
154
+ def benchmark_all(
155
+ fn,
156
+ *inputs,
157
+ grad=None,
158
+ repeats=10,
159
+ desc="",
160
+ verbose=True,
161
+ amp=False,
162
+ amp_dtype=torch.float16,
163
+ **kwinputs,
164
+ ):
165
+ """Use Pytorch Benchmark on the forward+backward pass of an arbitrary function."""
166
+ return (
167
+ benchmark_forward(
168
+ fn,
169
+ *inputs,
170
+ repeats=repeats,
171
+ desc=desc,
172
+ verbose=verbose,
173
+ amp=amp,
174
+ amp_dtype=amp_dtype,
175
+ **kwinputs,
176
+ ),
177
+ benchmark_backward(
178
+ fn,
179
+ *inputs,
180
+ grad=grad,
181
+ repeats=repeats,
182
+ desc=desc,
183
+ verbose=verbose,
184
+ amp=amp,
185
+ amp_dtype=amp_dtype,
186
+ **kwinputs,
187
+ ),
188
+ benchmark_combined(
189
+ fn,
190
+ *inputs,
191
+ grad=grad,
192
+ repeats=repeats,
193
+ desc=desc,
194
+ verbose=verbose,
195
+ amp=amp,
196
+ amp_dtype=amp_dtype,
197
+ **kwinputs,
198
+ ),
199
+ )
200
+
201
+
202
+ def pytorch_profiler(
203
+ fn,
204
+ *inputs,
205
+ trace_filename=None,
206
+ backward=False,
207
+ amp=False,
208
+ amp_dtype=torch.float16,
209
+ cpu=False,
210
+ verbose=True,
211
+ **kwinputs,
212
+ ):
213
+ """Wrap benchmark functions in Pytorch profiler to see CUDA information."""
214
+ if backward:
215
+ with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp):
216
+ out = fn(*inputs, **kwinputs)
217
+ if type(out) is tuple:
218
+ out = out[0]
219
+ g = torch.randn_like(out)
220
+ for _ in range(30): # Warm up
221
+ if backward:
222
+ for x in inputs:
223
+ if isinstance(x, torch.Tensor):
224
+ x.grad = None
225
+ with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp):
226
+ out = fn(*inputs, **kwinputs)
227
+ if type(out) is tuple:
228
+ out = out[0]
229
+ # Backward should be done outside autocast
230
+ if backward:
231
+ out.backward(g, retain_graph=True)
232
+ activities = ([torch.profiler.ProfilerActivity.CPU] if cpu else []) + [
233
+ torch.profiler.ProfilerActivity.CUDA
234
+ ]
235
+ with torch.profiler.profile(
236
+ activities=activities,
237
+ record_shapes=True,
238
+ # profile_memory=True,
239
+ with_stack=True,
240
+ ) as prof:
241
+ if backward:
242
+ for x in inputs:
243
+ if isinstance(x, torch.Tensor):
244
+ x.grad = None
245
+ with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp):
246
+ out = fn(*inputs, **kwinputs)
247
+ if type(out) is tuple:
248
+ out = out[0]
249
+ if backward:
250
+ out.backward(g, retain_graph=True)
251
+ if verbose:
252
+ # print(prof.key_averages().table(sort_by="self_cuda_time_total", row_limit=50))
253
+ print(prof.key_averages().table(row_limit=50))
254
+ if trace_filename is not None:
255
+ prof.export_chrome_trace(trace_filename)
256
+
257
+
258
+ def benchmark_memory(fn, *inputs, desc="", verbose=True, **kwinputs):
259
+ torch.cuda.empty_cache()
260
+ torch.cuda.reset_peak_memory_stats()
261
+ torch.cuda.synchronize()
262
+ fn(*inputs, **kwinputs)
263
+ torch.cuda.synchronize()
264
+ mem = torch.cuda.max_memory_allocated() / ((2**20) * 1000)
265
+ if verbose:
266
+ print(f"{desc} max memory: {mem}GB")
267
+ torch.cuda.empty_cache()
268
+ return mem
upstream/flash-linear-attention/benchmarks/ops/benchmark_based.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import torch
4
+ import triton
5
+
6
+ from fla.ops.based import fused_chunk_based, parallel_based
7
+ from fla.ops.based.naive import naive_chunk_based, naive_parallel_based
8
+
9
+ try:
10
+ from flash_attn import flash_attn_func
11
+ HAS_FLASH = True
12
+ except Exception:
13
+ HAS_FLASH = False
14
+
15
+
16
+ @triton.testing.perf_report(
17
+ triton.testing.Benchmark(
18
+ # argument names to use as an x-axis for the plot
19
+ x_names=['T'],
20
+ # different possible values for `x_name`
21
+ x_vals=[128 * 2 ** i for i in range(3, 8)],
22
+ # argument name whose value corresponds to a different line in the plot
23
+ line_arg='provider',
24
+ line_vals=['fused_chunk', 'torch', 'parallel', 'parallel_chunk', 'fused_chunk_bwd', 'torch_bwd',
25
+ 'parallel_bwd', 'parallel_chunk_bwd'] + (['flash', 'flash_bwd'] if HAS_FLASH else []),
26
+ # label name for the lines
27
+ line_names=['fused_chunk_fwd', 'torch_fwd', 'parallel_fwd', 'parallel_chunk_fwd',
28
+ 'fused_chunk_fwdbwd', 'torch_fwdbwd', 'parallel_fwdbwd',
29
+ 'parallel_chunk_fwdbwd'] + (['flash_fwd', 'flash_fwdbwd'] if HAS_FLASH else []),
30
+
31
+ # line styles
32
+ styles=[('green', '-'), ('blue', '-'), ('red', '-'), ('green', 'dotted'), ('blue', 'dotted'),
33
+ ('red', 'dotted'), ('red', '--'), ('red', ':')] + ([('cyan', '-'), ('cyan', 'dotted')] if HAS_FLASH else []),
34
+ ylabel="Execution Time (ms)", # label name for the y-axis
35
+ # name for the plot. Used also as a file name for saving the plot.
36
+ plot_name="Performance",
37
+ args={},
38
+ )
39
+ )
40
+ def benchmark(T, provider):
41
+ from fla.utils import device
42
+ dtype = torch.bfloat16
43
+ requires_grad = True
44
+ B, H, D = 8, 16, 128
45
+
46
+ if provider == 'flash' or provider == 'flash_bwd':
47
+ q = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
48
+ k = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
49
+ v = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
50
+ else:
51
+ q = torch.randn(B, H, T, 16, device=device, requires_grad=requires_grad, dtype=dtype)
52
+ k = torch.randn(B, H, T, 16, device=device, requires_grad=requires_grad, dtype=dtype)
53
+ v = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
54
+ do = torch.ones_like(v, dtype=dtype)
55
+
56
+ quantiles = [0.5, 0.2, 0.8]
57
+ results = 0, 0, 0
58
+ if provider == 'torch':
59
+ if T > 1024:
60
+ return results
61
+ results = triton.testing.do_bench(lambda: naive_parallel_based(q, k, v), quantiles=quantiles)
62
+ elif provider == 'fused_chunk':
63
+ results = triton.testing.do_bench(lambda: fused_chunk_based(q, k, v), quantiles=quantiles)
64
+ elif provider == 'parallel':
65
+ results = triton.testing.do_bench(lambda: parallel_based(q, k, v), quantiles=quantiles)
66
+ elif provider == 'parallel_chunk':
67
+ results = triton.testing.do_bench(lambda: naive_chunk_based(q, k, v), quantiles=quantiles)
68
+ elif provider == 'torch_bwd':
69
+ if T > 1024:
70
+ return results
71
+ results = triton.testing.do_bench(lambda: naive_parallel_based(q, k, v).backward(do), quantiles=quantiles)
72
+ elif provider == 'fused_chunk_bwd':
73
+ results = triton.testing.do_bench(lambda: fused_chunk_based(q, k, v).backward(do), quantiles=quantiles)
74
+ elif provider == 'parallel_bwd':
75
+ results = triton.testing.do_bench(lambda: parallel_based(q, k, v).backward(do), quantiles=quantiles)
76
+ elif provider == 'flash':
77
+ results = triton.testing.do_bench(lambda: flash_attn_func(q, k, v, causal=True), quantiles=quantiles)
78
+ elif provider == 'flash_bwd':
79
+ results = triton.testing.do_bench(lambda: flash_attn_func(q, k, v, causal=True).backward(do), quantiles=quantiles)
80
+ elif provider == 'parallel_chunk_bwd':
81
+ results = triton.testing.do_bench(lambda: naive_chunk_based(q, k, v).backward(do), quantiles=quantiles)
82
+ return results
83
+
84
+
85
+ if __name__ == '__main__':
86
+ benchmark.run(print_data=True, show_plots=True)
upstream/flash-linear-attention/benchmarks/ops/benchmark_delta_rule.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Install the newest triton version with
2
+ # pip install "git+https://github.com/openai/triton.git#egg=triton&subdirectory=python"
3
+
4
+ import torch
5
+ from benchmark import benchmark_backward, benchmark_combined, benchmark_forward
6
+ from torch.nn import functional as F
7
+
8
+ from fla.ops.delta_rule import chunk_delta_rule, fused_chunk_delta_rule
9
+ from fla.utils import device
10
+
11
+
12
+ def time_fwd(func, *args, **kwargs):
13
+ time_fb = benchmark_forward(func, *args, **kwargs)
14
+ return time_fb[1].mean
15
+
16
+
17
+ def time_fwd_bwd(func, *args, **kwargs):
18
+ time_fb = benchmark_combined(func, *args, **kwargs)
19
+ return time_fb[1].mean
20
+
21
+
22
+ def time_bwd(func, *args, **kwargs):
23
+ time_fb = benchmark_backward(func, *args, **kwargs)
24
+ return time_fb[1].mean
25
+
26
+
27
+ repeats = 256
28
+ dtype = torch.bfloat16
29
+
30
+
31
+ bs_seqlen_vals = [(8, 2048), (4, 4096), (2, 8192)]
32
+ causal_vals = [True]
33
+ headdim_vals = [64, 128, 256]
34
+ dim = 2048
35
+ dropout_p = 0.0
36
+
37
+
38
+ methods = (["chunk_delta_rule", "fused_chunk_delta_rule"])
39
+ time_f = {}
40
+ time_b = {}
41
+ time_f_b = {}
42
+ speed_f = {}
43
+ speed_b = {}
44
+ speed_f_b = {}
45
+ for causal in causal_vals:
46
+ for headdim in headdim_vals:
47
+ for B, seqlen in bs_seqlen_vals:
48
+ config = (causal, headdim, B, seqlen)
49
+ H = dim // headdim
50
+ q = torch.randn(B, H, seqlen, headdim, device=device, requires_grad=True, dtype=dtype)
51
+ k = F.normalize(torch.randn(B, H, seqlen, headdim, device=device, dtype=dtype), p=2, dim=-1).requires_grad_(True)
52
+ v = torch.randn(B, H, seqlen, headdim, device=device, requires_grad=True, dtype=dtype)
53
+ beta = torch.rand(B, H, seqlen, device=device, dtype=dtype).sigmoid().requires_grad_(True)
54
+ o1, _ = chunk_delta_rule(q, k, v, beta)
55
+ o1.sum().backward(retain_graph=True)
56
+ f_b = time_fwd_bwd(
57
+ chunk_delta_rule, q, k, v, beta, verbose=False
58
+ )
59
+ time_f_b[config, "chunk_delta_rule"] = f_b
60
+
61
+ # q = torch.randn(B, seqlen, H, headdim, device=device, requires_grad=True, dtype=dtype)
62
+ # k = torch.randn(B, seqlen, H, headdim, device=device, requires_grad=True, dtype=dtype)
63
+ # v = torch.randn(B, seqlen, H, headdim, device=device, requires_grad=True, dtype=dtype)
64
+ f_b = time_fwd_bwd(
65
+ fused_chunk_delta_rule, q, k, v, beta, verbose=False
66
+ )
67
+ time_f_b[config, "fused_chunk_delta_rule"] = f_b
68
+
69
+ print(f"### causal={causal}, headdim={headdim}, B={B}, seqlen={seqlen} ###")
70
+ for method in methods:
71
+ # time_f_b[config, method] = time_f[config, method] + time_b[config, method]
72
+ print(f"{method:>50} fwd + bwd:\t {time_f_b[config, method]*1000:>6.4f} ms ")
73
+
74
+ # speed_f[config, method] = efficiency(
75
+ # flops(B, seqlen, headdim, H, causal, mode="fwd"),
76
+ # time_f[config, method]
77
+ # )
78
+ # speed_b[config, method] = efficiency(
79
+ # flops(B, seqlen, headdim, H, causal, mode="bwd"),
80
+ # time_b[config, method]
81
+ # )
82
+ # speed_f_b[config, method] = efficiency(
83
+ # flops(B, seqlen, headdim, H, causal, mode="fwd_bwd"),
84
+ # time_f_b[config, method]
85
+ # )
86
+ # print(
87
+ # f"{method} fwd: {speed_f[config, method]:.2f} TFLOPs/s, "
88
+ # f"bwd: {speed_b[config, method]:.2f} TFLOPs/s, "
89
+ # f"fwd + bwd: {speed_f_b[config, method]:.2f} TFLOPs/s"
90
+ # )
91
+
92
+
93
+ # with open('flash2_attn_time.plk', 'wb') as fp:
94
+ # pickle.dump((speed_f, speed_b, speed_f_b), fp, protocol=pickle.HIGHEST_PROTOCOL)
upstream/flash-linear-attention/benchmarks/ops/benchmark_fla.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import torch
4
+ import triton
5
+
6
+ from fla.ops.based import parallel_based
7
+ from fla.ops.gla import fused_chunk_gla
8
+ from fla.ops.retention import fused_chunk_retention, parallel_retention
9
+
10
+ try:
11
+ from flash_attn import flash_attn_func
12
+ HAS_FLASH = True
13
+ except ImportError:
14
+ HAS_FLASH = False
15
+
16
+
17
+ @triton.testing.perf_report(
18
+ triton.testing.Benchmark(
19
+ # argument names to use as an x-axis for the plot
20
+ x_names=['T'],
21
+ # different possible values for `x_name`
22
+ x_vals=[128 * 2 ** i for i in range(0, 8)],
23
+ # argument name whose value corresponds to a different line in the plot
24
+ line_arg='provider',
25
+ # possible values for `line_arg``
26
+ line_vals=['retention_parallel', 'retention_fused_chunk',
27
+ 'gla_fused_chunk', 'based_parallel'] + (['flash'] if HAS_FLASH else []),
28
+ # label name for the lines
29
+ line_names=['retention_parallel_fwdbwd', 'retention_fused_chunk_fwdbwd',
30
+ 'gla_fused_chunk_fwdbwd', 'based_parallel_fwdbwd'] + (['flash_fwdbwd'] if HAS_FLASH else []),
31
+ # line styles
32
+ styles=[('green', '-'), ('blue', '--'), ('red', '-.'), ('cyan', ':')] + \
33
+ ([('yellow', 'dotted')] if HAS_FLASH else []),
34
+ ylabel="Execution Time (ms)", # label name for the y-axis
35
+ # name for the plot. Used also as a file name for saving the plot.
36
+ plot_name="Performance",
37
+ args={},
38
+ )
39
+ )
40
+ def benchmark(T, provider):
41
+ from fla.utils import device
42
+ dtype = torch.bfloat16
43
+ requires_grad = True
44
+ B, H, D = 16, 8, 128
45
+
46
+ if provider == 'flash':
47
+ q = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
48
+ k = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
49
+ v = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
50
+ elif "based" in provider:
51
+ q = torch.randn(B, H, T, 16, device=device, requires_grad=requires_grad, dtype=dtype)
52
+ k = torch.randn(B, H, T, 16, device=device, requires_grad=requires_grad, dtype=dtype)
53
+ v = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
54
+ elif "gla" in provider:
55
+ q = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
56
+ k = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
57
+ v = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
58
+ g = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
59
+ else:
60
+ q = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
61
+ k = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
62
+ v = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
63
+
64
+ do = torch.rand_like(v, dtype=dtype)
65
+
66
+ quantiles = [0.5, 0.2, 0.8]
67
+ results = 0, 0, 0
68
+ if provider == 'flash':
69
+ results = triton.testing.do_bench(lambda: flash_attn_func(q, k, v).backward(do), quantiles=quantiles)
70
+ elif provider == 'retention_parallel':
71
+ results = triton.testing.do_bench(lambda: parallel_retention(q, k, v).backward(do), quantiles=quantiles)
72
+ elif provider == 'retention_fused_chunk':
73
+ results = triton.testing.do_bench(lambda: fused_chunk_retention(q, k, v).backward(do), quantiles=quantiles)
74
+ elif provider == 'based_parallel':
75
+ results = triton.testing.do_bench(lambda: parallel_based(q, k, v).backward(do), quantiles=quantiles)
76
+ elif provider == 'gla_fused_chunk':
77
+ results = triton.testing.do_bench(lambda: fused_chunk_gla(q, k, v, g).backward(do), quantiles=quantiles)
78
+
79
+ return results
80
+
81
+
82
+ if __name__ == '__main__':
83
+ benchmark.run(print_data=True, show_plots=True)
upstream/flash-linear-attention/benchmarks/ops/benchmark_gla.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import torch
4
+ import triton
5
+ from torch.nn import functional as F
6
+
7
+ from fla.ops.gla import chunk_gla, fused_chunk_gla, fused_recurrent_gla
8
+ from fla.ops.retention import chunk_retention, parallel_retention
9
+ from fla.ops.retention.naive import naive_retention
10
+
11
+
12
+ @triton.testing.perf_report(
13
+ triton.testing.Benchmark(
14
+ # argument names to use as an x-axis for the plot
15
+ x_names=['T'],
16
+ # different possible values for `x_name`
17
+ x_vals=[128 * 2 ** i for i in range(0, 8)],
18
+ # argument name whose value corresponds to a different line in the plot
19
+ line_arg='provider',
20
+ # possible values for `line_arg``
21
+ line_vals=['fused_chunk_gla', 'recurrent_gla', 'chunk_gla', 'chunk_retention',
22
+ 'fused_chunk_gla_bwd', 'recurrent_gla_bwd', 'chunk_gla_bwd', 'chunk_retention_bwd'],
23
+ # label name for the lines
24
+ line_names=['fused_chunk_gla', 'recurrent_gla', 'chunk_gla', 'chunk_retention',
25
+ 'fused_chunk_gla_bwd', 'recurrent_gla_bwd', 'chunk_gla_bwd', 'chunk_retention_bwd'],
26
+ # line styles
27
+ styles=[('green', '-'), ('blue', '--'), ('red', '-.'),
28
+ ('cyan', ':'), ('yellow', 'dotted'), ('cyan', '--'), ('cyan', '-'), ('black', ':')],
29
+ ylabel="Execution Time (ms)", # label name for the y-axis
30
+ # name for the plot. Used also as a file name for saving the plot.
31
+ plot_name="Performance",
32
+ args={},
33
+ )
34
+ )
35
+ def benchmark(T, provider):
36
+ from fla.utils import device
37
+ dtype = torch.bfloat16
38
+ requires_grad = True
39
+ B, H, D = 16, 8, 128
40
+
41
+ q = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
42
+ k = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
43
+ g = F.logsigmoid(torch.randn(B, H, T, D, device=device, dtype=dtype)).clamp_min(-5).requires_grad_(requires_grad)
44
+ v = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
45
+
46
+ do = torch.ones_like(q, dtype=dtype)
47
+
48
+ quantiles = [0.5, 0.2, 0.8]
49
+ results = 0, 0, 0
50
+ if provider == 'torch':
51
+ if T > 2048:
52
+ return results
53
+ results = triton.testing.do_bench(lambda: naive_retention(q, k, v), quantiles=quantiles)
54
+ elif provider == 'recurrent_gla':
55
+ results = triton.testing.do_bench(lambda: fused_recurrent_gla(q, k, v, g), quantiles=quantiles)
56
+ elif provider == 'fused_chunk_gla':
57
+ results = triton.testing.do_bench(lambda: fused_chunk_gla(q, k, v, g), quantiles=quantiles)
58
+ elif provider == 'chunk_retention':
59
+ results = triton.testing.do_bench(lambda: chunk_retention(q, k, v), quantiles=quantiles)
60
+ elif provider == 'chunk_gla':
61
+ results = triton.testing.do_bench(lambda: chunk_gla(q, k, v, g), quantiles=quantiles)
62
+ elif provider == 'parallel':
63
+ results = triton.testing.do_bench(lambda: parallel_retention(q, k, v), quantiles=quantiles)
64
+ elif provider == 'torch_bwd':
65
+ if T > 2048:
66
+ return results
67
+ elif provider == 'chunk_retention_bwd':
68
+ results = triton.testing.do_bench(lambda: chunk_retention(q, k, v)[0].backward(do), quantiles=quantiles)
69
+ elif provider == 'recurrent_gla_bwd':
70
+ results = triton.testing.do_bench(lambda: fused_recurrent_gla(q, k, v, g)[0].backward(do), quantiles=quantiles)
71
+ elif provider == 'fused_chunk_gla_bwd':
72
+ results = triton.testing.do_bench(lambda: fused_chunk_gla(q, k, v, g)[0].backward(do), quantiles=quantiles)
73
+ elif provider == 'chunk_gla_bwd':
74
+ results = triton.testing.do_bench(lambda: chunk_gla(q, k, v, g)[0].backward(do), quantiles=quantiles)
75
+ elif provider == 'parallel_bwd':
76
+ results = triton.testing.do_bench(lambda: parallel_retention(q, k, v)[0].backward(do), quantiles=quantiles)
77
+ return results
78
+
79
+
80
+ if __name__ == '__main__':
81
+ benchmark.run(print_data=True)
upstream/flash-linear-attention/benchmarks/ops/benchmark_gsa.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import torch
4
+ import triton
5
+ from torch.nn import functional as F
6
+
7
+ from fla.ops.gla import chunk_gla
8
+ from fla.ops.gsa import chunk_gsa, fused_recurrent_gsa
9
+ from fla.ops.retention import chunk_retention
10
+
11
+ try:
12
+ from flash_attn import flash_attn_func
13
+ HAS_FLASH = True
14
+ except BaseException:
15
+ HAS_FLASH = False
16
+
17
+
18
+ @triton.testing.perf_report(
19
+ triton.testing.Benchmark(
20
+ # argument names to use as an x-axis for the plot
21
+ x_names=['T'],
22
+ # different possible values for `x_name`
23
+ x_vals=[128 * 2 ** i for i in range(0, 8)],
24
+ # argument name whose value corresponds to a different line in the plot
25
+ line_arg='provider',
26
+ # possible values for `line_arg``
27
+ line_vals=['gsa_recurrent', 'gsa_chunk', 'gla',
28
+ 'gsa_recurrent_bwd', 'gsa_chunk_bwd', 'gla_bwd', 'retention_bwd', 'flash_bwd'],
29
+ # label name for the lines
30
+ line_names=['gsa_recurrent', 'gsa_chunk', 'gla',
31
+ 'gsa_recurrent_bwd', 'gsa_chunk_bwd', 'gla_bwd', 'retention_bwd', 'flash_bwd'],
32
+ # line styles
33
+ styles=[('green', '-'), ('blue', '--'), ('red', '-.'),
34
+ ('cyan', ':'), ('yellow', 'dotted'), ('black', ':'), ('green', ':'), ('green', 'dotted'), ('green', ':')],
35
+ ylabel="Execution Time (ms)", # label name for the y-axis
36
+ # name for the plot. Used also as a file name for saving the plot.
37
+ plot_name="Performance",
38
+ args={},
39
+ )
40
+ )
41
+ def benchmark(T, provider):
42
+ from fla.utils import device
43
+ dtype = torch.bfloat16
44
+ requires_grad = True
45
+ B, H, D, M = 16, 4, 128, 64
46
+
47
+ q = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
48
+ k = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
49
+ v = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
50
+ if provider.startswith('gsa'):
51
+ f = F.logsigmoid(torch.randn(B, H, T, M, device=device, dtype=dtype))
52
+ s = (1 - f.exp()).to(f.dtype)
53
+ if provider.startswith('gla'):
54
+ g = F.logsigmoid(torch.randn(B, H, T, D, device=device, dtype=dtype))
55
+ g = g.clamp_min(-5).requires_grad_(requires_grad)
56
+ if provider.startswith('flash'):
57
+ q = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
58
+ k = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
59
+ v = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
60
+ do = torch.ones_like(v, dtype=dtype)
61
+
62
+ quantiles = [0.5, 0.2, 0.8]
63
+ if provider == 'gsa_recurrent':
64
+ return triton.testing.do_bench(lambda: fused_recurrent_gsa(q, k, v, s, f), quantiles=quantiles)
65
+ if provider == 'gsa_chunk':
66
+ return triton.testing.do_bench(lambda: chunk_gsa(q, k, v, s, f), quantiles=quantiles)
67
+ elif provider == 'gla':
68
+ return triton.testing.do_bench(lambda: chunk_gla(q, k, v, g), quantiles=quantiles)
69
+ elif provider == 'gsa_recurrent_bwd':
70
+ return triton.testing.do_bench(lambda: fused_recurrent_gsa(q, k, v, s, f)[0].backward(do), quantiles=quantiles)
71
+ elif provider == 'gsa_chunk_bwd':
72
+ return triton.testing.do_bench(lambda: chunk_gsa(q, k, v, s, f)[0].backward(do), quantiles=quantiles)
73
+ elif provider == 'gla_bwd':
74
+ return triton.testing.do_bench(lambda: chunk_gla(q, k, v, g)[0].backward(do), quantiles=quantiles)
75
+ elif provider == 'retention_bwd':
76
+ return triton.testing.do_bench(lambda: chunk_retention(q, k, v)[0].backward(do), quantiles=quantiles)
77
+ elif provider == 'flash_bwd':
78
+ return triton.testing.do_bench(lambda: flash_attn_func(q, k, v, causal=True).backward(do), quantiles=quantiles)
79
+
80
+
81
+ if __name__ == '__main__':
82
+ benchmark.run(print_data=True)
upstream/flash-linear-attention/benchmarks/ops/benchmark_hgrn.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import torch
4
+ import triton
5
+
6
+ from fla.ops.hgrn import chunk_hgrn, fused_recurrent_hgrn
7
+
8
+
9
+ @triton.testing.perf_report(
10
+ triton.testing.Benchmark(
11
+ # argument names to use as an x-axis for the plot
12
+ x_names=['T'],
13
+ # different possible values for `x_name`
14
+ x_vals=[128 * 2 ** i for i in range(0, 8)],
15
+ # argument name whose value corresponds to a different line in the plot
16
+ line_arg='provider',
17
+ # possible values for `line_arg``
18
+ line_vals=['chunk', 'recurrent', 'chunk_bwd', 'recurrent_bwd'],
19
+ # label name for the lines
20
+ line_names=['chunk', 'recurrent', 'chunk_bwd', 'recurrent_bwd'],
21
+ # line styles
22
+ styles=[('green', '-'), ('blue', '--'), ('red', '-.'), ('cyan', ':'), ('yellow', 'dotted'), ('black', 'dashed')],
23
+ ylabel="Execution Time (ms)", # label name for the y-axis
24
+ # name for the plot. Used also as a file name for saving the plot.
25
+ plot_name="Performance",
26
+ args={},
27
+ )
28
+ )
29
+ def benchmark(T, provider):
30
+ from fla.utils import device
31
+ dtype = torch.bfloat16
32
+ B, D = 16, 512
33
+
34
+ x = torch.randn((B, T, D), dtype=dtype, device=device)
35
+ g = torch.randn((B, T, D), dtype=dtype, device=device).sigmoid()
36
+ x = (1 - g) * x
37
+ x, g = (i.detach().clone().to(dtype).requires_grad_() for i in (x, g))
38
+ do = torch.randn_like(x, dtype=dtype)
39
+ quantiles = [0.5, 0.2, 0.8]
40
+ results = 0, 0, 0
41
+ if provider == 'chunk':
42
+ results = triton.testing.do_bench(lambda: chunk_hgrn(x, g), quantiles=quantiles)
43
+ if provider == 'recurrent':
44
+ results = triton.testing.do_bench(lambda: fused_recurrent_hgrn(x, g), quantiles=quantiles)
45
+ if provider == 'chunk_bwd':
46
+ results = triton.testing.do_bench(lambda: chunk_hgrn(x, g)[0].backward(do), quantiles=quantiles)
47
+ if provider == 'recurrent_bwd':
48
+ results = triton.testing.do_bench(lambda: fused_recurrent_hgrn(x, g)[0].backward(do), quantiles=quantiles)
49
+ return results
50
+
51
+
52
+ if __name__ == '__main__':
53
+ benchmark.run(print_data=True)
upstream/flash-linear-attention/benchmarks/ops/benchmark_nsa.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import torch
4
+ import triton
5
+ from flash_attn import flash_attn_func
6
+
7
+ from fla.ops.nsa import parallel_nsa
8
+
9
+
10
+ @triton.testing.perf_report(
11
+ triton.testing.Benchmark(
12
+ # argument names to use as an x-axis for the plot
13
+ x_names=['T'],
14
+ # different possible values for `x_name`
15
+ x_vals=[128 * 2 ** i for i in range(0, 8)],
16
+ # argument name whose value corresponds to a different line in the plot
17
+ line_arg='provider',
18
+ # possible values for `line_arg``
19
+ line_vals=['nsa', 'nsa_bwd', 'flash', 'flash_bwd'],
20
+ # label name for the lines
21
+ line_names=['nsa', 'nsa_bwd', 'flash', 'flash_bwd'],
22
+ # line styles
23
+ styles=[('green', '-'), ('blue', '-'), ('red', '-'), ('green', 'dotted'),
24
+ ('blue', 'dotted'), ('red', 'dotted'), ('cyan', '-'), ('cyan', 'dotted')],
25
+ ylabel="Execution Time (ms)", # label name for the y-axis
26
+ # name for the plot. Used also as a file name for saving the plot.
27
+ plot_name="Performance",
28
+ args={},
29
+ )
30
+ )
31
+ def benchmark(T, provider):
32
+ from fla.utils import device
33
+ dtype = torch.bfloat16
34
+ requires_grad = True
35
+ B, H, HQ, D, S = 4, 4, 64, 128, 16
36
+ block_size = 64
37
+
38
+ q = torch.randn(B, T, HQ, D, device=device, requires_grad=requires_grad, dtype=dtype)
39
+ k = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
40
+ v = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
41
+ do = torch.ones_like(q, dtype=dtype)
42
+
43
+ indices = torch.full((B, T, H, S), T, dtype=torch.long, device=device)
44
+ for b in range(B):
45
+ for t in range(T):
46
+ for h in range(H):
47
+ i_i = torch.randperm(max(1, triton.cdiv(t, block_size)))[:S]
48
+ indices[b, t, h, :len(i_i)] = i_i
49
+ indices = indices.sort(-1)[0]
50
+
51
+ quantiles = [0.5, 0.2, 0.8]
52
+ results = 0, 0, 0
53
+ if provider == 'nsa':
54
+ results = triton.testing.do_bench(
55
+ lambda: parallel_nsa(q, k, v, indices, block_size),
56
+ quantiles=quantiles
57
+ )
58
+ elif provider == 'nsa_bwd':
59
+ results = triton.testing.do_bench(
60
+ lambda: parallel_nsa(q, k, v, indices, block_size).backward(do),
61
+ quantiles=quantiles
62
+ )
63
+ elif provider == 'flash':
64
+ results = triton.testing.do_bench(
65
+ lambda: flash_attn_func(q, k, v, causal=True),
66
+ quantiles=quantiles
67
+ )
68
+ elif provider == 'flash_bwd':
69
+ results = triton.testing.do_bench(
70
+ lambda: flash_attn_func(q, k, v, causal=True).backward(do),
71
+ quantiles=quantiles
72
+ )
73
+ return results
74
+
75
+
76
+ if __name__ == '__main__':
77
+ benchmark.run(print_data=True, save_path='.')
upstream/flash-linear-attention/benchmarks/ops/benchmark_retention.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import os
4
+
5
+ import torch
6
+ import triton
7
+ from flash_attn import flash_attn_func
8
+
9
+ from fla.ops.retention import chunk_retention, parallel_retention
10
+
11
+
12
+ @triton.testing.perf_report(
13
+ triton.testing.Benchmark(
14
+ # argument names to use as an x-axis for the plot
15
+ x_names=['T'],
16
+ # different possible values for `x_name`
17
+ x_vals=[128 * 2 ** i for i in range(0, 8)],
18
+ # argument name whose value corresponds to a different line in the plot
19
+ line_arg='provider',
20
+ # possible values for `line_arg``
21
+ line_vals=['chunk', 'parallel', 'flash', 'chunk_bwd', 'parallel_bwd', 'flash_bwd'],
22
+ # label name for the lines
23
+ line_names=['chunk_fwd', 'parallel_fwd', 'flash_fwd', 'chunk_fwdbwd', 'parallel_fwdbwd', 'flash_fwdbwd'],
24
+ # line styles
25
+ styles=[('green', '-'), ('blue', '-'), ('red', '-'), ('green', 'dotted'), ('blue', 'dotted'), ('red', 'dotted')],
26
+ ylabel="Execution Time (ms)", # label name for the y-axis
27
+ # name for the plot. Used also as a file name for saving the plot.
28
+ plot_name="Performance",
29
+ args={},
30
+ )
31
+ )
32
+ def benchmark(T, provider):
33
+ from fla.utils import device
34
+ dtype = torch.bfloat16
35
+ requires_grad = True
36
+ B, H, D = 4, 8, 256
37
+ os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
38
+
39
+ if provider == 'flash' or provider == 'flash_bwd':
40
+ q = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
41
+ k = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
42
+ v = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
43
+ else:
44
+ q = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
45
+ k = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
46
+ v = torch.randn(B, H, T, D, device=device, requires_grad=requires_grad, dtype=dtype)
47
+ do = torch.ones_like(q, dtype=dtype)
48
+
49
+ quantiles = [0.5, 0.2, 0.8]
50
+ results = 0, 0, 0
51
+ if provider == 'chunk':
52
+ results = triton.testing.do_bench(lambda: chunk_retention(q, k, v), quantiles=quantiles)
53
+ elif provider == 'parallel':
54
+ results = triton.testing.do_bench(lambda: parallel_retention(q, k, v), quantiles=quantiles)
55
+ elif provider == 'flash':
56
+ results = triton.testing.do_bench(lambda: flash_attn_func(q, k, v, causal=True), quantiles=quantiles)
57
+ elif provider == 'chunk_bwd':
58
+ results = triton.testing.do_bench(lambda: chunk_retention(q, k, v)[0].backward(do), quantiles=quantiles)
59
+ elif provider == 'parallel_bwd':
60
+ results = triton.testing.do_bench(lambda: parallel_retention(q, k, v)[0].backward(do), quantiles=quantiles)
61
+ elif provider == 'flash_bwd':
62
+ results = triton.testing.do_bench(lambda: flash_attn_func(q, k, v, causal=True).backward(do), quantiles=quantiles)
63
+ return results
64
+
65
+
66
+ if __name__ == '__main__':
67
+ benchmark.run(print_data=True, save_path='.')
upstream/flash-linear-attention/benchmarks/ops/benchmark_rwkv.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import os
4
+
5
+ import torch
6
+ import triton
7
+ from torch.nn import functional as F
8
+
9
+ from fla.ops.gla import chunk_gla
10
+ from fla.ops.retention import chunk_retention
11
+ from fla.ops.rwkv6 import chunk_rwkv6
12
+ from fla.ops.rwkv7 import chunk_rwkv7
13
+
14
+ try:
15
+ from flash_attn import flash_attn_func
16
+ HAS_FLASH = True
17
+ except BaseException:
18
+ HAS_FLASH = False
19
+
20
+
21
+ @triton.testing.perf_report(
22
+ triton.testing.Benchmark(
23
+ # argument names to use as an x-axis for the plot
24
+ x_names=['T'],
25
+ # different possible values for `x_name`
26
+ x_vals=[128 * 2 ** i for i in range(0, 8)],
27
+ # argument name whose value corresponds to a different line in the plot
28
+ line_arg='provider',
29
+ # possible values for `line_arg``
30
+ # line styles
31
+ line_vals=['rwkv6', 'rwkv7', 'gla', 'flash', 'rwkv6_bwd', 'rwkv7_bwd', 'gla_bwd', 'retention_bwd', 'flash_bwd'],
32
+ # label name for the lines
33
+ line_names=['rwkv6', 'rwkv7', 'gla', 'flash', 'rwkv6_bwd', 'rwkv7_bwd', 'gla_bwd', 'retention_bwd', 'flash_bwd'],
34
+ # # line styles
35
+ styles=[
36
+ ('green', '-'), # rwkv6
37
+ ('blue', '--'), # rwkv7
38
+ ('red', '-.'), # gla
39
+ ('cyan', ':'), # rwkv6_bwd
40
+ ('magenta', '-'), # rwkv7_bwd
41
+ ('yellow', 'dotted'), # gla_bwd
42
+ ('black', ':'), # retention_bwd
43
+ ('gray', ':'), # flash
44
+ ('gray', '--') # flash_bwd
45
+ ],
46
+ ylabel="Execution Time (ms)", # label name for the y-axis
47
+ # name for the plot. Used also as a file name for saving the plot.
48
+ plot_name="Performance",
49
+ args={},
50
+ )
51
+ )
52
+ def benchmark(T, provider):
53
+ from fla.utils import device
54
+ dtype = torch.bfloat16
55
+ requires_grad = True
56
+ # Read B, H, D from environment variables, default to 16, 8, 128 if not set
57
+ B = int(os.getenv('BENCH_B', '8')) # Batch size
58
+ H = int(os.getenv('BENCH_H', '64')) # Number of heads
59
+ D = int(os.getenv('BENCH_D', '64')) # Dimension per head
60
+ with torch.no_grad():
61
+ q = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
62
+ k = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
63
+ v = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
64
+ if provider.startswith('flash'):
65
+ q = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
66
+ k = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
67
+ v = torch.randn(B, T, H, D, device=device, requires_grad=requires_grad, dtype=dtype)
68
+ if provider.startswith('gla'):
69
+ g = F.logsigmoid(torch.randn(B, T, H, D, device=device, dtype=dtype))
70
+ g = g.clamp_min(-5).requires_grad_(requires_grad)
71
+ if provider.startswith('rwkv6'):
72
+ w = F.logsigmoid(torch.randn(B, T, H, D, device=device, dtype=dtype)).requires_grad_(True)
73
+ u = torch.randn(H, D, device=device, dtype=dtype).requires_grad_(True)
74
+ if provider.startswith('rwkv7'):
75
+ q = torch.empty(B, T, H, D, device=device).uniform_(-1, 1).to(dtype=dtype).requires_grad_(True)
76
+ k = torch.empty(B, T, H, D, device=device).uniform_(-1, 1).to(dtype=dtype).requires_grad_(True)
77
+ v = torch.empty(B, T, H, D, device=device).uniform_(-1, 1).to(dtype=dtype).requires_grad_(True)
78
+ w = F.logsigmoid(torch.randn(B, T, H, D, device=device, dtype=dtype)).requires_grad_(True)
79
+ kk = torch.empty(B, T, H, D, device=device).uniform_(-1, 1)
80
+ kk = torch.nn.functional.normalize(kk, dim=-1).to(dtype=dtype)
81
+
82
+ a = -kk.clone().requires_grad_(True) # -kk
83
+ a_scale = torch.empty(B, T, H, D, device=device).uniform_(0, 0.1).to(dtype=dtype)
84
+ b = (kk * a_scale).requires_grad_(True) # kk*a
85
+
86
+ do = torch.ones_like(v, dtype=dtype)
87
+
88
+ quantiles = [0.5, 0.2, 0.8]
89
+ if provider == 'rwkv6':
90
+ results = triton.testing.do_bench(lambda: chunk_rwkv6(q, k, v, w, u), quantiles=quantiles)
91
+ elif provider == 'rwkv7':
92
+ results = triton.testing.do_bench(lambda: chunk_rwkv7(q, w, k, v, a, b), quantiles=quantiles)
93
+ elif provider == 'gla':
94
+ results = triton.testing.do_bench(lambda: chunk_gla(q, k, v, g), quantiles=quantiles)
95
+ elif provider == 'rwkv6_bwd':
96
+ results = triton.testing.do_bench(lambda: chunk_rwkv6(q, k, v, w, u)[0].backward(do), quantiles=quantiles)
97
+ elif provider == 'rwkv7_bwd':
98
+ results = triton.testing.do_bench(lambda: chunk_rwkv7(q, w, k, v, a, b)[0].backward(do), quantiles=quantiles)
99
+ elif provider == 'gla_bwd':
100
+ results = triton.testing.do_bench(lambda: chunk_gla(q, k, v, g)[0].backward(do), quantiles=quantiles)
101
+ elif provider == 'retention_bwd':
102
+ results = triton.testing.do_bench(lambda: chunk_retention(q, k, v)[0].backward(do), quantiles=quantiles)
103
+ elif provider == 'flash':
104
+ results = triton.testing.do_bench(lambda: flash_attn_func(q, k, v, causal=True), quantiles=quantiles)
105
+ elif provider == 'flash_bwd':
106
+ results = triton.testing.do_bench(lambda: flash_attn_func(q, k, v, causal=True).backward(do), quantiles=quantiles)
107
+ return results
108
+
109
+
110
+ if __name__ == '__main__':
111
+ benchmark.run(print_data=True)
upstream/flash-linear-attention/benchmarks/ops/benchmark_titans.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Install the newest triton version with
2
+ # pip install "git+https://github.com/openai/triton.git#egg=triton&subdirectory=python"
3
+
4
+ import torch
5
+ from benchmark import benchmark_backward, benchmark_combined, benchmark_forward
6
+ from torch.nn import functional as F
7
+
8
+ from fla.ops.titans.naive import chunk_titans_linear_ref
9
+
10
+ # from flash_attn import flash_attn_func
11
+
12
+
13
+ def time_fwd(func, *args, **kwargs):
14
+ time_fb = benchmark_forward(func, *args, **kwargs)
15
+ return time_fb[1].mean
16
+
17
+
18
+ def time_fwd_bwd(func, *args, **kwargs):
19
+ time_fb = benchmark_combined(func, *args, **kwargs)
20
+ return time_fb[1].mean
21
+
22
+
23
+ def time_bwd(func, *args, **kwargs):
24
+ time_fb = benchmark_backward(func, *args, **kwargs)
25
+ return time_fb[1].mean
26
+
27
+
28
+ repeats = 256
29
+ device = "cuda"
30
+ dtype = torch.bfloat16
31
+
32
+ bs_seqlen_vals = [(2, 1024), (2, 2048)]
33
+ causal_vals = [True]
34
+ headdim_vals = [4, 8]
35
+ dim = 16
36
+ dropout_p = 0.0
37
+
38
+ methods = ["naive_titans", "chunk_titans"]
39
+ time_f = {}
40
+ time_b = {}
41
+ time_f_b = {}
42
+ speed_f = {}
43
+ speed_b = {}
44
+ speed_f_b = {}
45
+ for causal in causal_vals:
46
+ for headdim in headdim_vals:
47
+ for B, seqlen in bs_seqlen_vals:
48
+ config = (causal, headdim, B, seqlen)
49
+ H = dim // headdim
50
+
51
+ q = torch.randn(
52
+ B, H, seqlen, headdim, device=device, requires_grad=True, dtype=dtype
53
+ )
54
+ k = F.normalize(
55
+ torch.randn(B, H, seqlen, headdim, device=device, dtype=dtype),
56
+ p=2,
57
+ dim=-1,
58
+ ).requires_grad_(True)
59
+ v = torch.randn(
60
+ B, H, seqlen, headdim, device=device, requires_grad=True, dtype=dtype
61
+ )
62
+ w = torch.randn(H, headdim, device=device, requires_grad=True, dtype=dtype)
63
+ b = torch.randn(H, headdim, device=device, requires_grad=True, dtype=dtype)
64
+ theta = torch.rand(
65
+ B, H, seqlen, 1, dtype=dtype, device=device, requires_grad=True
66
+ )
67
+ alpha = torch.rand(
68
+ B, H, seqlen, 1, dtype=dtype, device=device, requires_grad=True
69
+ )
70
+ eta = torch.rand(
71
+ B, H, seqlen, 1, dtype=dtype, device=device, requires_grad=True
72
+ )
73
+ o2, _ = chunk_titans_linear_ref(
74
+ q, k, v, w, b, theta, alpha, eta, chunk_size=16, use_chunk=False
75
+ )
76
+ o2.sum().backward(retain_graph=True)
77
+ f_b = time_fwd_bwd(
78
+ chunk_titans_linear_ref,
79
+ q,
80
+ k,
81
+ v,
82
+ w,
83
+ b,
84
+ theta,
85
+ alpha,
86
+ eta,
87
+ use_chunk=False,
88
+ verbose=False,
89
+ )
90
+ time_f_b[config, "naive_titans"] = f_b
91
+
92
+ o3, _ = chunk_titans_linear_ref(
93
+ q, k, v, w, b, theta, alpha, eta, chunk_size=16, use_chunk=True
94
+ )
95
+ o3.sum().backward(retain_graph=True)
96
+ f_b = time_fwd_bwd(
97
+ chunk_titans_linear_ref,
98
+ q,
99
+ k,
100
+ v,
101
+ w,
102
+ b,
103
+ theta,
104
+ alpha,
105
+ eta,
106
+ chunk_size=16,
107
+ use_chunk=True,
108
+ verbose=False,
109
+ )
110
+ time_f_b[config, "chunk_titans"] = f_b
111
+
112
+ print(f"### causal={causal}, headdim={headdim}, B={B}, seqlen={seqlen} ###")
113
+ for method in methods:
114
+ # time_f_b[config, method] = time_f[config, method] + time_b[config, method]
115
+ print(
116
+ f"{method:>50} fwd + bwd:\t {time_f_b[config, method] * 1000:>6.4f} ms "
117
+ )
118
+
119
+ # speed_f[config, method] = efficiency(
120
+ # flops(B, seqlen, headdim, H, causal, mode="fwd"),
121
+ # time_f[config, method]
122
+ # )
123
+ # speed_b[config, method] = efficiency(
124
+ # flops(B, seqlen, headdim, H, causal, mode="bwd"),
125
+ # time_b[config, method]
126
+ # )
127
+ # speed_f_b[config, method] = efficiency(
128
+ # flops(B, seqlen, headdim, H, causal, mode="fwd_bwd"),
129
+ # time_f_b[config, method]
130
+ # )
131
+ # print(
132
+ # f"{method} fwd: {speed_f[config, method]:.2f} TFLOPs/s, "
133
+ # f"bwd: {speed_b[config, method]:.2f} TFLOPs/s, "
134
+ # f"fwd + bwd: {speed_f_b[config, method]:.2f} TFLOPs/s"
135
+ # )
136
+
137
+ # with open('flash2_attn_time.plk', 'wb') as fp:
138
+ # pickle.dump((speed_f, speed_b, speed_f_b), fp, protocol=pickle.HIGHEST_PROTOCOL)
upstream/flash-linear-attention/benchmarks/ops/benchmark_ttt.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Install the newest triton version with
2
+ # pip install "git+https://github.com/openai/triton.git#egg=triton&subdirectory=python"
3
+
4
+ import torch
5
+ from benchmark import benchmark_backward, benchmark_combined, benchmark_forward
6
+ from torch.nn import functional as F
7
+
8
+ from fla.ops.delta_rule import chunk_delta_rule
9
+ from fla.ops.gla import chunk_gla
10
+ from fla.ops.ttt import chunk_ttt_linear, fused_chunk_ttt_linear
11
+ from fla.utils import device
12
+
13
+ # from flash_attn import flash_attn_func
14
+
15
+
16
+ def time_fwd(func, *args, **kwargs):
17
+ time_fb = benchmark_forward(func, *args, **kwargs)
18
+ return time_fb[1].mean
19
+
20
+
21
+ def time_fwd_bwd(func, *args, **kwargs):
22
+ time_fb = benchmark_combined(func, *args, **kwargs)
23
+ return time_fb[1].mean
24
+
25
+
26
+ def time_bwd(func, *args, **kwargs):
27
+ time_fb = benchmark_backward(func, *args, **kwargs)
28
+ return time_fb[1].mean
29
+
30
+
31
+ repeats = 256
32
+
33
+
34
+ dtype = torch.bfloat16
35
+
36
+
37
+ bs_seqlen_vals = [(8, 2048), (4, 4096), (2, 8192)]
38
+ causal_vals = [True]
39
+ # headdim_vals = [64, 128]
40
+ headdim_vals = [64,]
41
+ dim = 2048
42
+ dropout_p = 0.0
43
+
44
+
45
+ methods = (["chunk_gla", "chunk_delta_rule", "chunk_ttt_linear", "fused_chunk_ttt_linear"])
46
+ time_f = {}
47
+ time_b = {}
48
+ time_f_b = {}
49
+ speed_f = {}
50
+ speed_b = {}
51
+ speed_f_b = {}
52
+ for causal in causal_vals:
53
+ for headdim in headdim_vals:
54
+ for B, seqlen in bs_seqlen_vals:
55
+ config = (causal, headdim, B, seqlen)
56
+ H = dim // headdim
57
+ q = torch.randn(B, H, seqlen, headdim, device=device, requires_grad=True, dtype=dtype)
58
+ k = torch.randn(B, H, seqlen, headdim, device=device, requires_grad=True, dtype=dtype)
59
+ v = torch.randn(B, H, seqlen, headdim, device=device, requires_grad=True, dtype=dtype)
60
+ g = torch.randn(B, H, seqlen, headdim, device=device, dtype=dtype).sigmoid().requires_grad_(True) / 16
61
+ o1, _ = chunk_gla(q, k, v, g)
62
+ o1.sum().backward(retain_graph=True)
63
+ f_b = time_fwd_bwd(
64
+ chunk_gla, q, k, v, g, verbose=False
65
+ )
66
+ time_f_b[config, "chunk_gla"] = f_b
67
+
68
+ q = torch.randn(B, H, seqlen, headdim, device=device, requires_grad=True, dtype=dtype)
69
+ k = F.normalize(torch.randn(B, H, seqlen, headdim, device=device, dtype=dtype), p=2, dim=-1).requires_grad_(True)
70
+ v = torch.randn(B, H, seqlen, headdim, device=device, requires_grad=True, dtype=dtype)
71
+ beta = torch.rand(B, H, seqlen, device=device, dtype=dtype).sigmoid().requires_grad_(True)
72
+ o2, _ = chunk_delta_rule(q, k, v, beta)
73
+ o2.sum().backward(retain_graph=True)
74
+ f_b = time_fwd_bwd(
75
+ chunk_delta_rule, q, k, v, beta, verbose=False
76
+ )
77
+ time_f_b[config, "chunk_delta_rule"] = f_b
78
+
79
+ q = torch.randn(B, H, seqlen, headdim, device=device, requires_grad=True, dtype=dtype)
80
+ k = F.normalize(torch.randn(B, H, seqlen, headdim, device=device, dtype=dtype), p=2, dim=-1).requires_grad_(True)
81
+ v = torch.randn(B, H, seqlen, headdim, device=device, requires_grad=True, dtype=dtype)
82
+ w = torch.randn(H, headdim, device=device, requires_grad=True, dtype=dtype)
83
+ b = torch.randn(H, headdim, device=device, requires_grad=True, dtype=dtype)
84
+ eta = torch.rand(B, H, seqlen, 1, device=device, requires_grad=True, dtype=dtype) * 5e-3
85
+ o3, _, _ = chunk_ttt_linear(q, k, v, w, b, eta, chunk_size=16)
86
+ o3.sum().backward(retain_graph=True)
87
+ f_b = time_fwd_bwd(
88
+ chunk_ttt_linear, q, k, v, w, b, eta, chunk_size=16, verbose=False
89
+ )
90
+ time_f_b[config, "chunk_ttt_linear"] = f_b
91
+
92
+ q = torch.randn(B, H, seqlen, headdim, device=device, requires_grad=True, dtype=dtype)
93
+ k = F.normalize(torch.randn(B, H, seqlen, headdim, device=device, dtype=dtype), p=2, dim=-1).requires_grad_(True)
94
+ v = torch.randn(B, H, seqlen, headdim, device=device, requires_grad=True, dtype=dtype)
95
+ w = torch.randn(H, headdim, device=device, requires_grad=True, dtype=dtype)
96
+ b = torch.randn(H, headdim, device=device, requires_grad=True, dtype=dtype)
97
+ eta = torch.rand(B, H, seqlen, 1, device=device, requires_grad=True, dtype=dtype) * 5e-3
98
+ o4, _, _ = fused_chunk_ttt_linear(q, k, v, w, b, eta, chunk_size=16)
99
+ o4.sum().backward(retain_graph=True)
100
+ f_b = time_fwd_bwd(
101
+ fused_chunk_ttt_linear, q, k, v, w, b, eta, chunk_size=16, verbose=False
102
+ )
103
+ time_f_b[config, "fused_chunk_ttt_linear"] = f_b
104
+
105
+ print(f"### causal={causal}, headdim={headdim}, B={B}, seqlen={seqlen} ###")
106
+ for method in methods:
107
+ # time_f_b[config, method] = time_f[config, method] + time_b[config, method]
108
+ print(f"{method:>50} fwd + bwd:\t {time_f_b[config, method]*1000:>6.4f} ms ")
109
+
110
+ # speed_f[config, method] = efficiency(
111
+ # flops(B, seqlen, headdim, H, causal, mode="fwd"),
112
+ # time_f[config, method]
113
+ # )
114
+ # speed_b[config, method] = efficiency(
115
+ # flops(B, seqlen, headdim, H, causal, mode="bwd"),
116
+ # time_b[config, method]
117
+ # )
118
+ # speed_f_b[config, method] = efficiency(
119
+ # flops(B, seqlen, headdim, H, causal, mode="fwd_bwd"),
120
+ # time_f_b[config, method]
121
+ # )
122
+ # print(
123
+ # f"{method} fwd: {speed_f[config, method]:.2f} TFLOPs/s, "
124
+ # f"bwd: {speed_b[config, method]:.2f} TFLOPs/s, "
125
+ # f"fwd + bwd: {speed_f_b[config, method]:.2f} TFLOPs/s"
126
+ # )
127
+
128
+
129
+ # with open('flash2_attn_time.plk', 'wb') as fp:
130
+ # pickle.dump((speed_f, speed_b, speed_f_b), fp, protocol=pickle.HIGHEST_PROTOCOL)