Skip to content

Commit 63dc595

Browse files
committed
add liveness analysis demo
1 parent 62a1ecc commit 63dc595

File tree

6 files changed

+591
-17
lines changed

6 files changed

+591
-17
lines changed

.github/workflows/test.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ jobs:
7575
7676
python examples/mwe.py
7777
python examples/flash_attention.py
78+
python examples/liveness_analysis.py
7879
7980
test-other-host-bindings:
8081

examples/liveness_analysis.py

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
from mlir import ir
2+
from pathlib import Path
3+
4+
import mlir.extras.types as T
5+
import numpy as np
6+
from mlir.ir import InsertionPoint, IntegerAttr, UnitAttr
7+
8+
from mlir.extras.ast.canonicalize import canonicalize
9+
from mlir.extras.context import RAIIMLIRContextModule
10+
from mlir.extras.dialects.ext import memref, scf, arith, gpu, llvm
11+
from mlir.dialects import math
12+
13+
# noinspection PyUnresolvedReferences
14+
from mlir.extras.dialects.ext.gpu import (
15+
block_idx,
16+
thread_idx,
17+
grid_dim,
18+
func as gpu_func,
19+
set_container_module,
20+
module,
21+
get_compile_object_bytes,
22+
)
23+
from mlir.extras.runtime.passes import run_pipeline, Pipeline
24+
from mlir.extras.util import find_ops, walk_blocks_in_operation, walk_operations
25+
from mlir.extras.util.liveness import BlockInfoBuilder, Liveness
26+
27+
# just so it doesn't get DCE'd by black/reformat
28+
# TypeError: 'mlir._mlir_libs._mlir.ir.BlockArgument' object is not subscriptable
29+
_ = memref
30+
31+
ctx = RAIIMLIRContextModule()
32+
set_container_module(ctx.module)
33+
34+
35+
# just a default attr - actual target is set blow
36+
@module("kernels", [f'#rocdl.target<abi = "500">'])
37+
def gpu_module():
38+
pass
39+
40+
41+
ip = InsertionPoint.at_block_begin(gpu_module.regions[0].blocks[0])
42+
ip.__enter__()
43+
44+
Bc = 32
45+
Br = 32
46+
47+
B = 16
48+
nh = 12
49+
N = 128
50+
d = 128
51+
52+
softmax_scale = 1.0 / float(np.sqrt(d))
53+
54+
55+
rank_reduce = memref.rank_reduce
56+
57+
58+
# https://github.com/tspeterkim/flash-attention-minimal/blob/main/flash.cu
59+
@gpu_func(emit=True)
60+
@canonicalize(using=[scf.canonicalizer, arith.canonicalizer])
61+
def flash_attention(
62+
Q: T.memref(B, nh, N, d, T.f32()),
63+
K: T.memref(B, nh, N, d, T.f32()),
64+
V: T.memref(B, nh, N, d, T.f32()),
65+
l: T.memref(B, nh, N, T.f32()),
66+
m: T.memref(B, nh, N, T.f32()),
67+
O: T.memref(B, nh, N, d, T.f32()),
68+
):
69+
tx = thread_idx.x
70+
# batch idx, head_idx
71+
bx, by = block_idx.x, block_idx.y
72+
# gpu.printf("bx %ld, by %ld\n", bx, by)
73+
74+
# Offset into Q,K,V,O,l,m - different for each batch and head
75+
K = K[bx, by, :, :, rank_reduce]
76+
V = V[bx, by, :, :, rank_reduce]
77+
Q = Q[bx, by, :, :, rank_reduce]
78+
O = O[bx, by, :, :, rank_reduce]
79+
l = l[bx, by, :, rank_reduce]
80+
m = m[bx, by, :, rank_reduce]
81+
82+
# Define SRAM for Q,K,V,S
83+
sram = gpu.dynamic_shared_memory()
84+
Qi = memref.view(sram, (Br, d), dtype=T.f32())
85+
Kj = memref.view(sram, (Bc, d), dtype=T.f32(), shift=Qi.n_elements)
86+
Vj = memref.view(sram, (Bc, d), dtype=T.f32(), shift=Qi.n_elements + Kj.n_elements)
87+
S = memref.view(
88+
sram,
89+
(Br, Bc),
90+
dtype=T.f32(),
91+
shift=Qi.n_elements + Kj.n_elements + Vj.n_elements,
92+
)
93+
94+
for bc in scf.range_(0, N, Bc):
95+
# Load Kj, Vj to SRAM
96+
K_ = K[bc : bc + 1, :]
97+
V_ = V[bc : bc + 1, :]
98+
for x in scf.range_(0, d):
99+
Kj[tx, x] = K_[tx, x]
100+
Vj[tx, x] = V_[tx, x]
101+
102+
for br in scf.range_(0, N, Br):
103+
# Load Qi to SRAM, l and m to registers
104+
Q_ = Q[br : br + 1, :]
105+
for x in scf.range_(0, d):
106+
Qi[tx, x] = Q_[tx, x]
107+
108+
l_ = l[br : br + 1]
109+
m_ = m[br : br + 1]
110+
row_l_prev = l_[tx]
111+
row_m_prev = m_[tx]
112+
113+
# S = QK^T, row_m = rowmax(S)
114+
row_m: T.f32() = float(np.finfo(np.float32).min)
115+
for y, row_m, _ in scf.range_(0, Bc, iter_args=[row_m]):
116+
sum: T.f32() = 0.0
117+
for x, sum, _ in scf.range_(0, d, iter_args=[sum]):
118+
sum += Qi[tx, x] * Kj[y, x]
119+
sum = yield sum
120+
121+
sum *= softmax_scale
122+
S[tx, y] = sum
123+
124+
if sum > row_m:
125+
row_m_ = yield sum
126+
else:
127+
row_m_ = yield row_m
128+
129+
row_m = yield row_m_
130+
131+
# P = exp(S - row_m), row_l = rowsum(P)
132+
row_l: T.f32() = 0.0
133+
for y, row_l, _ in scf.range_(0, Bc, iter_args=[row_l]):
134+
S[tx, y] = math.exp(S[tx, y] - row_m)
135+
row_l += S[tx, y]
136+
row_l = yield row_l
137+
138+
# Compute new m and l
139+
row_m_new = arith.maximumf(row_m_prev, row_m)
140+
row_l_new = (
141+
math.exp(row_m_prev - row_m_new) * row_l_prev
142+
+ math.exp(row_m - row_m_new) * row_l
143+
)
144+
div = 1.0 / row_l_new
145+
f1 = row_l_prev * math.exp(row_m_prev - row_m_new)
146+
f2 = math.exp(row_m - row_m_new)
147+
148+
# Write O, l, m to HBM
149+
O_ = O[br : br + 1, :]
150+
for x in scf.range_(0, d):
151+
pv: T.f32() = 0.0 # Pij * Vj
152+
for y, pv, _ in scf.range_(0, Bc, iter_args=[pv]):
153+
pv += S[tx, y] * Vj[y, x]
154+
pv = yield pv
155+
156+
O_[tx, x] = div * (f1 * O_[tx, x] + f2 * pv)
157+
158+
l_[tx] = row_l_new
159+
m_[tx] = row_m_new
160+
161+
gpu.barrier()
162+
163+
164+
ip.__exit__(None, None, None)
165+
166+
assert gpu_module.operation.verify()
167+
l = Liveness(gpu_module)
168+
print(l)

mlir/extras/util/__init__.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from .util import *
2+
from .util import (
3+
_get_previous_frame_idents,
4+
_get_sym_name,
5+
_update_caller_vars,
6+
_unpack_sizes_element_type,
7+
)

0 commit comments

Comments
 (0)