Building LLMs from Scratch and Agent Development: A Practical Guide
This guide explains why rebuilding large language models from scratch is still the best way to understand them, then walks through core mechanisms such as attention, normalization, decoding, and KV caching. It also covers efficient architecture ideas, lightweight local deployment, agent workflows with tool calling, retrieval-augmented knowledge bases, and a staged approach for teaching and engineering practice. Readers will find practical acceptance criteria, minimal code skeletons, and deployment patterns that run on machines without dedicated accelerators.
1. Why Building from Scratch Still Matters
The ecosystem around large language models is rich in frameworks and tooling, but relying only on high-level APIs often creates a capability gap: teams can use models but cannot modify them. When issues appear, such as insufficient GPU memory, unmet inference throughput targets, retrieval drift, or failed tool calls, teams without low-level understanding are left to trial and error.
The value of rebuilding from scratch is not to reinvent the wheel. It is to turn a black box into modules that are observable, verifiable, and replaceable.
A practical path is to start with a tiny dataset and a tiny parameter count to get the training loop working end to end, then gradually swap in real corpora and larger structures. Each step should have a quantifiable acceptance criterion, for example whether the loss decreases steadily, whether generation shows repetitive degeneration, and whether inference latency stays within an acceptable range. This small, verifiable increment approach makes both teaching and engineering practice feasible on machines with ordinary memory configurations.
2. Core Technical Breakdown: From Attention to Generative Pretraining
2.1 Attention and Positional Information
Self-attention is essentially weighted information aggregation. The scaled dot-product form uses dimension normalization to avoid gradient vanishing. The multi-head structure allows different subspaces to attend to different relationship patterns. Positional encoding determines how the model perceives order. Common approaches include sinusoidal encoding and extrapolable rotary schemes; the latter extends better to longer contexts.
2.2 Normalization, Residuals, and Initialization
Pre-normalization places normalization before each sublayer, which makes training more stable. Residual connections keep the gradient path open. Weight initialization variance, learning rate warmup, and gradient clipping must be tuned together; otherwise even small models can show loss spikes.
2.3 Decoding Strategies and Inference Cost
The training objective is next-token prediction, while inference must handle strategies such as sampling temperature, top-p thresholds, and repetition penalties. The more critical engineering detail is the key-value cache: it reduces each step from recomputing the whole sequence to incremental computation, which is the prerequisite for feasible long-text interaction.
Illustrative code (structural skeleton, expressing module relationships only):
class Block(nn.Module):def __init__(self, d_model, n_head):super().__init__()self.norm1 = nn.LayerNorm(d_model)self.attn = MultiHeadAttention(d_model, n_head)self.norm2 = nn.LayerNorm(d_model)self.ffn = FeedForward(d_model, 4 * d_model)def forward(self, x, cache=None):h = self.norm1(x)x = x + self.attn(h, cache)h = self.norm2(x)return x + self.ffn(h)
3. An Abstract Understanding of Frontier Structural Innovations
A recent set of efficient architectures shares the same goal: finding a better trade-off between quality and cost. Multi-head latent attention compresses key-value representations through low-rank projection to reduce cache usage. Mixture-of-experts structures activate only part of the parameters via routing, decoupling total parameter count from per-token computation. Multi-token prediction introduces multiple prediction heads during training to improve sample efficiency and may accelerate inference. Reinforcement learning optimization based on rule-based rewards brings verifiable correctness signals into the alignment stage, reducing dependence on a separate reward model.
When studying these designs, focus on three questions: whether compression loses expressive power, whether routing is load-balanced, and whether rewards can be objectively verified. In engineering practice, prioritize ablation studies rather than copying structures directly.
4. Lightweight Local Deployment and Service Wrapping
With only 16GB of memory and no discrete GPU, feasible strategies include choosing a smaller parameter-scale model, using low-precision weight storage, controlling batch size and context length, and reusing the key-value cache. Deployment typically has three layers:
- Inference layer: the local runtime handles model loading and generation;
- Service layer: an asynchronous interface exposes streaming output so the frontend can render token by token;
- Access layer: local inference and cloud APIs are wrapped uniformly and switched by configuration, so business code does not perceive the difference.
async def chat(req: ChatRequest):async for token in runtime.stream(req.messages, max_tokens=512):yield token
For cloud calls, pay attention to common capability categories such as key management, logging services, monitoring and alerting, and quota management, and avoid writing credentials into code repositories.
5. Agent Development: Tool Calling and Parallel Workflows
An agent can be abstracted as a loop of plan, act, and observe. There are four implementation points: tool descriptions must provide clear input and output schemas; call parameters need schema validation and retry on failure; context must be trimmed to keep only observations relevant to the current subgoal; and multi-branch tasks should use parallel orchestration with results merged afterward.
plan = planner.submit(goal)results = await gather(*[tool.run(a) for a in plan.parallel_actions])answer = synthesizer.merge(plan.serial_actions, results)
Termination conditions must be set explicitly, such as maximum iterations and timeouts, to prevent infinite loops from consuming resources.
6. Retrieval-Augmented Knowledge Bases: From Naive Concatenation to Fusion Strategies
The basic pipeline is chunking, vectorization, recall, reranking, and generation. What really makes a difference is the retrieval strategy. Multi-query fusion rewrites one question from multiple perspectives to improve recall coverage. Task decomposition splits a complex question into subquestions that can be retrieved independently. Hypothetical document embeddings first let the model generate an expected answer, then use its representation to match the corpus, mitigating the mismatch between how questions are asked and how documents are phrased.
Evaluation should be independent of the generation step, focusing on recall hit rate, post-rerank relevance, and factual consistency of answers, while retaining cited snippets for manual verification.
7. Recommendations for Teaching and Engineering Practice
A course-based implementation is suggested in four stages: structural reproduction, training and inference optimization, deployment and service wrapping, and a capstone combining agents and knowledge bases. Each stage should include a runnable minimal example and an acceptance checklist. Code should consistently use a mainstream tensor computation framework to ensure it runs without dedicated acceleration hardware. The capstone can take a real scenario, such as enterprise internal document question answering, covering access control, result traceability, and cost control.
Overall, building from scratch provides low-level understanding, service wrapping and agents provide an engineering loop, and retrieval augmentation addresses knowledge freshness and accuracy. Only by combining the three can sustainable large-model application capability be formed.
