Skip to content

Commit 8fcfe20

Browse files
committed
add liveness analysis demo
1 parent 62a1ecc commit 8fcfe20

File tree

6 files changed

+377
-17
lines changed

6 files changed

+377
-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: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
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+
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: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
from collections import OrderedDict
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+
find_ancestor_op_in_block,
9+
)
10+
11+
# based on https://github.com/llvm/llvm-project/blob/07ae19c132e1b0adbdb3cc036b9f50624e2ed1b7/mlir/lib/Analysis/Liveness.cpp
12+
13+
14+
def escapes_block(v: Value, b: Block):
15+
# Check if value escapes, i.e., if there's a use
16+
# which is in a block that is not "our" block
17+
for use in v.uses:
18+
user = use.owner
19+
owner_block = user.block
20+
owner_block = find_ancestor_block_in_region(owner_block)
21+
if owner_block != b:
22+
return True
23+
return False
24+
25+
26+
class BlockInfoBuilder:
27+
block = None
28+
in_values = None
29+
out_values = None
30+
def_values = None
31+
use_values = None
32+
33+
def __init__(self, block):
34+
self.block = block
35+
self.in_values = set()
36+
self.out_values = set()
37+
self.def_values = set()
38+
self.use_values = set()
39+
40+
for arg in block.arguments:
41+
self.def_values.add(arg)
42+
if escapes_block(arg, self.block):
43+
self.out_values.add(arg)
44+
for op in block.operations:
45+
for r in op.results:
46+
if escapes_block(r, self.block):
47+
self.out_values.add(r)
48+
49+
# Mark all nested operation results as defined, and nested operation
50+
# operands as used. All defined value will be removed from the used set
51+
# at the end.
52+
for op in block.operations:
53+
for nested_op in walk_operations(op):
54+
self.def_values |= set(nested_op.results)
55+
self.use_values |= set(nested_op.operands)
56+
for b in walk_blocks_in_operation(nested_op):
57+
self.def_values |= set(b.arguments)
58+
59+
self.use_values -= self.def_values
60+
61+
# newIn = use U out - def
62+
def update_livein(self):
63+
new_in = (self.use_values | self.out_values) - self.def_values
64+
# It is sufficient to check the set sizes (instead of their contents) since
65+
# the live-in set can only grow monotonically during all update operations.
66+
if len(new_in) == len(self.in_values):
67+
return set()
68+
self.in_values = new_in
69+
return new_in
70+
71+
def update_liveout(self, builders):
72+
for succ in self.block.successors:
73+
self.out_values |= builders[succ].in_values
74+
75+
76+
def build_block_mapping(op) -> dict[Block, BlockInfoBuilder]:
77+
to_process = OrderedDict()
78+
builders = {}
79+
for b in walk_blocks_in_operation(op):
80+
builder = builders[b] = BlockInfoBuilder(b)
81+
if not builder.update_livein():
82+
continue
83+
for p in b.predecessors:
84+
if p in to_process:
85+
continue
86+
to_process[p] = True
87+
88+
while to_process:
89+
# Pairs are returned in LIFO order if last is true or FIFO order if false.
90+
current, _ = to_process.popitem(last=False)
91+
builder = builders[current]
92+
builder.update_liveout(builders)
93+
if not builder.update_livein():
94+
continue
95+
for p in current.predecessors:
96+
if p in to_process:
97+
continue
98+
to_process[p] = True
99+
100+
return builders
101+
102+
103+
class LivenessBlockInfo:
104+
block: Block = None
105+
in_values = None
106+
out_values = None
107+
108+
def __init__(self, block, in_values, out_values):
109+
self.block = block
110+
self.in_values = in_values
111+
self.out_values = out_values
112+
113+
def is_livein(self, v: Value):
114+
return v in self.in_values
115+
116+
def is_liveout(self, v: Value):
117+
return v in self.out_values
118+
119+
def get_start_operation(self, v: Value):
120+
owner = v.owner
121+
if self.is_livein(v) or not owner:
122+
return self.block.operations[0]
123+
return owner
124+
125+
def get_end_operation(self, v: Value, start_op: Operation):
126+
if self.is_livein(v):
127+
return self.block.operations[-1]
128+
end_op = start_op
129+
for use in v.uses:
130+
use_op = find_ancestor_op_in_block(use.owner)
131+
132+
133+
class Liveness:
134+
operation = None
135+
block_mapping = None
136+
137+
def __init__(self, op):
138+
self.operation = op
139+
self.block_mapping = {}
140+
141+
builders = build_block_mapping(self.operation)
142+
for block, builder in builders.items():
143+
assert block == builder.block
144+
self.block_mapping[block] = LivenessBlockInfo(
145+
builder.block, builder.in_values, builder.out_values
146+
)

0 commit comments

Comments
 (0)