12.3  선형 점화식과 병렬 스캔

12.1절 의 게이트 신경망은 수백 스텝에 걸쳐 정보를 유지할 수 있지만, 매 스텝의 게이트와 후보 상태가 이전 상태 \(\mathbf{h}_{t-1}\) 에 의존하기 때문에 시퀀스를 여전히 한 번에 토큰 하나씩 처리합니다. \(4{,}096\) 개 토큰으로 이루어진 시퀀스에서 트랜스포머가 대규모 행렬 곱셈으로 모든 위치를 병렬 처리하는 동안, GRU는 \(4{,}096\) 번의 순차 갱신을 수행하느라 학습 중 GPU의 대부분을 유휴 상태로 남겨 둡니다. 순환 신경망이 \(O(1)\) 상태 기반 자기회귀 생성을 유지하면서도 모든 위치에 대해 병렬로 학습할 수 있을까요?

가능합니다. 게이트와 후보 상태가 오직 현재 입력 \(\mathbf{x}_t\) 에만 의존하게 만들어 점화식을 \(\mathbf{h}_{t-1}\) 에 대해 선형(더 정확히는 아핀(affine))으로 바꾸는 순간 그렇게 됩니다. 아핀 갱신은 프리픽스 합(prefix sum) (Hillis 와/과 Steele 1986년) 과 똑같이 결합 법칙에 따라 합성할 수 있어, 단 \(\lceil \log_2 T \rceil\) 번의 병렬 라운드만으로 \(T\) 개의 모든 상태를 계산할 수 있습니다. 아래에서는 스칼라 감쇠에서 출발해 Feng 기타 (2024년) 의 최소 GRU(MinGRU)로 나아가고, 병렬 결합 스캔(parallel associative scan)을 구현한 뒤, 바이트 단위 WikiText-103에서 MinGRU를 평가하고 최대 \(16{,}384\) 개 토큰까지 순차 GRU 및 인과적 어텐션과 실제 실행 시간 스케일링을 비교합니다.

12.3.1 선형 점화식

12.3.1.1 단일 감쇠 스칼라

이전 값의 고정 비율 \(a \in (0, 1)\) 을 유지하고 입력 \(x_t\) 를 더하는 스칼라 상태 \(h_t\) 부터 시작해 봅시다:

\[h_t = a\, h_{t-1} + x_t, \qquad h_0 = 0. \tag{12.3.1}\]

식 12.3.1 의 식을 시간축으로 펼치면 \(h_t\) 가 과거 입력들로 직접 표현됩니다:

\[h_t = \sum_{s=1}^{t} a^{t-s} x_s. \tag{12.3.2}\]

모든 \(h_t\) 는 반감기가 \(\ln 2 / \ln(1/a)\) 스텝(\(a = 0.9\) 일 때 \(\approx 7\) 스텝, \(a = 0.999\) 일 때 \(\approx 693\) 스텝)인 과거 입력들의 지수 가중 이동 평균이며, 그레이디언트 \(\partial h_t / \partial x_s = a^{t-s}\) 역시 정확히 같은 비율로 감쇠합니다.

12.3.1.2 입력 의존적 감쇠

입력에 의존하는 원소별 감쇠 \(\mathbf{a}_t \in (0, 1)^d\) 와 쓰기(write) 벡터 \(\mathbf{b}_t \in \mathbb{R}^d\) 를 갖는 벡터 상태 \(\mathbf{h}_t \in \mathbb{R}^d\) 로 일반화하면 다음 아핀 점화식을 얻습니다:

\[ \mathbf{h}_t = \mathbf{a}_t \odot \mathbf{h}_{t-1} + \mathbf{b}_t, \qquad \mathbf{a}_t = \mathbf{a}(\mathbf{x}_t), \quad \mathbf{b}_t = \mathbf{b}(\mathbf{x}_t). \tag{12.3.3}\]

식 12.3.3 의 점화식을 펼치면 거듭제곱 \(a^{t-s}\) 이 중간 감쇠들의 누적곱으로 대체됩니다:

\[ \mathbf{h}_t = \sum_{s=1}^{t} \Big( \prod_{r=s+1}^{t} \mathbf{a}_r \Big) \odot \mathbf{b}_s. \tag{12.3.4}\]

\(\mathbf{a}_t\) 와 \(\mathbf{b}_t\) 가 오직 \(\mathbf{x}_t\) 에만 의존하므로, 점화식이 실행되기 전에 전체 시퀀스에 걸쳐 \(T\) 개의 모든 감쇠 벡터와 쓰기 벡터를 병렬로 미리 계산할 수 있습니다. 또한 각 \(\mathbf{a}_r \in (0, 1)^d\) 이므로 과거의 쓰기 내용을 폭주 없이 선택적으로 보존(\(\mathbf{a}_r \approx \mathbf{1}\))하거나 비울(\(\mathbf{a}_r \approx \mathbf{0}\)) 수 있습니다.

12.3.1.3 최소 GRU (minGRU)

12.1.3절 의 표준 GRU에서 이전 상태 \(\mathbf{h}_{t-1}\) 이 들어가는 세 곳을 살펴봅시다:

\[ \begin{aligned} \mathbf{z}_t &= \sigma(\mathbf{W}_{\textrm{xz}} \mathbf{x}_t + \underbrace{\mathbf{W}_{\textrm{hz}} \mathbf{h}_{t-1}}_{\textrm{(1)}} + \mathbf{b}_\textrm{z}),\\ \mathbf{r}_t &= \sigma(\mathbf{W}_{\textrm{xr}} \mathbf{x}_t + \underbrace{\mathbf{W}_{\textrm{hr}} \mathbf{h}_{t-1}}_{\textrm{(2)}} + \mathbf{b}_\textrm{r}),\\ \tilde{\mathbf{h}}_t &= \tanh\big(\mathbf{W}_{\textrm{xh}} \mathbf{x}_t + \underbrace{\mathbf{W}_{\textrm{hh}} (\mathbf{r}_t \odot \mathbf{h}_{t-1})}_{\textrm{(3)}} + \mathbf{b}_\textrm{h}\big), \end{aligned} \]

그 뒤에 \(\mathbf{h}_t = \mathbf{z}_t \odot \mathbf{h}_{t-1} + (1 - \mathbf{z}_t) \odot \tilde{\mathbf{h}}_t\) 가 이어집니다. 표시된 세 개의 순환 의존성을 제거하면(이로써 리셋 게이트 \(\mathbf{r}_t\) 는 완전히 사라짐) Feng 기타 (2024년) 의 최소 GRU(minGRU)가 얻어집니다:

\[ \begin{aligned} \mathbf{z}_t &= \sigma(\mathbf{W}_\textrm{z} \mathbf{x}_t + \mathbf{b}_\textrm{z}), \qquad \tilde{\mathbf{h}}_t = \tanh(\mathbf{W}_\textrm{h} \mathbf{x}_t + \mathbf{b}_\textrm{h}), \\ \mathbf{h}_t &= \mathbf{z}_t \odot \mathbf{h}_{t-1} + (1 - \mathbf{z}_t) \odot \tilde{\mathbf{h}}_t. \end{aligned} \tag{12.3.5}\]

이는 감쇠 \(\mathbf{a}_t = \mathbf{z}_t\) 와 쓰기 \(\mathbf{b}_t = (1 - \mathbf{z}_t) \odot \tilde{\mathbf{h}}_t\) 를 갖는 식 12.3.3 의 아핀 점화식이며, 층의 매개변수 수를 \(6d^2\) 에서 \(2d^2\) 으로 줄여 줍니다. 단일 minGRU 층은 \(\mathbf{h}_{t-1}\) 에 이미 무엇이 들어 있는지에 따라 게이트를 조건화할 수 없지만, 여러 minGRU 블록을 위치별 MLP와 함께 쌓으면 시간축 병렬 평가를 포기하지 않고도 그 능력의 상당 부분을 회복할 수 있습니다. 각 층의 게이트가 바로 아래 층의 상태들을 볼 수 있기 때문입니다. 이를 통해 GRU가 매 스텝마다 수행하는 상태 의존적 게이팅을 층당 한 라운드씩 확보하게 됩니다. 고정된 수의 라운드만으로는 할 수 없는 일이 무엇인지는 12.7.3.5절 에서 측정합니다.

12.3.2 병렬 스캔

12.3.2.1 아핀 스텝 합성하기

식 12.3.4 의 펼쳐진 합을 모든 \(t = 1, \ldots, T\) 에 대해 순진하게 계산하면 \(O(T^2)\) 번의 연산이 걸립니다. 대신 함수 합성의 결합 법칙을 활용합니다. 스텝 \(t\) 의 아핀 사상 \(\mathbf{h} \mapsto \mathbf{a}_t \odot \mathbf{h} + \mathbf{b}_t\) 를 순서쌍 \((\mathbf{a}_t, \mathbf{b}_t)\) 로 나타내 봅시다. 스텝 1에 이어 스텝 2를 적용하면 \(\mathbf{a}_2 \odot (\mathbf{a}_1 \odot \mathbf{h} + \mathbf{b}_1) + \mathbf{b}_2\) 가 되며, 이는 다음 계수를 갖는 또 다른 아핀 사상입니다:

\[ (\mathbf{a}_1, \mathbf{b}_1) \bullet (\mathbf{a}_2, \mathbf{b}_2) = (\mathbf{a}_1 \odot \mathbf{a}_2,\ \mathbf{a}_2 \odot \mathbf{b}_1 + \mathbf{b}_2). \tag{12.3.6}\]

함수 합성은 결합 법칙을 만족하고 임의 구간의 스텝들을 합성한 결과 역시 동일한 크기의 단일 \((\mathbf{a}, \mathbf{b})\) 쌍이므로, \(\mathbf{h}_0 = \mathbf{0}\) 으로부터 \(\mathbf{h}_1, \ldots, \mathbf{h}_T\) 를 계산하는 문제는 연산자 \(\bullet\) 에 대한 결합 프리픽스 스캔(scan)으로 귀결됩니다(\(\mathbf{h}_t\) 는 \(t\) 번째 프리픽스의 두 번째 성분에서 판독).

12.3.2.2 배가 스케줄

그림 12.3.1 에서는 \(T = 8\) 스텝에서 Hillis 와/과 Steele (1986년) 의 병렬 배가 스케줄(doubling schedule)을 보여 줍니다. 라운드 \(r = 0, 1, \ldots, \lceil \log_2 T \rceil - 1\) 에서 모든 위치는 자신보다 스트라이드 \(2^r\) 만큼 앞에 있는 위치와 결합합니다. \(\lceil \log_2 T \rceil\) 라운드가 끝나면 모든 위치가 완전한 프리픽스를 보유하게 됩니다.

그림 12.3.1: 8개 스텝에 대한 병렬 스캔. 각 상자는 해당 값이 어느 스텝들을 결합한 것인지 보여 주며, \((1{:}4)\) 는 스텝 1부터 4까지를 뜻합니다. 매 라운드마다 각 위치는 고정된 스트라이드만큼 앞선 위치와 결합하고(파란색 화살표), 스트라이드는 라운드마다 두 배씩 커지며, 점선 화살표는 값을 그대로 복사합니다. 청록색 상자는 완성된 프리픽스를 나타냅니다. \(\log_2 8 = 3\) 라운드가 지나면 모든 위치가 완성된 프리픽스를 갖습니다.

Hillis–Steele 배가 스케줄은 \(\lceil \log_2 T \rceil\) 번의 병렬 라운드에 걸쳐 \(O(T \log_2 T)\) 번의 결합 연산을 수행하는 반면, Blelloch (1990년) 의 일 효율적(work-efficient) 업스윕/다운스윕 트리 스케줄은 크기가 줄어드는 \(2\lceil \log_2 T \rceil\) 번의 라운드에 걸쳐 \(\sim 2T\) 번의 결합 연산만 수행합니다.

간결한 배가 스케줄을 associative_scan으로 직접 작성합니다.

XLA에 내장된 일 효율적 jax.lax.associative_scan을 호출합니다.

12.3.2.3 구현

linear_scan은 선택적 초기 상태 \(\mathbf{h}_0\) 을 첫 번째 쓰기 \(\mathbf{b}_1 \leftarrow \mathbf{a}_1 \odot \mathbf{h}_0 + \mathbf{b}_1\) 에 반영한 뒤, 시간축(축 1)을 따라 식 12.3.3 의 모든 상태 \(\mathbf{h}_1, \ldots, \mathbf{h}_T\) 를 계산합니다.

def associative_scan(combine, elems):
    """All prefixes of elems under an associative combine; time is axis 1."""
    s = 1
    # Autograd keeps the tensors of every round for the backward pass
    while s < elems[0].shape[1]:  # Combine every position with the one s back
        earlier = tuple(x[:, :-s] for x in elems)
        later = tuple(x[:, s:] for x in elems)
        elems = tuple(torch.cat([x[:, :s], y], 1)
                      for x, y in zip(elems, combine(earlier, later)))
        s *= 2
    return elems

def linear_scan(a, b, h0=None):
    """All states of h_t = a_t * h_{t-1} + b_t; time is the second axis."""
    a = a.expand_as(b)  # Decays may omit axes on which they do not vary
    if h0 is not None:  # Fold the initial state into the first step
        b = torch.cat([a[:, :1] * h0.unsqueeze(1) + b[:, :1], b[:, 1:]], 1)
    def combine(earlier, later):
        (a1, b1), (a2, b2) = earlier, later
        return a1 * a2, a2 * b1 + b2
    return associative_scan(combine, (a, b))[1]
def linear_scan(a, b, h0=None):
    """All states of h_t = a_t * h_{t-1} + b_t; time is the second axis."""
    a = jnp.broadcast_to(a, b.shape)  # Decays may omit axes; broadcast them
    if h0 is not None:  # Fold the initial state into the first step
        b = b.at[:, 0].add(a[:, 0] * h0)
    def combine(earlier, later):
        (a1, b1), (a2, b2) = earlier, later
        return a1 * a2, a2 * b1 + b2
    # Autograd keeps the intermediate results of the scan for the backward pass
    return jax.lax.associative_scan(combine, (a, b), axis=1)[1]

2의 거듭제곱이 아닌 길이 \(T = 100\) 에서 스텝별 순차 루프와 linear_scan을 비교해 검증해 봅시다.

def sequential_scan(a, b):
    h, states = torch.zeros_like(b[:, 0]), []
    for a_t, b_t in zip(a.unbind(1), b.unbind(1)):
        h = a_t * h + b_t
        states.append(h)
    return torch.stack(states, 1)

a, b = torch.rand(4, 100, 8), torch.randn(4, 100, 8)
print(f'max deviation: '
      f'{(linear_scan(a, b) - sequential_scan(a, b)).abs().max():.1e}')
max deviation: 4.8e-07
def sequential_scan(a, b):
    def step(h, ab):
        h = ab[0] * h + ab[1]
        return h, h
    # lax.scan steps through the leading axis, so time goes first
    ab = (jnp.swapaxes(a, 0, 1), jnp.swapaxes(b, 0, 1))
    return jnp.swapaxes(jax.lax.scan(step, jnp.zeros_like(b[:, 0]), ab)[1], 0, 1)

key_a, key_b = jax.random.split(d2l.get_key())
a = jax.random.uniform(key_a, (4, 100, 8))
b = jax.random.normal(key_b, (4, 100, 8))
print(f'max deviation: '
      f'{jnp.abs(linear_scan(a, b) - sequential_scan(a, b)).max():.1e}')
max deviation: 4.8e-07

병렬 스캔과 순차 루프는 float32 반올림 허용 오차(\(< 10^{-6}\)) 내에서 일치합니다.

12.3.3 선형 순환 언어 모델

12.3.3.1 텍스트에서의 minGRU

두 선형 투영(\(\mathbf{W}_\textrm{z}\) 와 \(\mathbf{W}_\textrm{h}\)) 바깥에 linear_scan을 감싸면 d2l.SeqLM에 바로 끼워 넣을 수 있는 시퀀스 믹서로서 식 12.3.5 의 MinGRU가 구현됩니다.

class MinGRU(nn.Module):
    """The minimal GRU: its gate and candidate read only the input."""
    def __init__(self, num_inputs, num_hiddens):
        super().__init__()
        self.W_z = nn.Linear(num_inputs, num_hiddens)  # Update gate (decay)
        self.W_h = nn.Linear(num_inputs, num_hiddens)  # Candidate state
        d2l.init_lecun(self)

    def coefficients(self, X):
        """Decays a_t and writes b_t of the linear recurrence."""
        Z = torch.sigmoid(self.W_z(X))
        return Z, (1 - Z) * torch.tanh(self.W_h(X))

    def forward(self, X):  # X: (batch_size, num_steps, num_inputs)
        return linear_scan(*self.coefficients(X))
class MinGRU(nnx.Module):
    """The minimal GRU: its gate and candidate read only the input."""
    def __init__(self, num_inputs, num_hiddens, *, rngs):
        self.W_z = nnx.Linear(num_inputs, num_hiddens, rngs=rngs)  # Decay
        self.W_h = nnx.Linear(num_inputs, num_hiddens, rngs=rngs)

    def coefficients(self, X):
        """Decays a_t and writes b_t of the linear recurrence."""
        Z = jax.nn.sigmoid(self.W_z(X))
        return Z, (1 - Z) * jnp.tanh(self.W_h(X))

    def __call__(self, X):  # X: (batch_size, num_steps, num_inputs)
        return linear_scan(*self.coefficients(X))

게이트에서 \(\mathbf{h}_{t-1}\) 을 제거하면 바이트 단위 WikiText-103에서 모델링 품질이 얼마나 손해 볼까요? 12.1.4.2절 에서와 정확히 동일한 설정(d2l.SeqLM 4블록, 128바이트 윈도, 1,000스텝)을 사용하여 먼저 text_model과 세 가지 비교군 arms를 정의합니다. GRU(\(d = 256\), \(3.81\textrm{M}\) 매개변수), 동일 너비의 minGRU(\(d = 256\), \(2.76\textrm{M}\) 매개변수), 그리고 매개변수 수를 맞춘 폭 확장 minGRU(minGRU, d=302, \(3.81\textrm{M}\) 매개변수)입니다:

torch.set_float32_matmul_precision('high')  # fp32 matmuls may use tf32

def text_model(mixer, d):  # 256 byte values; four blocks of width d
    return d2l.SeqLM(256, d, [mixer(d) for _ in range(4)]).to(d2l.try_gpu())

gru = lambda d: d2l.Recurrent(d2l.init_lecun(nn.GRU(d, d, batch_first=True)))
min_gru = lambda d: MinGRU(d, d)
arms = {'GRU': (gru, 256), 'minGRU': (min_gru, 256),
        'minGRU, d=302': (min_gru, 302)}  # As many parameters as the GRU
def text_model(mixer, d):  # 256 byte values; four blocks of width d
    rngs = nnx.Rngs(d2l.get_key())
    return d2l.SeqLM(256, d, [mixer(d, rngs) for _ in range(4)], rngs=rngs)

lecun = nnx.initializers.lecun_normal()  # For the recurrent matrices
gru = lambda d, rngs: nnx.RNN(
    nnx.GRUCell(d, d, recurrent_kernel_init=lecun, rngs=rngs), unroll=8)
min_gru = lambda d, rngs: MinGRU(d, d, rngs=rngs)
arms = {'GRU': (gru, 256), 'minGRU': (min_gru, 256),
        'minGRU, d=302': (min_gru, 302)}  # As many parameters as the GRU

128바이트 WikiText103 데이터셋을 불러와 세 실험군 모두에 대해 d2l.text_table을 실행하고, 내부 분석을 위해 첫 번째로 학습된 minGRU 모델을 보관합니다:

data = d2l.WikiText103(batch_size=64, num_steps=128)
trained = d2l.text_table(text_model, arms, data)
model = trained['minGRU'][0]  # The model we look inside below
                           validation        0-15       16-63      64-127   ms/step
GRU             3,817,216 1.299/1.300 1.490/1.491 1.273/1.274 1.270/1.271 33/32
minGRU          2,764,544 1.343/1.348 1.520/1.520 1.319/1.323 1.317/1.324 26/26
minGRU, d=302   3,816,932 1.328/1.329 1.508/1.507 1.303/1.304 1.301/1.303 26/28
data = d2l.WikiText103(batch_size=64, num_steps=128)
trained = d2l.text_table(text_model, arms, data)
model = trained['minGRU'][0]  # The model we look inside below
                           validation        0-15       16-63      64-127   ms/step
GRU             3,814,144 1.300/1.299 1.491/1.491 1.274/1.273 1.271/1.271 16/16
minGRU          2,764,544 1.346/1.345 1.520/1.521 1.320/1.320 1.321/1.320 10/10
minGRU, d=302   3,816,932 1.330/1.330 1.510/1.508 1.305/1.306 1.305/1.304 10/10

동일 너비(\(d = 256\))에서 minGRU는 GRU보다 바이트당 \(\sim 0.05\) nats 뒤처지며(\(1.35\) 대 \(1.30\)), 동일 매개변수 수(minGRU, d=302)에서는 그 격차의 약 5분의 2를 좁혀(\(\sim 1.33\)) 12.1.4.2절 의 단순 \(\tanh\) RNN과 나란히 자리하면서도 어텐션 베이스라인(\(1.38\))을 능가하고 순차 루프 대신 병렬 스캔으로 학습됩니다.

12.3.3.2 학습된 모델 내부 살펴보기

minGRU가 순환 상태에 얼마나 의존하는지 확인하기 위해, 매 스텝 직전에 상태를 0으로 초기화하여(\(\mathbf{h}_t = \mathbf{b}_t\) 가 현재 바이트에만 의존하도록 하는 StateReset) 학습된 \(d = 256\) 모델을 평가합니다.

class StateReset(nn.Module):
    """A minGRU layer whose state is reset to zero before every step."""
    def __init__(self, layer):
        super().__init__()
        self.layer = layer

    def forward(self, X):
        return self.layer.coefficients(X)[1]

layers = model.mixers
loss = np.mean(d2l.loss_by_position(model, data))
model.mixers = nn.ModuleList([StateReset(layer) for layer in layers])
reset = np.mean(d2l.loss_by_position(model, data))
model.mixers = layers
print(f'validation loss: {loss:.3f} nats per byte, '
      f'with the state reset at every step: {reset:.3f}')
validation loss: 1.343 nats per byte, with the state reset at every step: 2.481
class StateReset(nnx.Module):
    """A minGRU layer whose state is reset to zero before every step."""
    def __init__(self, layer):
        self.layer = layer

    def __call__(self, X):
        return self.layer.coefficients(X)[1]

layers = model.mixers
loss = np.mean(d2l.loss_by_position(model, data))
model.mixers = nnx.List([StateReset(layer) for layer in layers])
reset = np.mean(d2l.loss_by_position(model, data))
model.mixers = layers
print(f'validation loss: {loss:.3f} nats per byte, '
      f'with the state reset at every step: {reset:.3f}')
validation loss: 1.346 nats per byte, with the state reset at every step: 2.482

상태를 0으로 리셋하면 검증 손실이 바이트당 \(1.35\) 에서 \(2.48\) nats로 치솟는데(사실상 11.2절 의 경험적 바이트 바이그램 베이스라인인 바이트당 \(2.45\) nats 수준), 이는 바이트당 \(1.1\) nats 이상의 성능 향상이 상태에 실려 전달된 문맥에서 비롯됨을 확인해 줍니다.

또한 첫 번째 블록의 업데이트 게이트 감쇠 \(\mathbf{z}_t\) 분포가 학습 전후에 어떻게 달라지는지도 살펴볼 수 있습니다. d2l.SeqLM에 first_mixer_input을 추가하면 첫 번째 믹서에 공급되는 정규화된 토큰 임베딩을 추출할 수 있습니다.

@d2l.add_to_class(d2l.SeqLM)
def first_mixer_input(self, X):
    """What the first mixer reads: the normalized token embeddings."""
    return self.norms[0](self.embedding(X))
@d2l.add_to_class(d2l.SeqLM)
def first_mixer_input(self, X):
    """What the first mixer reads: the normalized token embeddings."""
    return self.norms[0](self.embedding(X))

학습되지 않은 minGRU와 학습된 model 양쪽에서 검증 미니배치를 first_gates에 통과시키면 \(0.5\), \(0.9\), \(0.99\) 를 초과하는 업데이트 게이트의 비율이 표로 정리됩니다:

def first_gates(model, X):  # Gates of the first layer
    return model.mixers[0].coefficients(model.first_mixer_input(X))[0]

X, _ = next(iter(data.val_dataloader()))  # Validation text
X = X.to(next(model.parameters()).device)
with torch.inference_mode():
    Z_init = first_gates(text_model(min_gru, 256), X)  # Untrained
    Z = first_gates(model, X)
print('gate above  half-life in steps  share at initialization  trained')
for g in (0.5, 0.9, 0.99):
    print(f'{g:10}  {math.log(2) / -math.log(g):17.0f}  '
          f'{(Z_init > g).float().mean():23.1%}  '
          f'{(Z > g).float().mean():7.1%}')
gate above  half-life in steps  share at initialization  trained
       0.5                  1                    49.0%    53.4%
       0.9                  7                     1.3%    17.1%
      0.99                 69                     0.0%     0.1%
def first_gates(model, X):  # Gates of the first layer
    return model.mixers[0].coefficients(model.first_mixer_input(X))[0]

X = jnp.asarray(next(iter(data.val_dataloader()))[0])  # Validation text
Z_init = first_gates(text_model(min_gru, 256), X)  # Untrained
Z = first_gates(model, X)
print('gate above  half-life in steps  share at initialization  trained')
for g in (0.5, 0.9, 0.99):
    print(f'{g:10}  {math.log(2) / -math.log(g):17.0f}  '
          f'{(Z_init > g).mean():23.1%}  {(Z > g).mean():7.1%}')
gate above  half-life in steps  share at initialization  trained
       0.5                  1                    49.1%    52.3%
       0.9                  7                     1.7%    17.8%
      0.99                 69                     0.0%     0.0%

학습을 거치면 반감기가 \(\ge 7\) 바이트인 게이트(\(g > 0.9\))의 비중이 열 배 이상(\(\sim 1\%\) 에서 약 \(18\%\) 로) 증가하여 128바이트 윈도에서 필요한 단어 수준 시간 스케일에 부합하게 되는 반면, 영 편향 초기화에서 출발해서는 \(g > 0.99\)(반감기 69바이트)에 도달하는 게이트가 거의 없습니다.

12.3.4 어텐션과의 비용 비교

12.3.4.1 연산량, 깊이 및 메모리

표 12.3.1 에서는 \(T\) 개의 토큰에 대해 너비 \(d\) 인 단일 층의 점근적 학습 연산량, 순차 깊이, 자기회귀 생성 상태를 비교합니다.

표 12.3.1: 상수 인자를 생략한, \(T\) 개 토큰에 대한 너비 \(d\) 단일 층의 비용.
층 학습 연산량 연속 실행 스텝 수 생성 시 메모리
GRU, 한 번에 한 스텝씩 \(T d^2\) \(T\) \(d\)
minGRU, 배가 스캔 \(T d^2 + T d \log_2 T\) \(\log_2 T\) \(d\)
minGRU, 일 효율적 스캔 \(T d^2 + T d\) \(2 \log_2 T\) \(d\)
인과적 어텐션 \(T d^2 + T^2 d\) 소수의 행렬 곱 \(2 T d\)

GRU와 minGRU는 모두 \(O(Td^2)\) 의 투영 연산을 수행하고 디코딩 중 \(O(d)\) 상태 벡터를 유지하지만, minGRU는 순차 학습 깊이를 \(T\) 번의 행렬-벡터 스텝에서 \(O(\log_2 T)\) 번의 원소별 스캔 라운드로 줄입니다. 인과적 어텐션은 학습 중 순차 깊이가 \(O(1)\) 이지만, 어텐션 스코어 및 혼합 연산량이 \(O(T^2 d)\) 로 이차 비례해 증가하고(\(T \approx 4d\) 부근에서 \(8Td^2\) 투영 FLOPs와 교차), 추론 KV 캐시 역시 \(2Td\) 로 선형 증가합니다.

12.3.4.2 실측 비용

실제 하드웨어에서 이 스케일링 법칙들이 어디서 교차하는지 확인하기 위해, 시퀀스 길이 \(T\) 를 \(512\) 에서 \(16{,}384\) 까지 스윕하면서 배치당 총 토큰 수를 \(B \times T = 65{,}536\) 으로 고정한 채 너비 \(d = 256\), float16 조건에서 순전파+역전파 시간을 측정합니다. 총 토큰 수가 고정되어 있으므로 비용이 \(T\) 에 엄격히 선형인 층은 수평선을 그리는 반면, \(O(T)\) 순차 스텝이나 \(O(T^2)\) 쌍별 연산이 지배하는 층은 \(T\) 가 두 배가 될 때마다 실행 시간도 두 배로 늘어납니다.

d, tokens = 256, 65536  # Width; tokens per call, in sequences of length T
device, half = d2l.try_gpu(), torch.float16  # 16-bit floats throughout
timed = {'GRU': d2l.Recurrent(nn.GRU(d, d, batch_first=True)),
         'minGRU': torch.compile(MinGRU(d, d)),
         'attention': d2l.CausalAttention(d, num_heads=4)}
for layer in timed.values():
    layer.to(device, half)

def time_call(layer, T):
    """Milliseconds for a forward and backward pass over tokens / T
    sequences of length T."""
    X = torch.randn(tokens // T, T, d, device=device, dtype=half,
                    requires_grad=True)
    return 1000 * d2l.Benchmark(lambda: layer(X).float().sum().backward(),
                                warmup=1, repeats=3).time
class FusedAttention(d2l.CausalAttention):
    """Causal attention through cuDNN's fused kernel."""
    @staticmethod
    def attend(q, k, v):
        return jax.nn.dot_product_attention(q, k, v, is_causal=True,
                                            implementation='cudnn')

d, tokens = 256, 65536  # Width; tokens per call, in sequences of length T
half, rngs = jnp.float16, nnx.Rngs(d2l.get_key())  # 16-bit floats
timed = {'GRU': nnx.RNN(nnx.GRUCell(d, d, recurrent_kernel_init=lecun,
                                    param_dtype=half, rngs=rngs), unroll=8),
         'minGRU': MinGRU(d, d, rngs=rngs),
         'attention': FusedAttention(d, num_heads=4, rngs=rngs)}
for layer in timed.values():  # Every weight in 16 bits
    params = nnx.state(layer, nnx.Param)
    nnx.update(layer, jax.tree.map(lambda p: p.astype(half), params))

@nnx.jit
def forward_backward(layer, X):
    loss = lambda layer, X: layer(X).astype(jnp.float32).sum()
    return nnx.grad(loss, argnums=(0, 1))(layer, X)

def time_call(layer, T):
    """Milliseconds for a forward and backward pass over tokens / T
    sequences of length T."""
    X = jax.random.normal(d2l.get_key(), (tokens // T, T, d), half)
    return 1000 * d2l.Benchmark(lambda: forward_backward(layer, X),
                                warmup=1, repeats=3).time

시퀀스 길이 \(T \in \{512, 1024, 2048, 4096, 8192, 16384\}\) 에 걸쳐 time_call을 스윕하여 로그–로그 축 위에서 GRU, minGRU, attention의 실제 실행 시간을 비교합니다:

lengths = [512, 1024, 2048, 4096, 8192, 16384]
times = {name: [time_call(layer, T) for T in lengths]
         for name, layer in timed.items()}
print('T        ', *(f'{T:>7d}' for T in lengths))
for name, ms in times.items():
    print(f'{name:9s}', *(f'{t:7.1f}' for t in ms))
d2l.plot(lengths, list(times.values()), 'sequence length',
         'milliseconds per call', legend=list(times), xscale='log',
         yscale='log', figsize=(4.5, 3))
T             512    1024    2048    4096    8192   16384
GRU          20.2    35.6    69.7   113.3   197.6   425.6
minGRU        4.0     4.3     4.5     5.0     5.2     5.6
attention     2.1     2.4     3.2     4.7     7.9    13.7

lengths = [512, 1024, 2048, 4096, 8192, 16384]
times = {name: [time_call(layer, T) for T in lengths]
         for name, layer in timed.items()}
print('T        ', *(f'{T:>7d}' for T in lengths))
for name, ms in times.items():
    print(f'{name:9s}', *(f'{t:7.1f}' for t in ms))
d2l.plot(lengths, list(times.values()), 'sequence length',
         'milliseconds per call', legend=list(times), xscale='log',
         yscale='log', figsize=(4.5, 3))
T             512    1024    2048    4096    8192   16384
GRU          11.6    18.6    33.5    54.0    93.8   195.3
minGRU        1.3     1.1     1.1     1.1     1.2     1.2
attention     2.9     3.0     3.9     5.9     9.8    17.2

실측 스케일링 곡선은 표 12.3.1 의 결과와 정확히 부합합니다:

  • GRU: 모든 길이에서 가장 느리며, \(T\) 번의 순차 스텝을 시간축으로 병렬화할 수 없기 때문에 \(T = 512\) 에서 \(16{,}384\) 로 갈 때 \(15\times\) 이상 증가합니다.
  • minGRU: 시퀀스 길이가 32배 증가하는 전 구간에 걸쳐 거의 평탄하게 유지됩니다.
  • attention: \(O(Td^2)\) 투영과 메모리 트래픽이 지배하는 \(T \approx 2{,}048\) 까지는 거의 평탄하다가, \(O(T^2 d)\) 어텐션 항이 지배하기 시작하면 길이가 두 배가 될 때마다 실행 시간이 \(2\times\) 씩 늘어나는 위쪽 기울기로 꺾입니다.

minGRU의 배가 스캔은 증가폭이 \(50\%\) 미만입니다. 짧은 길이에서는 더 빨랐던 attention은 \(T = 4{,}096\) 부근에서 교차한 뒤 \(T = 16{,}384\) 에서는 약 \(2.5\times\) 뒤처집니다.

minGRU의 일 효율적 스캔은 평탄하게 유지되며 모든 길이에서 attention보다 빠르고, \(T = 16{,}384\) 에서는 약 \(14\times\) 빠릅니다.

minGRU에 아직 부족한 것은 다중 시간 스케일 메모리를 체계적으로 초기화하고 제어하는 방법이며, 이 문제는 12.4절 에서 연속 시간 상태 공간 모델을 통해 다룹니다.

12.3.5 요약

순환 층의 게이트에서 이전 상태 \(\mathbf{h}_{t-1}\) 을 제거하면 \((\mathbf{a}_1, \mathbf{b}_1) \bullet (\mathbf{a}_2, \mathbf{b}_2) = (\mathbf{a}_1 \odot \mathbf{a}_2, \mathbf{a}_2 \odot \mathbf{b}_1 + \mathbf{b}_2)\) 를 통해 스텝들이 결합 법칙에 따라 합성되는 아핀 점화식 \(\mathbf{h}_t = \mathbf{a}_t \odot \mathbf{h}_{t-1} + \mathbf{b}_t\) 를 얻습니다. 결합 스캔은 디코딩 시의 \(O(1)\) 상태 순차 갱신을 그대로 유지하면서 학습 중에는 \(O(\log_2 T)\) 번의 병렬 라운드만으로 \(T\) 개의 모든 상태를 계산합니다. 이를 GRU에 적용해 단순화한 MinGRU는 바이트 단위 WikiText-103에서 동일 매개변수 수의 단순 RNN과 동등한 성능을 내면서(전체 GRU 대비 바이트당 약 \(0.03\) nats 차이), 최대 \(16{,}384\) 개 토큰까지 거의 일정한 토큰당 시간으로 학습되어 긴 컨텍스트에서 순차 GRU보다 한 자릿수 이상 빠르고 이차 복잡도 어텐션보다도 수 배 빠르게 동작합니다.

12.3.6 연습 문제

  1. 합성에 대한 닫힘 성질. 병렬 스캔에는 결합 법칙 이상의 조건이 필요합니다. 매 결합 연산의 비용이 동일하려면, 임의 길이의 연속 스텝들을 합성한 결과 역시 단일 스텝과 같은 개수의 숫자로 기술되어야 합니다.
    1. 밀집 행렬 \(\mathbf{A}_t \in \mathbb{R}^{d \times d}\) 를 갖는 점화식 \(\mathbf{h}_t = \mathbf{A}_t \mathbf{h}_{t-1} + \mathbf{b}_t\) 로 식 12.3.6 의 합성 규칙을 일반화하되, 각 곱셈 인자의 순서를 정확히 유지하십시오. 결합 연산 한 번과 순차 스텝 한 번의 곱셈-덧셈(MACs) 횟수를 세어 보십시오. \(T = 4096\), \(d = 64\) 에서 약 \(T \log_2 T\) 번의 결합을 수행하는 배가 스캔의 총 연산량을 순차 루프의 연산량과 비교하십시오. 이 비교는 밀집 전이 행렬에 대해 무엇을 시사합니까?
    2. 스칼라 스텝 \(h \mapsto \tanh(w_t h + c_t)\) 에 대해, \(w_1, w_2 \neq 0\) 인 두 스텝의 합성은 어떠한 \(w\) 와 \(c\) 에 대해서도 \(h \mapsto \tanh(w h + c)\) 형태로 나타낼 수 없음을 보이십시오. \(k\) 개 스텝의 합성을 표현하려면 스캔이 무엇을 저장해야 합니까?
  2. [code] 직접 계산 경로. 스칼라 감쇠의 경우 식 12.3.4 의 펼쳐진 합은 스캔 없이 누적곱 \(P_t = a_1 a_2 \cdots a_t\) 와 누적합 한 번으로 계산할 수 있습니다.
    1. \(h_t = P_t \sum_{s=1}^{t} b_s / P_s\) 임을 보이십시오. 라이브러리의 cumprod와 cumsum으로 이를 구현하고, 0.9 근처에서 추출한 감쇠 값들에 대해 32비트 부동소수점에서 linear_scan과 비교하십시오. 어느 길이에서 실패하며, 스캔은 왜 그 길이에서 실패하지 않습니까?
    2. Feng 기타 (2024년) 의 연구에서는 감쇠와 쓰기 값의 로그를 다루고 합을 누적 log-sum-exp로 대체하여 이 공식을 보완합니다. 이 보완 기법을 구현하십시오. 쓰기 값들의 부호에 대해 어떤 조건이 필요하며, 저자들은 이를 어떻게 해결합니까?
  3. [code] 후보 비선형성. MinGRU는 후보 \(\tilde{\mathbf{h}}_t\) 에 \(\tanh\) 를 유지하는 반면, Feng 기타 (2024년) 의 연구에서는 선형 후보를 사용합니다.
    1. \(\mathbf{h}_0 = \mathbf{0}\) 에서 시작하여 \(\mathbf{h}_t\) 의 각 좌표를 후보들 \(\tilde{\mathbf{h}}_1, \ldots, \tilde{\mathbf{h}}_t\) 의 가중합으로 나타내십시오. 가중치들이 음이 아니고 합이 최대 1임을 보인 뒤, \(\tanh\) 가 있을 때와 없을 때 각각 모든 길이에서 성립하는 \(|\mathbf{h}_t|\) 의 상한을 유도하십시오.
    2. \(\tanh\) 를 제거하고 이 절의 언어 모델을 d2l.train_text로 두 번 학습한 뒤, MinGRU의 두 실행 결과와 검증 손실을 비교하십시오. 그 차이가 실행 간 편차보다 큽니까? 관찰한 결과를 앞서 유도한 상한과 연결해 설명하십시오.
  4. [code] 상태 전달. linear_scan은 초기 상태를 입력으로 받으므로 긴 시퀀스를 여러 조각으로 나누어 처리할 수 있습니다.
    1. 길이 \(T\) 인 시퀀스를 길이 \(\tau\) 인 청크들로 분할하고, 이전 청크의 최종 상태에서 시작해 각 청크마다 스캔을 실행한 뒤, 이어붙인(concatenated) 상태들이 전체 시퀀스를 한 번에 호출한 결과와 일치하는지 확인하십시오.
    2. 이제 모든 청크 경계에서 전달되는 상태를 통한 그레이디언트를 차단하십시오. 상태 값 자체는 변하지 않습니다. 스텝 \(t\) 에서의 손실 그레이디언트에 대한 기여분 중 어떤 부분이 사라지며, 학습된 모델이 텍스트를 생성할 때 여전히 활용할 수 있는 의존성은 무엇입니까? 절단된 시간 역전파(8.5절)와 비교하십시오.
  5. [code] 일 효율적 스캔. ● 재귀적 스케줄은 배가 스케줄보다 적은 연산을 수행합니다. 인접한 쌍들을 결합해 시퀀스 길이를 절반으로 줄이고, 절반 길이 시퀀스를 재귀적으로 스캔해 짝수 번째 프리픽스들을 얻은 뒤, 한 번의 결합 연산을 추가해 나머지 각 프리픽스를 구합니다.
    1. \(T = 2^k\) 에 대해 각 스케줄의 결합 횟수와 결합 라운드 수를 세고, \(T = 16384\) 에서 순차 루프의 \(T - 1\) 스텝과 비교하십시오.
    2. 슬라이싱을 사용해 두 스케줄을 모두 구현하고 sequential_scan과 결과를 대조한 뒤, 12.3.4절 의 측정 길이들에서 실행 시간을 재어 보십시오. 실행 시간의 비율이 결합 횟수의 비율을 그대로 따릅니까? 짧은 길이에서는 왜 그렇지 않을 수 있는지 설명하십시오.

토론