Während High-Level-APIs die Komplexität moderner Large Language Models (LLMs) abstrahieren, erfordert die Optimierung von Inferenzlatenz und GPU-VRAM-Durchsatz ein tiefes Verständnis hardwarenaher Algorithmen.

In diesem technischen Leitfaden analysieren wir drei Schlüsseltechnologien moderner Frontier-Modelle: Rotary Position Embeddings (RoPE), FlashAttention-2 Kernel-Logik und KV-Cache-Speichermanagement.


1. Mathematische Formulierung von Rotary Position Embeddings (RoPE)

Absolute Positionseinbettungen lassen sich nicht auf Sequenzlängen jenseits des Trainingsfensters verallgemeinern. RoPE kodiert relative Positionsinformationen direkt in die Query- ($Q$) und Key-Vektoren ($K$) über Rotationen in der komplexen Ebene.

Für ein 2D-Merkmalspaar $(x_1, x_2)$ an Position $m$ mit Kreisfrequenz $\theta_i = 10000^{-2(i-1)/d}$ lautet die Rotationsoperation $\mathbf{R}_{\Theta,m}^d$:

$$\mathbf{R}_{\Theta, m}^d \mathbf{x}_m = \begin{pmatrix} \cos m\theta_1 & -\sin m\theta_1 & 0 & 0 & \dots \\ \sin m\theta_1 & \cos m\theta_1 & 0 & 0 & \dots \\ 0 & 0 & \cos m\theta_2 & -\sin m\theta_2 & \dots \\ \vdots & \vdots & \vdots & \vdots & \ddots \end{pmatrix} \begin{pmatrix} x_1 \\ x_2 \\ x_3 \\ \vdots \end{pmatrix}$$

Das Skalarprodukt zwischen rotierten Queries und Keys bewahrt exakt die relative Distanz $(m - n)$:

$$\langle \mathbf{R}_{\Theta, m}^d \mathbf{q}_m, \mathbf{R}_{\Theta, n}^d \mathbf{k}_n \rangle = \mathbf{q}_m^T \mathbf{R}_{\Theta, n-m}^d \mathbf{k}_n$$

1.1 Optimierte PyTorch-RoPE-Implementierung

import torch

def apply_rotary_emb(x: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor:
    """
    Wendet Rotary Position Embeddings auf Query- und Key-Tensoren an.
    Form von x: [batch, seq_len, num_heads, head_dim]
    """
    x_complex = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2))
    freqs_cis = freqs_cis.unsqueeze(0).unsqueeze(2)
    x_rotated = x_complex * freqs_cis
    return torch.view_as_real(x_rotated).flatten(3).type_as(x)