Large Language Models Explained: Architecture, Training, Model Selection, and Applications

    This article explains how large language models work, from Transformer architecture and autoregressive generation to self-attention and the three main training stages. It also compares LLMs with traditional fine-tuned models and outlines practical criteria for selecting a base model, including task fit, context length, inference cost, deployment, and licensing.

    Large Language Models Explained: Architecture, Training, Model Selection, and Applications

    1. Why Understand Large Language Models First

    Over the past two years, large language models that can understand natural language, generate text, and call tools have rapidly entered research and business scenarios. For many teams, the question is no longer whether they can use LLMs, but which model to choose, how to use it well, and whether costs can be controlled. Answering these questions requires understanding the model’s underlying mechanisms, capability boundaries, and technical evolution path.

    This article is organized around four layers: principles, model selection, capability activation, and application implementation. It is intended for both newcomers and developers with engineering experience.

    2. Technical Evolution and Mainstream Architectures

    Based on the Transformer structure, pretrained language models have broadly developed along three architectural routes.

    1. Encoder-only architecture: This architecture understands text through bidirectional context and is well suited to understanding tasks such as classification, information extraction, and semantic matching. Around 2021, research interest in this category declined noticeably. A common reflection was that much work focused on optimizing benchmark leaderboard scores and drifted away from improving general language capabilities.

    2. Encoder-Decoder architecture: The encoder reads the input, and the decoder generates output autoregressively. This architecture is suitable for tasks with a clear input-output structure, such as translation and summarization. Some research models and large models developed in China use this structure.

    3. Decoder-only architecture: This architecture keeps only a stack of decoders with causal masking and uses “predict the next token” as a unified training objective. The same paradigm can cover question answering, writing, code, reasoning, and many other tasks. Most large models with strong general capabilities currently belong to this architecture, and it is the paradigm adopted by most large language models.

    From a research ecosystem perspective, from 2018 to around 2021, most related papers and models were open source, and community collaboration was active. After 2021, parameter scales continued to grow, training costs rose significantly, and leading work gradually shifted toward closed source. Only a few organizations continued to release model weights, which also drove the development of the open-source ecosystem. The boundary between open and closed source changes over time, so model selection should be based on the model versions and license terms available at the time.

    3. Underlying Principles

    3.1 Autoregressive Generation

    The model first splits text into tokens, then calculates a probability distribution for the next token based on the existing sequence. After a new token is sampled, it is appended to the input, and the process repeats until an end token is generated. This process appears simple, but to make accurate predictions, the model must encode a large amount of grammar, factual knowledge, reasoning patterns, and other regularities in its parameters.

    3.2 Self-Attention Mechanism

    Self-attention is the core of the Transformer. Each position generates three sets of vectors: Query, Key, and Value. The similarity between the query and keys is used to assign weights to each position, and then the value vectors are weighted and summed. Below is a simplified NumPy example showing single-head attention computation with causal masking:

    1. import numpy as np
    2. def causal_self_attention(x, Wq, Wk, Wv):
    3. # x: [seq_len, d_model]
    4. q, k, v = x @ Wq, x @ Wk, x @ Wv
    5. scores = q @ k.T / np.sqrt(k.shape[-1])
    6. # Mask future positions so each token can only see itself and preceding content
    7. mask = np.triu(np.ones_like(scores), k=1).astype(bool)
    8. scores = np.where(mask, -1e9, scores)
    9. weights = np.exp(scores - scores.max(axis=-1, keepdims=True))
    10. weights /= weights.sum(axis=-1, keepdims=True)
    11. return weights @ v

    Causal masking is the prerequisite for decoder-only architectures to generate token by token. Actual models stack dozens of layers, each containing multiple attention heads and a feed-forward network, together with residual connections and normalization.

    3.3 Three Training Stages

    • Pretraining: The model learns next-token prediction on large-scale unlabeled text, acquiring general language capabilities and a large amount of world knowledge. This stage requires the largest compute investment.
    • Instruction tuning: Using instruction-answer paired data, the model learns to organize responses according to user intent rather than simply continuing text.
    • Preference alignment: Using preference data annotated by humans or models, the model is guided to produce outputs that are more helpful, honest, and safe.

    The three stages address “being able to speak,” “understanding instructions,” and “speaking as expected,” respectively. None can be omitted.

    4. How to Choose Between LLMs and Traditional Fine-Tuned Models

    The traditional approach is to fine-tune a small or medium-sized model for a specific task using labeled data. Its advantages are stable single-task accuracy, low inference cost, and controllable behavior. Its disadvantages are that each task requires separately collecting labeled data and training, transfer to new tasks is costly, and generalization capability is limited.

    The advantage of large language models is that they can complete multiple tasks with prompts or a few examples, and they have strong language understanding and generation capabilities. They are suitable for scenarios with frequently changing requirements and scarce labeled data. Their disadvantages are also clear: high inference cost, high response latency, and uncertain output. They usually require additional format constraints, retrieval augmentation, and evaluation systems.

    In practice, the following judgments can be used as references.

    • Single task, sufficient data, latency-sensitive: Prefer fine-tuned small models, such as classification, tagging, and real-time risk control.
    • Diverse tasks, scarce data, open-ended generation: Prefer LLMs, such as knowledge question answering, copywriting, and code assistance.
    • Combining both: Use LLMs to generate training data or provide fallback responses, and use small models for high-frequency, fixed request paths, balancing quality and cost.

    5. Key Dimensions for Base Model Selection

    When selecting a model, it is not advisable to look only at aggregate leaderboard scores. Each dimension should be evaluated against business conditions.

    1. Task fit: Test with real business samples, focusing on accuracy, format adherence, and the reasonableness of refusals.
    2. Context length: Document question answering and codebase analysis have high requirements for long context. However, the longer the context, the higher the compute cost, and the model’s ability to use middle content may decline. This needs to be tested in practice.
    3. Inference cost and latency: Estimate monthly costs based on the unit price per thousand tokens, first-token response time, and throughput, and set budget caps and alerts.
    4. Deployment method: Calling through a hosted API enables fast launch and is suitable for rapid validation. Private deployment is suitable for sensitive data, but VRAM, concurrency capacity, and operations investment need to be evaluated.
    5. Licensing and compliance: Check the model license terms, including whether commercial use is permitted and whether user data is used for retraining.