콘텐츠로 이동

행렬곱

문서 상태

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

코어 0에서 BF16 [16, 256] @ [256, 128] → [16, 128] 계산. 전체 실행 파일을 SDK 환경에 저장한 뒤 실행.

1
HA_TOOLCHAIN=1 python3 matmul.py

입력과 weight 배치

인자 커널의 메모리 공간 장치 할당 kind 코어 수신 위치
입력 a shared_dram dram_word_interleaved sram
weight mpu_dram mpu_tensor mpu_buffer
출력 out shared_dram dram_word_interleaved 출력 DRAM

Weight는 mpu_tensor로 할당한 뒤 CPU tensor를 copy_로 복사. 입력과 weight에 같은 메모리 배치를 적용하지 않도록 주의.

1
2
3
4
weight = torch.ops.lpu.empty_with_kind(
    [256, 128], "mpu_tensor", dtype=torch.bfloat16, device="lpu:0"
)
weight.copy_(w_cpu)

커널 본문

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
device = legato.get_context().get_device()
with device.get_top():
    legato.tensor.request_load(a, device.get_core(0), "sram")
    legato.tensor.request_load(weight, device.get_core(0), "mpu_buffer")
with device.get_core(0):
    x = legato.tensor.receive(a, 0, "sram")
    weight_type = legato.get_model().tensor_type(
        legato.types.float("bfloat16"), [256, 128], "mpu_weight"
    )
    w = legato.tensor.receive_type(weight_type, 0, None, "mpu_buffer")
    legato.tensor.memcpy(out, x @ w)

mpu_buffer로 보낸 weight를 mpu_weight 타입으로 수신한 뒤 @로 행렬곱. 수신 번호는 목적 메모리별로 구분되므로 SRAM 입력과 MPU weight 모두 0 사용.

실행과 비교

legato.session(...)에서 matmul(a, weight, out) 호출. 인자는 기본 universal 선언을 사용하며 tensor를 직접 전달. out.cpu()로 결과 회수 후 FP32 CPU 행렬곱을 BF16으로 변환한 기준값과 전체 출력 비교. 예제의 허용 오차는 rtol=0.02, atol=0.002. 변경한 입력 범위·shape의 검증 기준은 별도 설정 필요. 성공 시 PASS: matmul [16, 256] @ [256, 128], BF16, core 0 출력.