Skip to content

Commit 82281ad

Browse files
committed
add liveness analysis demo
1 parent 62a1ecc commit 82281ad

File tree

6 files changed

+351
-17
lines changed

6 files changed

+351
-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: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
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+
def softmax(x, axis=None):
56+
x_max = np.amax(x, axis=axis, keepdims=True)
57+
exp_x_shifted = np.exp(x - x_max)
58+
return exp_x_shifted / np.sum(exp_x_shifted, axis=axis, keepdims=True)
59+
60+
61+
def manual_attn(q, k, v):
62+
att = q @ k.transpose(0, 1, 3, 2) * (1.0 / float(np.sqrt(k.shape[-1])))
63+
att = softmax(att, axis=-1)
64+
y = att @ v
65+
return y
66+
67+
68+
rank_reduce = memref.rank_reduce
69+
70+
71+
# https://github.com/tspeterkim/flash-attention-minimal/blob/main/flash.cu
72+
@gpu_func(emit=True)
73+
@canonicalize(using=[scf.canonicalizer, arith.canonicalizer])
74+
def flash_attention(
75+
Q: T.memref(B, nh, N, d, T.f32()),
76+
K: T.memref(B, nh, N, d, T.f32()),
77+
V: T.memref(B, nh, N, d, T.f32()),
78+
l: T.memref(B, nh, N, T.f32()),
79+
m: T.memref(B, nh, N, T.f32()),
80+
O: T.memref(B, nh, N, d, T.f32()),
81+
):
82+
tx = thread_idx.x
83+
# batch idx, head_idx
84+
bx, by = block_idx.x, block_idx.y
85+
# gpu.printf("bx %ld, by %ld\n", bx, by)
86+
87+
# Offset into Q,K,V,O,l,m - different for each batch and head
88+
K = K[bx, by, :, :, rank_reduce]
89+
V = V[bx, by, :, :, rank_reduce]
90+
Q = Q[bx, by, :, :, rank_reduce]
91+
O = O[bx, by, :, :, rank_reduce]
92+
l = l[bx, by, :, rank_reduce]
93+
m = m[bx, by, :, rank_reduce]
94+
95+
# Define SRAM for Q,K,V,S
96+
sram = gpu.dynamic_shared_memory()
97+
Qi = memref.view(sram, (Br, d), dtype=T.f32())
98+
Kj = memref.view(sram, (Bc, d), dtype=T.f32(), shift=Qi.n_elements)
99+
Vj = memref.view(sram, (Bc, d), dtype=T.f32(), shift=Qi.n_elements + Kj.n_elements)
100+
S = memref.view(
101+
sram,
102+
(Br, Bc),
103+
dtype=T.f32(),
104+
shift=Qi.n_elements + Kj.n_elements + Vj.n_elements,
105+
)
106+
107+
for bc in scf.range_(0, N, Bc):
108+
# Load Kj, Vj to SRAM
109+
K_ = K[bc : bc + 1, :]
110+
V_ = V[bc : bc + 1, :]
111+
for x in scf.range_(0, d):
112+
Kj[tx, x] = K_[tx, x]
113+
Vj[tx, x] = V_[tx, x]
114+
115+
for br in scf.range_(0, N, Br):
116+
# Load Qi to SRAM, l and m to registers
117+
Q_ = Q[br : br + 1, :]
118+
for x in scf.range_(0, d):
119+
Qi[tx, x] = Q_[tx, x]
120+
121+
l_ = l[br : br + 1]
122+
m_ = m[br : br + 1]
123+
row_l_prev = l_[tx]
124+
row_m_prev = m_[tx]
125+
126+
# S = QK^T, row_m = rowmax(S)
127+
row_m: T.f32() = float(np.finfo(np.float32).min)
128+
for y, row_m, _ in scf.range_(0, Bc, iter_args=[row_m]):
129+
sum: T.f32() = 0.0
130+
for x, sum, _ in scf.range_(0, d, iter_args=[sum]):
131+
sum += Qi[tx, x] * Kj[y, x]
132+
sum = yield sum
133+
134+
sum *= softmax_scale
135+
S[tx, y] = sum
136+
137+
if sum > row_m:
138+
row_m_ = yield sum
139+
else:
140+
row_m_ = yield row_m
141+
142+
row_m = yield row_m_
143+
144+
# P = exp(S - row_m), row_l = rowsum(P)
145+
row_l: T.f32() = 0.0
146+
for y, row_l, _ in scf.range_(0, Bc, iter_args=[row_l]):
147+
S[tx, y] = math.exp(S[tx, y] - row_m)
148+
row_l += S[tx, y]
149+
row_l = yield row_l
150+
151+
# Compute new m and l
152+
row_m_new = arith.maximumf(row_m_prev, row_m)
153+
row_l_new = (
154+
math.exp(row_m_prev - row_m_new) * row_l_prev
155+
+ math.exp(row_m - row_m_new) * row_l
156+
)
157+
div = 1.0 / row_l_new
158+
f1 = row_l_prev * math.exp(row_m_prev - row_m_new)
159+
f2 = math.exp(row_m - row_m_new)
160+
161+
# Write O, l, m to HBM
162+
O_ = O[br : br + 1, :]
163+
for x in scf.range_(0, d):
164+
pv: T.f32() = 0.0 # Pij * Vj
165+
for y, pv, _ in scf.range_(0, Bc, iter_args=[pv]):
166+
pv += S[tx, y] * Vj[y, x]
167+
pv = yield pv
168+
169+
O_[tx, x] = div * (f1 * O_[tx, x] + f2 * pv)
170+
171+
l_[tx] = row_l_new
172+
m_[tx] = row_m_new
173+
174+
gpu.barrier()
175+
176+
177+
ip.__exit__(None, None, None)
178+
179+
assert gpu_module.operation.verify()
180+
print(gpu_module)
181+
182+
183+
Liveness(gpu_module)

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+
)

mlir/extras/util/liveness.py

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
from collections import deque
2+
3+
from ...ir import Block, Value, Operation
4+
from .util import (
5+
walk_blocks_in_operation,
6+
walk_operations,
7+
find_ancestor_block_in_region,
8+
)
9+
10+
11+
class BlockInfoBuilder:
12+
block = None
13+
in_values = None
14+
out_values = None
15+
def_values = None
16+
use_values = None
17+
18+
def __init__(self, block):
19+
self.block = block
20+
self.in_values = set()
21+
self.out_values = set()
22+
self.def_values = set()
23+
self.use_values = set()
24+
25+
def gather_out_values(v: Value):
26+
for use in v.uses:
27+
user = use.owner.operation
28+
owner_block = user.block
29+
owner_block = find_ancestor_block_in_region(owner_block)
30+
if owner_block != block:
31+
self.out_values.add(v)
32+
break
33+
34+
for arg in block.arguments:
35+
gather_out_values(arg)
36+
for op in block.operations:
37+
for r in op.results:
38+
gather_out_values(r)
39+
40+
for op in block.operations:
41+
for nested_op in walk_operations(op):
42+
self.def_values |= set(nested_op.results)
43+
self.use_values |= set(nested_op.operands)
44+
for b in walk_blocks_in_operation(nested_op):
45+
self.def_values |= set(b.arguments)
46+
47+
self.use_values -= self.def_values
48+
49+
def update_livein(self):
50+
new_in = self.use_values
51+
new_in |= self.out_values
52+
new_in -= self.def_values
53+
54+
if len(new_in) == len(self.in_values):
55+
return set()
56+
self.in_values = new_in
57+
return new_in
58+
59+
def update_liveout(self, builders):
60+
for succ in self.block.successors:
61+
self.out_values -= builders[succ].in_values
62+
63+
64+
def build_block_mapping(op):
65+
visited = set()
66+
to_process = deque()
67+
builders = {}
68+
for b in walk_blocks_in_operation(op):
69+
builder = builders[b] = BlockInfoBuilder(b)
70+
if builder.update_livein():
71+
for p in b.predecessors:
72+
if p not in visited:
73+
to_process.append(p)
74+
visited.add(p)
75+
76+
while to_process:
77+
current = to_process.popleft()
78+
builder = builders[current]
79+
builder.update_liveout(builders)
80+
if builder.update_livein():
81+
for p in current.predecessors:
82+
if p not in visited:
83+
to_process.append(p)
84+
visited.add(p)
85+
86+
return builders
87+
88+
89+
class LivenessBlockInfo:
90+
block = None
91+
in_values = None
92+
out_values = None
93+
94+
def __init__(self, block, in_values, out_values):
95+
self.block = block
96+
self.in_values = in_values
97+
self.out_values = out_values
98+
99+
100+
class Liveness:
101+
operation = None
102+
block_mapping = None
103+
104+
def __init__(self, op):
105+
self.operation = op
106+
self.block_mapping = {}
107+
108+
builders = build_block_mapping(self.operation)
109+
for block, builder in builders.items():
110+
assert block == builder.block
111+
self.block_mapping[block] = LivenessBlockInfo(
112+
builder.block, builder.in_values, builder.out_values
113+
)

0 commit comments

Comments
 (0)