콘텐츠로 이동

Weight-Quantized Matmul

mm_weight_quant와 addmm_weight_quant는 호스트에서 packing한 weight blob을 입력으로 받습니다. hart.weight_converter가 weight, 양자화 파라미터, 선택 사항인 bias로 필요한 opaque 버퍼를 만듭니다. Legato는 이 rank 1 i8 payload의 내부 구조를 해석하지 않고(opaque) mpu_packed_buffer로 스트리밍하며, EVT0 MPU에서 행렬 곱을 수행합니다.

검증 범위

아래 전체 예제는 converter 출력의 바이트 수를 검사하고, 네 가지 변형을 **launch=False인 BINARY**까지 컴파일합니다. FSim이나 하드웨어에서 FP8 수치가 일치한다는 것까지 보장하지는 않습니다. 현재 EVT0 Torch FSim의 양자화 판별 조건(predicate)에는 FP8/FP4가 빠져 있어서, packing된 scale 메타데이터가 올바르게 처리되지 않습니다. FP8 입력 채널 케이스는 scale shape이 호환되지 않아 실패할 수 있으며, 출력 채널 케이스를 launch해서 예외 없이 끝나더라도 수치 정확성이 검증된 것은 아닙니다. Lagora FP8 grouping 이슈를 참고하십시오.

이는 시뮬레이터의 제약이며, 이 문서에는 그 수정이 포함되어 있지 않습니다. FSim 검증을 손쉽게 해 보려는 용도로 이 샘플들의 launch를 켜지 마십시오.

Granularity와 shape

granularity [C, M] weight의 scale shape quant_group_size
"per_output_channel" [M] 무시됨
"per_input_channel" [C / group_size, M] 실제 C 그룹 크기, 기본값 128

입력 채널 단위로 그룹을 묶는 경우, 그룹 크기는 128 이상의 128 배수여야 하고 C가 이 값으로 나누어떨어져야 합니다. 그룹 크기 인자는 converter 설정과 일치해야 합니다. bias의 shape은 [M]이며, packing하기 전의 bias dtype은 addmm_weight_quant에 따로 넘깁니다.

Packing과 컴파일

weight_quant_matmul.py를 내려받거나, native 컴파일러/toolchain과 hart.weight_converter를 쓸 수 있는 환경에서 저장소에 있는 파일을 실행하십시오.

1
HA_TOOLCHAIN=1 python "$DOCS_ROOT/docs/legato-language/tutorials/code/weight_quant_matmul.py"

weight_i8에는 .to(torch.float8_e4m3fn).view(torch.int8)로 만든 **FP8 E4M3FN 비트 패턴**이 들어 있습니다. 부호 있는 정수를 무작위로 생성해 넣는 것은 FP8 양자화 절차가 아니며, 그런 값은 NaN을 나타내는 비트 패턴이 될 수 있습니다. scale_f32는 FP32 그대로입니다. converter에 넘기는 bytearray 버퍼는 convert()가 반환할 때까지 살아 있도록 유지합니다. 그렇게 하지 않고 임시 버퍼를 원시 포인터로 넘기면 dangling 포인터가 될 수 있습니다.

모든 커널은 출력 파라미터를 가지며 결과를 명시적으로 store합니다. CPU 인자는 타입이 지정된 이 커널들을 컴파일하는 데만 쓰이며, 디바이스 launch에는 전혀 쓰이지 않습니다. 네 가지 바이트 수(8704, 8704, 16896, 9216)는 예제에 나온 구성에서 converter가 실제로 출력한 크기와 대조해 확인한 값이므로, 다른 shape이나 양자화 형식에 그대로 가져다 쓰지 마십시오.

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

w는 파라미터 어노테이션에서는 shared_dram 저장 공간을 쓰고, receive 타입에서는 mpu_packed_buffer를 씁니다. mpu_weight는 tile 단위로 구성된 rank 2 이상의 텐서를 전제로 하므로, mpu_packed_buffer 대신 mpu_weight를 쓰면 안 됩니다. 다른 구성에서는 packing된 크기를 hart.weight_converter.get_converted_size로 구하거나 converter 출력에서 확인하십시오. Bertha API와 Bertha 레이아웃을 참고하십시오.