attention = d2l.MultiHeadAttention(num_hiddens=64, num_heads=4)
X = torch.randn(1, 8, 64)
perm = torch.randperm(8)
Y = attention(X, X, X)
Y_perm = attention(X[:, perm], X[:, perm], X[:, perm])
print(f'max |Y[perm] - Y_perm|: {(Y[:, perm] - Y_perm).abs().max():.2e}')10.4 위치 정보
문장 “dog bites man”과 “man bites dog”은 똑같은 세 단어로 이루어져 있습니다. 이를 10.3절 의 마스킹 없는 셀프 어텐션 층에 통과시키면 어텐션 가중치가 오직 토큰 내용에만 의존하기 때문에 순서만 바뀐 정확히 동일한 출력 벡터들이 나옵니다. 어순을 구별하려면 표현이나 점수 규칙 안에 위치 정보를 주입해야 합니다.
위치 인코딩 기법은 크게 세 계열로 나뉩니다. 각 토큰 임베딩에 위치 벡터 \(\mathbf{p}_i\) 를 더하는 방식, 쿼리와 키를 위치 의존적인 각도로 회전시키는 방식(회전 위치 임베딩, RoPE), 또는 어텐션 점수에서 거리 페널티를 빼는 방식(ALiBi)입니다. 세 방식 모두 훈련 문맥 길이 안에서는 위치를 잘 구별하지만, 더 긴 시퀀스로 외삽할 때는 매우 다르게 거동합니다. 먼저 셀프 어텐션의 순열 대칭성을 정식화한 뒤, 길이 \(128\) 에서 훈련하고 최대 길이 \(512\) 까지 평가하는 2층 어텐션 전용 바이트 언어 모델(TinyCharLM)에서 다섯 가지 위치 기법을 구축해 비교합니다.
10.4.1 순열 등변성
\(\mathbf{X} \in \mathbb{R}^{n \times d}\) 가 \(n\) 개의 토큰 벡터를 담고 있고 \(\mathbf{S} = \mathbf{X}\mathbf{W}_q(\mathbf{X}\mathbf{W}_k)^\top/\sqrt{d_h}\) 에 대해 \(f(\mathbf{X}) = \mathrm{softmax}(\mathbf{S})\,\mathbf{X}\mathbf{W}_v\) 가 드롭아웃을 끈 마스킹 없는 셀프 어텐션(10.3절)을 나타낸다고 합시다. \(n\) 개 토큰의 순서를 재배열하는 것은 \(\mathbf{X}\) 의 왼쪽에 \(n \times n\) 순열 행렬 \(\boldsymbol{\Pi}\) 를 곱하는 것에 해당합니다.
명제(순열 등변성). 모든 순열 행렬 \(\boldsymbol{\Pi}\) 에 대해 \(f(\boldsymbol{\Pi} \mathbf{X}) = \boldsymbol{\Pi} f(\mathbf{X})\) 가 성립합니다.
증명. 선형 투영은 행별로 작용하므로 \(\mathbf{W}_q, \mathbf{W}_k, \mathbf{W}_v\) 에 대해 \((\boldsymbol{\Pi}\mathbf{X})\mathbf{W} = \boldsymbol{\Pi}(\mathbf{X}\mathbf{W})\) 입니다. 따라서 점수 행렬은 \(\boldsymbol{\Pi} \mathbf{S} \boldsymbol{\Pi}^\top\) 가 됩니다. 행별 소프트맥스는 행 및 열 순열과 가환(commute)이므로 \(\mathrm{softmax}(\boldsymbol{\Pi} \mathbf{S} \boldsymbol{\Pi}^\top) = \boldsymbol{\Pi}\, \mathrm{softmax}(\mathbf{S})\, \boldsymbol{\Pi}^\top\) 입니다. 여기에 순열 변환된 값 \(\boldsymbol{\Pi}\mathbf{X}\mathbf{W}_v\) 를 곱하고 \(\boldsymbol{\Pi}^\top \boldsymbol{\Pi} = \mathbf{I}\) 를 쓰면 \(\boldsymbol{\Pi} f(\mathbf{X})\) 를 얻습니다. 헤드들을 이어 붙이고 행별로 \(\mathbf{W}_o\) 를 적용해도 등변성은 그대로 보존됩니다. \(\blacksquare\)
4-헤드 MultiHeadAttention 층에서 순열 등변성을 수치적으로 검증해 봅시다.
max |Y[perm] - Y_perm|: 1.08e-07
attention = d2l.MultiHeadAttention(num_hiddens=64, num_heads=4,
rngs=nnx.Rngs(d2l.get_key()))
key_X, key_perm = jax.random.split(d2l.get_key())
X = jax.random.normal(key_X, (1, 8, 64))
perm = jax.random.permutation(key_perm, 8)
Y = attention(X, X, X)
Y_perm = attention(X[:, perm], X[:, perm], X[:, perm])
print(f'max |Y[perm] - Y_perm|: {jnp.abs(Y[:, perm] - Y_perm).max():.2e}')max |Y[perm] - Y_perm|: 0.00e+00
등변 층이나 토큰별 MLP를 여러 겹 쌓아도 등변성은 유지됩니다. 다만 인과적 마스크는 위치 \(i\) 가 \(i+1\) 개의 선행 토큰에 어텐션하게 만들므로 순열 대칭성을 깨뜨리며, 아래에서 살펴볼 NoPE가 바로 이 비대칭성을 활용합니다.
10.4.2 절대 위치 임베딩
원조 트랜스포머 (Vaswani 기타 2017년) 는 각 토큰 임베딩 \(\mathbf{x}_i\) 에 위치 벡터 \(\mathbf{p}_i \in \mathbb{R}^d\)(\(\mathbf{P}\) 의 \(i\) 번째 행)를 더함으로써 입력 단에서 순열 대칭성을 깨뜨립니다. 토큰 순서를 뒤섞으면 \(\mathbf{X} + \mathbf{P}\) 가 \(\boldsymbol{\Pi}\mathbf{X} + \mathbf{P} \neq \boldsymbol{\Pi}(\mathbf{X} + \mathbf{P})\) 로 매핑됩니다.
10.4.2.1 학습된 위치 임베딩
BERT (Devlin 기타 2018년) 및 GPT-2 (Radford 기타 2019년) 같은 모델은 고정된 최대 길이 \(L_{\max}\) 까지 위치마다 하나의 매개변수 행을 갖는 훈련 가능한 임베딩 테이블 \(\mathbf{P} \in \mathbb{R}^{L_{\max} \times d}\) 를 사용합니다. 훈련 문맥 길이를 넘어서는 행들은 그레이디언트를 한 번도 받지 못하므로 학습된 테이블은 본 적 없는 위치로 외삽할 수 없습니다.
10.4.2.2 사인파 인코딩
학습 매개변수 없이 임의의 길이에 대해 위치 벡터를 정의하기 위해 Vaswani 기타 (2017년) 연구진은 기하 간격 주파수 \(\omega_m = 10000^{-2m/d}\) 를 갖는 \(d/2\) 개의 사인과 코사인으로 \(\mathbf{P}\) 의 \(i\) 번째 행을 채웁니다.
\[ p_{i, 2m} = \sin\left(\frac{i}{10000^{2m/d}}\right), \qquad p_{i, 2m+1} = \cos\left(\frac{i}{10000^{2m/d}}\right). \tag{10.4.1}\]
\(\omega_m\) 이 토큰당 \(1\) 라디안(\(m = 0\))에서 \(10^{-4}\)(\(m = d/2 - 1\)) 쪽으로 작아짐에 따라 열 쌍들은 이진 카운터의 연속 아날로그처럼 작동합니다. 낮은 인덱스의 열은 빠르게 진동하여 인접한 위치들을 분리하고, 높은 인덱스의 열은 넓은 구간에 걸쳐 서서히 변합니다.
def sinusoidal_encoding(max_len, num_hiddens):
"""The (max_len, num_hiddens) table of sinusoidal position codes."""
theta = torch.arange(max_len)[:, None] / 10000 ** (
torch.arange(0, num_hiddens, 2) / num_hiddens)
return torch.stack([torch.sin(theta), torch.cos(theta)],
-1).reshape(max_len, num_hiddens)
P = sinusoidal_encoding(60, 32)
d2l.plot(torch.arange(60), P[:, 6:10].T, xlabel='position',
figsize=(6, 2.5), legend=[f'column {d}' for d in range(6, 10)])def sinusoidal_encoding(max_len, num_hiddens):
"""The (max_len, num_hiddens) table of sinusoidal position codes."""
theta = jnp.arange(max_len)[:, None] / 10000 ** (
jnp.arange(0, num_hiddens, 2) / num_hiddens)
return jnp.stack([jnp.sin(theta), jnp.cos(theta)],
-1).reshape(max_len, num_hiddens)
P = sinusoidal_encoding(60, 32)
d2l.plot(jnp.arange(60), P[:, 6:10].T, xlabel='position',
figsize=(6, 2.5), legend=[f'column {d}' for d in range(6, 10)])\(60 \times 32\) 전체 인코딩 행렬 P를 히트맵으로 표시해 보면, 정수 카운터의 이진 자릿수처럼 왼쪽의 빠르게 진동하는 고주파 쌍에서 오른쪽의 서서히 변하는 저주파 쌍으로 전이되는 모습을 볼 수 있습니다.
d2l.show_heatmaps(P[None, None], xlabel='column (encoding dimension)',
ylabel='row (position)', figsize=(3.5, 4), cmap='Blues')d2l.show_heatmaps(P[None, None], xlabel='column (encoding dimension)',
ylabel='row (position)', figsize=(3.5, 4), cmap='Blues')10.4.2.3 회전으로서의 사인파 인코딩
삼각함수의 덧셈정리에 의해 위치 \(i\) 를 오프셋 \(\delta\) 만큼 이동시키면 각 주파수 쌍 \((2m, 2m+1)\) 에 오직 \(\delta\) 에만 의존하는 \(2 \times 2\) 회전이 적용됩니다.
\[ \begin{bmatrix} \cos(\delta \omega_m) & \sin(\delta \omega_m) \\ -\sin(\delta \omega_m) & \cos(\delta \omega_m) \end{bmatrix} \begin{bmatrix} p_{i, 2m} \\ p_{i, 2m+1} \end{bmatrix} = \begin{bmatrix} \sin\left((i+\delta) \omega_m\right) \\ \cos\left((i+\delta) \omega_m\right) \end{bmatrix} = \begin{bmatrix} p_{i+\delta, 2m} \\ p_{i+\delta, 2m+1} \end{bmatrix}. \tag{10.4.2}\]
그러나 \(\mathbf{p}_i\) 가 \(\mathbf{x}_i\) 에 더해지기 때문에 \(\mathbf{A} = \mathbf{W}_q \mathbf{W}_k^\top / \sqrt{d_h}\) 에 대한 쌍선형 어텐션 점수는 네 개의 항으로 전개됩니다.
\[ \begin{aligned} (\mathbf{x}_i + \mathbf{p}_i)^\top \mathbf{A}\, (\mathbf{x}_j + \mathbf{p}_j) &= \underbrace{\mathbf{x}_i^\top \mathbf{A}\, \mathbf{x}_j}_{\textrm{content--content}} + \underbrace{\mathbf{x}_i^\top \mathbf{A}\, \mathbf{p}_j}_{\textrm{content--position}} \\ &\quad + \underbrace{\mathbf{p}_i^\top \mathbf{A}\, \mathbf{x}_j}_{\textrm{position--content}} + \underbrace{\mathbf{p}_i^\top \mathbf{A}\, \mathbf{p}_j}_{\textrm{position--position}}. \end{aligned} \tag{10.4.3}\]
두 교차항은 내용을 절대 위치와 결합시키며(\(i\) 와 \(j\) 가 함께 이동할 때 값이 변함), \(\mathbf{p}_i^\top \mathbf{A}\, \mathbf{p}_j\) 조차도 \(\mathbf{A}\) 가 \(2 \times 2\) 스케일드 회전 블록들을 갖는 블록 대각 행렬일 때만 순전히 \(j - i\) 에 의존합니다(2 참조).
10.4.3 회전 위치 임베딩
회전 위치 임베딩(rotary position embeddings, RoPE) (Su 기타 2024년) 은 모든 점수가 오직 상대 오프셋 \(j - i\) 에만 의존하도록 쿼리와 키에 위치 변환을 곱셈적으로 적용합니다.
\[ (\mathbf{R}_i \mathbf{q})^\top (\mathbf{R}_j \mathbf{k}) = \mathbf{q}^\top \mathbf{R}_i^\top \mathbf{R}_j \mathbf{k} = \mathbf{q}^\top \mathbf{R}_{j-i} \mathbf{k} \quad \textrm{for all } i, j. \tag{10.4.4}\]
최대 랭크(full-rank) \(\mathbf{R}_0\) 조건과 함께 \(\mathbf{R}_i^\top \mathbf{R}_j = \mathbf{R}_{j-i}\) 를 요구하면 다음 세 성질이 도출됩니다: (1) (\(\mathbf{R}_0^\top \mathbf{R}_0 = \mathbf{R}_0\) 로부터) \(\mathbf{R}_0 = \mathbf{I}\); (2) \(\mathbf{R}_i^\top \mathbf{R}_i = \mathbf{I}\), 즉 모든 \(\mathbf{R}_i\) 는 노름을 보존하는 직교 행렬; (3) \(\mathbf{R}_{i+j} = \mathbf{R}_i \mathbf{R}_j\), 즉 \(\mathbf{R}_i = \mathbf{R}_1^i\). (\(\mathbf{W}_q, \mathbf{W}_k\) 에 흡수 가능한) 적절한 정규직교 기저에서 임의의 직교 행렬 \(\mathbf{R}_1\) 은 \(2 \times 2\) 평면 회전들로 분해됩니다. RoPE는 각 쿼리와 키의 \(d_h\) 개 좌표를 \(d_h/2\) 개 쌍으로 나누고 위치 \(i\) 의 쌍 \(m\) 을 \(\omega_m = 10000^{-2m/d_h}\) 에 대해 \(i\omega_m\) 만큼 회전시킵니다(그림 10.4.1).
\[ \begin{aligned} \mathbf{R}_i &= \begin{bmatrix} R(i\omega_0) & & \\ & \ddots & \\ & & R(i\omega_{d_h/2-1}) \end{bmatrix}, \\ R(\alpha) &= \begin{bmatrix} \cos\alpha & -\sin\alpha \\ \sin\alpha & \cos\alpha \end{bmatrix}. \end{aligned} \tag{10.4.5}\]
값 벡터는 회전시키지 않으므로 전역 위치 이동에 대해 층 출력의 불변성이 보장됩니다. RoPE는 현대 오픈 가중치 언어 모델들의 표준 위치 인코딩입니다.
def rope_tables(n, d, offset=0, base=10000.0, scale=None,
device=None):
"""Cosines and sines, each (n, d/2), of the angles of the positions
offset, ..., offset + n - 1."""
pos = torch.arange(n, dtype=torch.float32, device=device) + offset
omega = base ** (-torch.arange(0, d, 2, device=device) / d)
if scale is not None: # One angle factor per pair, shape (d/2,)
omega = omega * scale
theta = pos[:, None] * omega[None, :]
return torch.cos(theta), torch.sin(theta)
def rope(x, offset=0, base=10000.0, scale=None, tables=None):
"""Rotate feature pairs of x (..., num_steps, d) by position angles;
tables from rope_tables take the place of offset, base, and scale."""
if tables is None:
tables = rope_tables(*x.shape[-2:], offset, base, scale, x.device)
# Angles in fp32, tables in the dtype of x: bf16 queries stay bf16
cos, sin = (u.to(x.dtype) for u in tables)
x1, x2 = x[..., 0::2], x[..., 1::2]
return torch.stack([x1 * cos - x2 * sin,
x1 * sin + x2 * cos], -1).flatten(-2)def rope_tables(n, d, offset=0, base=10000.0, scale=None):
"""Cosines and sines, each (n, d/2), of the angles of the positions
offset, ..., offset + n - 1."""
pos = jnp.arange(n, dtype=jnp.float32) + offset
omega = base ** (-jnp.arange(0, d, 2) / d)
if scale is not None: # One angle factor per pair, shape (d/2,)
omega = omega * scale
theta = pos[:, None] * omega[None, :]
return jnp.cos(theta), jnp.sin(theta)
def rope(x, offset=0, base=10000.0, scale=None, tables=None):
"""Rotate feature pairs of x (..., num_steps, d) by position angles;
tables from rope_tables take the place of offset, base, and scale."""
if tables is None:
tables = rope_tables(*x.shape[-2:], offset, base, scale)
# Angles in fp32, tables in the dtype of x: bf16 queries stay bf16
cos, sin = (u.astype(x.dtype) for u in tables)
x1, x2 = x[..., 0::2], x[..., 1::2]
return jnp.stack([x1 * cos - x2 * sin,
x1 * sin + x2 * cos], -1).reshape(x.shape)모든 위치를 임의의 오프셋만큼 이동시켜도 RoPE 점수는 float32 반올림 오차 범위 안에서 동일하게 유지되는 반면, 가산 사인파 점수는 식 10.4.3 의 내용–위치 교차항 때문에 \(O(1)\) 만큼 변합니다.
T, d = 32, 64
q, k = torch.randn(T, d), torch.randn(T, d)
scores = lambda off: rope(q, off) @ rope(k, off).T / math.sqrt(d)
for off in (1, 17, 480):
print(f'RoPE, all positions shifted by {off:>3}: max score change '
f'{(scores(off) - scores(0)).abs().max():.1e}')
P = sinusoidal_encoding(600, d)
added = lambda off: (q + P[off:off+T]) @ (k + P[off:off+T]).T / math.sqrt(d)
print(f'additive sinusoidal, shifted by 17: max score change '
f'{(added(17) - added(0)).abs().max():.1e}')RoPE, all positions shifted by 1: max score change 2.0e-06
RoPE, all positions shifted by 17: max score change 2.1e-06
RoPE, all positions shifted by 480: max score change 1.5e-05
additive sinusoidal, shifted by 17: max score change 2.7e+00
T, d = 32, 64
key_q, key_k = jax.random.split(d2l.get_key())
q, k = jax.random.normal(key_q, (T, d)), jax.random.normal(key_k, (T, d))
# Full float32 matmuls: GPU default (TF32) round-off would hide the check
dot = lambda a, b: jnp.matmul(a, b.T, precision='highest') / math.sqrt(d)
scores = lambda off: dot(rope(q, off), rope(k, off))
for off in (1, 17, 480):
print(f'RoPE, all positions shifted by {off:>3}: max score change '
f'{jnp.abs(scores(off) - scores(0)).max():.1e}')
P = sinusoidal_encoding(600, d)
added = lambda off: dot(q + P[off:off+T], k + P[off:off+T])
print(f'additive sinusoidal, shifted by 17: max score change '
f'{jnp.abs(added(17) - added(0)).max():.1e}')RoPE, all positions shifted by 1: max score change 2.1e-06
RoPE, all positions shifted by 17: max score change 2.1e-06
RoPE, all positions shifted by 480: max score change 1.9e-05
additive sinusoidal, shifted by 17: max score change 2.8e+00
10.4.4 거리 페널티와 무인코딩
토큰, 쿼리, 키 벡터를 전혀 건드리지 않는 두 가지 기법도 있습니다.
ALiBi(Attention with Linear Biases, (Press 기타 2022년))는 헤드 \(h \in \{1, \ldots, H\}\) 의 인과적 어텐션 점수에서 선형 거리 페널티를 직접 뺍니다.
\[ \mathrm{score}_{ij} = \frac{\mathbf{q}_i^\top \mathbf{k}_j}{\sqrt{d_h}} - m_h\,(i - j), \qquad m_h = 2^{-8h/H}. \tag{10.4.6}\]
기하 수열 기울기 \(m_h\)(예: \(H = 4\) 일 때 \(1/4, 1/16, 1/64, 1/256\))는 고정 테이블 크기 없이도 서로 다른 헤드에 서로 다른 최신성 지평(recency horizon)을 부여합니다.
NoPE(No Positional Encoding, (Kazemnejad 기타 2023년))는 위치 신호를 전혀 추가하지 않고 순열 대칭성을 깨기 위해 오직 (위치 \(i\) 에서 \(i + 1\) 개의 키를 노출하는) 인과적 마스크에만 의존합니다.
10.4.5 훈련 길이 너머로의 외삽
다섯 가지 기법이 훈련 분포 내부와 더 긴 문맥으로 외삽할 때 각각 어떻게 작동하는지 비교하기 위해 길이 \(L = 128\) 바이트에서 훈련하고 길이 \(128\), \(256\), \(512\) 에서 혼란도를 평가합니다.
10.4.5.1 언어 모델 TinyCharLM
TinyCharLM은 256개의 바이트 값을 너비 \(d = 128\) 로 임베딩하고 두 개의 인과적 셀프 어텐션 블록(너비 \(d_h = 32\) 인 \(H = 4\) 개 헤드, 위치 정보가 오직 pos를 통해서만 유입되도록 MLP와 정규화 층 생략)을 거친 뒤 가중치 공유(tied) 임베딩 (Press 와/과 Wolf 2017년) 을 통해 바이트 로짓으로 투영합니다.
class TinyCharLM(nn.Module):
"""Attention-only language model."""
def __init__(self, vocab_size, num_hiddens=128, num_heads=4, num_blks=2,
pos='rope', max_len=512, bias=False):
super().__init__()
assert pos in ('learned', 'sinusoidal', 'rope', 'alibi', 'none')
self.num_heads, self.pos = num_heads, pos
self.token_emb = nn.Embedding(vocab_size, num_hiddens)
nn.init.normal_(self.token_emb.weight, std=0.02)
if pos == 'learned':
self.pos_emb = nn.Embedding(max_len, num_hiddens)
nn.init.normal_(self.pos_emb.weight, std=0.02)
if pos == 'sinusoidal':
self.register_buffer('P', sinusoidal_encoding(max_len,
num_hiddens))
if pos == 'rope': # Base and per-pair angle factors of the rotation
self.rope_base = 10000.0
self.register_buffer('rope_scale',
torch.ones(num_hiddens // num_heads // 2))
self.blks = nn.ModuleList([nn.ModuleDict(dict(
qkv=nn.Linear(num_hiddens, 3 * num_hiddens, bias=bias),
proj=nn.Linear(num_hiddens, num_hiddens, bias=bias)))
for _ in range(num_blks)])
def stream(self, X, num_blks=None):
"""Residual stream after the first num_blks blocks (default: all),
and the attention weights of those blocks."""
H, maps = self.embed(X), []
for blk in self.blks[:num_blks]:
out, weights = self.attend(blk, H)
H, maps = H + out, maps + [weights]
return H, maps
def forward(self, X):
return F.linear(self.stream(X)[0], self.token_emb.weight) # Tied
def attention_weights(self, X):
"""Per-block attention maps, each (batch, num_heads, T, T)."""
return self.stream(X)[1]class TinyCharLM(nnx.Module):
"""Attention-only language model."""
def __init__(self, vocab_size, num_hiddens=128, num_heads=4, num_blks=2,
pos='rope', max_len=512, bias=False, *, rngs):
assert pos in ('learned', 'sinusoidal', 'rope', 'alibi', 'none')
self.num_heads, self.pos = num_heads, pos
init = nnx.initializers.normal(0.02)
self.token_emb = d2l.Embed(vocab_size, num_hiddens,
embedding_init=init, rngs=rngs)
if pos == 'learned':
self.pos_emb = nnx.Embed(max_len, num_hiddens,
embedding_init=init, rngs=rngs)
if pos == 'sinusoidal':
self.P = nnx.Cache(sinusoidal_encoding(max_len, num_hiddens))
if pos == 'rope': # Base and per-pair angle factors of the rotation
self.rope_base = 10000.0
self.rope_scale = nnx.Cache(
jnp.ones(num_hiddens // num_heads // 2))
self.blks = nnx.List([nnx.Dict(
qkv=d2l.Linear(num_hiddens, 3 * num_hiddens, use_bias=bias,
rngs=rngs),
proj=d2l.Linear(num_hiddens, num_hiddens, use_bias=bias,
rngs=rngs))
for _ in range(num_blks)])
def stream(self, X, num_blks=None):
"""Residual stream after the first num_blks blocks (default: all),
and the attention weights of those blocks."""
H, maps = self.embed(X), []
for blk in self.blks[:num_blks]:
out, weights = self.attend(blk, H)
H, maps = H + out, maps + [weights]
return H, maps
def __call__(self, X):
return self.token_emb.attend(self.stream(X)[0]) # Tied output head
def attention_weights(self, X):
"""Per-block attention maps, each (batch, num_heads, T, T)."""
return self.stream(X)[1]embed에서는 공유 출력 로짓을 바꾸지 않으면서 \(\mathcal{N}(0, 0.02^2)\) 토큰 임베딩과 스케일을 맞추기 위해 사인파 테이블에 \(1/\sqrt{d}\) 을 곱합니다.
@d2l.add_to_class(TinyCharLM)
def embed(self, X):
"""Token embeddings plus the absolute position code, if any."""
H = self.token_emb(X)
if self.pos == 'learned':
H = H + self.pos_emb(torch.arange(X.shape[1], device=X.device))
if self.pos == 'sinusoidal': # Table scaled to the token embeddings
H = H + self.P[:X.shape[1]] / math.sqrt(H.shape[-1])
return H@d2l.add_to_class(TinyCharLM)
def embed(self, X):
"""Token embeddings plus the absolute position code, if any."""
H = self.token_emb(X)
if self.pos == 'learned':
H = H + self.pos_emb(jnp.arange(X.shape[1]))
if self.pos == 'sinusoidal': # Table scaled to the token embeddings
H = H + self.P[:X.shape[1]] / math.sqrt(H.shape[-1])
return Hattend에서 RoPE는 쿼리와 키를 회전시키는 반면 ALiBi는 소프트맥스 전 점수에 거리 편향 \(-m_h(i - j)\) 를 더합니다.
@d2l.add_to_class(TinyCharLM)
def alibi(self, T, device):
"""ALiBi bias -m_h (i - j) of every head, (num_heads, T, T)."""
h = torch.arange(1, self.num_heads + 1, device=device)
slopes = 2.0 ** (-8.0 * h / self.num_heads)
pos = torch.arange(T, device=device, dtype=torch.float32)
return slopes[:, None, None] * (pos[None, :] - pos[:, None])
@d2l.add_to_class(TinyCharLM)
def attend(self, blk, H):
"""Output of attention block blk on the stream H, and its weights."""
B, T, D = H.shape
q, k, v = blk['qkv'](H).chunk(3, -1)
q, k, v = (u.reshape(B, T, self.num_heads, -1).transpose(1, 2)
for u in (q, k, v))
if self.pos == 'rope':
q = rope(q, base=self.rope_base, scale=self.rope_scale)
k = rope(k, base=self.rope_base, scale=self.rope_scale)
scores = q @ k.transpose(-2, -1) / math.sqrt(q.shape[-1])
if self.pos == 'alibi':
scores = scores + self.alibi(T, H.device)
weights = d2l.masked_softmax(scores, d2l.causal_mask(T, device=H.device))
out = (weights @ v).transpose(1, 2).reshape(B, T, D)
return blk['proj'](out), weights@d2l.add_to_class(TinyCharLM)
def alibi(self, T):
"""ALiBi bias -m_h (i - j) of every head, (num_heads, T, T)."""
h = jnp.arange(1, self.num_heads + 1)
slopes = 2.0 ** (-8.0 * h / self.num_heads)
pos = jnp.arange(T, dtype=jnp.float32)
return slopes[:, None, None] * (pos[None, :] - pos[:, None])
@d2l.add_to_class(TinyCharLM)
def attend(self, blk, H):
"""Output of attention block blk on the stream H, and its weights."""
B, T, D = H.shape
q, k, v = jnp.split(blk['qkv'](H), 3, axis=-1)
q, k, v = (u.reshape(B, T, self.num_heads, -1).swapaxes(1, 2)
for u in (q, k, v))
if self.pos == 'rope':
q = rope(q, base=self.rope_base, scale=self.rope_scale[...])
k = rope(k, base=self.rope_base, scale=self.rope_scale[...])
scores = q @ k.swapaxes(-2, -1) / math.sqrt(q.shape[-1])
if self.pos == 'alibi':
scores = scores + self.alibi(T)
weights = d2l.masked_softmax(scores, d2l.causal_mask(T))
out = (weights @ v).swapaxes(1, 2).reshape(B, T, D)
return blk['proj'](out), weights10.4.5.2 실험
d2l.WikiText103(9.3.1절)의 128바이트 윈도 위에서 각 기법마다 세 개의 시드를 \(3{,}000\) AdamW 스텝 동안 훈련합니다.
data = d2l.WikiText103(batch_size=64, num_steps=128)
schemes = ('learned', 'sinusoidal', 'rope', 'alibi', 'none')
def train_tiny(**kwargs):
"""A TinyCharLM after 3000 steps, and its final training loss."""
model = TinyCharLM(len(data.vocab), **kwargs)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3,
weight_decay=0.0)
return model, d2l.final_loss(d2l.train_steps(model, data, optimizer,
3000))
runs = {} # Three independently initialized models per scheme
for pos in schemes:
trained = [train_tiny(pos=pos) for _ in range(3)]
runs[pos] = [model for model, _ in trained]
print(f'{pos:>10}: final training loss '
+ ', '.join(f'{loss:.2f}' for _, loss in trained))
models = {pos: ms[0] for pos, ms in runs.items()} # The first run of each learned: final training loss 2.28, 2.27, 2.26
sinusoidal: final training loss 2.26, 2.28, 2.29
rope: final training loss 2.02, 2.00, 1.99
alibi: final training loss 2.31, 2.29, 2.31
none: final training loss 2.45, 2.46, 2.47
data = d2l.WikiText103(batch_size=64, num_steps=128)
schemes = ('learned', 'sinusoidal', 'rope', 'alibi', 'none')
def train_tiny(**kwargs):
"""A TinyCharLM after 3000 steps, and its final training loss."""
model = TinyCharLM(len(data.vocab), **kwargs,
rngs=nnx.Rngs(d2l.get_key()))
optimizer = nnx.Optimizer(model, optax.adamw(1e-3, weight_decay=0.0),
wrt=nnx.Param)
return model, d2l.final_loss(d2l.train_steps(model, data, optimizer,
3000))
runs = {} # Three independently initialized models per scheme
for pos in schemes:
trained = [train_tiny(pos=pos) for _ in range(3)]
runs[pos] = [model for model, _ in trained]
print(f'{pos:>10}: final training loss '
+ ', '.join(f'{loss:.2f}' for _, loss in trained))
models = {pos: ms[0] for pos, ms in runs.items()} # The first run of each learned: final training loss 2.26, 2.26, 2.29
sinusoidal: final training loss 2.34, 2.22, 2.32
rope: final training loss 2.00, 2.02, 1.98
alibi: final training loss 2.29, 2.30, 2.31
none: final training loss 2.47, 2.45, 2.47
닫힌 형식의 바이트 바이그램 베이스라인과 나란히, 동일한 검증 바이트들을 \(n \in \{128, 256, 512\}\) 길이 윈도로 재묶어 검증 혼란도를 평가합니다.
train_len, batch = data.num_steps, 16
contexts = (train_len, 2 * train_len, 4 * train_len)
block = batch * max(contexts) # Whole minibatches at every context
num_bytes = (len(data.val) - 1) // block * block
X, Y = data.windows(data.val, range(0, num_bytes, train_len))
eval_sets = {}
for n in contexts: # The same bytes, regrouped into windows of n
Xn, Yn = X.reshape(-1, n), Y.reshape(-1, n)
eval_sets[n] = [(Xn[i:i + batch], Yn[i:i + batch])
for i in range(0, len(Xn), batch)]
def perplexities(model):
return [d2l.lm_perplexity(model, eval_sets[n]) for n in contexts]
def mean_range(values):
"""Mean and (min-max) of the runs, one column of the table."""
return f'{np.mean(values):5.1f} ({min(values):.1f}-{max(values):.1f})'
ppls = {pos: [perplexities(model) for model in ms] for pos, ms in runs.items()}
print(f'{num_bytes:,} validation bytes, mean (min-max) of three runs')
print(f'{"context":>10}: ' + ''.join(f'{n:>18}' for n in contexts))
for pos in schemes: # zip(*...) turns runs x contexts into contexts x runs
print(f'{pos:>10}: '
+ ''.join(f'{mean_range(col):>18}' for col in zip(*ppls[pos])))1,138,688 validation bytes, mean (min-max) of three runs
context: 128 256 512
learned: 9.6 (9.5-9.7) 15.3 (14.9-15.8) 19.7 (18.7-21.1)
sinusoidal: 9.7 (9.4-9.9) 12.8 (12.5-13.3) 15.3 (14.7-15.9)
rope: 7.3 (7.2-7.4) 11.8 (10.5-13.6) 27.0 (18.4-35.5)
alibi: 9.9 (9.8-10.0) 9.9 (9.8-10.0) 9.9 (9.7-9.9)
none: 11.6 (11.5-11.7) 11.7 (11.6-11.8) 11.8 (11.8-11.8)
train_len, batch = data.num_steps, 16
contexts = (train_len, 2 * train_len, 4 * train_len)
block = batch * max(contexts) # Whole minibatches at every context
num_bytes = (len(data.val) - 1) // block * block
X, Y = data.windows(data.val, range(0, num_bytes, train_len))
eval_sets = {}
for n in contexts: # The same bytes, regrouped into windows of n
Xn, Yn = X.reshape(-1, n), Y.reshape(-1, n)
eval_sets[n] = [(Xn[i:i + batch], Yn[i:i + batch])
for i in range(0, len(Xn), batch)]
def perplexities(model):
return [d2l.lm_perplexity(model, eval_sets[n]) for n in contexts]
def mean_range(values):
"""Mean and (min-max) of the runs, one column of the table."""
return f'{np.mean(values):5.1f} ({min(values):.1f}-{max(values):.1f})'
ppls = {pos: [perplexities(model) for model in ms] for pos, ms in runs.items()}
print(f'{num_bytes:,} validation bytes, mean (min-max) of three runs')
print(f'{"context":>10}: ' + ''.join(f'{n:>18}' for n in contexts))
for pos in schemes: # zip(*...) turns runs x contexts into contexts x runs
print(f'{pos:>10}: '
+ ''.join(f'{mean_range(col):>18}' for col in zip(*ppls[pos])))1,138,688 validation bytes, mean (min-max) of three runs
context: 128 256 512
learned: 9.6 (9.4-9.7) 18.0 (15.3-20.7) 25.4 (19.8-31.8)
sinusoidal: 9.8 (9.1-10.3) 12.9 (12.4-13.4) 15.7 (14.3-16.5)
rope: 7.3 (7.2-7.4) 12.4 (12.2-12.7) 27.4 (27.0-28.0)
alibi: 10.0 (9.9-10.0) 9.9 (9.8-10.0) 9.9 (9.8-9.9)
none: 11.7 (11.6-11.7) 11.8 (11.8-11.8) 11.9 (11.9-11.9)
이 수치들의 기준점을 잡기 위해 훈련 말뭉치의 라플라스 평활화 경험적 전이 빈도로부터 동일한 검증 윈도에서의 정확한 바이트 수준 바이그램 혼란도를 계산합니다.
V = len(data.vocab)
counts = np.ones((V, V)) # Byte pair counts, plus one for unseen pairs
for s in range(0, len(data.train) - 1, 10**7): # Chunks of 10^7 bytes
a = data.train[s:s + 10**7 + 1].astype(np.int64)
counts += np.bincount(a[:-1] * V + a[1:], minlength=V * V).reshape(V, V)
bigram = counts / counts.sum(1, keepdims=True) # P(next byte | this byte)
x, y = np.asarray(X).reshape(-1), np.asarray(Y).reshape(-1)
print(f'byte bigram: perplexity {np.exp(-np.log(bigram[x, y]).mean()):.1f}')byte bigram: perplexity 11.6
V = len(data.vocab)
counts = np.ones((V, V)) # Byte pair counts, plus one for unseen pairs
for s in range(0, len(data.train) - 1, 10**7): # Chunks of 10^7 bytes
a = data.train[s:s + 10**7 + 1].astype(np.int64)
counts += np.bincount(a[:-1] * V + a[1:], minlength=V * V).reshape(V, V)
bigram = counts / counts.sum(1, keepdims=True) # P(next byte | this byte)
x, y = np.asarray(X).reshape(-1), np.asarray(Y).reshape(-1)
print(f'byte bigram: perplexity {np.exp(-np.log(bigram[x, y]).mean()):.1f}')byte bigram: perplexity 11.6
훈련 길이(\(n = 128\))에서는 RoPE가 가장 낮은 혼란도(\(7.3\))를 달성하여 학습된 임베딩(\(9.6\)), 사인파(\(9.7\)–\(9.8\)), ALiBi(\(9.9\)–\(10.0\))를 모두 앞서며, 네 기법 모두 바이트 바이그램 베이스라인(\(11.6\))을 개선합니다. 반면 이 작은 2-블록 모델에서 NoPE는 바이그램 수준에 머뭅니다.
\(n = 512\) 에서는 표현이 훈련 범위 밖의 값을 만나는 세 기법의 성능이 급격히 저하됩니다. 학습된 임베딩은 미학습 행(\(128\)–\(511\))을 만나고, 사인파 저주파 열은 본 적 없는 값을 취하며, RoPE의 저주파 쌍은 훈련 중 한 번도 본 적 없는 각도로 회전합니다. 반면 ALiBi의 혼란도는 \(9.9\) 에서 평평하게 유지됩니다. 그 이유를 알아보기 위해 ALiBi의 네 헤드가 거리 \(\ge 128\) 인 키들에 부여하는 어텐션 가중치 비율을 측정하고 거리 \(\ge 128\) 인 모든 키를 마스킹했을 때와 비교합니다.
alibi_model, T = models['alibi'], max(contexts)
device = next(alibi_model.parameters()).device
X_eval = eval_sets[T][0][0].to(device) # 16 windows of 512 bytes
i = torch.arange(T, device=device)
far = i[:, None] - i[None, :] >= train_len # Offsets never trained on
def far_weight(weights):
"""Per head: mean weight on far keys, over queries from train_len on."""
return (weights * far).sum(-1)[..., train_len:].mean((0, -1)).tolist()
with torch.inference_mode():
maps = alibi_model.attention_weights(X_eval)
bias_only = d2l.masked_softmax(alibi_model.alibi(T, device)[None],
d2l.causal_mask(T, device=device))
print(f'{"head":>10}: ' + ''.join(f'{h:>9}' for h in range(1, 5)))
for name, weights in [('bias alone', bias_only)] + [
(f'block {b}', w) for b, w in enumerate(maps, 1)]:
print(f'{name:>10}: ' + ''.join(f'{w:9.3f}' for w in far_weight(weights))) head: 1 2 3 4
bias alone: 0.000 0.000 0.115 0.401
block 1: 0.000 0.000 0.115 0.400
block 2: 0.000 0.000 0.111 0.395
alibi_model, T = models['alibi'], max(contexts)
X_eval = eval_sets[T][0][0] # 16 windows of 512 bytes
i = jnp.arange(T)
far = i[:, None] - i[None, :] >= train_len # Offsets never trained on
def far_weight(weights):
"""Per head: mean weight on far keys, over queries from train_len on."""
return (weights * far).sum(-1)[..., train_len:].mean((0, -1)).tolist()
maps = alibi_model.attention_weights(X_eval)
bias_only = d2l.masked_softmax(alibi_model.alibi(T)[None], d2l.causal_mask(T))
print(f'{"head":>10}: ' + ''.join(f'{h:>9}' for h in range(1, 5)))
for name, weights in [('bias alone', bias_only)] + [
(f'block {b}', w) for b, w in enumerate(maps, 1)]:
print(f'{name:>10}: ' + ''.join(f'{w:9.3f}' for w in far_weight(weights))) head: 1 2 3 4
bias alone: 0.000 0.000 0.115 0.401
block 1: 0.000 0.000 0.115 0.401
block 2: 0.000 0.001 0.119 0.390
훈련된 ALiBi 가중치를 복사한 뒤 길이 \(T = 512\) 에서 평가할 때 거리 \(\ge 128\) 인 모든 키를 하드 마스킹(window=train_len)하는 WindowedALiBi로 이를 직접 확인합니다.
class WindowedALiBi(TinyCharLM):
"""ALiBi whose queries see only the window most recent keys."""
def __init__(self, *args, window, **kwargs):
super().__init__(*args, **kwargs)
self.window = window
def alibi(self, T, device):
i = torch.arange(T, device=device)
return super().alibi(T, device).masked_fill(
i[:, None] - i[None, :] >= self.window, -math.inf)
full, windowed = [], []
for model in runs['alibi']:
model_w = WindowedALiBi(len(data.vocab), pos='alibi',
window=train_len).to(device)
model_w.load_state_dict(model.state_dict()) # Same trained weights
full.append(d2l.lm_perplexity(model, eval_sets[T]))
windowed.append(d2l.lm_perplexity(model_w, eval_sets[T]))
for name, ppl in ('all keys', full), (f'keys < {train_len} back', windowed):
print(f'{name:>16}: perplexity at {T} {mean_range(ppl)}') all keys: perplexity at 512 9.9 (9.7-9.9)
keys < 128 back: perplexity at 512 9.9 (9.7-9.9)
class WindowedALiBi(TinyCharLM):
"""ALiBi whose queries see only the window most recent keys."""
def __init__(self, *args, window, **kwargs):
super().__init__(*args, **kwargs)
self.window = window
def alibi(self, T):
i = jnp.arange(T)
return jnp.where(i[:, None] - i[None, :] >= self.window, -jnp.inf,
super().alibi(T))
full, windowed = [], []
for model in runs['alibi']:
model_w = WindowedALiBi(len(data.vocab), pos='alibi', window=train_len,
rngs=nnx.Rngs(d2l.get_key()))
nnx.update(model_w, nnx.state(model)) # Same trained weights
full.append(d2l.lm_perplexity(model, eval_sets[T]))
windowed.append(d2l.lm_perplexity(model_w, eval_sets[T]))
for name, ppl in ('all keys', full), (f'keys < {train_len} back', windowed):
print(f'{name:>16}: perplexity at {T} {mean_range(ppl)}') all keys: perplexity at 512 9.9 (9.8-9.9)
keys < 128 back: perplexity at 512 9.9 (9.8-9.9)
거리 \(\ge 128\) 인 모든 키를 제거해도 ALiBi의 혼란도는 전혀 변하지 않습니다. 가파른 헤드들은 이미 먼 키들을 무시하고 있으며, 완만한 헤드들은 128바이트 너머로부터 얻을 것이 없는 넓은 최신성 가중 평균을 계산하기 때문입니다. 즉, 평탄한 외삽 곡선은 해당 기법이 먼 키들 때문에 망가지지 않음을 보여줄 뿐 먼 키들로부터 장거리 정보를 실제로 추출한다는 뜻은 아닙니다.
10.4.5.3 훈련된 모델의 문맥 확장하기
왜 RoPE는 훈련 길이 \(L = 128\) 너머에서 망가지며 어떻게 이를 복구할 수 있을까요? 헤드 너비 \(d_h = 32\) 에서 \(16\) 개 좌표 쌍은 주기 \(2\pi / \omega_m = 2\pi \cdot 10000^{m/16}\) 을 가집니다. 처음 \(6\) 개의 빠른(고주파) 쌍은 주기가 \(\le 112 < 128\) 이어서 이미 훈련 윈도 안에서 완전한 회전을 마치는 반면, 나머지 \(10\) 개의 느린(저주파) 쌍은 주기가 \(199\) 부터 \(35{,}000\) 까지여서 \(n = 512\) 에서 본 적 없는 각도 영역으로 회전해 들어갑니다.
위치 보간(position interpolation) (Chen 기타 2023년) 은 새로운 문맥 범위를 훈련된 구간 \([0, 128)\) 안으로 다시 매핑하기 위해 모든 각도에 \(128 / 512 = 1/4\) 을 곱합니다. 그러나 미세조정 없이 빠른 쌍들까지 함께 축소하면 인접 바이트를 구별하는 데 쓰이던 국소 위상차가 파괴됩니다. 빠른 쌍들은 그대로 두고 느린 쌍들만 스케일링하면—YaRN (Peng 기타 2024년) 및 밑을 \(b \mapsto b\, s^{d_h/(d_h - 2)}\) 로 키우는 NTK 인지 스케일링의 핵심 아이디어—추가 훈련 비용을 전혀 들이지 않고도 외삽 혼란도의 대부분을 회복할 수 있습니다.
rope_model = models['rope']
d_head = 2 * rope_model.rope_scale.numel()
periods = (2 * math.pi
* rope_model.rope_base ** (torch.arange(0, d_head, 2) / d_head))
slow = periods > train_len
print(f'{int(slow.sum())} of {d_head // 2} pairs have periods above '
f'{train_len}')
ones = torch.ones(d_head // 2)
shrink = train_len / max(contexts) # Longest context into the trained one
factors = {'unscaled': ones, 'all pairs': ones * shrink,
'slow pairs': torch.where(slow, ones * shrink, ones)}
print(f'{"context":>10}: ' + ''.join(f'{n:>18}' for n in contexts))
for name, factor in factors.items(): # Each of the three trained RoPE runs
ppl = []
for rope_model in runs['rope']:
rope_model.rope_scale.copy_(factor)
ppl.append(perplexities(rope_model))
rope_model.rope_scale.copy_(ones)
print(f'{name:>10}: ' + ''.join(f'{mean_range(col):>18}'
for col in zip(*ppl)))10 of 16 pairs have periods above 128
context: 128 256 512
unscaled: 7.3 (7.2-7.4) 11.8 (10.5-13.6) 27.0 (18.4-35.5)
all pairs: 40.5 (37.9-43.4) 40.7 (38.2-43.6) 40.8 (38.3-43.7)
slow pairs: 8.0 (7.8-8.2) 8.5 (8.2-8.7) 8.8 (8.5-9.1)
rope_model = models['rope']
d_head = 2 * rope_model.rope_scale.shape[0]
periods = (2 * math.pi
* rope_model.rope_base ** (jnp.arange(0, d_head, 2) / d_head))
slow = periods > train_len
print(f'{int(slow.sum())} of {d_head // 2} pairs have periods above '
f'{train_len}')
ones = jnp.ones(d_head // 2)
shrink = train_len / max(contexts) # Longest context into the trained one
factors = {'unscaled': ones, 'all pairs': ones * shrink,
'slow pairs': jnp.where(slow, ones * shrink, ones)}
print(f'{"context":>10}: ' + ''.join(f'{n:>18}' for n in contexts))
for name, factor in factors.items(): # Each of the three trained RoPE runs
ppl = []
for rope_model in runs['rope']:
rope_model.rope_scale[...] = factor
ppl.append(perplexities(rope_model))
rope_model.rope_scale[...] = ones
print(f'{name:>10}: ' + ''.join(f'{mean_range(col):>18}'
for col in zip(*ppl)))10 of 16 pairs have periods above 128
context: 128 256 512
unscaled: 7.3 (7.2-7.4) 12.4 (12.2-12.7) 27.4 (27.0-28.0)
all pairs: 39.7 (33.3-50.6) 40.1 (33.6-51.2) 40.2 (33.7-51.4)
slow pairs: 8.1 (7.9-8.5) 8.7 (8.3-9.5) 9.1 (8.6-10.1)
느린 쌍들만 재스케일링하면 가중치를 단 하나도 업데이트하지 않고 길이-512 혼란도를 약 \(27\) 에서 약 \(9\) 로 낮출 수 있으며, 목표 길이에서 짧게 미세조정하면 남은 격차도 완전히 해소됩니다(6 참조).
10.4.6 요약
마스킹 없는 셀프 어텐션은 모든 토큰 순열 \(\boldsymbol{\Pi}\) 에 대해 \(f(\boldsymbol{\Pi} \mathbf{X}) = \boldsymbol{\Pi} f(\mathbf{X})\) 를 만족하는 순열 등변 함수입니다. 가산 위치 임베딩(학습된 테이블 또는 사인파)은 입력 단에서 이 대칭성을 깨뜨리지만 절대 인덱스에 묶인 내용–위치 교차항을 도입하며 훈련 길이 너머에서 성능이 저하됩니다. 어텐션 점수가 오직 상대 오프셋 \(j - i\) 에만 의존하도록 요구하면 쿼리와 키에 직교 평면 회전(RoPE)이 강제되는 반면, ALiBi는 헤드별 선형 거리 페널티 \(-m_h(i - j)\) 를 뺍니다. 훈련 윈도 너머에서 RoPE는 파장이 훈련 길이를 초과하는 저주파 좌표 쌍들에서 집중적으로 저하되며, 고주파 쌍들은 그대로 둔 채 이 느린 쌍들만 선택적으로 보간하면 장문맥 성능이 복원됩니다.
10.4.7 연습 문제
- 서로 다른 위치, 서로 다른 코드. 주파수 \(\omega_m = 1/10000^{2m/d}\) 를 갖는 너비 \(d\) 인 식 10.4.1 사인파 테이블의 \(i\) 번째 행을 \(\mathbf{p}_i\) 라 합시다.
- 다음 식이 성립함을 보이고, \[\mathbf{p}_i^\top \mathbf{p}_{i+\delta} = \sum_{m=0}^{d/2-1} \cos(\delta\,\omega_m),\] 이로부터 \(\|\mathbf{p}_i - \mathbf{p}_{i+\delta}\|^2\) 을 유도하여 두 값 모두 오프셋 \(\delta\) 에만 의존함을 결론지으십시오.
- 모든 \(m\) 에 대해 \((i - i')\,\omega_m\) 이 \(2\pi\) 의 정수배일 때만 \(\mathbf{p}_i = \mathbf{p}_{i'}\) 가 성립하며, 따라서
max_len값과 무관하게 서로 다른 두 정수 위치는 결코 같은 행을 공유하지 않음을 결론지으십시오. - 가장 빠른 쌍은 주기가 \(2\pi\) 이므로 \(2\pi\) 의 배수에 가까운 정수 오프셋에서 거의 반복됩니다. 각도가 \(2\pi\) 의 배수에 가장 가까워지는 오프셋 \(\delta < 512\) 를 찾고 잔차 각도를 구하십시오. \(d = 32\) 에 대해 이 오프셋에서의 \(\|\mathbf{p}_i - \mathbf{p}_{i+\delta}\|\) 를 \(\delta = 1\) 에서의 값과 비교하고, 거의 반복되는 이 두 위치를 서로 떨어뜨려 놓는 쌍들이 어느 것인지 밝힌 뒤 10.4.2.2절 의 이진 카운터 비유와 연결해 설명하십시오.
- 점수 안의 가산 코드. 10.4.2.2절 의 가산 인코딩을 사용하면 첫 번째 층 헤드는 \(\mathbf{A} = \mathbf{W}_q \mathbf{W}_k^\top / \sqrt{d_h}\) 에 대해 식 10.4.3 의 네 항으로 위치 \(i\) 와 \(j\) 의 입력에 점수를 매깁니다.
- 평면을 \(\pi/2\) 만큼 회전시키는 행렬을 \(\mathbf{J}\) 라 합시다. 식 10.4.2 의 결과를 사용하여 \(\mathbf{A}\) 가 주파수 쌍마다 하나씩 \(2 \times 2\) 블록 \(a_m \mathbf{I} + b_m \mathbf{J}\) 를 갖는 블록 대각 행렬일 때 위치–위치 항 \(\mathbf{p}_i^\top \mathbf{A}\, \mathbf{p}_j\) 가 오직 \(j - i\) 에만 의존함을 보이십시오(1 에서는 \(\mathbf{A} = \mathbf{I}\) 인 경우를 다룹니다). 이어서 서로 다른 두 주파수 쌍을 결합하는 \(\mathbf{A}\) 의 0이 아닌 성분이 단 하나라도 있으면 이 성질이 깨짐을 보이십시오.
- 내용–위치 항 \(\mathbf{x}_i^\top \mathbf{A}\, \mathbf{p}_j\) 가 \(j\) 의 모든 이동에 대해 불변이 되는 조건을 구하십시오. 이 답을 사용해 10.4.3절 의 이동 테스트에서 가산 인코딩의 점수가 변한 이유와 왜 RoPE에는 내용–위치 항이 없는지 설명하십시오.
- [code] 외삽이 실패하는 지점. 문맥 512에서 측정한 10.4.5.2절 의 혼란도는 각 시퀀스의 모든 위치에 걸쳐 손실을 평균 낸 값입니다.
- 다섯 모델 각각에서 길이-512 시퀀스의 위치 0부터 127까지의 로짓이 처음 128개 토큰만 넣고 계산한 로짓과 부동소수점 반올림 오차 범위 내에서 일치함을 수치적으로 확인하십시오.
TinyCharLM의 어떤 두 가지 성질이 모든 기법에서 이를 보장합니까? - 다섯 모델에 대해 길이-512 시퀀스들의 모든 위치에서 검증 손실을 계산하고 16개 위치 윈도 단위로 평균을 내어 위치에 대해 그리십시오. 각 기법에서 곡선이 위치 128 아래에서 유지하던 수준을 어디서 벗어나며, 위치 128에서 손실이 불연속적으로 뛰는지 아니면 서서히 커지는지 확인하십시오.
attend를 오버라이드하는 서브클래스에서 인과적 마스크에 띠(band) 제약을 추가하여models['rope']의 모든 쿼리를 자기 자신을 포함한 최근 128개 키로 제한하고, 훈련된 가중치를 복사해 넣은 뒤 측정을 반복하십시오. 위치 128 너머의 윈도 곡선을 위치 128 아래의 비윈도 곡선과 비교하십시오. 오프셋 127 너머의 키들이 문맥 512에서 나타난 RoPE 성능 저하의 원인입니까?
- 다섯 모델 각각에서 길이-512 시퀀스의 위치 0부터 127까지의 로짓이 처음 128개 토큰만 넣고 계산한 로짓과 부동소수점 반올림 오차 범위 내에서 일치함을 수치적으로 확인하십시오.
- 대칭성을 유지하는 편향. ● 소프트맥스 직전에 증명의 점수 행렬 \(\mathbf{S}\) 에 고정 행렬 \(\mathbf{B} \in \mathbb{R}^{n \times n}\) 을 더하여 셀프 어텐션 층(10.3절)이 \(\mathrm{softmax}(\mathbf{S} + \mathbf{B})\, \mathbf{X}\mathbf{W}_v\) 를 계산한다고 가정합시다.
- \(\boldsymbol{\Pi}^\top \mathbf{B} \boldsymbol{\Pi} = \mathbf{B}\) 를 만족하는 모든 순열 행렬 \(\boldsymbol{\Pi}\) 에 대해 앞선 명제가 여전히 성립함을 보이십시오.
- 모든 순열에 대해 이 조건을 만족하는 행렬 \(\mathbf{B}\) 를 모두 찾고 각각의 행렬이 어텐션 가중치를 어떻게 변화시키는지 설명하십시오.
- 인과적 마스크가 없으면 식 10.4.6 의 ALiBi 편향은 대칭 형태인 \(B_{ij} = -m_h\,|i - j|\) 로 확장됩니다. 이 행렬을 보존하는 순열들을 구하고, 다른 위치 신호 없이 이 편향만 받는 비마스킹 층에 대해 이 결과가 무엇을 뜻하는지 서술하십시오. 왜 식 10.4.6 의 인과적 ALiBi는 이 대칭성을 공유하지 않는지 설명하십시오.
- RoPE의 오프셋 선호도. ● 쿼리 \(\mathbf{q}\) 와 키 \(\mathbf{k}\) 를 식 10.4.5 의 회전이 작용하는 \(d_h/2\) 개의 2차원 쌍 \(\mathbf{q}^{(m)}, \mathbf{k}^{(m)} \in \mathbb{R}^2\) 로 나누고, 쿼리 위치 \(i\) 로부터 키 위치 \(j\) 까지의 오프셋을 \(\delta = j - i\) 라 합시다.
- 식 10.4.4 의 RoPE 점수가 다음과 같음을 보이십시오. \[\sum_{m=0}^{d_h/2-1} \|\mathbf{q}^{(m)}\|\, \|\mathbf{k}^{(m)}\| \cos(\delta\,\omega_m - \psi_m), \tag{10.4.7}\] 여기서 \(\psi_m\) 은 \(\mathbf{k}^{(m)}\) 에서 \(\mathbf{q}^{(m)}\) 으로의 각도(그림 10.4.1 의 \(\varphi\) 와 부호가 반대인 각도)입니다.
- 모든 쌍이 직전 토큰인 오프셋 \(\delta = -1\) 에서 최댓값을 기여하도록 각도 \(\psi_m\) 을 선택하십시오. 모든 곱 \(\|\mathbf{q}^{(m)}\|\, \|\mathbf{k}^{(m)}\|\) 이 \(c\) 로 같을 때 \(\delta\) 의 함수로서 점수가 너비 \(d_h\) 사인파 테이블에 대한 1 의 점곱 \(\mathbf{p}_i^\top \mathbf{p}_{i+\delta}\) 를 평행이동해 \(c\) 배 한 것과 같음을 보이십시오.
- \(d_h = 32\) 이고 오프셋 \(\delta = -127, \ldots, 0\) 에 어텐션하는 위치 127의 쿼리를 택합시다. 인자 \(1/\sqrt{d_h}\) 을 \(c\) 에 흡수시켜 어텐션 로짓이 위 점수와 같다고 둡시다. 오프셋 \(-1\) 이 소프트맥스 가중치의 절반을 가져가는 \(c\) 값을 구하고 이 오프셋과 가장 치열하게 경쟁하는 오프셋들을 식별하십시오. 오프셋 \(-1\) 의 점수와 그 인접 이웃 점수들 사이의 격차를 결정짓는 쌍들은 어느 것입니까?
- [extended] 위치 보간. ● 10.4.5.3절 의 마지막 셀은 추가 훈련 없이 훈련된 RoPE 모델들의 각도를 재스케일링했습니다. 이 문제에서는 그 결과를 분석하고 NTK 인지 스케일링의 밑 변경을 추가한 뒤 미세조정으로 레시피를 완성합니다.
- 훈련 오프셋 0부터 127 사이에서 완전한 한 바퀴 회전을 마치는 쌍은 더 긴 오프셋이 만드는 모든 각도를 모듈로 \(2\pi\) 기준 \(\omega_m/2\) 이내에서 이미 마주쳤음을 보이십시오. \(d_h = 32\) 에 대해 재스케일링 전, \(128/512\) 균일 재스케일링 후, 주기가 128개 위치를 초과하는 쌍들만 재스케일링한 후 각각에 대해 오프셋 \(-1\) 점수와 인접 이웃 점수 사이의 5 격차를 계산하고 이를 셀에서 출력된 문맥 128 혼란도와 연결해 설명하십시오.
- 밑 \(b' = b\, s^{d_h/(d_h-2)}\) 이 \(\omega_0\) 는 그대로 유지하면서 \(\omega_{d_h/2-1}\) 을 \(s\) 로 나눔을 보이십시오. \(s = 4\) 에 대해
models['rope']의rope_base를 이 밑으로 설정하고 추가 훈련 없이 128, 256, 512에서 평가하여 셀의 두 재스케일링 방식과 비교하십시오. - 훈련된
models['rope']의 복사본에서 각각 출발하여 셀의 두 재스케일링 방식 각각으로d2l.WikiText103(batch_size=16, num_steps=512)위에서 문맥 512로 몇백 스텝 미세조정하십시오. 128, 256, 512에서 다시 평가하여 비스케일 모델 및 10.4.5.2절 실험의 동일 길이 ALiBi 모델과 비교하십시오.