콘텐츠로 이동

벡터 덧셈: 첫 커널 실행

문서 상태

소유: CL팀 · 기준: Legato 0.14.1+public, PyTorch 2.10.0+cpu, Bertha EVT0 · 최종 확인: 2026-10-19

BF16 [1, 256] 입력 두 개를 코어 0에서 더하고 같은 shape의 출력에 저장. 전체 실행 파일을 SDK 환경에 저장한 뒤 실행.

1
2
export HA_TOOLCHAIN=1
python3 vector_add.py

Bertha 카드가 연결된 HW runtime 환경에서 실행. 성공 시 PASS: vector_add [1, 256], BF16, core 0 출력.

전체 코드

 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
"""BF16 vector addition on one Bertha EVT0 core."""

import torch
import torch_ha  # Registers the LPU device and torch.ops.lpu operations.
import legato
import legato.model.bertha as bertha


def get_bertha(ctx):
    return bertha.Bertha(ctx, "bertha", num_cores=32)


@legato.compile(backend=get_bertha)
def vector_add(
    a: legato.get_model().tensor_type(legato.types.float("bfloat16"), [1, 256], "shared_dram"),
    b: legato.get_model().tensor_type(legato.types.float("bfloat16"), [1, 256], "shared_dram"),
    out: legato.get_model().tensor_type(legato.types.float("bfloat16"), [1, 256], "shared_dram"),
):
    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), "sram")
    with device.get_core(0):
        tile_type = legato.types.tensor(legato.types.float("bfloat16"), [1, 256])
        x = legato.tensor.receive_type(tile_type, 0, None, "sram")
        y = legato.tensor.receive_type(tile_type, 1, None, "sram")
        legato.tensor.memcpy(out, x + y)


def main():
    shape = [1, 256]
    a_cpu = ((torch.arange(256).reshape(shape) % 17 - 8) / 8).to(torch.bfloat16)
    b_cpu = ((torch.arange(256).reshape(shape) % 13 - 6) / 8).to(torch.bfloat16)
    a, b, out = [
        torch.ops.lpu.empty_with_kind(
            shape, "dram_word_interleaved", dtype=torch.bfloat16, device="lpu:0"
        )
        for _ in range(3)
    ]
    a.copy_(a_cpu)
    b.copy_(b_cpu)
    with legato.session(output_type=legato.OutputType.BINARY, output_path="vector_add"):
        vector_add(a, b, out)
    actual = out.cpu()  # Synchronous readback waits for the result.
    torch.testing.assert_close(actual, a_cpu + b_cpu, rtol=0, atol=0)
    print("PASS: vector_add [1, 256], BF16, core 0")


if __name__ == "__main__":
    main()

작성 순서

  1. get_bertha: 대상 장치 설정. 이 예제는 Bertha EVT0의 32코어 구성을 사용.
  2. @legato.compile: 커널 함수와 backend 연결. 인자 타입에 dtype·shape·메모리 공간 지정.
  3. get_top()에서 입력 적재 요청, get_core(0)에서 수신·계산·출력 저장.
  4. CPU 입력을 LPU 메모리로 복사한 뒤 legato.session(...) 안에서 커널 호출.
  5. out.cpu()의 동기 복사로 결과를 회수하고 CPU 계산값과 비교.
구분 이 예제의 설정
장치 메모리 타입의 shared_dram에 대응하는 dram_word_interleaved로 할당
인자 선언·전달 param_kinds 미지정 시 기본 universal. 호출 시 tensor를 직접 전달
receive_type의 번호 해당 코어에 요청한 SRAM 입력 순서. a는 0, b는 1

request_load는 DRAM → SRAM 이동, memcpy는 계산 결과의 출력 저장. 입출력 tensor는 결과 회수까지 유지. 이 예제의 이진수로 정확히 표현 가능한 입력은 오차 없이 비교.

컴파일만 수행

세션에 launch=False를 지정하면 바이너리만 생성. 실제 LPU 실행이나 수치 검증을 의미하지 않음. 전체 예제에서 이 옵션만 바꾸면 뒤의 결과 비교도 실행되므로, 컴파일만 확인할 때는 결과 회수·비교 코드를 함께 생략.

1
2
with legato.session(output_type=legato.OutputType.BINARY, output_path="vector_add", launch=False):
    vector_add(a, b, out)

오류 확인

증상 먼저 확인할 항목
세션 밖 호출 오류 커널 호출을 with legato.session(...): 안으로 이동
인자 전달 위치 오류 param_kinds와 Arg의 top·core 대응
컴파일·메모리 배치 오류 타입 선언과 실제 tensor의 dtype·shape·할당 kind 일치 여부
결과 불일치 입력 수신 순서, 출력 저장 영역, CPU 기준값

컴파일 결과의 출력 위치와 중간 IR은 Compiler Session 참고.