콘텐츠로 이동

수학 연산

수학 연산은 legato.math에서 제공합니다. 이 연산들은 Core compute.* 연산을 생성하며 텐서의 논리 shape을 유지합니다. 즉 물리적으로 padding된 hole [logical, physical)은 추가 원소로 취급하지 않습니다.

이 페이지는 언어 / Core 규약을 다룹니다. shape broadcast와 rank 분해는 Broadcasting에서 설명합니다. 완성된 커널 예제는 연산 함수와 Masking과 Causal Attention에 있습니다. 타겟별 lowering은 이 페이지가 아니라 Language/Bertha에서 다룹니다.

공통 관례

컴파일된 값과 인터프리터 값

텐서 피연산자(input, weight, bias, query, key, softmax에 직접 넘긴 maximum)는 컴파일된 값이어야 합니다. 즉 receive, allocate, @, 또는 다른 legato.math 호출의 결과여야 합니다.

기하 구조 인자와 제어 인자는 컴파일 시점에 **인터프리터**가 평가합니다. axis, keepdim, stride, dilation, padding, padding_mode, kernel_size, epsilon, scale, causal, group_size가 여기에 해당합니다. 이 인자들은 텐서가 아니라 Python / constexpr 값입니다.

attention_scores의 mask_start는 예외입니다. decode에서 동적 cache offset을 넘길 수 있도록, 이 인자는 컴파일된 index 값으로 받습니다.

축

음수 axis는 끝에서부터 세며, 프론트엔드가 이를 [0, rank) 범위의 값으로 변환합니다.

1
2
3
if axis < -rank or axis >= rank:
    error  # LE: axis가 범위를 벗어남
axis = axis + rank if axis < 0 else axis

Logical vs physical

연산은 논리 크기를 기준으로 합니다. 마지막 차원을 (70, 256)으로 쓰면 RMSNorm / LayerNorm / softmax / reduction은 그 길이를 70으로 봅니다. hole [70, 256)은 해당 연산의 항등원(합과 정규화는 0, max / softmax shift는 -inf)으로 채워지므로, 물리 크기 전체를 순회해도 논리 범위만 순회한 것과 결과가 같습니다. Broadcasting을 참고하십시오.

Channels-last spatial 텐서

conv, depthwise conv, pooling은 channels-last 레이아웃을 씁니다.

Rank 구분 Activation Weight
1D [N*, X, C] or [N*, X, Cin] [KX, C] or [KX, Cin, Cout]
2D [N*, H, W, C] or [N*, H, W, Cin] [KH, KW, C] or [KH, KW, Cin, Cout]

N*은 앞쪽에 붙는 0개 이상의 batch 차원입니다. 이 차원들은 결과에 그대로 복사되며, batch 없는 leaf([X, C] / [H, W, C])를 반복하는 prefix 루프로 바뀝니다. weight와 bias에는 N* prefix가 없습니다. 즉 같은 SSA 값이 모든 leaf에 그대로 전달됩니다. Broadcasting: spatial N*을 참고하십시오.


Element-wise 단항 연산

각 호출은 함수 하나를 모든 논리 원소에 적용하고 입력과 rank, 크기, dtype이 같은 텐서를 반환합니다. 축 인자가 없고 원소 사이의 reduction도 없으므로, packed 상태인 rank N 텐서는 벡터 leaf 하나로 flatten할 수 있습니다. 다만 마지막 차원이 padding된 경우에는 rank 1 leaf를 반복하는 prefix 루프로 남아야 합니다.

1
2
3
# 텐서 T. 결과와 shape, dtype이 같음
for idx in logical_indices(T):
    result[idx] = f(T[idx])
호출 f(x) 정의역
exp e^x float
sqrt √x float. x < 0이면 결과는 유한하지 않은 값
abs \|x\| float 또는 정수
log ln(x) (자연로그) float. x ≤ 0이면 결과는 유한하지 않은 값
sin / cos / tan 라디안 단위 삼각함수 float

컴파일러는 정의역 검사를 넣지 않습니다. 정의역 밖의 입력은 피연산자 dtype의 IEEE-754 규칙에 따라 처리됩니다. log는 log2나 log10이 아닙니다.

1
2
3
gate = x / (1.0 + legato.math.exp(-x))          # LUT 없는 SiLU
shifted = scores - row_max
weights = legato.math.exp(shifted)               # softmax 분자

exp

1
exp(tensor: Value)

Compute element-wise exponential of a tensor.

Parameters:

  • tensor (Value): The input tensor.

Returns:

  • result (Value): Tensor with exp applied element-wise.

sqrt

1
sqrt(tensor: Value)

Compute element-wise square root of a tensor.

Parameters:

  • tensor (Value): The input tensor.

Returns:

  • result (Value): Tensor with sqrt applied element-wise.

abs

1
abs(tensor: Value)

Compute element-wise absolute value of a tensor.

Parameters:

  • tensor (Value): The input tensor.

Returns:

  • result (Value): Tensor with abs applied element-wise.

log

1
log(tensor: Value)

Compute element-wise natural logarithm of a tensor.

Parameters:

  • tensor (Value): The input tensor.

Returns:

  • result (Value): Tensor with log applied element-wise.

sin

1
sin(tensor: Value)

Compute element-wise sine of a tensor.

Parameters:

  • tensor (Value): The input tensor.

Returns:

  • result (Value): Tensor with sin applied element-wise.

cos

1
cos(tensor: Value)

Compute element-wise cosine of a tensor.

Parameters:

  • tensor (Value): The input tensor.

Returns:

  • result (Value): Tensor with cos applied element-wise.

tan

1
tan(tensor: Value)

Compute element-wise tangent of a tensor.

Parameters:

  • tensor (Value): The input tensor.

Returns:

  • result (Value): Tensor with tan applied element-wise.

백엔드 지원

이 API 레퍼런스는 프론트엔드 연산과 그 수학적 의미를 설명합니다. 현재 EVT0 lowering이 지원하는 것은 컴파일러가 인식하는 attention/정규화 패턴, maximum을 직접 넘긴 softmax, 그리고 아래 제약을 만족하는 standalone reduce_max입니다. 지원하지 않는 것으로 알려진 standalone reduction은 보통 executor assignment 단계에서 실패하며, 이때 headline LE0121과 함께 LE2119(마지막 축이 아님)나 LE2120(keepdim=True 누락) 같은 사유가 기록됩니다. softmax(scores, -1)은 maximum reduction을 생성하므로 그 reduction의 타겟 제약도 만족해야 합니다. 컴파일 diagnostics 예제와 검증된 연산 함수와 Masking, Causal Attention 예제를 참고하십시오.

마찬가지로 standalone full/full_like와 일반적인 mask 조합은 현재 EVT0 바이너리로 lowering되지 않습니다. causal attention에는 지원되는 attention_scores 패턴을 쓰거나, mask를 적용한 score와 mask 이후의 maximum을 명시적으로 넘기십시오. 프론트엔드 MLIR만 확인해서는 이 백엔드 경로를 검증할 수 없습니다.

EVT1에서는 마지막 축의 BF16 softmax를 reduce_max(scores, -1, True)로 시작해 sub → exp → reduce_sum(..., -1, True) → div로 이어지는 형태로 쓸 수 있습니다. 시뮬레이터 회귀 테스트는 [32, 256] 입력을 사용하며, reduction 대상 폭은 BF16 원소 64개의 배수여야 합니다. 이 패턴이 인식된다고 해서 EVT1에서 모든 reduction이나 dtype을 standalone으로 지원한다는 뜻은 아닙니다. EVT1 검증 표를 참고하십시오.

Reduction 연산

reduction은 **축 하나**만 접습니다. 텐서 전체를 fold하는 것이 아니므로 나머지 차원은 모두 그대로 유지됩니다. keepdim=False(기본값)이면 axis가 제거되고, keepdim=True이면 그 축이 크기 1로 바뀌어 결과를 입력과 그대로 broadcast할 수 있습니다 (scores - reduce_max(scores, -1, True)).

Bertha EVT0에서 standalone reduce_max는 VPU에서 row-major FP16, BF16, FP32 텐서를 대상으로 하며, keepdim=True이고 reduction 축이 마지막 축일 때 지원됩니다. 논리 폭은 정적이어야 하며, 원소 수는 1 이상 16384 이하여야 합니다. prefix 차원은 동적이어도 되며, 정렬된 행 view는 물리 pitch가 더 커도 됩니다. 물리 크기는 논리 폭을 원소 64개 단위로 올림한 크기를 담을 수 있어야 합니다. 정렬되지 않은 입력에서 reduction이 사용하는 꼬리 부분은 입력 규약에 따라 -inf로 채웁니다.

1
2
3
4
5
6
7
8
9
# 입력 shape S, 축 a, keepdim k
if k:
    out_shape = S with S[a] replaced by 1
else:
    out_shape = S with axis a removed

for out_idx in indices(out_shape):
    slice = input along axis a at out_idx
    result[out_idx] = fold(slice)     # max / min / sum

fold는 다음과 같습니다.

1
2
3
reduce_max:  acc = -inf;  acc = max(acc, x)
reduce_min:  acc = +inf;  acc = min(acc, x)
reduce_sum:  acc = 0;     acc = acc + x

fold에는 논리 원소만 참여합니다. 물리적으로 padding된 꼬리 부분은 해당 fold의 항등원(-inf / +inf / 0)일 뿐, 추가 데이터가 아닙니다.

axis는 인터프리터 값인 정수여야 합니다. 프론트엔드는 rank가 줄어드는 keepdim=False도 받아들이지만, 그 결과의 물리 크기가 호환되지 않으면 Bertha의 물리 shape 추론 단계에서 assert가 발생할 수 있습니다. attention/softmax 패턴에서는 keepdim=True를 쓰십시오. 다만 그렇게 한다고 해서 일반 reduction까지 백엔드에서 standalone으로 지원된다는 뜻은 아닙니다. _KEEPDIM_DEFAULT 값은 아래 각 API 항목에 적혀 있습니다.

1
2
row_max = legato.math.reduce_max(masked, -1, True)   # [rows, 1]
denom = legato.math.reduce_sum(exp_scores, -1, True)

reduce_max

1
reduce_max(tensor: Value, axis: Value, keepdim: Value = _KEEPDIM_DEFAULT)

Compute maximum along an axis.

Parameters:

  • tensor (Value): The input tensor.
  • axis (Value): Axis to reduce along. Negative values count from the end.
  • keepdim (Value): If True, the reduced axis is retained with size 1. Defaults to False. Default: _KEEPDIM_DEFAULT.

Returns:

  • result (Value): Reduced tensor. If keepdim=False (default), the axis is removed; if keepdim=True, the axis dimension becomes 1.
1
2
reduce_max(tensor, axis, keepdim=_KEEPDIM_DEFAULT)
_KEEPDIM_DEFAULT = False

reduce_min

1
reduce_min(tensor: Value, axis: Value, keepdim: Value = _KEEPDIM_DEFAULT)

Compute minimum along an axis.

Parameters:

  • tensor (Value): The input tensor.
  • axis (Value): Axis to reduce along. Negative values count from the end.
  • keepdim (Value): If True, the reduced axis is retained with size 1. Defaults to False. Default: _KEEPDIM_DEFAULT.

Returns:

  • result (Value): Reduced tensor. If keepdim=False (default), the axis is removed; if keepdim=True, the axis dimension becomes 1.
1
2
reduce_min(tensor, axis, keepdim=_KEEPDIM_DEFAULT)
_KEEPDIM_DEFAULT = False

reduce_sum

1
reduce_sum(tensor: Value, axis: Value, keepdim: Value = _KEEPDIM_DEFAULT)

Compute sum along an axis.

Parameters:

  • tensor (Value): The input tensor.
  • axis (Value): Axis to reduce along. Negative values count from the end.
  • keepdim (Value): If True, the reduced axis is retained with size 1. Defaults to False. Default: _KEEPDIM_DEFAULT.

Returns:

  • result (Value): Reduced tensor. If keepdim=False (default), the axis is removed; if keepdim=True, the axis dimension becomes 1.
1
2
reduce_sum(tensor, axis, keepdim=_KEEPDIM_DEFAULT)
_KEEPDIM_DEFAULT = False

Softmax

softmax는 shape을 유지합니다. 즉 result.shape == tensor.shape입니다. 계산은 수치적으로 안정된 다음 방식을 따릅니다.

1
2
3
4
5
# 텐서 X, 축 a, shift M  (M은 fiber별 maximum)
shifted = X - M                         # M을 a에 broadcast
numer   = exp(shifted)
denom   = reduce_sum(numer, a, keepdim=True)
result  = numer / denom

maximum을 생략하면 프론트엔드는 axis에 대해 keepdim=True인 reduce_max를 먼저 생성하고, 이어서 compute.softmax를 생성합니다. maximum을 넘기면 compute.softmax만 생성됩니다. 이때 컴파일러는 maximum이 max(X, axis)와 같은지 검사하지 않습니다.

maximum은 axis를 크기 1로 남겨 둔 형태여도 되고 squeeze한 형태여도 됩니다. dtype과, reduction되지 않는 차원의 크기는 X와 일치해야 합니다. maximum의 **값**은 호출자가 책임져야 합니다.

  • mask 이후 텐서에서 구한 유한한 max를 쓰는 것이 좋습니다.
  • mask 이전의 max를 재사용하면 그 값은 상한에 지나지 않습니다. mask 이후의 max와 차이가 크거나 mask 후 행 전체가 -inf이면 underflow가 일어나 0/0 = NaN이 될 수 있습니다.

softmax는 그룹을 구분하지 않습니다. GQA score 텐서 [group_size * q_len, seq_k]도 일반적인 행들로 취급하며, head별로 풀어내지 않습니다.

마지막 축에 대한 softmax는 rank 1 행 leaf로 분해됩니다. Broadcasting: 마지막 축의 행 단위 연산을 참고하십시오.

1
2
probs = legato.math.softmax(scores, -1)              # reduce_max 생성
probs = legato.math.softmax(scores, -1, row_max)     # 계산해 둔 max 재사용

softmax

1
softmax(tensor: Value, axis: Value, maximum: Value | None = None)

Numerically-stable softmax over axis.

Emits a keepdim compute.reduce_max before compute.softmax when maximum is omitted or None. A supplied maximum emits only compute.softmax. Group-agnostic: it treats the grouped [group_size * q_len, seq_k] score tensor as ordinary rows.

Parameters:

  • tensor (Value): The input scores (compiled).
  • axis (Value): Softmax axis. Negative values count from the end.
  • maximum (Value | None): Optional compiled precomputed shift with matching dtype and runtime non-reduced extents. It may retain axis with size one or squeeze it, and must have sufficient storage and bounds. The caller is responsible for its numerical values. For numerical stability, prefer a finite maximum of the actual post-mask tensor. Reusing a pre-mask maximum across nonpositive masks supplies only an upper bound; large gaps or all-masked rows can underflow or produce NaN. These numerical preconditions are not checked by the compiler. Default: None.

Returns:

  • result (Value): Softmax probabilities, the same shape as tensor.

Attention score

attention_scores는 Q @ Kᵀ에 scale을 곱하고, 선택에 따라 causal masking을 적용한 것입니다. key는 이미 matmul에 맞는 형태(Kᵀ)로 받으며, 암묵적으로 transpose하지 않습니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# query : [B*, q_len, G * d_k]
# key   : [B*, d_k, seq_k]          # K^T
# result: [B*, G * q_len, seq_k]    # 그룹별 token-major
# scale > 0, G = group_size >= 1
# mask_start는 생략하면 0. causal이 true일 때만 지정 가능

B* = broadcast(query.shape[:-2], key.shape[:-2])   # matmul과 같은 규칙

for g in 0 .. G-1:
    Qg = query[..., g*d_k : (g+1)*d_k]             # [B*, q_len, d_k]
    band = (Qg @ key) * scale                      # [B*, q_len, seq_k]
    result[..., g*q_len : (g+1)*q_len, :] = band
    if causal:
        for i in 0 .. q_len-1:
            for j in 0 .. seq_k-1:
                if j > i + mask_start:
                    result[..., g*q_len + i, j] = -inf

G = 1이면 일반적인 single-head / head별 attention입니다. 즉 [q_len, d_k] @ [d_k, seq_k] → [q_len, seq_k]입니다.

G > 1이면 grouped-query packing입니다. query에서 서로 인접한 d_k 폭의 band(구간)들이 key 하나를 공유합니다. 결과에는 그 G개의 score 행렬이 head-major가 아니라 token-major([G * q_len, seq_k])로 쌓입니다. causal 대각선의 기준은 각 band 안의 token 인덱스 i이며, packing된 행 번호 g*q_len + i가 아닙니다.

mask_start는 decode에 맞춰 대각선 위치를 옮깁니다. 즉 cache offset이 past_len인 새 token은 mask_start=past_len을 써서 [0, past_len] 구간에 attend하고, K window의 나머지는 mask합니다. seq_k가 정적이면 상수 mask_start는 0 <= mask_start < seq_k를 만족해야 합니다.

scale은 인터프리터 값인 양수 float입니다(보통 1/sqrt(d_k)). causal과 group_size도 인터프리터 값입니다. query와 key는 dtype이 같아야 하고 rank가 2 이상이어야 합니다. 안쪽 차원이 정적이면 query.shape[-1] == group_size * key.shape[-2]를 만족해야 합니다.

1
2
3
scores = legato.math.attention_scores(q, k_t, 1.0 / (d_k ** 0.5), True, 1)
scores = legato.math.attention_scores(q, k_t, scale, True, 1, past_len)
scores = legato.math.attention_scores(q_g, k_g_t, scale, True, group_size)

attention_scores

1
attention_scores(query: Value, key: Value, scale: Value, causal: Value, group_size: Value, mask_start: Value | None = None)

Compute scaled grouped-query attention scores (QK^T) with optional causal masking.

For group_size > 1, query packs adjacent d_k bands that share one K head. Scores are token-major [group_size * q_len, seq_k].

Parameters:

  • query (Value): Query tensor [q_len, group_size * d_k] (compiled).
  • key (Value): Key tensor in matmul-ready K^T form [d_k, seq_k] (compiled).
  • scale (Value): Score multiplier, e.g. 1/sqrt(d_k) (interpreted float).
  • causal (Value): Whether to apply the causal diagonal mask (interpreted bool).
  • group_size (Value): Grouped-query reuse factor, >= 1 (interpreted int).
  • mask_start (Value | None): Optional causal-mask offset index (compiled); valid only when causal is true. Defaults to no offset. Default: None.

Returns:

  • result (Value): The scaled (and optionally masked) scores [group_size * q_len, seq_k].

Grouped 행렬 곱

legato.math.matmul(lhs, rhs, group_size)는 Python의 @가 아닙니다. @는 일반 matmul입니다(산술 연산 참고). 이 helper는 attention_scores와 짝을 이루는 GQA용 P @ V 연산입니다. token-major로 쌓인 lhs의 행을 G개의 band로 나누며, 모든 band가 rhs 하나를 공유합니다.

1
2
3
4
5
6
7
8
9
# lhs : [B*, G * M, K]
# rhs : [B*, K, N]
# out : [B*, M, G * N]
# G = group_size >= 1. lhs.shape[-2]가 정적이면 G로 나누어떨어져야 함

B* = broadcast(lhs.shape[:-2], rhs.shape[:-2])

for g in 0 .. G-1:
    out[..., :, g*N : (g+1)*N] = lhs[..., g*M : (g+1)*M, :] @ rhs

G = 1이면 일반적인 [M, K] @ [K, N] → [M, N]입니다. G > 1이면 G개의 head 결과를 서로 인접한 열 band([M, G*N])에 기록하며, 이는 grouped-query attention에서 쓰는 concat 순서와 같습니다.

1
2
3
# scores_g는 [G * q_len, seq_k], v_g는 [seq_k, d_k]
# 결과는 [q_len, G * d_k] — head들이 마지막 차원에 이어 붙음
ctx = legato.math.matmul(probs_g, v_g, group_size)

matmul

1
matmul(lhs: Value, rhs: Value, group_size: Value)

Grouped P@V matrix multiplication.

For group_size > 1, lhs is token-major [group_size * M, K] and the result is banded [M, group_size * N].

Parameters:

  • lhs (Value): Left tensor [group_size * M, K] (compiled).
  • rhs (Value): Right (shared) tensor [K, N] (compiled).
  • group_size (Value): Grouped reuse factor, >= 1 (interpreted int).

Returns:

  • result (Value): The product [M, group_size * N].

Spatial 기하 구조

conv, depthwise conv, pooling은 같은 기하 구조를 공유합니다. 즉 channels-last 레이아웃을 쓰고, padding은 변(side)마다 따로 지정하는 튜플로 주며, spatial 축마다 출력 길이 공식 하나를 적용합니다. 아래 하위 절들은 **기본값**과 **결과 shape**에 대한 규약을 설명하고, window 샘플링은 그 뒤에서 설명합니다.

튜플 형식

숫자로 주는 기하 구조 인자는 항상 정수로 이루어진 Python tuple(또는 list)입니다. PyTorch처럼 scalar padding=1이나 대칭 (H, W) pad 쌍으로 주는 방식이 아닙니다.

Rank stride / dilation / kernel_size padding
1D (X,) (left, right)
2D (H, W) (top, bottom, left, right)

튜플의 길이는 검사됩니다. 1D 호출에 stride=(1, 1)을 주거나 2D 호출에 padding=(1, 1)을 주면 프론트엔드 에러가 납니다. 각 호출의 기본값 상수는 해당 API 항목 아래에 적혀 있습니다.

출력 shape

결과의 rank는 입력의 rank와 같습니다. 앞쪽 N*(spatial suffix 앞에 있는 모든 차원)은 그대로 복사됩니다. 각 spatial 축의 크기는 아래 공식으로 계산한 값으로 바뀌고, 마지막 축은 출력 채널이 됩니다.

 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
# 입력을 나눔. spatial_rank는 1 또는 2.
#   1D suffix = [I,  C_in]
#   2D suffix = [IH, IW, C_in]
N*     = input.shape[:-spatial_rank-1]
I[...] = input.shape[-spatial_rank-1 : -1]     # spatial 크기 한 개 또는 두 개
C_in   = input.shape[-1]

# 커널과 출력 채널은 연산에 따라 다름.
if dwconv:
    K[...] = weight.shape[:spatial_rank]       # [KX] 또는 [KH, KW]
    C_out  = weight.shape[-1]                  # C_in과 같아야 함
    dil[...] = 1
elif conv:
    K[...] = weight.shape[:spatial_rank]
    C_in_w = weight.shape[spatial_rank]        # C_in과 같아야 함
    C_out  = weight.shape[-1]
    dil[...] = dilation                        # 기본값은 모두 1
elif pool:
    K[...] = kernel_size
    C_out  = C_in
    dil[...] = 1

# 축별 출력 길이 (정수 나눗셈. 프론트엔드
# `_spatial_output_dim` / Core `inferSpatialOutputDim`과 동일).
def spatial_out(I, K, stride, dilation, pad_before, pad_after):
    if I is dynamic or K is dynamic:
        return dynamic                          # ? / -1로 표기
    effective = dilation * (K - 1) + 1
    O = (I + pad_before + pad_after - effective) // stride + 1
    if O <= 0:
        error                                   # 출력 길이가 양수가 아님
    return O

# 1D padding은 (left, right), 2D는 (top, bottom, left, right).
# 축 d는 padding[2*d], padding[2*d+1]과 stride[d], dil[d], K[d]를 사용.
O[...] = [spatial_out(I[d], K[d], stride[d], dil[d],
                      padding[2*d], padding[2*d+1])
          for d in spatial axes]

result.shape = N* ++ O[...] ++ [C_out]

padding_mode는 O를 바꾸지 않습니다. reflect / replicate / circular는 tap이 어느 입력 원소를 읽는지만 바꾸며, 공식에 쓰는 padding된 길이는 그대로 I + pad_before + pad_after입니다.

어떤 spatial 축의 I가 동적(-1 / ?)이면 그 축의 O도 동적으로 남습니다. I와 K가 정적이면 O도 항상 정적이며, 이 O는 > 0이어야 합니다. stride, dilation, kernel_size는 양수여야 하고, padding의 각 항목은 ≥ 0이어야 합니다.

N*은 비어 있을 수도 있고([X, C]는 이미 leaf입니다), batch 차원 여러 개일 수도 있습니다 ([2, 4, 8, 64] 1D conv는 [2, 4]를 그대로 두고 8 → Xout만 바꿉니다). weight와 kernel_size는 batch 축을 만들지 않습니다. 각 호출의 계산 예는 해당 API 항목에 있습니다.

Padding된 좌표를 샘플링하는 방법

spatial 인덱스 p는 padding된 좌표 공간 [-pad_before, I + pad_after) 안의 값입니다. 소스 인덱스는 s = p입니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
def sample(x, s, I, mode, *, pad_value):
    if 0 <= s < I:
        return x[s]
    if mode == "zeros":
        return pad_value
    if mode == "replicate":
        return x[0] if s < 0 else x[I - 1]
    if mode == "circular":
        return x[s - I * floor(s / I)]  # wrap. 0 쪽으로 버림하는 나머지가 아님
    if mode == "reflect":
        # 양 끝점에서 되돌아옴. 가장자리 원소는 반복하지 않음.
        # s = -1 -> 1, s = I -> I-2. I > 1이어야 함.
        while s < 0 or s >= I:
            if s < 0:
                s = -s
            else:
                s = 2 * (I - 1) - s
        return x[s]

2D에서는 1D 규칙을 H와 W에 각각 독립적으로 적용합니다.

padding_mode는 conv에만 있는 문자열 인자이며 _VALID_PADDING_MODES ("zeros", "reflect", "replicate", "circular") 중 하나여야 합니다. depthwise conv는 암묵적으로 "zeros"를 씁니다. pooling에는 mode가 없습니다. max pooling은 pad_value = -inf를 쓰므로 pad가 window의 최댓값으로 선택되는 일이 없고, average pooling은 **합**을 구할 때 pad_value = 0을 쓰되 나눌 때는 그대로 커널 전체 면적으로 나눕니다 (Pooling 참고). 타겟에 따라 일부 mode를 거부할 수 있지만, 이는 백엔드 규칙이며 이 규약에 포함되지 않습니다.

Window 순회

한 축의 출력 좌표 o 하나에 대해서는 다음과 같이 순회합니다.

1
2
3
4
origin = o * stride - pad_before
for t in 0 .. K-1:
    s = origin + t * dilation          # pool / dwconv에서는 dilation이 1
    tap[t] = sample(..., s, ...)

Depthwise convolution

각 채널은 독립된 FIR 필터로 처리됩니다. Cin → Cout으로 채널을 섞지 않고, bias가 없으며, dilation / padding_mode 인자도 없습니다 (dilation은 항상 1이고 pad는 0으로 채웁니다).

1
2
3
4
5
6
7
# dwconv_1d: input [N*, X, C],  weight [KX, C]          → [N*, Xout, C]
# dwconv_2d: input [N*, H, W, C], weight [KH, KW, C]    → [N*, Hout, Wout, C]

for n in N*:
    for c in 0 .. C-1:
        result[n, ..., c] = conv1d_or_2d(input[n, ..., c], weight[..., c],
                                         stride, padding, dilation=1)

1D의 경우를 풀어 쓰면 다음과 같습니다.

1
2
3
4
5
6
7
8
# Xout은 K=KX, dilation=1로 spatial_out에서 계산
for n, xo, c in indices(N*, Xout, C):
    acc = 0
    origin = xo * stride_x - pad_left
    for t in 0 .. KX-1:
        xi = origin + t
        acc += sample_zeros(input[n, :, c], xi, X) * weight[t, c]
    result[n, xo, c] = acc

2D에서는 여기에 (pad_top, pad_bottom, stride_h)를 쓰는 H 방향의 KH 루프가 추가됩니다. weight의 C는 입력의 C와 일치해야 합니다. 커널 차원은 tap이며 batch 차원이 아닙니다.

dwconv_1d

1
dwconv_1d(input: Value, weight: Value, stride: Value = _DWCONV1D_STRIDE_DEFAULT, padding: Value = _DWCONV1D_PADDING_DEFAULT)

Channels-last 1D depthwise convolution.

input is [N*, X, C], weight is [KX, C], and the result is [N*, Xout, C]. stride has length 1; padding is (left, right).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
dwconv_1d(input, weight, stride=_DWCONV1D_STRIDE_DEFAULT, padding=_DWCONV1D_PADDING_DEFAULT)

_DWCONV1D_STRIDE_DEFAULT  = (1,)       # (X,)
_DWCONV1D_PADDING_DEFAULT = (0, 0)     # (left, right)

# bias, dilation, padding_mode 없음 — dilation은 1, pad는 0
# 결과 [N*, Xout, C]
#   Xout = spatial_out(X, KX, stride[0], 1, padding[0], padding[1])
# 기본값을 쓰는 호출 dwconv_1d(x, w)에서 x [19, 64], w [4, 64]이면:
#   Xout = (19 + 0 + 0 - 4) // 1 + 1 = 16  →  [16, 64]

dwconv_2d

1
dwconv_2d(input: Value, weight: Value, stride: Value = _CONV2D_STRIDE_DEFAULT, padding: Value = _CONV2D_PADDING_DEFAULT)

Channels-last 2D depthwise convolution.

input is [N*, H, W, C], weight is [KH, KW, C], and the result is [N*, Hout, Wout, C]. stride is (H, W); padding is (top, bottom, left, right).

1
2
3
4
5
6
7
8
9
dwconv_2d(input, weight, stride=_CONV2D_STRIDE_DEFAULT, padding=_CONV2D_PADDING_DEFAULT)

_CONV2D_STRIDE_DEFAULT  = (1, 1)          # (H, W)  — conv_2d와 공유
_CONV2D_PADDING_DEFAULT = (0, 0, 0, 0)    # (top, bottom, left, right)

# bias, dilation, padding_mode 없음 — dilation은 1, pad는 0
# 결과 [N*, Hout, Wout, C]
#   Hout = spatial_out(H, KH, stride[0], 1, padding[0], padding[1])
#   Wout = spatial_out(W, KW, stride[1], 1, padding[2], padding[3])

Convolution

dense(depthwise가 아닌) convolution은 입력 채널 Cin을 섞어 출력 채널 Cout을 만든 뒤, 필요하면 rank 1 bias를 더합니다. channels-last 레이아웃과 N* 규칙은 depthwise와 같습니다. 다만 weight에는 출력 채널 축이 추가됩니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# conv_1d: input [N*, X, Cin],    weight [KX, Cin, Cout]         → [N*, Xout, Cout]
# conv_2d: input [N*, H, W, Cin], weight [KH, KW, Cin, Cout]     → [N*, Hout, Wout, Cout]
# bias (선택): [Cout]

for n in N*:
    for cout in 0 .. Cout-1:
        acc = 0
        for cin in 0 .. Cin-1:
            acc += conv(input[n, ..., cin], weight[..., cin, cout],
                        stride, dilation, padding, padding_mode)
        if bias is not None:
            acc += bias[cout]
        result[n, ..., cout] = acc

padding_mode를 포함한 1D의 경우를 풀어 쓰면 다음과 같습니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
for n, xo, cout in indices(N*, Xout, Cout):
    acc = 0
    origin = xo * stride_x - pad_left
    for t in 0 .. KX-1:
        xi = origin + t * dilation_x
        for cin in 0 .. Cin-1:
            acc += sample(input[n, :, cin], xi, X, padding_mode, pad_value=0)
                    * weight[t, cin, cout]
    if bias is not None:
        acc += bias[cout]
    result[n, xo, cout] = acc

입력의 Cin은 weight의 Cin과 일치해야 합니다. bias를 주는 경우 dtype이 같은 rank 1 [Cout]이어야 합니다. 프론트엔드는 compute.conv를 생성합니다.

conv_1d

1
conv_1d(input: Value, weight: Value, bias: Value | None = None, stride: Value = _CONV1D_STRIDE_DEFAULT, dilation: Value = _CONV1D_DILATION_DEFAULT, padding: Value = _CONV1D_PADDING_DEFAULT, padding_mode: Value = _PADDING_MODE_DEFAULT)

Channels-last 1D convolution.

input is [N*, X, Cin], weight is [KX, Cin, Cout], optional bias is [Cout], and the result is [N*, Xout, Cout]. stride and dilation have length 1; padding is (left, right).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
conv_1d(input, weight, bias=None,
        stride=_CONV1D_STRIDE_DEFAULT,
        dilation=_CONV1D_DILATION_DEFAULT,
        padding=_CONV1D_PADDING_DEFAULT,
        padding_mode=_PADDING_MODE_DEFAULT)

_CONV1D_STRIDE_DEFAULT   = (1,)       # (X,)
_CONV1D_DILATION_DEFAULT = (1,)       # (X,) — dilation 하나, 값은 1
_CONV1D_PADDING_DEFAULT  = (0, 0)     # (left, right)
_PADDING_MODE_DEFAULT    = "zeros"

# 결과 [N*, Xout, Cout]
#   effective = dilation[0] * (KX - 1) + 1
#   Xout = (X + padding[0] + padding[1] - effective) // stride[0] + 1
# x [8, 64], w [3, 64, 64]인 conv_1d(x, w)는 모든 기본값을 사용:
#   Xout = (8 + 0 + 0 - (1*(3-1)+1)) // 1 + 1 = 6  →  [6, 64]
# conv_1d(x, w, None, (1,), (1,), (1, 1), "zeros"):
#   Xout = (8 + 1 + 1 - 3) // 1 + 1 = 8  →  [8, 64]

conv_2d

1
conv_2d(input: Value, weight: Value, bias: Value | None = None, stride: Value = _CONV2D_STRIDE_DEFAULT, dilation: Value = _CONV2D_DILATION_DEFAULT, padding: Value = _CONV2D_PADDING_DEFAULT, padding_mode: Value = _PADDING_MODE_DEFAULT)

Channels-last 2D convolution.

input is [N*, H, W, Cin], weight is [KH, KW, Cin, Cout], optional bias is [Cout], and the result is [N*, Hout, Wout, Cout]. stride and dilation are (H, W); padding is (top, bottom, left, right).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
conv_2d(input, weight, bias=None,
        stride=_CONV2D_STRIDE_DEFAULT,
        dilation=_CONV2D_DILATION_DEFAULT,
        padding=_CONV2D_PADDING_DEFAULT,
        padding_mode=_PADDING_MODE_DEFAULT)

_CONV2D_STRIDE_DEFAULT   = (1, 1)          # (H, W)
_CONV2D_DILATION_DEFAULT = (1, 1)          # (H, W) — 두 축 모두 1
_CONV2D_PADDING_DEFAULT  = (0, 0, 0, 0)    # (top, bottom, left, right)
_PADDING_MODE_DEFAULT    = "zeros"

# 결과 [N*, Hout, Wout, Cout]
#   Hout = spatial_out(H, KH, stride[0], dilation[0], padding[0], padding[1])
#   Wout = spatial_out(W, KW, stride[1], dilation[1], padding[2], padding[3])
# 기본 pad를 쓰는 conv_2d(x, w): Hout = H - KH + 1, Wout = W - KW + 1

Pooling

pooling은 dilation이 1인 conv와 같은 방식으로 window를 순회한 뒤, 채널별로 window 안의 값을 reduction합니다. weight는 없습니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# 1D: input [N*, X, C]       → [N*, Xout, C]
# 2D: input [N*, H, W, C]    → [N*, Hout, Wout, C]
# kernel_size는 필수. dilation은 항상 1

area = product(kernel_size)              # KX 또는 KH * KW

for n, o..., c in result indices:
    window = sampled taps at o (dilation=1)
    if max:
        result[n, o..., c] = max(window)          # pad tap은 -inf
    if avg:
        result[n, o..., c] = sum(window) / area   # pad tap은 0

average pooling은 항상 pad를 포함한 커널 전체 면적으로 나눕니다 (PyTorch 용어로 count_include_pad=True). 따라서 가장자리 밖으로 걸친 window에서는 분자에 더해지는 실제 원소 수가 분모(커널 면적)보다 적습니다. 이것이 Core 규약이며, count_include_pad=False인 avg_pool과는 다릅니다.

max pooling은 -inf로 padding하므로, window 전체가 pad인 경우가 아니면 pad가 window의 max가 될 수 없습니다 (그런 기하 구조는 O가 양수가 아니게 되므로 거부됩니다. 실제 tap 없이 pad만으로 window가 채워지는 경우에만 -inf가 그대로 남습니다).

max_pool_1d

1
max_pool_1d(input: Value, kernel_size: Value, stride: Value | None = None, padding: Value = _POOL1D_PADDING_DEFAULT)

Channels-last 1D max pooling over [N*, X, C].

1
2
3
4
5
6
7
8
max_pool_1d(input, kernel_size, stride=None, padding=_POOL1D_PADDING_DEFAULT)

_POOL1D_PADDING_DEFAULT = (0, 0)     # (left, right)
# stride에는 이름 붙은 상수가 없음: None이면 stride = kernel_size
# 결과 [N*, Xout, C]
#   Xout = spatial_out(X, KX, stride[0], 1, padding[0], padding[1])
# x [8, 64]인 max_pool_1d(x, (2,)): stride는 (2,)가 됨
#   Xout = (8 + 0 + 0 - 2) // 2 + 1 = 4  →  [4, 64]

avg_pool_1d

1
avg_pool_1d(input: Value, kernel_size: Value, stride: Value | None = None, padding: Value = _POOL1D_PADDING_DEFAULT)

Channels-last 1D average pooling over [N*, X, C].

1
2
3
4
5
6
avg_pool_1d(input, kernel_size, stride=None, padding=_POOL1D_PADDING_DEFAULT)

_POOL1D_PADDING_DEFAULT = (0, 0)     # (left, right)
# stride=None → kernel_size (max_pool_1d와 같은 규칙)
# 결과 [N*, Xout, C]. 나누는 수는 pad를 포함한 KX
# x [8, 64]인 avg_pool_1d(x, (2,)): Xout = 4

max_pool_2d

1
max_pool_2d(input: Value, kernel_size: Value, stride: Value | None = None, padding: Value = _POOL2D_PADDING_DEFAULT)

Channels-last 2D max pooling over [N*, H, W, C].

1
2
3
4
5
6
7
max_pool_2d(input, kernel_size, stride=None, padding=_POOL2D_PADDING_DEFAULT)

_POOL2D_PADDING_DEFAULT = (0, 0, 0, 0)    # (top, bottom, left, right)
# stride=None → kernel_size
# 결과 [N*, Hout, Wout, C]
#   Hout = spatial_out(H, KH, stride[0], 1, padding[0], padding[1])
#   Wout = spatial_out(W, KW, stride[1], 1, padding[2], padding[3])

avg_pool_2d

1
avg_pool_2d(input: Value, kernel_size: Value, stride: Value | None = None, padding: Value = _POOL2D_PADDING_DEFAULT)

Channels-last 2D average pooling over [N*, H, W, C].

1
2
3
4
avg_pool_2d(input, kernel_size, stride=None, padding=_POOL2D_PADDING_DEFAULT)

_POOL2D_PADDING_DEFAULT = (0, 0, 0, 0)    # (top, bottom, left, right)
# stride=None → kernel_size. 나누는 수는 pad를 포함한 KH * KW

정규화

두 연산 모두 축 하나**를 정규화하고 입력 shape을 유지합니다. epsilon은 인터프리터 값이며 ≥ 0인 유한한 scalar로, 수치 안정성을 위해 제곱근 안에 더해집니다. 나누는 수는 **논리 축 길이 D이며, 물리적으로 padding된 폭이 아닙니다. _AXIS_DEFAULT와 _EPSILON_DEFAULT의 값은 아래 각 API 항목에 적혀 있습니다.

affine 벡터(정규화 결과에 곱하고 더하는 weight와 bias)는 그 축 방향으로 채널마다 값 하나를 가집니다. shape은 rank 1 [D]이거나, input과 rank가 같으면서 앞쪽 차원이 모두 1이고 마지막 차원이 D인 형태입니다. 이 벡터는 reduction되지 않는 차원들에 걸쳐 broadcast됩니다. dtype은 input과 일치해야 합니다.

정규화 대상이 마지막 축이면 텐서는 rank 1 행 leaf로 분해됩니다. Broadcasting: 마지막 축의 행 단위 연산을 참고하십시오.

RMSNorm

weight는 필수입니다. 평균을 빼지 않고 bias도 없습니다.

1
2
3
4
5
# 입력 X, weight W, 축 a, epsilon ε
D   = X.shape[a]                                # 논리 크기
ms  = reduce_sum(X * X, a, keepdim=True) / D    # 제곱의 평균
rms = sqrt(ms + ε)
result = (X / rms) * W

즉 x / sqrt(mean(x²) + ε) * weight입니다.

LayerNorm

평균을 빼서 중심화한 뒤 편향된 표준편차(/ (D-1)이 아니라 / D)로 나눕니다. weight와 bias는 서로 독립적으로 생략할 수 있습니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 입력 X, 선택적 weight W, 선택적 bias B, 축 a, epsilon ε
D        = X.shape[a]
mean     = reduce_sum(X, a, keepdim=True) / D
centered = X - mean
var      = reduce_sum(centered * centered, a, keepdim=True) / D
std      = sqrt(var + ε)
result   = centered / std
if W is not None:
    result = result * W
if B is not None:
    result = result + B

순서는 중심화 → sqrt(var + ε)로 나누기 → scale → shift로 고정되어 있습니다. affine을 둘 다 생략해도 LayerNorm이며, 이때는 정규화만 수행합니다.

1
2
3
4
y = legato.math.rms_norm(x, gamma)                    # axis=-1, ε=1e-5
y = legato.math.layer_norm(x, gamma, beta)
y = legato.math.layer_norm(x)                         # 정규화만
y = legato.math.layer_norm(x, None, None, -1, 1e-6)

rms_norm

1
rms_norm(input: Value, weight: Value, axis: Value = _AXIS_DEFAULT, epsilon: Value = _EPSILON_DEFAULT)

Root-mean-square normalization along axis with a required affine weight.

1
2
3
4
5
rms_norm(input, weight, axis=_AXIS_DEFAULT, epsilon=_EPSILON_DEFAULT)

_AXIS_DEFAULT    = -1
_EPSILON_DEFAULT = 1e-5
# weight는 필수. result.shape == input.shape

layer_norm

1
layer_norm(input: Value, weight: Value | None = None, bias: Value | None = None, axis: Value = _AXIS_DEFAULT, epsilon: Value = _EPSILON_DEFAULT)

Mean-centered layer normalization along axis with optional affine operands.

1
2
3
4
5
layer_norm(input, weight=None, bias=None, axis=_AXIS_DEFAULT, epsilon=_EPSILON_DEFAULT)

_AXIS_DEFAULT    = -1
_EPSILON_DEFAULT = 1e-5
# weight와 bias는 서로 독립적으로 생략 가능