Open AI IT TCET Pinwheel Logo
OPEN AI ITTCET-IT COMMITTEE
Architecture Deep Dives16 min read • July 2026

LLaMA3Architecture:RotaryEmbeddings&SwiGLUImplementation

System engineering deep dive into Rotary Position Embeddings (RoPE), SwiGLU activation functions, and KV-cache generation loops.

Reference / Authors: Touvron et al. (Meta AI, 2024)

Abstract & Theoretical Context

Open foundation language models like LLaMA 3 incorporate three crucial structural improvements over original Transformer baselines: Rotary Position Embedding (RoPE) for relative positional encoding, SwiGLU activation functions for feed-forward MLP blocks, and Grouped-Query Attention (GQA) for memory-bandwidth efficiency during token generation. Rotary Position Embedding (RoPE) multiplies key and query vectors by a complex rotation matrix depending on token position. This guarantees that inner products between queries and keys decay smoothly as relative distance between tokens increases. SwiGLU replaces standard GELU activations in the MLP layer, splitting the hidden projection into gate and up projections to yield superior empirical performance and smoother loss landscapes during pre-training.

Mathematical Formulations & Variables

1. Rotary Position Embedding (RoPE):
   R_Theta,m^d * x = ( x_1 * cos(m 	heta_1) - x_2 * sin(m 	heta_1),
                       x_1 * sin(m 	heta_1) + x_2 * cos(m 	heta_1), ... )
   - Encodes position m by rotating 2D sub-vectors by angle m * 	heta_i
   - 	heta_i = 10000^(-2(i-1)/d)

2. SwiGLU Feed-Forward Layer:
   SwiGLU(x) = ( Swish(x * W_gate) * (x * W_up) ) * W_down
   where Swish(x) = x * sigma(eta x) (with eta = 1)

PyTorch Implementation Code

llama-3-rope-swiglu-architecture.py
1import torch
2import torch.nn as nn
3import torch.nn.functional as F
4
5def precompute_rope_freqs(dim: int, seq_len: int, theta: float = 10000.0) -> torch.Tensor:
6 """Precomputes RoPE complex rotation frequencies for sequence length."""
7 freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
8 t = torch.arange(seq_len, dtype=torch.float32)
9 freqs = torch.outer(t, freqs)
10 freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
11 return freqs_cis
12
13def apply_rotary_emb(xq: torch.Tensor, xk: torch.Tensor, freqs_cis: torch.Tensor):
14 """Applies RoPE rotation matrix to query and key tensors."""
15 xq_complex = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
16 xk_complex = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
17
18 freqs_cis = freqs_cis[:xq.shape[1], :].unsqueeze(0).unsqueeze(2)
19 xq_out = torch.view_as_real(xq_complex * freqs_cis).flatten(3)
20 xk_out = torch.view_as_real(xk_complex * freqs_cis).flatten(3)
21 return xq_out.type_as(xq), xk_out.type_as(xk)
22
23class SwiGLU(nn.Module):
24 """SwiGLU Feed-Forward MLP Block."""
25 def __init__(self, d_model: int, d_ff: int):
26 super().__init__()
27 self.w_gate = nn.Linear(d_model, d_ff, bias=False)
28 self.w_up = nn.Linear(d_model, d_ff, bias=False)
29 self.w_down = nn.Linear(d_ff, d_model, bias=False)
30
31 def forward(self, x: torch.Tensor) -> torch.Tensor:
32 return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))

Step-by-Step Reproduction Guide

11. Frequency Precomputation: Generate `freqs_cis` tensor for max sequence length during model initialization.
22. Q & K Transformation: Reshape queries and keys into 2D pairs prior to RoPE matrix multiplication.
33. SwiGLU Integration: Replace `nn.GELU()` or `nn.ReLU()` MLP blocks with `SwiGLU` gate and up linear projections.
44. KV Cache Allocation: Allocate key-value cache buffer of shape `(Batch, Num_KV_Heads, Max_Seq_Len, Head_Dim)` for fast autoregressive generation.

Key Insights & Operator Insights

  • Relative Position Encoding: RoPE allows extrapolation to longer sequence lengths than seen during initial pre-training.
  • SwiGLU Efficiency: Uses 8/3 d_model hidden dimensions instead of standard 4x d_model while maintaining compute parity.
  • Grouped-Query Attention: Shares key-value heads across multiple query heads to reduce KV-cache memory footprints during generation.
HARDWARE & SYSTEM REQUIREMENTS

NVIDIA RTX 3090 / 4090 (24GB VRAM) or Apple M3 Max Silicon