콘텐츠로 이동

산술 연산

Legato의 산술 연산은 컴파일된 함수 안에서 Python 연산자로 작성합니다. 연산자는 scalar 값과 텐서를 대상으로 하며, 피연산자의 타입과 shape이 서로 호환되어야 합니다.

Element-wise 산술

1
2
3
4
5
6
add = a + b
sub = a - b
mul = a * b
div = a / b
floor_div = a // b
power = a**b

텐서 산술은 broadcasting을 포함한 컴파일러의 텐서 shape 규칙을 따릅니다.

EVT1에서는 shape이 같은 BF16 텐서끼리의 뺄셈, 곱셈, 나눗셈도 이제 덧셈과 마찬가지로 VPU로 lowering됩니다. 수치 검증에는 [16, 256] 입력을 사용합니다. backend=bertha.evt1을 명시적으로 선택하십시오. 다만 그렇다고 해서 모든 broadcast나 dtype, 또는 위 목록의 나머지 연산자까지 EVT1에서 지원한다는 뜻은 아닙니다. 검증된 EVT1 경로를 참고하십시오.

행렬 곱

행렬 곱에는 Python의 @ 연산자를 쓰십시오.

1
result = lhs @ rhs

Bertha의 matmul weight에는 선택한 백엔드가 받아들이는 저장 kind가 필요합니다. 컴파일러는 호환되는 SRAM weight를 연산에 맞게 준비하며, 텐서는 SRAM에 유지됩니다.

SRAM weight는 batch prefix에서 다시 읽을 수 있습니다. 앞쪽의 크기 1인 차원은 제거되고, 값이 달라지는 batch 차원은 반복마다 slice됩니다. "mpu_buffer" 스트림을 지속적으로 저장된 SRAM 텐서처럼 재사용할 수는 없으며, 지원되지 않는 재사용에는 LE0184가 보고됩니다. Weight 저장 공간 요구 사항을 참고하십시오.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# 스트리밍되는 일회성 matmul (batch replay 없음).
weight_type = legato.get_model().tensor_type(
    legato.types.float("bfloat16"), [256, 128], "mpu_weight"
)
loaded_weight = legato.tensor.receive_type(weight_type, 0, None, "mpu_buffer")
result = loaded_input @ loaded_weight

# SRAM 경로: 컴파일러가 MPU tensor layout으로 packing하고 N*에 걸쳐 다시 load할 수 있음.
sram_w = legato.tensor.receive(sram_weight, 0, "sram")
batched = batched_lhs @ sram_w

batch 규칙은 Broadcasting에서 설명합니다. Bertha 예제도 참고하십시오.

비트 연산

비트 연산자는 정수 scalar에 쓸 수 있으며 Python 문법을 따릅니다. >>는 항상 산술(부호 확장) shift이며, 부호 없는 오른쪽 shift 연산자는 따로 없습니다.

1
2
3
4
5
6
left = a << b
right = a >> b
bit_and = a & b
bit_or = a | b
bit_xor = a ^ b
bit_not = ~a

비교

<, <=, >, >=, ==, != 같은 비교 연산의 결과는 bool 값이나 bool 텐서입니다.

현재 EVT0 백엔드에서 scalar 정수/index의 순서 비교에는 음이 아닌 값만 사용해야 합니다. 피연산자가 음수일 때의 부호 있는(signed) 순서는 보장되지 않기 때문입니다. 이 제약은 if, for, while의 흐름을 제어하는 비교에도 적용됩니다. 동등 비교, bool 처리, EVT1 구현은 이와 별개의 경로입니다.

1
mask = scores < threshold

bool 텐서는 흔히 legato.tensor.where와 함께 씁니다.

1
2
filled = legato.tensor.full_like(scores, neg_inf)
masked_scores = legato.tensor.where(mask, scores, filled)

Cast

scalar 값을 원하는 Legato 타입으로 변환하려면 legato.language.arith.cast를 쓰십시오.

1
2
3
4
from legato.language import arith

zero = arith.cast(0, legato.types.index())
scale = arith.cast(8.0, legato.types.float("bfloat16"))

부동소수점과 정수 scalar 변환

rounding 정책을 명시해서 변환하려면 legato.language에서 arith를 import한 뒤 arith.fp2int(value, policy)를 쓰십시오. "round_to_even"은 가장 가까운 정수로 반올림하되 두 정수의 정확히 중간인 값은 짝수 쪽으로 보내고, "towards_zero"는 소수 부분을 버립니다. 정책은 컴파일 시점에 정해지는 문자열이며, 결과는 int32입니다. 이 변환은 scalar 연산이며, cast로 rounding 정책 선택을 대신할 수는 없습니다.

arith.int2fp(value)는 int16 또는 int32 scalar를 float32로 변환합니다. 그보다 넓은 정수 타입은 값이 int32 범위에 들어가는 경우에 한해 먼저 int32로 cast하십시오. 이 변환을 런타임에서 지원하는 백엔드는 현재 EVT0뿐이며, 프론트엔드 컴파일이 성공했다고 해서 EVT1에서도 지원된다는 뜻은 아닙니다.

1
2
3
4
5
6
from legato.language import arith

# 실행 컨텍스트 안에서 x는 float32 scalar, n은 int32 scalar입니다.
nearest = arith.fp2int(x, "round_to_even")
truncated = arith.fp2int(x, "towards_zero")
floating = arith.int2fp(n)

fp2int

1
fp2int(value: Value, policy: Value)

Convert a float scalar to an int32 scalar.

Parameters:

  • value (Value): The float scalar to convert.
  • policy (Value): Interpreted rounding policy string. "round_to_even" rounds to the nearest integer, and ties go to the even integer. "towards_zero" drops the fractional part.

Returns:

  • The int32 scalar.

Example:

1
2
3
4
5
6
7
from legato.language import arith

@legato.compile(backend=get_backend)
def fn(x: legato.types.float("float32")):
    device = legato.get_context().get_device()
    with device.get_core(0):
        i = arith.fp2int(x, "round_to_even")

int2fp

1
int2fp(value: Value)

Convert an int16 or int32 scalar to a float32 scalar.

Parameters:

  • value (Value): The integer scalar to convert. Cast other integer types to int32 first.

Returns:

  • The float32 scalar.

Example:

1
2
3
4
5
6
7
from legato.language import arith

@legato.compile(backend=get_backend)
def fn(x: legato.types.integer("int32")):
    device = legato.get_context().get_device()
    with device.get_core(0):
        f = arith.int2fp(x)

수학 함수와 reduction

element-wise 수학 함수와 reduction은 legato.math에서 제공합니다.

1
2
3
row_max = legato.math.reduce_max(scores, -1)
exp_scores = legato.math.exp(scores - row_max)
denom = legato.math.reduce_sum(exp_scores, -1)

legato.math API 전체는 수학 연산을 참고하십시오.