Legato
Legato는 HyperAccel LPU용 커널을 작성하기 위한 Python eDSL입니다.
프로그래밍 모델을 Python에 가깝게 유지하면서도, 컴파일러가 데이터 배치, executor 선택, 연산을 타겟 백엔드로 lowering(IR을 내리는 과정)하는 데 필요한 구조를 제공합니다.
왜 Legato인가?
Legato를 통한 커널에는 아래 내용들을 기술합니다.
- 각 단계를 어느 실행 유닛(Top, 특정 코어, 전체 코어)이 실행하는지
- 텐서가 언제 메모리 사이를 이동하는지
- 어떤 텐서 타입, 레이아웃, 동적 차원을 기대하는지
- 어떤 값이 컴파일 시점 파라미터인지
컴파일러는 이어서 프로그램을 검증, Legato IR을 거쳐 lowering을 수행,
백엔드 패스를 실행해 Binary, ASM, IR 등 요청된 형태의 산출물(artifact)을 출력합니다.
간단한 Bertha 예제
제공된 예제들은 legato eDSL로 특정 동작을 기술하고 이를 테스트해 볼 수 있는 예제입니다.
legato eDSL을 특정 하드웨어에 실행하기 위해 @legato.compile의 backend 인자에 함수(backend=lambda)를 넘깁니다.
이 함수는 현재 활성화된 MLIR 컨텍스트 ctx를 받아, 대상 하드웨어를 나타내는 compute model 인스턴스를 반환합니다.
현재 제공된 예제는 bertha.Bertha를 사용해 Bertha에서 동작합니다.
공통 설정과 시뮬레이터(Simulator)/하드웨어(Hardware) 요구 사항은 예제 실행하기를 참고하십시오.
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 | """Single-core BF16 matmul with a bounded dynamic activation row count."""
import os
from pathlib import Path
import torch
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"))
@legato.compile(
backend=lambda ctx: bertha.Bertha(ctx, "bertha"),
param_kinds={"a": "universal", "b": "top", "out": "core"},
)
def simple_matmul(
a: legato.get_model().tensor_type(legato.types.float("bfloat16"), ((-1, 10), 256), "shared_dram"),
b: legato.get_model().tensor_type(legato.types.float("bfloat16"), [256, 128], "mpu_dram"),
out: legato.get_model().tensor_type(legato.types.float("bfloat16"), [10, 128], "shared_dram"),
):
"""Load BF16 operands, multiply on core zero, and store the output."""
device = legato.get_context().get_device()
with device.get_top():
legato.tensor.request_load(a, device.get_core(0), "sram")
legato.tensor.request_load(b, device.get_core(0), "mpu_buffer")
with device.get_core(0):
weight_type = legato.get_model().tensor_type(legato.types.float("bfloat16"), [256, 128], "mpu_weight")
loaded_a = legato.tensor.receive(a, 0, "sram")
loaded_b = legato.tensor.receive_type(weight_type, 0, None, "mpu_buffer")
result = loaded_a @ loaded_b
legato.tensor.memcpy(out, result)
def main():
"""Compare the complete output with a CPU matrix product."""
# Register the LPU PyTorch backend before allocating device tensors.
import hart
import torch_ha
torch_ha._autoload()
# HA_BACKEND=sim selects EVT0 Torch FSim; otherwise use the hardware runtime.
if os.environ.get("HA_BACKEND") == "sim":
OUTPUT.mkdir(parents=True, exist_ok=True)
hart.set_fsim_env(
hart.HaDeviceVersion.BERTHA_CLOUD_EVT0,
hart.HaFSimComputeMode.TORCH,
str(OUTPUT / "fsim.log"),
"error",
)
hart.set_device(0)
# Keep CPU inputs reproducible without initializing a device RNG.
torch.random.default_generator.manual_seed(0)
a_cpu = (torch.randn(10, 256) * 0.25).to(torch.bfloat16)
b_cpu = (torch.randn(256, 128) * 0.25).to(torch.bfloat16)
# Allocate the physical layout expected by the kernel and copy contiguous host data.
a = torch.ops.lpu.empty_with_kind(list(a_cpu.shape), "dram_word_interleaved", dtype=a_cpu.dtype, device="lpu:0")
a.copy_(a_cpu.contiguous())
# Allocate the physical layout expected by the kernel and copy contiguous host data.
b = torch.ops.lpu.empty_with_kind(list(b_cpu.shape), "mpu_tensor", dtype=b_cpu.dtype, device="lpu:0")
b.copy_(b_cpu.contiguous())
out_cpu = torch.zeros(10, 128, dtype=torch.bfloat16)
# Allocate the physical layout expected by the kernel and copy contiguous host data.
out = torch.ops.lpu.empty_with_kind(
list(out_cpu.shape), "dram_word_interleaved", dtype=out_cpu.dtype, device="lpu:0"
)
out.copy_(out_cpu.contiguous())
# Compile a binary and launch it on the selected device.
with legato.session(output_type=legato.OutputType.BINARY, output_path=str(OUTPUT), launch=True):
simple_matmul(a, legato.Arg(b, bertha.top), legato.Arg(out, bertha.core(0)))
# Surface asynchronous execution errors before reading the result.
hart.stream_synchronize()
# Read back the synchronized result and compare every element with the CPU reference.
actual = out.cpu().float()
assert torch.isfinite(actual).all(), "Non-finite device result"
torch.testing.assert_close(actual, (a_cpu.float() @ b_cpu.float()).float(), atol=0.05, rtol=0.05)
if __name__ == "__main__":
main()
|
핵심 개념
세션 (Sessions)
컴파일된 함수는 legato.session(...) 안에서 실행해야 합니다.
세션은 출력 artifact의 종류와, 컴파일러 artifact 및 로그를 기록할 위치를 선택합니다.
| with legato.session(output_type=legato.OutputType.MLIR, output_path="test-output"):
kernel(*args)
|
지원하는 출력 artifact의 종류는 MLIR, CORE_IR, BACKEND_IR, ASM, BINARY입니다.
컨텍스트
Legato는 Python with 문으로 실행기 컨텍스트를 선택합니다.
device.get_top(): Bertha의 Top 영역으로 최상위 orchestration과 load 요청 발행을 담당합니다.
device.get_core(i): 코어 하나에서 실행되는 동작에 사용됩니다.
device.get_all_cores(): 모든 코어에서 실행되는 동작에 사용됩니다.
일반 Python과 달리, 한 영역에서 만든 값은 다른 영역에서 바로 사용할 수 없으므로 뒤의 영역에서 쓰려면 yield로 내보내야 합니다.
자세한 내용은 컨텍스트 관리를 참고하십시오.
텐서 이동 (Tensor Movement)
데이터 이동은 명시적입니다.
request_load: top 컨텍스트에서 데이터 전송을 발행하고, receive 또는 receive_type이 대상 코어(혹은 코어들) 컨텍스트에서 그 데이터를 실제 영역에 받아오는 동작으로 이루어집니다.
| with device.get_top():
legato.tensor.request_load(input_data, device.get_core(0), "sram")
with device.get_core(0):
loaded = legato.tensor.receive(input_data, 0, "sram")
|
타입과 레이아웃 (Types And Layouts)
텐서가 백엔드 고유의 메모리/레이아웃 종류에 묶여 있을 때는 함수 Annotation에 legato.get_model().tensor_type(...)을 사용합니다.
자주 쓰는 Bertha 종류는 다음과 같습니다.
"shared_memory", "shared_dram"
"row_major"
- 특수 value 방식 DRAM 레이아웃을 가리키는
"value_dram", "mpu_dram"
- 특수 key 방식 DRAM 레이아웃을 가리키는
"key_dram", "transposed_mpu_dram"
"mpu_weight", "mpu_packed_buffer", "sliced_dram"
다음에 볼 문서