콘텐츠로 이동

PyTorch 연동

Legato 커널은 HyperAccel LPU 디바이스에서 실행되며 PyTorch 텐서와 함께 쓸 수 있습니다. PyTorch에서 Legato를 쓰는 방법은 두 가지입니다.

  • 디바이스에 상주하는 텐서를 직접 만들어 데이터를 채운 뒤, 그 텐서를 넘겨 **Legato 커널을 직접 호출**합니다. 이 방법은 이 페이지에서 설명합니다.
  • torch.compile(..., backend="legato")로 **PyTorch 모델을 컴파일**합니다. Legato로 PyTorch 모델 컴파일하기를 참고하십시오.

이 페이지는 직접 호출 경로, 즉 디바이스 텐서를 만들고 데이터를 채운 뒤 컴파일된 Legato 커널에 넘기는 과정을 다룹니다.

디바이스 텐서 만들기

Legato 커널은 입력을 디바이스 메모리에서 읽습니다. 호스트에서는 torch.ops.lpu.empty_with_kind로 디바이스에 상주하는 텐서를 만듭니다. 이 함수는 LPU에 텐서를 할당하고, 데이터가 메모리에 어떤 레이아웃으로 놓이는지를 나타내는 **레이아웃 kind**를 그 텐서에 기록합니다.

1
2
3
4
5
6
7
8
import torch
import torch_ha

torch_ha._autoload()  # 멱등. Torch 백엔드 autoload가 꺼져 있을 때도 마찬가지

weight = torch.ops.lpu.empty_with_kind(
    [256, 128], "mpu_tensor", dtype=torch.bfloat16, device="lpu:0"
)

디바이스 텐서 채우기

empty_with_kind는 초기화되지 않은 텐서를 반환합니다. 데이터를 CPU에서 만든 뒤 디바이스 텐서로 복사하십시오.

1
weight.copy_(torch.randn(256, 128, dtype=torch.bfloat16))

출력 텐서도 같은 방식으로 만들며, 값은 채우지 않고 커널이 써넣도록 둡니다.

종류 선택

empty_with_kind에 넘기는 kind 문자열은 그 텐서를 받는 커널 파라미터의 Annotation kind, 즉 tensor_type(dtype, shape, kind)의 세 번째 인자와 맞아야 합니다. 둘은 다음과 같이 일대일로 대응합니다.

empty_with_kind 이름 Annotation kind 사용되는 tensor의 종류
"dram_word_interleaved" "shared_dram" / "shared_memory" activation
"mpu_tensor" "mpu_dram" / "value_dram" weight / value
"mpu_tensor_transposed" "transposed_mpu_dram" / "key_dram" 전치된 weight / key

Note

kind마다 이름이 두 개씩 있는데(예: "shared_dram" / "shared_memory"), 현재 컴파일러에서는 두 이름이 같은 kind를 가리키는 별칭(alias)이므로 어느 쪽으로 써도 동작이 같습니다.

그 밖의 empty_with_kind 이름으로 만든 텐서나 kind 없이 만든 텐서는 기본 경로인 shared memory → SRAM 경로를 따르므로, 이런 텐서를 위 세 kind 중 하나를 받는 파라미터에 넘기면 launch 시점에 에러가 발생합니다.

"mpu_tensor"와 "mpu_tensor_transposed" 레이아웃을 쓰려면 rank가 2 이상이고, dtype 비트 폭이 4, 8, 16 중 하나이며, 선택한 백엔드가 받아들이는 shape이어야 합니다. kind와 할당 요구 사항은 Bertha 레이아웃을 참고하십시오.

물리 저장 공간 (Physical storage)

(4, (70, 256)) 같은 타입에는 원소 256개짜리 physical row가 실제로 있어야 합니다. compact한 [4, 70] 텐서를 자동으로 padding해 주지는 않습니다. 먼저 backing 텐서 전체를 할당하고 데이터를 복사해 넣은 뒤, 그 텐서의 논리 view를 넘기십시오. (LPU의 메모리 공간에 padding이 포함된 텐서를 할당하여 물리적 공간을 잡아두는 것을 backing이라 합니다.)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
cpu = torch.randn(4, 70, dtype=torch.bfloat16)
padded_cpu = torch.zeros(4, 256, dtype=torch.bfloat16)
padded_cpu[:, :70] = cpu
storage = torch.ops.lpu.empty_with_kind(
    [4, 256], "dram_word_interleaved", dtype=torch.bfloat16, device="lpu:0"
)
storage.copy_(padded_cpu)
logical = storage[:, :70]  # shape [4, 70], 행 stride 256
# logical을 이에 맞는 (4, (70, 256)) Annotation의 커널 파라미터에 넘깁니다.
# 출력은 backing 전체를 CPU로 복사한 뒤 CPU 결과를 잘라 냅니다.

행 stride가 Annotation과 다른 compact 디바이스 텐서는 shared DRAM launch 검증에서 거부됩니다. 호스트와 데이터를 주고받을 때는 연속되지 않은 디바이스 view를 거치지 말고, backing 텐서 전체를 복사하거나 읽으십시오. backing 저장 공간은 스트림 동기화(synchronization)가 끝날 때까지 살려 두어야 합니다.

커널에 텐서 넘기기

각 텐서를 파라미터의 param_kinds에 맞게 감싼 뒤 legato.session 안에서 커널을 호출하십시오. 감싸는 규칙, 즉 top / core / universal 배치(placement)와 Arg·Args의 차이는 인자 바인딩에서 설명합니다.

전체 예제

공통 설정과 시뮬레이터/하드웨어 요구 사항은 예제 실행하기를 참고하십시오.

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