A Complete Guide to Open-Source LLM Architectures and Engineering Practices
This article maps the open-source large language model landscape across three dimensions: architecture paradigm, parameter and activation scale, and licensing boundaries. It then walks through four key modifications in modern decoder-only models, pre-normalization, RMSNorm, gated feed-forward networks, and rotary position embeddings, with the motivation and PyTorch implementations for each. Finally, it covers practical engineering concerns such as memory budgeting, quantization, batching and KV cache reuse, observability, and cloud deployment, along with a suggested adoption order for teams starting from a dense autoregressive baseline.
1. Why You Need a Map of the Open-Source LLM Landscape
Over the past two years, the number and size of open-weight models have grown explosively. For developers and enterprise users, the hard part is not “finding a model” but “making explainable, reproducible trade-offs among capability, license, GPU memory footprint, inference throughput, and fine-tuning cost.”
A practical approach is to build a coordinate system for open models along three dimensions:
- Architecture paradigm: autoregressive decoders (decoder-only), encoder-decoder, and sparse mixture-of-experts (MoE) structures.
- Parameter and activation scale: in dense models, total parameters equal activated parameters; in sparse models, the ratio of “total parameters / parameters activated per token” determines the asymmetric cost in compute and memory.
- License and commercial boundaries: whether commercial use is allowed, whether attribution is required, and whether derivative models are subject to the same open-source obligations. This directly determines whether a model can go into production.
It is worth stressing that model “popularity” does not equal “fit.” A model that leads on general leaderboards may not excel at long context, code completion, structured output, or low-resource languages. So the first principle of selection is always: build a small evaluation set from your own business corpus first, then compare models side by side.
2. The Technical Lineage of Mainstream Open-Source Models
In terms of technical evolution, the open-source camp has roughly formed four clear routes:
- Dense autoregressive route: mainly standard decoder stacks with fixed layer counts and fixed hidden dimensions. It has the highest engineering maturity, and its inference implementation is the easiest for acceleration frameworks to support.
- Sparse expert route: a routing network activates only some experts in each forward pass, keeping per-token compute controllable while total parameters are very large. The cost is a marked increase in the complexity of memory footprint and routing load-balancing tuning.
- Encoder-decoder route: still cost-effective for tasks that are “long input, short output,” such as translation, summarization, and information extraction.
- Multimodal extension route: a vision encoder or projection layer is attached to the language backbone, mapping images, video, and audio into the same token space for unified probabilistic modeling.
For the vast majority of teams, starting from a dense autoregressive model is the lowest-risk path: the ecosystem is complete, quantization and distillation approaches are mature, and memory requirements are predictable.
3. Four Key Modifications in Modern Decoder Architectures
When the original Transformer is engineered into a modern large model, four substitutions are typically made: post-normalization becomes pre-normalization, layer normalization is replaced by root mean square normalization, the plain feed-forward layer is replaced by a gated feed-forward layer, and absolute positional encoding is replaced by rotary position encoding. Each is explained below in terms of motivation and implementation.
3.1 Pre-Normalization: Keeping the Residual Path “Clean”
Post-normalization inserts normalization into the residual trunk, so gradients must pass through the normalization operator to backpropagate, and deep networks are prone to instability early in training. Pre-normalization moves normalization before each sublayer, turning the residual path into an almost unobstructed identity mapping. This allows a larger learning rate from the start of training, and pairs well with longer warmup and a looser hyperparameter search.
The structure can be sketched as:
x -> RMSNorm -> SelfAttention -> +residual-> RMSNorm -> GatedFFN -> +residual
3.2 Root Mean Square Normalization: Dropping Mean Centering, Keeping Only Scaling
Layer normalization computes both the mean and the variance, and performs two steps: subtracting the mean and dividing by the standard deviation. RMSNorm only uses the mean square of the input vector for scaling, eliminating the mean statistic and the centering operation, which removes one reduction and one element-wise subtraction. Its mathematical form is:
RMSNorm(a) = a / sqrt( mean(a_i^2) + eps ) * g
Here g is a learnable per-channel scaling vector, and eps avoids division by zero. Two easily overlooked details in engineering implementations: first, the mean square should be computed in single precision to avoid half-precision accumulation overflow; second, the final result must be explicitly cast back to the input precision to prevent type mismatches in downstream operators.
import torchimport torch.nn as nnclass RMSNorm(nn.Module):"""An equivalent layer normalization that only performs scale normalization."""def __init__(self, hidden_size: int, eps: float = 1e-6):super().__init__()self.weight = nn.Parameter(torch.ones(hidden_size))self.eps = epsdef forward(self, x: torch.Tensor) -> torch.Tensor:in_dtype = x.dtype# Compute the mean square in fp32 for numerical stabilityvar = x.to(torch.float32).pow(2).mean(-1, keepdim=True)x = x * torch.rsqrt(var + self.eps)return (self.weight * x).to(in_dtype)
3.3 Gated Feed-Forward Networks: Introducing Nonlinear Gating via Element-Wise Products
A standard feed-forward layer is a two-stage “up-project, activate, down-project” structure. A gated feed-forward network splits the up-projection into two paths: one passes through an activation function and is multiplied element-wise with the other, then the result is down-projected:
FFN(x) = W_down( act( W_gate(x) ) * W_up(x) )
The common activation choice is from the Swish family, defined as Swish(x) = x * sigmoid(beta * x). This function has an interesting shape: as beta approaches 0 it degenerates into a linear function, as beta approaches infinity it approaches ReLU, and at 1 it is both smooth and non-monotonic, which makes it better than ReLU at preserving gradient flow in deep networks. Because the gated structure adds an extra projection, practice usually lowers the hidden ratio of the two up-projection matrices from 4x to about 8/3x, keeping the parameter count roughly on par with a standard feed-forward layer.
class GatedFFN(nn.Module):def __init__(self, dim: int, hidden: int):super().__init__()self.gate = nn.Linear(dim, hidden, bias=False)self.up = nn.Linear(dim, hidden, bias=False)self.down = nn.Linear(hidden, dim, bias=False)def forward(self, x):return self.down(torch.nn.functional.silu(self.gate(x)) * self.up(x))
3.4 Rotary Position Embeddings: Writing Relative Position into the Inner Product
Absolute positional encoding adds a position vector to the word vector and extrapolates poorly to longer lengths. Rotary position embedding instead rotates each two-dimensional subspace by an angle based on position, so that when two tokens take an attention dot product, the result depends only on their relative distance. It has three advantages: no extra parameters, a natural relative-position property, and some extrapolation potential beyond the training length (which can be extended further with interpolation or frequency-scaling strategies).
def build_rope(seq_len: int, dim: int, base: float = 10000.0):# dim must be even; every two dimensions share one rotation angleinv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))t = torch.arange(seq_len).float()freqs = torch.outer(t, inv_freq) # [seq_len, dim/2]return torch.cos(freqs), torch.sin(freqs)def apply_rope(x, cos, sin):x1, x2 = x[..., 0::2], x[..., 1::2]cos, sin = cos[None, :, None, :], sin[None, :, None, :]return torch.stack([x1 * cos - x2 * sin,x1 * sin + x2 * cos], dim=-1).flatten(-2)
4. From Architecture to Engineering: What Actually Matters
- Estimate the memory budget as four separate items: weights + gradients + optimizer states + activations. For full fine-tuning, optimizer states are often several times the size of the weights, which is the direct reason parameter-efficient fine-tuning (training only low-rank side paths or adapters) has become mainstream.
- Quantization is the first lever for cutting inference cost. Everything from post-training quantization to lower-bit integer quantization can substantially compress memory, but accuracy regression must be re-evaluated, especially for long-text and structured-output tasks.
- On the inference side, solve batching and caching first. Continuous batching and KV cache reuse usually deliver higher throughput gains than switching to a smaller model.
- Observability cannot be skipped. Wiring throughput, time-to-first-token latency, peak memory, and failure rate into a unified logging, monitoring, and alerting system is what lets you produce verifiable conclusions during capacity planning.
- When moving to the cloud, compose general-purpose capabilities: use object storage for model weights and datasets, a container platform for elastically scaling inference services, a message queue to smooth out traffic peaks and troughs, and logging plus monitoring and alerting to close the loop.
5. Conclusion
Choosing an open-source LLM is fundamentally an optimization problem under engineering constraints, and understanding these four modifications, pre-normalization, RMSNorm, gated feed-forward networks, and rotary position embeddings, lets you quickly judge any new model’s structural lineage and tuning focus. The suggested order of adoption: first clarify the task and license boundaries, then pick a dense autoregressive model as a baseline, then validate with your own evaluation set, and finally use quantization, batching, and elastic deployment to bring cost into an acceptable range.
