1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237 | """Pack valid FP8 payloads and compile all quantized matmul variants (no FSim launch)."""
import os
from pathlib import Path
import torch
from hart.weight_converter import (
ArchitectureType,
DataType,
QuantType,
Shape,
Tensor,
TensorType,
WeightConverterConfig,
convert,
)
import legato
import legato.model.bertha as bertha
# Store compiler artifacts and optional simulator logs in a configurable directory.
OUTPUT = Path(os.environ.get("LEGATO_EXAMPLE_OUTPUT", "legato_example_output"))
def _to_bytes(tensor: torch.Tensor) -> bytearray:
return bytearray(tensor.contiguous().cpu().numpy().tobytes())
def pack_fp8_weight(
weight_i8: torch.Tensor,
scale_f32: torch.Tensor,
*,
quant_type: QuantType,
group_size: int = 128,
bias_f32: torch.Tensor | None = None,
) -> torch.Tensor:
"""Pack an FP8 EVT0 weight.
`weight_i8` is `[C, M]`; `scale_f32` is `[M]` for output-channel-wise
or `[C / group_size, M]` for input-channel-wise.
"""
input_channels, output_channels = weight_i8.shape
cfg = WeightConverterConfig(
ArchitectureType.EVT0,
quant_type,
group_size if quant_type == QuantType.InputChannelWiseQuant else 0,
)
num_groups = input_channels // group_size if quant_type == QuantType.InputChannelWiseQuant else 1
weight_buf = _to_bytes(weight_i8)
scale_buf = _to_bytes(scale_f32)
weight = Tensor(
weight_buf,
Shape(1, 1, input_channels, output_channels),
DataType.FP8,
TensorType.Weight,
)
scale = Tensor(
scale_buf,
Shape(1, 1, num_groups, output_channels),
DataType.FP32,
TensorType.Scale,
)
bias = None
bias_buf = None
if bias_f32 is not None:
bias_buf = _to_bytes(bias_f32)
bias = Tensor(
bias_buf,
Shape(1, 1, 1, output_channels),
DataType.FP32,
TensorType.Bias,
)
packed = convert(cfg, weight, bias, scale, None, None, None, output_data_type=DataType.BF16)
return torch.frombuffer(bytearray(packed), dtype=torch.int8).clone()
@legato.compile(
backend=lambda ctx: bertha.Bertha(ctx, "bertha"), param_kinds={"a": "universal", "w": "top", "out": "core"}
)
def mm_weight_quant_oc(
a: legato.get_model().tensor_type(legato.types.float("bfloat16"), [4, 128], "shared_memory"),
w: legato.get_model().tensor_type(legato.types.integer("int8"), [8704], "shared_dram"),
out: legato.get_model().tensor_type(legato.types.float("bfloat16"), [4, 64], "shared_dram"),
):
"""Compile an output-channel-wise FP8 packed-weight matmul."""
device = legato.get_context().get_device()
with device.get_top():
legato.tensor.request_load(a, device.get_core(0), "sram")
legato.tensor.request_load(w, device.get_core(0), "mpu_packed_buffer")
with device.get_core(0):
lhs = legato.tensor.receive_type(
legato.get_model().tensor_type(legato.types.float("bfloat16"), [4, 128], "row_major"),
0,
None,
"sram",
)
rhs = legato.tensor.receive_type(
legato.get_model().tensor_type(legato.types.integer("int8"), [8704], "mpu_packed_buffer"),
0,
None,
"mpu_packed_buffer",
)
result = device.mm_weight_quant(lhs, rhs, legato.types.float("float8"), [128, 64], "per_output_channel")
legato.tensor.memcpy(out, result)
@legato.compile(
backend=lambda ctx: bertha.Bertha(ctx, "bertha"), param_kinds={"a": "universal", "w": "top", "out": "core"}
)
def mm_weight_quant_ic_128(
a: legato.get_model().tensor_type(legato.types.float("bfloat16"), [4, 128], "shared_memory"),
w: legato.get_model().tensor_type(legato.types.integer("int8"), [8704], "shared_dram"),
out: legato.get_model().tensor_type(legato.types.float("bfloat16"), [4, 64], "shared_dram"),
):
"""Compile FP8 packed matmul with the default 128-channel group."""
device = legato.get_context().get_device()
with device.get_top():
legato.tensor.request_load(a, device.get_core(0), "sram")
legato.tensor.request_load(w, device.get_core(0), "mpu_packed_buffer")
with device.get_core(0):
lhs = legato.tensor.receive_type(
legato.get_model().tensor_type(legato.types.float("bfloat16"), [4, 128], "row_major"),
0,
None,
"sram",
)
rhs = legato.tensor.receive_type(
legato.get_model().tensor_type(legato.types.integer("int8"), [8704], "mpu_packed_buffer"),
0,
None,
"mpu_packed_buffer",
)
result = device.mm_weight_quant(lhs, rhs, legato.types.float("float8"), [128, 64], "per_input_channel")
legato.tensor.memcpy(out, result)
@legato.compile(
backend=lambda ctx: bertha.Bertha(ctx, "bertha"), param_kinds={"a": "universal", "w": "top", "out": "core"}
)
def mm_weight_quant_ic_256(
a: legato.get_model().tensor_type(legato.types.float("bfloat16"), [4, 256], "shared_memory"),
w: legato.get_model().tensor_type(legato.types.integer("int8"), [16896], "shared_dram"),
out: legato.get_model().tensor_type(legato.types.float("bfloat16"), [4, 64], "shared_dram"),
):
"""Compile FP8 packed matmul with an explicit 256-channel group."""
device = legato.get_context().get_device()
with device.get_top():
legato.tensor.request_load(a, device.get_core(0), "sram")
legato.tensor.request_load(w, device.get_core(0), "mpu_packed_buffer")
with device.get_core(0):
lhs = legato.tensor.receive_type(
legato.get_model().tensor_type(legato.types.float("bfloat16"), [4, 256], "row_major"),
0,
None,
"sram",
)
rhs = legato.tensor.receive_type(
legato.get_model().tensor_type(legato.types.integer("int8"), [16896], "mpu_packed_buffer"),
0,
None,
"mpu_packed_buffer",
)
result = device.mm_weight_quant(lhs, rhs, legato.types.float("float8"), [256, 64], "per_input_channel", 256)
legato.tensor.memcpy(out, result)
@legato.compile(
backend=lambda ctx: bertha.Bertha(ctx, "bertha"), param_kinds={"a": "universal", "w": "top", "out": "core"}
)
def addmm_weight_quant_ic(
a: legato.get_model().tensor_type(legato.types.float("bfloat16"), [4, 128], "shared_memory"),
w: legato.get_model().tensor_type(legato.types.integer("int8"), [9216], "shared_dram"),
out: legato.get_model().tensor_type(legato.types.float("bfloat16"), [4, 64], "shared_dram"),
):
"""Compile an FP8 packed matmul with a packed FP32 bias."""
device = legato.get_context().get_device()
with device.get_top():
legato.tensor.request_load(a, device.get_core(0), "sram")
legato.tensor.request_load(w, device.get_core(0), "mpu_packed_buffer")
with device.get_core(0):
lhs = legato.tensor.receive_type(
legato.get_model().tensor_type(legato.types.float("bfloat16"), [4, 128], "row_major"),
0,
None,
"sram",
)
rhs = legato.tensor.receive_type(
legato.get_model().tensor_type(legato.types.integer("int8"), [9216], "mpu_packed_buffer"),
0,
None,
"mpu_packed_buffer",
)
result = device.addmm_weight_quant(
lhs,
rhs,
legato.types.float("float8"),
[128, 64],
"per_input_channel",
legato.types.float("float32"),
)
legato.tensor.memcpy(out, result)
CASES = {
"mm_weight_quant_oc": (mm_weight_quant_oc, 128, QuantType.OutputChannelQuant, 128, False, 8704),
"mm_weight_quant_ic_128": (mm_weight_quant_ic_128, 128, QuantType.InputChannelWiseQuant, 128, False, 8704),
"mm_weight_quant_ic_256": (mm_weight_quant_ic_256, 256, QuantType.InputChannelWiseQuant, 256, False, 16896),
"addmm_weight_quant_ic": (addmm_weight_quant_ic, 128, QuantType.InputChannelWiseQuant, 128, True, 9216),
}
def verify_case(name):
"""Check a packed weight's byte count and compile its kernel without launching."""
torch.random.default_generator.manual_seed(0)
kernel, channels, quant_type, group_size, use_bias, expected_bytes = CASES[name]
# int8 is the transport container for real FP8 E4M3FN encodings, not integer quantization.
weight = (torch.randn(channels, 64) * 0.25).to(torch.float8_e4m3fn).view(torch.int8)
scale_shape = (64,) if quant_type == QuantType.OutputChannelQuant else (channels // group_size, 64)
scale = torch.rand(scale_shape, dtype=torch.float32) * 0.09 + 0.01
bias = torch.randn(64) * 0.1 if use_bias else None
packed = pack_fp8_weight(weight, scale, quant_type=quant_type, group_size=group_size, bias_f32=bias)
assert packed.numel() == expected_bytes, (kernel.__name__, packed.numel(), expected_bytes)
activation = torch.randn(4, channels, dtype=torch.bfloat16)
output = torch.empty(4, 64, dtype=torch.bfloat16)
# Compile a binary without initializing a device or launching.
with legato.session(output_type=legato.OutputType.BINARY, output_path=str(OUTPUT), launch=False):
kernel(activation, legato.Arg(packed, bertha.top), legato.Arg(output, bertha.core(0)))
def main():
"""Check converter byte counts and lower all four variants to a binary artifact."""
for name in CASES:
verify_case(name)
if __name__ == "__main__":
main()
|