수학 연산¶
수학 연산은 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 | |
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 | |
| 호출 | 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 | |
exp¶
1 | |
Compute element-wise exponential of a tensor.
Parameters:
tensor(Value): The input tensor.
Returns:
result(Value): Tensor with exp applied element-wise.
sqrt¶
1 | |
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 | |
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 | |
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 | |
Compute element-wise sine of a tensor.
Parameters:
tensor(Value): The input tensor.
Returns:
result(Value): Tensor with sin applied element-wise.
cos¶
1 | |
Compute element-wise cosine of a tensor.
Parameters:
tensor(Value): The input tensor.
Returns:
result(Value): Tensor with cos applied element-wise.
tan¶
1 | |
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 | |
fold는 다음과 같습니다.
1 2 3 | |
fold에는 논리 원소만 참여합니다.
물리적으로 padding된 꼬리 부분은 해당 fold의 항등원(-inf / +inf / 0)일 뿐, 추가 데이터가 아닙니다.
axis는 인터프리터 값인 정수여야 합니다.
프론트엔드는 rank가 줄어드는 keepdim=False도 받아들이지만,
그 결과의 물리 크기가 호환되지 않으면 Bertha의 물리 shape 추론 단계에서 assert가 발생할 수 있습니다.
attention/softmax 패턴에서는 keepdim=True를 쓰십시오.
다만 그렇게 한다고 해서 일반 reduction까지 백엔드에서 standalone으로 지원된다는 뜻은 아닙니다.
_KEEPDIM_DEFAULT 값은 아래 각 API 항목에 적혀 있습니다.
1 2 | |
reduce_max¶
1 | |
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_min¶
1 | |
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_sum¶
1 | |
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 | |
Softmax¶
softmax는 shape을 유지합니다. 즉 result.shape == tensor.shape입니다.
계산은 수치적으로 안정된 다음 방식을 따릅니다.
1 2 3 4 5 | |
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 | |
softmax¶
1 | |
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 retainaxiswith 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 astensor.
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 | |
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 | |
attention_scores¶
1 | |
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 whencausalis 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 | |
G = 1이면 일반적인 [M, K] @ [K, N] → [M, N]입니다.
G > 1이면 G개의 head 결과를 서로 인접한 열 band([M, G*N])에 기록하며,
이는 grouped-query attention에서 쓰는 concat 순서와 같습니다.
1 2 3 | |
matmul¶
1 | |
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 | |
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 | |
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 | |
Depthwise convolution¶
각 채널은 독립된 FIR 필터로 처리됩니다.
Cin → Cout으로 채널을 섞지 않고, bias가 없으며, dilation / padding_mode 인자도 없습니다
(dilation은 항상 1이고 pad는 0으로 채웁니다).
1 2 3 4 5 6 7 | |
1D의 경우를 풀어 쓰면 다음과 같습니다.
1 2 3 4 5 6 7 8 | |
2D에서는 여기에 (pad_top, pad_bottom, stride_h)를 쓰는 H 방향의 KH 루프가 추가됩니다.
weight의 C는 입력의 C와 일치해야 합니다. 커널 차원은 tap이며 batch 차원이 아닙니다.
dwconv_1d¶
1 | |
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_2d¶
1 | |
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 | |
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 | |
padding_mode를 포함한 1D의 경우를 풀어 쓰면 다음과 같습니다.
1 2 3 4 5 6 7 8 9 10 11 | |
입력의 Cin은 weight의 Cin과 일치해야 합니다.
bias를 주는 경우 dtype이 같은 rank 1 [Cout]이어야 합니다.
프론트엔드는 compute.conv를 생성합니다.
conv_1d¶
1 | |
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_2d¶
1 | |
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 | |
Pooling¶
pooling은 dilation이 1인 conv와 같은 방식으로 window를 순회한 뒤, 채널별로 window 안의 값을 reduction합니다. weight는 없습니다.
1 2 3 4 5 6 7 8 9 10 11 12 | |
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 | |
Channels-last 1D max pooling over [N*, X, C].
1 2 3 4 5 6 7 8 | |
avg_pool_1d¶
1 | |
Channels-last 1D average pooling over [N*, X, C].
1 2 3 4 5 6 | |
max_pool_2d¶
1 | |
Channels-last 2D max pooling over [N*, H, W, C].
1 2 3 4 5 6 7 | |
avg_pool_2d¶
1 | |
Channels-last 2D average pooling over [N*, H, W, C].
1 2 3 4 | |
정규화¶
두 연산 모두 축 하나**를 정규화하고 입력 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 / sqrt(mean(x²) + ε) * weight입니다.
LayerNorm¶
평균을 빼서 중심화한 뒤 편향된 표준편차(/ (D-1)이 아니라 / D)로 나눕니다.
weight와 bias는 서로 독립적으로 생략할 수 있습니다.
1 2 3 4 5 6 7 8 9 10 11 | |
순서는 중심화 → sqrt(var + ε)로 나누기 → scale → shift로 고정되어 있습니다.
affine을 둘 다 생략해도 LayerNorm이며, 이때는 정규화만 수행합니다.
1 2 3 4 | |
rms_norm¶
1 | |
Root-mean-square normalization along axis with a required affine weight.
1 2 3 4 5 | |
layer_norm¶
1 | |
Mean-centered layer normalization along axis with optional affine operands.
1 2 3 4 5 | |