콘텐츠로 이동

연산 함수와 Masking

연산은 legato.math 아래에 있으며, 텐서 선택에는 legato.tensor.where를 씁니다. 프론트엔드가 어떤 언어 연산을 받아들인다고 해서, 그 연산을 standalone으로 썼을 때도 EVT0 바이너리로 lowering할 수 있다는 뜻은 아닙니다.

이 실행 가능한 예제는 이미 mask를 적용한 score와 행별 maximum을 호스트에서 넘겨주고, 디바이스에서는 legato.math.softmax(scores, -1, maximum)을 수행합니다. mask와 maximum은 호스트에서 준비하고, standalone full_like fill은 쓰지 않습니다. 마지막 축에 대한 standalone reduce_max도 아래의 EVT0 제약을 만족하면 지원됩니다. 지원되는 attention 패턴의 일부로 mask를 디바이스에서 생성하는 경우는 Causal Attention을 참고하십시오.

maximum은 mask를 적용한 뒤 각 행의 maximum이어야 합니다. 호출자는 모든 행에 유한한 score가 적어도 하나는 남도록 해야 합니다. 이 예제는 BF16 score에 유한한 -30 mask를 쓰며, CPU에서도 정확히 같은 유한 mask 방식으로 계산해 결과를 검증합니다.

math_and_masking.py를 내려받거나, 체크아웃한 파일을 실행하십시오. 환경 설정은 예제 실행하기를 참고하십시오.

1
HA_BACKEND=sim HA_TOOLCHAIN=1 python "$DOCS_ROOT/docs/legato-language/tutorials/code/math_and_masking.py"
 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
"""Masked softmax using a host-computed maximum of the already-masked scores."""

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"))
def masked_softmax(
    scores: legato.get_model().tensor_type(legato.types.float("bfloat16"), [4, 256], "shared_dram"),
    maximum: legato.get_model().tensor_type(legato.types.float("bfloat16"), (4, (1, 256)), "shared_dram"),
    out: legato.get_model().tensor_type(legato.types.float("bfloat16"), [4, 256], "shared_dram"),
):
    """Consume already-masked scores and the maximum of each masked row."""
    device = legato.get_context().get_device()
    with device.get_top():
        legato.tensor.request_load(scores, device.get_core(0), "sram")
        legato.tensor.request_load(maximum, device.get_core(0), "sram")
    with device.get_core(0):
        x = legato.tensor.receive(scores, 0, "sram")
        m = legato.tensor.receive(maximum, 0, "sram")
        legato.tensor.memcpy(out, legato.math.softmax(x, -1, m))


def main():
    """Build the mask and maximum on the host, then verify the device normalization."""
    # 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)
    scores_cpu = torch.randn(4, 256, dtype=torch.bfloat16)
    positions = torch.arange(252, 256).unsqueeze(1)
    scores_cpu = scores_cpu.masked_fill(torch.arange(256).unsqueeze(0) > positions, -30.0)
    max_host = torch.zeros(4, 256, dtype=torch.bfloat16)
    max_host[:, :1] = scores_cpu.max(-1, keepdim=True).values
    # Allocate the physical layout expected by the kernel and copy contiguous host data.
    maximum_storage = torch.ops.lpu.empty_with_kind(
        list(max_host.shape), "dram_word_interleaved", dtype=max_host.dtype, device="lpu:0"
    )
    maximum_storage.copy_(max_host.contiguous())
    maximum = maximum_storage[:, :1]
    out_cpu = torch.zeros_like(scores_cpu)
    # 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())
    # Allocate the physical layout expected by the kernel and copy contiguous host data.
    scores = torch.ops.lpu.empty_with_kind(
        list(scores_cpu.shape), "dram_word_interleaved", dtype=scores_cpu.dtype, device="lpu:0"
    )
    scores.copy_(scores_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):
        masked_softmax(scores, maximum, out)
    # 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, (torch.softmax(scores_cpu.float(), -1)).float(), atol=0.001, rtol=0.05)


if __name__ == "__main__":
    main()
  • legato.math.exp(tensor)
  • legato.math.sqrt(tensor)
  • legato.math.reduce_max(tensor, axis)
  • legato.math.reduce_min(tensor, axis)
  • legato.math.reduce_sum(tensor, axis)
  • legato.tensor.tril(tensor, diagonal)
  • legato.tensor.where(condition, true_value, false_value)

Bertha EVT0에서 합쳐진 attention score

attention이 여러 head band로 나뉘어 있으면, legato.math.reduce_max(scores, -1, True)를 빼기 전에 부분 score 텐서들을 먼저 더하십시오. band별로 따로 구한 maximum을 더하면 그 합이 합쳐진 어떤 score보다도 커져서, 지수 함수 값이 모두 underflow될 수 있습니다.

standalone VPU maximum lowering은 keepdim=True인 FP16, BF16, FP32 마지막 축 reduction을 지원합니다. 행은 row-major여야 하고, 논리 폭은 정적이며 원소 1~16384개 범위여야 합니다. 물리 크기는 행을 원소 64개 그룹 단위로 올림한 크기를 담을 수 있어야 합니다. 행이 정렬되어 있지 않으면 lowering 단계에서 실제로 읽히는 꼬리 부분을 -inf로 채우며, 정렬된 행은 채울 필요가 없습니다. reduction 범위를 벗어난 물리 영역은 건드리지 않습니다. 각 행의 주소는 물리 pitch를 그대로 유지하며, prefix 차원은 동적이어도 되지만 reduction 대상의 논리 폭이 동적인 경우는 아직 지원하지 않습니다. attention 전용 MPU maximum fusion은 기존 그대로입니다. 지원하지 않는 것으로 알려진 축이나 dtype은 구성 요소 검사에서 기록되며, 보통 executor assignment 단계에서 보고됩니다. headline과 candidate 사유 코드의 예시는 컴파일 diagnostics 예제를 참고하십시오. sliding-window attention에서는 window mask를 적용한 뒤에 maximum을 구하십시오. 그래야 제외된 attention sink가 shift를 결정하지 않습니다.