Skip to content

Commit 3be9575

Browse files
committed
add norm example
1 parent 08e4fec commit 3be9575

1 file changed

Lines changed: 385 additions & 0 deletions

File tree

‎examples/xegpu/norm.py‎

Lines changed: 385 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,385 @@
1+
# RUN: %PYTHON %s --dump-kernel=xegpu-wg | FileCheck %s
2+
# CHECK: module attributes {gpu.container_module} {
3+
4+
"""
5+
XeGPU row-wise vector norm / normalization (L1 / L2) benchmark.
6+
"""
7+
8+
import argparse
9+
from functools import cached_property
10+
11+
import numpy as np
12+
from mlir import ir
13+
14+
from lighthouse import dialects as lh_dialects
15+
from lighthouse.execution.runner import Runner
16+
from lighthouse.pipeline.driver import TransformDriver
17+
from lighthouse.execution import GPUMemoryManager
18+
from lighthouse.utils.numpy import mlir_to_numpy_dtype
19+
from lighthouse.ingress.mlir_gen import get_mlir_elem_type
20+
from lighthouse.ingress.mlir_gen.gpu_norm_payload import generate_gpu_norm_payload
21+
from lighthouse.schedule.parameters import ScheduleParameters
22+
from lighthouse.schedule.xegpu import reduction_schedule, xegpu_to_binary
23+
24+
25+
def norm_complexity(M: int, N: int, nbytes: int, norm_kind: str, normalize: bool):
26+
"""
27+
Complexity of a row-wise norm in the max-scaled stable form.
28+
29+
Per element: abs, max-compare, divide by the row max, add -- plus a multiply
30+
for L2's square, and one more divide when normalizing. The per-row work (a
31+
multiply, and a sqrt for L2) is O(M) and ignored.
32+
"""
33+
flops_per_elem = 4 if norm_kind == "l1" else 5
34+
if normalize:
35+
flops_per_elem += 1
36+
flop_count = M * N * flops_per_elem
37+
memory_reads = M * N * nbytes # read input
38+
memory_writes = (M * N if normalize else M) * nbytes
39+
return flop_count, memory_reads, memory_writes
40+
41+
42+
def check_correctness(
43+
input_arr: np.ndarray,
44+
output_arr: np.ndarray,
45+
norm_kind: str,
46+
normalize: bool,
47+
verbose: int = 0,
48+
) -> bool:
49+
x = input_arr.astype(np.float32)
50+
if norm_kind == "l1":
51+
norms = np.sum(np.abs(x), axis=1)
52+
else:
53+
norms = np.sqrt(np.sum(x * x, axis=1))
54+
output_ref = x / norms[:, None] if normalize else norms
55+
56+
output = output_arr.astype(np.float32)
57+
58+
if verbose > 1:
59+
print("Reference solution (first 8 rows):")
60+
print(output_ref[:8])
61+
print("Computed solution (first 8 rows):")
62+
print(output[:8])
63+
64+
# The kernel sums N scaled terms in a different order than numpy, so compare
65+
# on a relative tolerance rather than exactly.
66+
success = np.allclose(output, output_ref, rtol=1e-4, atol=1e-5)
67+
68+
if verbose:
69+
if success:
70+
print("PASSED")
71+
else:
72+
print("FAILED!")
73+
rel = np.abs(output - output_ref) / np.maximum(np.abs(output_ref), 1e-30)
74+
print(f" Max relative diff: {rel.max():.6e}")
75+
return success
76+
77+
78+
class XeGPUNorm:
79+
"""
80+
Row-wise Lp norm / normalization on XeGPU.
81+
82+
Computes, per row of an (M, N) input, either the norm itself
83+
84+
out[i] = sum_j |x[i, j]| (L1)
85+
out[i] = sqrt(sum_j x[i, j]^2) (L2)
86+
87+
or, with `normalize`, the input divided through by it -- the
88+
`torch.nn.functional.normalize` / cosine-similarity step:
89+
90+
out[i, j] = x[i, j] / norm[i]
91+
92+
Both use the numerically stable max-scaled form, which makes the op a
93+
`max -> elementwise -> sum` dependent-reduction chain -- the same shape as
94+
softmax, and fusable into a single online loop the same way.
95+
"""
96+
97+
def __init__(
98+
self,
99+
M: int,
100+
N: int,
101+
dtype: str = "f32",
102+
norm_kind: str = "l2",
103+
normalize: bool = False,
104+
):
105+
self.M = M
106+
self.N = N
107+
self.shape = (M, N)
108+
self.row_shape = (M,)
109+
self.norm_kind = norm_kind
110+
self.normalize = normalize
111+
self.out_shape = self.shape if normalize else self.row_shape
112+
assert dtype == "f32", "Only f32 type is supported for norm"
113+
self.elem_type = get_mlir_elem_type(dtype)
114+
self.dtype = mlir_to_numpy_dtype(self.elem_type)
115+
self.memory_manager_class = GPUMemoryManager
116+
self.payload_function_name = "payload"
117+
118+
@cached_property
119+
def _initial_host_arrays(self) -> tuple[np.ndarray]:
120+
"""Generate initial values on host with numpy."""
121+
np.random.seed(42)
122+
# Magnitudes in [0.5, 1.5] with random signs. Kept away from zero because
123+
# the stable form divides by the row maximum: an all-zero row would make
124+
# the scaled term 0/0.
125+
magnitude = np.random.uniform(0.5, 1.5, self.shape).astype(self.dtype)
126+
sign = np.random.choice([-1.0, 1.0], self.shape).astype(self.dtype)
127+
input_arr = magnitude * sign
128+
output_arr = np.zeros(self.out_shape, dtype=self.dtype)
129+
return (output_arr, input_arr)
130+
131+
def get_complexity(self) -> tuple[int, int, int]:
132+
nbytes = np.dtype(self.dtype).itemsize
133+
return norm_complexity(self.M, self.N, nbytes, self.norm_kind, self.normalize)
134+
135+
def payload_module(self) -> ir.Module:
136+
"""Generate MLIR module for the norm payload."""
137+
mod = generate_gpu_norm_payload(
138+
func_name=self.payload_function_name,
139+
M=self.M,
140+
N=self.N,
141+
dtype=self.elem_type,
142+
norm_kind=self.norm_kind,
143+
normalize=self.normalize,
144+
)
145+
# The 2D input, and the 1D per-row result when not normalizing, each need
146+
# their own alloc/copy helpers.
147+
ranks_and_types = [(2, self.elem_type), (1, self.elem_type)]
148+
self.memory_manager_class.emit_memory_management_funcs(
149+
mod, ranks_and_types=ranks_and_types
150+
)
151+
return mod
152+
153+
def schedule_modules(
154+
self,
155+
stop_at_stage: str | None = None,
156+
parameters: ScheduleParameters | None = None,
157+
) -> list[ir.Module]:
158+
"""Generate transform schedule for the norm."""
159+
schedules = []
160+
schedules.append(Runner.get_bench_wrapper_schedule(self.payload_function_name))
161+
162+
schedules.append(
163+
reduction_schedule(
164+
payload_func_name=self.payload_function_name,
165+
stop_at_stage=stop_at_stage,
166+
params=parameters,
167+
)
168+
)
169+
170+
if stop_at_stage and stop_at_stage != "final":
171+
return schedules
172+
173+
schedules.append(xegpu_to_binary())
174+
175+
return schedules
176+
177+
def shared_libs(self) -> list[str]:
178+
return ["libmlir_levelzero_runtime.so"]
179+
180+
181+
def parse_cli():
182+
parser = argparse.ArgumentParser(
183+
description="Row-wise L1/L2 norm using MLIR XeGPU",
184+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
185+
)
186+
parser.add_argument(
187+
"--norm",
188+
type=str,
189+
choices=["l1", "l2"],
190+
default="l2",
191+
help="Which norm to compute.",
192+
)
193+
parser.add_argument(
194+
"--sizes",
195+
type=int,
196+
nargs=2,
197+
default=[1024, 512],
198+
help="M,N matrix sizes (MxN); the norm reduces N.",
199+
)
200+
parser.add_argument(
201+
"--wg-rows",
202+
type=int,
203+
default=64,
204+
help="Number of rows per workgroup.",
205+
)
206+
parser.add_argument(
207+
"--sg-rows",
208+
type=int,
209+
default=8,
210+
help="Number of rows per subgroup.",
211+
)
212+
parser.add_argument(
213+
"--subgroup-size",
214+
type=int,
215+
default=16,
216+
help="Subgroup size.",
217+
)
218+
parser.add_argument(
219+
"--reduction-step-size",
220+
type=int,
221+
default=16,
222+
help="Step size for reduction loop tiling (optional).",
223+
)
224+
parser.add_argument(
225+
"--normalize",
226+
action="store_true",
227+
help="Divide the input through by the row norms (torch F.normalize) "
228+
"instead of returning the norms.",
229+
)
230+
parser.add_argument(
231+
"--online",
232+
action="store_true",
233+
help="Fuse the max and sum reductions into a single online (one-pass) "
234+
"reduction loop.",
235+
)
236+
parser.add_argument(
237+
"--nruns",
238+
type=int,
239+
default=1000,
240+
help="Number of runs to average the execution time.",
241+
)
242+
parser.add_argument(
243+
"--nwarmup",
244+
type=int,
245+
default=1000,
246+
help="Number of warm-up iterations before benchmarking.",
247+
)
248+
parser.add_argument(
249+
"--check-result",
250+
action="store_true",
251+
help="Check the result of the norm computation.",
252+
)
253+
parser.add_argument(
254+
"--dump-kernel",
255+
type=str,
256+
choices=[
257+
"initial",
258+
"tiled",
259+
"vectorized",
260+
"bufferized",
261+
"gpu-outlining",
262+
"xegpu-initial",
263+
"xegpu-wg",
264+
"final",
265+
],
266+
help="Dump kernel IR at different stages of lowering and exit without "
267+
"executing the kernel.",
268+
)
269+
parser.add_argument(
270+
"--dump-schedule",
271+
action="store_true",
272+
help="Dump transform schedule.",
273+
)
274+
parser.add_argument(
275+
"--verbose",
276+
"-v",
277+
action="count",
278+
default=0,
279+
help="Increase output verbosity (e.g. print reference and computed solutions).",
280+
)
281+
args = parser.parse_args()
282+
return args
283+
284+
285+
if __name__ == "__main__":
286+
args = parse_cli()
287+
288+
params = ScheduleParameters(
289+
[
290+
{
291+
"layer_kind": "reduction",
292+
"sizes": args.sizes,
293+
"wg_rows": args.wg_rows,
294+
"sg_rows": args.sg_rows,
295+
"subgroup_size": args.subgroup_size,
296+
"reduction_step_size": args.reduction_step_size,
297+
"fuse_dependant_reductions": args.online,
298+
# Normalizing writes a full (M, N) result, so its epilogue spans
299+
# the reduced axis and gets tiled along it. A bare norm's result
300+
# is one scalar per row, so there is no full-extent pass to tile.
301+
"epilogue_spans_reduction_dim": args.normalize,
302+
}
303+
]
304+
)
305+
306+
M, N = args.sizes
307+
dtype = "f32"
308+
309+
with ir.Context(), ir.Location.unknown():
310+
lh_dialects.register_and_load()
311+
wload = XeGPUNorm(
312+
M=M, N=N, dtype=dtype, norm_kind=args.norm, normalize=args.normalize
313+
)
314+
315+
if args.dump_kernel or args.dump_schedule:
316+
pipeline = TransformDriver(
317+
wload.schedule_modules(
318+
stop_at_stage=args.dump_kernel, parameters=params
319+
)
320+
)
321+
payload = pipeline.apply(wload.payload_module())
322+
if args.dump_kernel:
323+
print(payload)
324+
if args.dump_schedule:
325+
for schedule_module in wload.schedule_modules(parameters=params):
326+
print(schedule_module)
327+
else:
328+
pipeline = TransformDriver(wload.schedule_modules(parameters=params))
329+
payload = pipeline.apply(wload.payload_module())
330+
runner = Runner(
331+
payload,
332+
mem_manager_cls=wload.memory_manager_class,
333+
shared_libs=wload.shared_libs(),
334+
)
335+
if args.check_result:
336+
# Setup callback function to copy result from device to host.
337+
result_host_copy = np.zeros(wload.out_shape, dtype=wload.dtype)
338+
argument_access_callback = Runner.get_gpu_argument_access_callback(
339+
result_host_copy, arg_index=0
340+
)
341+
342+
# Execute kernel once.
343+
runner.execute(
344+
host_input_buffers=wload._initial_host_arrays,
345+
payload_function_name=wload.payload_function_name,
346+
argument_access_callback=argument_access_callback,
347+
)
348+
349+
# Compute reference solution on host.
350+
success = check_correctness(
351+
wload._initial_host_arrays[1],
352+
result_host_copy,
353+
wload.norm_kind,
354+
wload.normalize,
355+
verbose=args.verbose,
356+
)
357+
if not success:
358+
raise ValueError("Result mismatch!")
359+
else:
360+
print("Result is correct. Proceeding to benchmark...")
361+
362+
times = runner.benchmark(
363+
host_input_buffers=wload._initial_host_arrays,
364+
nruns=args.nruns,
365+
nwarmup=args.nwarmup,
366+
)
367+
times *= 1e6 # convert to microseconds
368+
elapsed = np.mean(times)
369+
flop_count = wload.get_complexity()[0]
370+
gflops = flop_count / (elapsed * 1e-6) / 1e9
371+
372+
def list2str(a):
373+
return ",".join(map(str, a))
374+
375+
print(
376+
f"norm={args.norm} "
377+
f"{'normalize ' if args.normalize else ''}"
378+
f"sizes={list2str(args.sizes)} "
379+
f"dt={dtype} "
380+
f"wg-rows={args.wg_rows} "
381+
f"sg-rows={args.sg_rows} "
382+
f"subgroup-size={args.subgroup_size} "
383+
f"time(us): {elapsed:.2f} "
384+
f"GFLOPS: {gflops:.2f} "
385+
)

0 commit comments

Comments
 (0)