LearnerBox logo LearnerBox Infosystems LLP
  • AI News & Industry Updates

    How AI Is Changing Healthcare: Diagnosis, Drug Discovery, and Patient Care

    ai healthcare hero light

    Medicine’s Quiet Revolution

    Healthcare has always advanced in waves, examples being germ theory, antibiotics, the randomised controlled trial, genomic sequencing. Each wave took decades to become standard practice. Artificial intelligence is different. The pace at which AI tools have moved from research papers to clinical wards has compressed that timeline dramatically, and the breadth of the transformation, including touching diagnostics, drug development, genomics, and patient management simultaneously, has no obvious historical parallel.

    This is not hype at distance. It is measurable, already underway, and raising genuinely difficult questions about how medicine will be practised, validated, and governed in the decade ahead.

    Seeing What Human Eyes Miss: AI in Medical Imaging

    The area where AI has achieved the most clinically validated impact is medical imaging. As of December 2025, over 1,300 AI-enabled medical devices have received FDA marketing authorisation, with 1,039 specifically for radiology — accounting for roughly 80% of all approved AI medical tools. These are not experimental prototypes; they are deployed daily in hospitals across the United States, Europe, and Asia.

    The performance numbers are striking. Deep learning models can identify tumours, strokes, and fractures within seconds, with real-world studies demonstrating up to 17.6% higher breast cancer detection rates. In stroke treatment, where neurological damage accumulates with every passing minute, AI has reduced door-to-treatment intervals by as much as 30 minutes, with measurable improvements in survival rates and patient outcomes.

    The mechanism is convolutional neural networks trained on tens of millions of labelled scans. These networks learn to identify statistical patterns in pixel distributions that correlate with pathology — patterns that may be too subtle or spatially diffuse for a human radiologist under time pressure to consistently detect. In breast cancer screening specifically, AI-assisted interpretations have lowered false negatives by almost 9% and decreased unnecessary recall rates — reducing both missed cancers and patient anxiety from false alarms simultaneously.

    The caveat is important. AI is not a substitute for doctors: it can make mistakes or generate false positives, and over-reliance risks impairing clinicians’ skills. The clinical consensus, reflected in nearly every major radiology society’s guidance, is that AI functions best as a co-pilot — triaging the scan queue, flagging anomalies for human review, and performing automated measurements — while the radiologist retains diagnostic authority.

    The AlphaFold Moment: Rewriting Drug Discovery

    If imaging AI represents evolutionary improvement in existing workflows, AlphaFold represents something more fundamental: a solution to a problem that had defeated biology for half a century.

    Proteins fold from linear amino acid chains into precise three-dimensional structures that determine their function. Predicting that structure from sequence alone — the protein folding problem — was considered one of the hardest open problems in science. Google DeepMind’s AlphaFold 2, published in Nature in 2021, solved it with accuracy comparable to experimental methods. Its creators Demis Hassabis and John Jumper were awarded the 2024 Nobel Prize in Chemistry for the work. By November 2025, AlphaFold was being used by over three million researchers across more than 190 countries, tackling problems including antimicrobial resistance, crop resilience, and heart disease.

    AlphaFold 3, released in 2024, extended the capability beyond proteins to predict the structure and interactions of DNA, RNA, ligands, and small molecules — with at least a 50% improvement over existing methods for protein-molecule interactions, and doubled prediction accuracy for some drug-relevant interaction categories. For drug discovery, this is transformative. The traditional pipeline required experimental determination of a target protein’s structure — a process taking months or years — before rational drug design could begin. AlphaFold collapses that step to hours.

    The pharmaceutical industry has responded at scale. A landmark development at the 2026 J.P. Morgan Healthcare Conference was a $1 billion co-innovation lab announced by Nvidia and Eli Lilly, aimed at creating a continuous learning system connecting agentic wet labs with computational dry labs around the clock. AstraZeneca, Bristol Myers Squibb, Roche, and Recursion Pharmaceuticals have all announced multi-hundred-million-dollar AI drug discovery partnerships in the same period.

    The critical open question is clinical validation. The most advanced AI-designed drugs are now entering Phase III pivotal trials in 2026, with multiple clinical readouts expected throughout the year — the first large-scale test of whether AI genuinely improves success rates beyond the pharmaceutical industry’s persistent 90% clinical trial failure rate. Computational elegance and clinical efficacy are not the same thing. The next two years will determine whether the investment thesis is justified.

    Genomics, Precision Medicine, and the Individual Patient

    Beyond imaging and drug design, AI is enabling a more fundamental shift in how medicine conceptualises the patient. Traditional medicine treats populations — a drug is approved because it outperforms placebo in a trial of thousands. Precision medicine asks a different question: which treatment is most likely to work for this specific patient, given their genetic profile, biomarkers, and disease subtype?

    AI-powered clinical decision support systems are stepping into the gap created by the rapid and unmanageable expansion of medical knowledge. Platforms like OpenEvidence, among the most widely adopted decision support tools in US medicine, allow physicians to rapidly search medical literature, synthesise findings, and check drug interactions at the point of care.

    In genomics, models trained on population-scale genetic databases can now identify disease-causing variants with a precision that was impossible using statistical methods alone. These systems can speed up genetic diagnosis for rare and complex illnesses by frequently ranking the true disease-causing mutation within the top ten candidates, and guide personalised treatment by linking genetic variants directly to their expected clinical manifestations.

    The combination of genomic data, electronic health records, and AI-driven pattern recognition is creating what researchers describe as a “learning health system” — one in which every patient encounter generates data that improves predictions for the next patient with a similar profile. This is medicine learning from itself at a scale and speed that no previous generation of clinicians could achieve.

    The Governance Problem

    The pace of deployment has outrun the pace of regulation, and the gap is generating legitimate concern. Roughly 200 state AI bills are being tracked in 2026 alone, and 83% of polled healthcare workers say AI needs more regulation — reflecting broad industry support for clearer governance frameworks even as the federal government takes a largely deregulatory stance.

    The EU AI Act’s high-risk provisions, which take effect August 2026, classify AI systems used in medical diagnosis and drug development as high-risk — requiring conformity assessments, transparency obligations, and human oversight mechanisms. The US approach remains more fragmented, relying primarily on the FDA’s device authorisation framework, which does not require rigorous clinical validation — FDA clearance alone does not guarantee real-world effectiveness.

    The algorithmic bias problem deserves specific attention. AI systems trained predominantly on data from specific demographic groups — which describes most current medical AI, given the historical composition of clinical trial populations — can perform significantly worse for underrepresented groups. A model that detects diabetic retinopathy with 95% accuracy on one ethnic population may perform at 80% on another, with no visible signal in aggregate accuracy statistics that a problem exists.

    What Comes Next

    The trajectory of AI in healthcare points toward three developments that are likely to define the next decade. Multimodal AI — systems that integrate imaging, genomics, clinical notes, and wearable sensor data simultaneously — will produce risk models and diagnostic tools with a richness that no single-modality system can match. Agentic AI in clinical workflows will handle administrative burden, prior authorisation, documentation, and care coordination autonomously, returning clinician time to patients. And AI-designed therapeutics will, if the current Phase III trials vindicate the approach, fundamentally alter the economics of bringing new drugs to market.

    None of this makes medicine easier. It makes it more capable and correspondingly more demanding of the humans who must govern, validate, and take clinical responsibility for what these systems produce. That, ultimately, is where the most important work remains to be done.

  • AI Foundations

    What Is the Difference Between AI, Machine Learning, and Data Science?

    Three Terms, One Persistent Confusion

    Artificial Intelligence, Machine Learning, and Data Science are three of the most frequently used, and three of the most consistently conflated, terms in technology today. Job descriptions blend them interchangeably. News articles use them as synonyms. Even within organisations, teams labelled differently are sometimes doing work that is functionally indistinguishable.

    The confusion is understandable. The three fields overlap substantially, share tooling and mathematical foundations, and have converged further in recent years as data-driven methods have come to dominate AI research. But they are not the same thing, and treating them as such leads to poor hiring decisions, misdirected research investment, and architectural choices that do not match the problem at hand.

    Understanding the precise relationship between the three, conceptually and historically, is a foundational literacy requirement for any graduate-level practitioner working in or adjacent to these fields.

    Artificial Intelligence: The Broadest Umbrella

    Artificial Intelligence is the oldest and broadest of the three terms. Coined at the 1956 Dartmouth Conference, it refers to any computational system designed to exhibit behaviour that would be considered intelligent if performed by a human. That definition is deliberately wide — wide enough to encompass everything from a rule-based expert system written in 1982 to a multimodal transformer model trained on tens of trillions of tokens in 2025.

    AI is best understood as a goal rather than a methodology. The goal is to construct systems that perceive, reason, plan, communicate, or act in ways that approximate or surpass human cognitive capabilities in specific domains. How that goal is pursued is left open. Classical AI pursued it through symbolic reasoning — explicit logical rules, decision trees, knowledge graphs, and first-order predicate logic. Planning algorithms like A* search, constraint satisfaction solvers, and game-playing engines such as Deep Blue all qualify as AI under this definition without involving any statistical learning whatsoever.

    The important implication is that AI does not require data in the modern sense. An expert system that encodes the diagnostic rules of a cardiologist is AI. A theorem prover that verifies software correctness through formal logic is AI. Neither learns from data, neither involves statistics, and neither would commonly be described as machine learning.

    Machine Learning: A Methodology Within AI

    Machine Learning is a specific approach to building AI systems: one in which the system learns its decision rules from data rather than having those rules programmed explicitly. The formal definition, due to Tom Mitchell (1997), remains precise and useful: a computer program is said to learn from experience EEE with respect to task TTT and performance measure PPP if its performance at TTT, as measured by PPP, improves with experience EEE.

    ML is therefore a proper subset of AI. Every machine learning system is an AI system, but not every AI system uses machine learning. The methodological distinction is significant. Classical AI is brittle in novel environments and requires expert knowledge to be manually encoded. ML systems can generalise to inputs their designers never explicitly considered, provided those inputs resemble the training distribution.

    The field subdivides along several axes. Supervised learning trains on labelled input-output pairs and learns a function mapping inputs to outputs so that regression and classification are the canonical tasks. Unsupervised learning finds structure in unlabelled data, including clustering, dimensionality reduction, and density estimation. Reinforcement learning trains an agent through interaction with an environment, optimising a cumulative reward signal rather than a fixed labelled dataset.

    Deep learning, the sub-field built on multi-layer neural networks trained via backpropagation, is itself a subset of machine learning, and the one most responsible for the capabilities that define the current AI era. The relationship is therefore nested: deep learning \subset machine learning \subset artificial intelligence.

    Data Science: A Practice, Not a Discipline

    Data Science occupies a different conceptual register from the other two. Where AI is a goal and machine learning is a methodology, data science is best understood as a practice — the interdisciplinary activity of extracting knowledge and actionable insight from data using a combination of statistical analysis, computational tools, domain expertise, and communication skills.

    The term was popularised in the early 2010s, partly as a rebranding of applied statistics and partly to capture a genuinely new set of competencies demanded by the scale and variety of data that modern organisations generate. A data scientist working on customer churn prediction might use logistic regression, a gradient boosted tree, or a neural network depending on the dataset size and interpretability requirements — but the primary obligation is to the insight and its business consequences, not to any particular algorithmic paradigm.

    Data science is explicitly interdisciplinary in a way that AI and ML are not required to be. The canonical Venn diagram of the field places it at the intersection of mathematics and statistics, domain expertise, and computer science. A machine learning engineer who cannot communicate findings to a non-technical stakeholder, cannot clean a messy real-world dataset, and cannot frame a business problem as a statistical one is not doing data science, regardless of how sophisticated the model they deploy.

    This distinction matters in practice. Data science places significant emphasis on exploratory data analysis, statistical inference, experimental design, causal reasoning, and data visualisation — competencies that a pure ML engineer may have only superficially. Conversely, a statistician doing regression modelling on clinical trial data is doing data science without doing machine learning or AI in any substantive sense.

    Where They Overlap — and Where They Diverge

    The Venn diagram of the three fields in 2026 looks quite different from how it looked in 2012. Deep learning has absorbed so much of what was previously done by hand-crafted feature engineering and classical statistical modelling that the boundary between ML and data science has blurred considerably. A modern data scientist working on a large unstructured dataset containing text, images, and sensor streams will routinely deploy pre-trained neural network models, use transformer-based embeddings as features, and interact with foundation models through API calls. These tasks would once have been considered the exclusive domain of ML research.

    Similarly, the boundary between ML and AI has compressed. The dominant AI paradigm of the current era is data-driven — foundation models, reinforcement learning, and generative systems — to the point where the distinction between AI and ML is now less a technical boundary than a level-of-abstraction distinction. When practitioners say “AI system,” they typically mean a system whose core capability is conferred by a trained model. When they say “ML pipeline,” they are emphasising the data flow, training process, and model lifecycle management.

    The divergence that remains most meaningful is between data science and the other two. Data science is oriented toward understanding — answering questions about what happened, why it happened, and what is likely to happen — and is deeply embedded in the statistical tradition of inference under uncertainty. AI and ML are oriented toward capability-building systems that perceive, decide, generate, or act. A causal inference study examining why a marketing campaign underperformed is data science. A recommendation system that predicts what product a user will purchase next is machine learning. An autonomous agent that browses the web, synthesises information, and executes a multi-step workflow is AI. All three draw on overlapping mathematical tools, but they ask fundamentally different questions and are held to different standards of success.

    A Practical Summary

    AIMachine LearningData Science
    NatureGoal / fieldMethodologyPractice
    Core questionCan a machine behave intelligently?Can a system learn from data?What does the data tell us?
    Requires data?Not necessarilyYesYes
    Requires ML?Not necessarilyNot necessarily
    Primary outputIntelligent systemTrained modelInsight or decision
    Rooted inComputer science, logicStatistics, optimisationStatistics, domain knowledge

    Conclusion

    AI is the destination. Machine learning is one of the most powerful roads toward it. Data science is the discipline of reading the map and extracting understanding from the data that both feeds and evaluates the journey. Treating these three as synonyms is not merely imprecise; it produces teams that are misaligned with their actual objectives, architectures chosen for the wrong reasons, and practitioners evaluated against the wrong competency profiles.

    The clearest sign of genuine literacy in this space is not fluency with any specific tool or algorithm; it is the ability to pick up a problem and correctly identify which of these three framings it actually requires.

  • AI Foundations

    Beyond the Hype: Demystifying the Architecture, Evolution, and Mechanics of Machine Intelligence

    The term “Machine Intelligence” (MI), often used interchangeably with Artificial Intelligence (AI) and Machine Learning (ML), has graduated from speculative science fiction into the core infrastructure of modern computing. However, cutting through the industry marketing requires looking at MI not as a singular “thinking mind,” but as a highly sophisticated convergence of statistical learning, algorithmic optimization, and distributed computational systems.

    This post explores what machine intelligence truly is under the hood, how it evolved structurally, the core tools that power it today, and its high-stakes applications.

    Gemini Generated Image ekf5t3ekf5t3ekf5

    Defining Machine Intelligence: What It Is (and Isn’t)

    We define Machine Intelligence as the capacity of a computational system to execute tasks by constructing generalized probabilistic models from empirical data, rather than following explicitly programmed deterministic rules. ### The Paradigmatic Shift

    To understand MI, consider the fundamental shift in the computing paradigm:

    • Classical Programming (Symbolic AI): Rules+DataAnswers\text{Rules} + \text{Data} \rightarrow \text{Answers}
    • Machine Intelligence: Data+AnswersRules\text{Data} + \text{Answers} \rightarrow \text{Rules}

    Instead of a software engineer hard-coding conditional statements (e.g., if-then-else), an MI system evaluates high-dimensional feature spaces to identify statistical regularities. It adjusts internal scalar values, known as weights and biases, to minimize a loss function via optimization techniques like Stochastic Gradient Descent (SGD).

           [ Classical Computing ]
    Rules + Data -----------> [ System ] -----------> Answers
    
           [ Machine Intelligence ]
    Data + Answers ---------> [ System ] -----------> Rules (Trained Model)
    

    The Evolutionary Timeline: From Rules to Representations

    The road to modern MI has been marked by swings between intense optimism and funding droughts, historically known as “AI Winters.”

    The Symbolic Era (1950s–1980s)

    Early AI focused on hard-coded logic and symbolic reasoning. Pioneers like John McCarthy and Marvin Minsky believed intelligence could be formalized through deductive logic. While this birthed powerful deterministic tools like chess engines and rule-based “expert systems,” it collapsed when faced with the messy, non-linear realities of natural language and computer vision.

    The Connectionist Resurgence (1980s–2000s)

    The paradigm shifted toward connectionism, or modeling intelligence using artificial neural networks (ANNs). The rediscovery of the backpropagation algorithm in the mid-1980s allowed multi-layer networks to learn internal representations. However, this era stalled due to a lack of computational hardware and data starvation.

    The Deep Learning and Foundation Model Boom (2010s–Present)

    The modern era was ignited in 2012 when AlexNet won the ImageNet competition, proving that deep convolutional neural networks (CNNs), when paired with Graphics Processing Units (GPUs), shattered classical vision benchmarks.

    The breakthrough accelerated with the introduction of the Transformer architecture by Vaswani et al. in 2017. By replacing recurrence with self-attention mechanisms, Transformers paved the way for massive foundation models (like the GPT and Claude families) and the modern shift toward Agentic AI, which are systems capable of autonomous multi-step reasoning and tool execution.

    The Modern MI Stack: Frameworks and Infrastructure

    Building machine intelligence today relies on a highly mature ecosystem of software and hardware.

    The Software Frameworks

    Modern ML architecture is dominated by two primary open-source ecosystems:

    • PyTorch (Backed by Meta): The preferred library for academic research and cutting-edge deployment due to its dynamic computation graph, which allows for intuitive debugging and flexible model design.
    • TensorFlow / Keras (Backed by Google): Renowned for its highly stable, static graph execution, making it a staple for rigid enterprise production pipelines.
    • Classical Libraries: For tabular data and standard statistical modeling, scikit-learn, XGBoost, and LightGBM remain the industry standard for gradient-boosted decision trees.
    Managed Enterprise Platforms

    At scale, engineers rarely train models on local machines. They utilize cloud-native MLOps (Machine Learning Operations) suites like Google Cloud Vertex AI, Amazon SageMaker, and IBM watsonx.ai. These platforms handle the end-to-end lifecycle, including data lineage tracking, hyperparameter tuning, distributed training orchestration, and real-time model drift monitoring.

    High-Impact Applications

    Machine intelligence is changing operations across technical and scientific fields through advanced applications:

    IndustryPrimary TechniqueReal-World Impact
    BiomedicineStructural Bioinformatics & Deep LearningAlphaFold revolutionized structural biology by predicting 3D protein structures directly from amino acid sequences, cutting drug discovery timelines down from years to days.
    Quantitative FinanceTime-Series Forecasting & Reinforcement LearningAutomated market making, algorithmic high-frequency trading, and real-time anomaly detection pipelines for credit fraud detection.
    Autonomous SystemsComputer Vision & Sensor FusionAutonomous drones and edge-AI vehicles mapping environments in real time using 3D object detection and semantic segmentation.
    Enterprise SoftwareLLMOps & Retrieval-Augmented Generation (RAG)Transitioning from simple chatbots to Agentic Systems that autonomously interface with databases, draft code, and manage cross-platform workflows.

    Looking Ahead: The Post-Graduate Frontier

    For researchers and engineers, the current frontier of machine intelligence is no longer just about scaling parameter counts. The focus has pivoted toward deep systemic challenges:

    • Inference Efficiency: Compressing massive models via quantization, pruning, and Knowledge Distillation to run on low-power edge devices.
    • Explainable AI (XAI): Peering inside the “black box” of deep neural networks to mathematically trace why a model made a specific prediction.
    • Alignment and Robustness: Ensuring models fail gracefully when exposed to out-of-distribution (OOD) data or adversarial attacks.

    Machine intelligence is not a magical artifact; it is an elegant mathematical framework built on linear algebra, calculus, and probability, brought to life by massive parallel computing. Understanding its mechanics is the first step toward building its future.

  • AI News & Industry Updates

    DeepSeek: The $6 Million Model That Shook Wall Street and Challenged the AI Establishment

    A Startup Nobody Saw Coming

    In the summer of 2023, a hedge fund manager in Hangzhou, China, quietly spun off an AI research lab. By January 2025, that lab had triggered what CBS News described as a shockwave through Wall Street, briefly dethroned ChatGPT as the most downloaded free app on Apple’s App Store, and forced a fundamental reassessment of the assumptions underlying hundreds of billions of dollars in AI infrastructure investment. The company was DeepSeek. The model was R1. And nothing in the AI industry looked quite the same afterward.

    For enterprise AI leaders evaluating model strategy, AI governance, and infrastructure spending, understanding DeepSeek is not optional. It is a case study in how architectural innovation can disrupt market assumptions, and a live stress test of every claim that frontier AI requires frontier compute budgets.

    How DeepSeek Actually Works

    DeepSeek is built on the same transformer foundation that underlies GPT-4, Claude, and Llama — but with two architectural decisions that distinguish it fundamentally from the models it competes with.

    The first is the Mixture-of-Experts (MoE) architecture. DeepSeek-V3 has 671 billion total parameters but only activates approximately 37 billion for any given query. This routs each input through only the most relevant subset of the model’s capacity. This “sparse activation” approach means the compute cost per inference is a fraction of what a dense 671B model would require, while retaining the representational capacity of the full parameter count.

    The second is a deeply optimised training pipeline. DeepSeek achieved state-of-the-art benchmark performance using only 2.8 million H800 GPU hours of training time, approximately ten times less training compute than the similarly performing Llama 3.1 405B. The $6 million training cost figure that broke investors’ assumptions is a consequence of this efficiency, not a trick.

    DeepSeek-R1, released in January 2025, is based on DeepSeek-V3 and is focused on advanced reasoning tasks, directly competing with OpenAI’s o1 model in performance while maintaining a significantly lower cost structure. Like the o-series models, R1 uses extended chain-of-thought reasoning — generating an internal scratchpad before committing to a final answer — to dramatically improve performance on mathematics, code, and logical inference tasks.

    The third structural difference is perhaps the most commercially significant: all DeepSeek models are released under open-weight licences such as MIT for R1, Apache 2.0 for subsequent releases. OpenAI’s models are fully proprietary. Anthropic’s models are fully proprietary. DeepSeek publishes the weights for free. Any enterprise can download and self-host the model at zero per-token cost.

    Does It Actually Work?

    The honest answer is: yes, significantly. But with important caveats.

    On reasoning benchmarks, R1 was legitimately competitive with OpenAI’s o1 at launch. Its mathematical reasoning in particular was rated best-in-class by several independent evaluations. For code generation, structured analysis, and multilingual tasks, it performs at a level that rivals or exceeds models costing orders of magnitude more to run via API.

    The limitations are real, however. According to testing by Vectara, DeepSeek-R1 hallucinates at a rate of 14.3%, compared to approximately 2% for OpenAI’s GPT-4. Its safety guardrails are also notably weaker than those of Western frontier models: Palo Alto Networks found it is relatively easy to bypass DeepSeek’s safety guardrails, and Enkrypt AI reported that R1 is four times more likely to produce malware or insecure code than OpenAI’s o1.

    For enterprise deployment, this matters. A model that performs exceptionally on benchmarks but hallucinates at seven times the rate of its main competitor and fails adversarial testing is not a drop-in replacement for production workflows where reliability and safety alignment are contractual or regulatory requirements.

    The Market Shock: DeepSeek Monday

    The broader AI industry was unprepared for what happened on January 27, 2025. Nvidia’s stock dropped nearly 18% that Monday morning, now referred to as “DeepSeek Monday” on Wall Street. Roughly $600 billion in market value evaporated in a single trading session, the largest single-day loss for any company in stock market history. Microsoft, Alphabet, Broadcom, and ASML all fell in sympathy. By the end of the week, over $1 trillion had been erased from American tech stocks.

    The mechanism of the panic was straightforward: if a Chinese lab could produce a frontier-capable model for $6 million, the foundational investment thesis driving demand for Nvidia’s chips — that training frontier AI requires tens of thousands of the most expensive GPUs available — appeared to be falsified in one announcement.

    Nvidia CEO Jensen Huang pushed back directly. As TechCrunch reported, Huang called DeepSeek’s R1 “incredibly exciting” and argued the market had it exactly backwards: more efficient models lower the cost of AI deployment, which accelerates adoption, which increases aggregate demand for compute. That argument proved correct. Nvidia’s shares are up 58% since the DeepSeek selloff, and its growth rate has continued to defy expectations. The panic was real; the underlying catastrophe was not.

    The Controversies

    DeepSeek’s emergence generated controversy on multiple fronts simultaneously, and none of them have been cleanly resolved.

    Data privacy. DeepSeek notes in its privacy policy that personal information it collects from users is held on secure servers located in the People’s Republic of China. Under that policy, the company collects device model, operating system, keystroke patterns or rhythms, IP address, and system language. Chinese law grants Beijing broad authority to access data from companies based in China — the same legal structure that made TikTok a Congressional target. For enterprise users handling sensitive data, this is a non-negotiable concern.

    Censorship. A CBS News analysis of the application found that DeepSeek did not return any results for a prompt seeking information about the 1989 Tiananmen Square protests and subsequent massacre. The model also declined to answer questions about the Uyghur situation and Taiwan’s political status, while providing detailed answers about criticisms of Western political figures. This ideological alignment is baked into the base model’s training, not merely a surface-level filter.

    Distillation allegations. OpenAI told the Financial Times that it had seen evidence that its models were used by DeepSeek to train its own — which would be a breach of OpenAI’s terms of service. White House AI czar David Sacks said there was “substantial evidence” that DeepSeek had “distilled the knowledge out of OpenAI’s models.” DeepSeek has not publicly addressed the allegation in detail, and the legal status of model distillation remains an unresolved question across the industry.

    Chip access. DeepSeek built its models using Nvidia H800 GPUs and these chips are designed specifically for the Chinese market after the US banned exports of the more powerful H100 and A100 chips in late 2022. In a September 2025 Nature paper, DeepSeek acknowledged it also owns A100 chips used for early-stage experiments. US officials have alleged access to restricted hardware acquired after export controls took effect, though Nvidia has maintained that DeepSeek’s use of its technology was export-control compliant.

    What This Means for Enterprise AI Strategy

    DeepSeek’s net contribution to the enterprise AI landscape is a genuinely mixed signal. It proved that architectural efficiency, and not raw compute, is the binding constraint on frontier model quality, which is a productive finding for the whole field. It demonstrated that open-weight frontier models are viable, which expands the strategic options available to enterprises that want to self-host rather than depend on API access.

    But anyone handling sensitive business data should not use the DeepSeek app or API directly — and the hallucination rate and safety posture make it unsuitable for high-stakes production workflows without significant additional investment in evaluation and guardrails. For research, mathematics, and coding tasks in non-sensitive environments, the open-weight models offer exceptional performance at zero per-token cost.

    The deeper strategic lesson is one DeepSeek did not intend to teach: that the efficiency frontier in AI is far from exhausted, that architectural innovation can close capability gaps that compute alone cannot, and that the assumption that building frontier AI requires a $100 million training budget was always more fragile than the market priced it to be.

  • The Science of AI

    How Large Language Models Work — Part 5: Inference, Sampling, Emergent Behaviour, and Open Frontiers

    This is the final part of a five-part series on the internal mechanics of large language models. Parts 1–4 covered tokenization, embeddings, attention, the transformer block, and the training and alignment pipeline. Part 5 addresses inference: how a trained model generates text, the mathematics of sampling, context window management, emergent capabilities, and the open research frontiers shaping the next generation of LLMs.

    From Trained Weights to Generated Text

    A trained, aligned LLM is a fixed mathematical function: given a sequence of input tokens, it produces a probability distribution over the next token. Inference is the process of repeatedly applying this function to generate text, while the engineering decisions made at inference time have a surprisingly large impact on the quality, diversity, safety, and cost of model outputs.

    At each generation step tt, the model computes:P(tn+1t1,t2,,tn;θ)=softmax(WUhn(N))P(t_{n+1} \mid t_1, t_2, \ldots, t_n;\, \theta) = \text{softmax}(W_U \cdot \mathbf{h}_n^{(N)})

    where hn(N)Rd\mathbf{h}_n^{(N)} \in \mathbb{R}^d is the final-layer hidden state at position nnn, WURV×dW_U \in \mathbb{R}^{|V| \times d} is the unembedding matrix (often tied to the transpose of the input embedding matrix WEW_EWE​), and the resulting vector of logits over V|V| vocabulary entries is passed through softmax to produce a probability distribution. A token is then drawn from this distribution (called the sampling step) appended to the context, and the process repeats.

    The Mathematics of Sampling

    How a token is selected from the output distribution is not trivial. Naive greedy decoding that always selects the highest-probability token tends to produce repetitive, degenerate outputs. Real systems use one or more of the following strategies.

    Temperature scaling. Before applying softmax, the logits are divided by a temperature parameter T>0T > 0T>0:PT(tn+1=k)=exp(zk/T)jexp(zj/T)P_T(t_{n+1} = k) = \frac{\exp(z_k / T)}{\sum_j \exp(z_j / T)}

    As T0T \to 0, the distribution concentrates on the single highest-logit token, equivalent to greedy decoding. As TT \to \infty, the distribution approaches uniformity with maximum entropy, maximum randomness. Values of T[0.6,1.0]T \in [0.6, 1.0] are typical for creative generation; T[0.0,0.3]T \in [0.0, 0.3] for precise factual or code generation tasks. Temperature does not change which token is most probable; instead, it changes how peaked or flat the distribution is.

    Top-k sampling. The distribution is truncated to only the kk highest-probability tokens, which are then renormalised and sampled from. A typical value is k=40k = 40. Top-kk prevents the model from sampling tokens with negligible probability, but it is sensitive to the shape of the distribution. In a uniform distribution, k=40k = 40 keeps 40 of many reasonable options; in a very peaked distribution, k=40k = 40 may retain tokens with near-zero probability.

    **Nucleus (top-pp) sampling.** Rather than fixing the number of tokens, nucleus sampling fixes the cumulative probability mass: the smallest set of tokens Vp\mathcal{V}_p​ such that kVpP(tk)p\sum_{k \in \mathcal{V}_p} P(t_k) \geq p is retained and renormalised. A typical value is p=0.9p = 0.9 or p=0.95p = 0.95. Nucleus sampling adapts naturally to the distribution’s shape. A peaked distribution retains few tokens, a flat one retains many – this is now the dominant strategy in production systems.

    Min-p sampling. A newer variant, increasingly adopted in open-source inference stacks, sets a dynamic minimum probability threshold relative to the top token: any token with P(tk)<pmin×P(tmax)P(t_k) < p_{\min} \times P(t_{\max}) is discarded. This keeps tokens that are meaningfully competitive with the best option while discarding genuinely improbable ones, and empirically reduces repetition more effectively than top-ppp at matched quality.

    In practice, production inference systems combine multiple strategies: temperature scaling applied first to reshape the distribution, followed by top-pp or min-pp truncation, followed by top-kk as a hard ceiling. The specific combination and hyperparameters are treated as tunable properties of a deployment configuration, not fixed properties of the model itself.

    Context Windows and Memory Management

    Every inference call operates within a context window, which is the maximum sequence length the model can process in a single forward pass. For GPT-4, the context window is 128K tokens; for Gemini 1.5 Pro, it extended to 1 million tokens; Llama 3.1 supports 128K. Context window length is not a free parameter, rather, it is constrained by the quadratic O(n2)O(n^2) attention cost and, critically, by KV cache memory.

    As established in Part 2, the KV cache stores the key and value tensors for every previous token at every layer, avoiding redundant recomputation during autoregressive generation. The memory footprint is:KV cache memory=2×n×Nlayers×nheads×dk×bytes per element\text{KV cache memory} = 2 \times n \times N_{\text{layers}} \times n_{\text{heads}} \times d_k \times \text{bytes per element}

    For a model with 96 layers, 96 heads, dk=128d_k = 128, processing a 128K-token context in FP16: 2×128000×96×96×128×26012 \times 128000 \times 96 \times 96 \times 128 \times 2 \approx 601 GB. This exceeds the VRAM of any single current GPU by a factor of roughly 10, which is why long-context inference requires either model parallelism across multiple devices, quantisation of KV cache entries to lower precision (INT8 or INT4), or approximate attention methods that reduce what must be stored.

    Several efficient attention variants address this scaling problem. Flash Attention (Dao et al., 2022) reorders the attention computation to avoid materialising the full n×nn \times n attention matrix in high-bandwidth memory, reducing memory complexity from O(n2)O(n^2) to O(n)O(n) while maintaining identical numerical output. Grouped-query attention (GQA), used in Llama 2 and 3, shares key and value heads across multiple query heads, reducing KV cache size by a factor of gg (the group size) without significant quality degradation. Sliding window attention, used in Mistral, restricts each token to attend only within a fixed window of recent tokens, allowing arbitrarily long sequences at the cost of cross-window recall.

    Emergent Capabilities and Phase Transitions

    One of the most scientifically consequential, and practically important, observations in LLM scaling is the phenomenon of emergent capabilities: abilities that are essentially absent in smaller models and appear abruptly as scale crosses some threshold, without being explicitly trained for.

    Wei et al. (2022) documented dozens of such capabilities: few-shot chain-of-thought reasoning, multi-step arithmetic, word unscrambling, and logical deduction all exhibit sharp phase transitions: near-zero performance at sub-threshold scales, near-human performance above it. The sharpness of these transitions distinguishes emergence from smooth capability growth and has profound implications for predicting what a model trained at a given scale will be able to do.

    The mechanism underlying emergence is debated. One influential account (the “grokking” hypothesis, from Power et al. at Anthropic) suggests that models first memorise training examples, then undergo a phase transition in which they discover a compressed algorithmic solution that generalises to held-out data. Another account, from Anthropic’s interpretability research, suggests that emergent capabilities correspond to the model assembling multi-step circuits, consisting of sequences of attention heads and FFN layers that compose to implement a non-trivial algorithm, and that these circuits can only form once the model has sufficient depth and width to represent all required intermediate computations simultaneously.

    From an engineering standpoint, emergence creates a prediction problem. The GPT-3 scaling curve gave no warning that a GPT-4-scale model would exhibit chain-of-thought reasoning, code execution, or structured tool use. This motivates careful capability elicitation and evaluation at each new model generation —(the practice of red-teaming) as a safety and capability discovery discipline.

    Chain-of-Thought and Reasoning Models

    The most practically significant emergent capability is multi-step reasoning — and the discovery that it can be dramatically improved by prompting or training the model to externalise its intermediate steps.

    Chain-of-thought prompting (Wei et al., 2022) established that providing examples of step-by-step reasoning in the prompt elicits dramatically better performance on multi-step arithmetic, commonsense reasoning, and symbolic manipulation tasks without any additional training. The effect is robust and scales with model size: smaller models gain little from chain-of-thought, but models above approximately 100B parameters show large, consistent improvements.

    Reasoning models — exemplified by OpenAI’s o1 and o3, and Anthropic’s Claude’s extended thinking mode — take this further by training models to produce extended internal reasoning traces before generating a final answer. The training procedure uses reinforcement learning on verifiable outcomes: the model is rewarded for producing correct final answers to problems where correctness can be checked algorithmically (mathematics, code execution, formal logic), and the RL signal drives the model to develop longer, more structured reasoning traces that are instrumentally useful for producing correct outputs.

    The result is a qualitatively different inference regime. A standard GPT-style model generates tokens in a single forward pass per token, with effective reasoning depth bounded by model depth. A reasoning model generates a long internal monologue, often thousands of tokens of scratchpad, before committing to an answer, effectively trading inference-time compute for reasoning quality. This represents a fundamental shift in the compute profile of AI: capability is no longer a fixed function of model size, but can be increased at inference time by allocating more tokens to reasoning.

    Open Frontiers: Mechanistic Interpretability, Multimodality, and Agents

    Three research frontiers are most likely to define the next phase of LLM development.

    Mechanistic interpretability is the program of reverse-engineering what computations specific model components implement. The goal is to go beyond behavioural evaluation — what the model does — to structural understanding — what algorithm it uses to do it. Anthropic’s superposition hypothesis (Elhage et al., 2022) established that neural networks represent more features than they have dimensions by encoding features as directions in a high-dimensional space and tolerating controlled interference between them. The subsequent Sparse Autoencoder (SAE) program — also led at Anthropic — has made it possible to decompose model activations into sparse, interpretable features: human-understandable concepts that each activate for a specific, semantically coherent set of inputs. SAE-based interpretability tools are now being applied to frontier models at production scale, with the goal of identifying circuits responsible for deception, sycophancy, and unsafe behaviours before deployment.

    Multimodality extends the transformer architecture beyond text. Vision-language models (GPT-4V, Gemini, Claude 3) process images by encoding them through a vision encoder — typically a Vision Transformer (ViT) — into a sequence of patch embeddings that are projected into the LLM’s token embedding space and concatenated with text tokens before the first transformer layer. Audio-language models (GPT-4o’s audio mode) follow an analogous pattern with a spectrogram encoder. The frontier is native multimodality — a single model trained end-to-end on text, image, audio, and video tokens simultaneously, rather than modality-specific encoders bolted onto a text backbone.

    Agentic systems extend the inference loop beyond token generation to include tool use, memory retrieval, and sequential decision-making. An agent wraps an LLM in a loop: the model generates text that includes structured tool calls (web search, code execution, database queries); the tool results are appended to the context; the model continues generating, possibly issuing further tool calls, until it produces a final response. Multi-agent systems extend this further: multiple LLM instances, each with different system prompts and tool access, communicate with each other through structured message passing. The engineering challenges are significant — context management, tool reliability, error recovery, and safety alignment in agentic settings are all active areas of research — but the capability ceiling of agentic LLMs is substantially higher than single-turn generation.

    A Map of the Whole

    Across this five-part series, we have traced the complete path from raw string to generated output:

    1. Tokenization — BPE or SentencePiece converts text into integer token IDs from a vocabulary of 32K–256K entries.
    2. Embedding — each token ID is projected into a ddd-dimensional vector; positional information is added via learned embeddings, sinusoidal encoding, or RoPE.
    3. AttentionNNN transformer blocks each apply multi-head self-attention: Q, K, V projections; scaled dot products; causal masking; softmax; value aggregation.
    4. Feed-forward network — each block applies a position-wise two-layer MLP with SwiGLU activation, implementing key-value memory over learned factual associations.
    5. Training — next-token prediction loss over trillions of tokens; AdamW with cosine decay; Chinchilla-optimal compute allocation; distributed parallelism at scale.
    6. Alignment — SFT on human demonstrations, reward model training on preference rankings, RLHF with PPO or DPO to concentrate capability toward preferred outputs.
    7. Inference — temperature scaling, nucleus or min-ppp sampling, KV cache management, and extended chain-of-thought reasoning to generate high-quality outputs efficiently.

    The transformer is a simple, composable architectural primitive. What it does, when trained at sufficient scale on sufficient data, and aligned to human preferences, is not simple at all.

    This concludes the five-part series on how large language models work. If you have found this series useful, the natural next steps are the mechanistic interpretability literature (Anthropic’s Transformer Circuits thread), the Chinchilla and scaling laws papers, and Neel Nanda’s open-source interpretability tooling at TransformerLens.

  • The Science of AI

    How Large Language Models Work — Part 4: Training, Scaling Laws, and RLHF

    This is Part 4 of a five-part series on the internal mechanics of large language models. Part 3 covered the complete transformer block and architectural variants. Part 4 addresses how models are trained: the pre-training objective, loss functions, the Chinchilla scaling laws, and the alignment pipeline of instruction tuning and RLHF that transforms a raw language model into a useful assistant.

    The Pre-Training Objective

    The entire capability of a modern LLM emerges from one deceptively simple training objective: predict the next token. Given a sequence of tokens [t1,t2,,tn][t_1, t_2, \ldots, t_n], the model is trained to maximise the log-probability of each token given all preceding tokens:LPT=1ni=1nlogP(tit1,,ti1;θ)\mathcal{L}_{\text{PT}} = -\frac{1}{n} \sum_{i=1}^{n} \log P(t_i \mid t_1, \ldots, t_{i-1};\, \theta)

    This is the negative log-likelihood loss, or equivalently, cross-entropy between the model’s predicted distribution and the one-hot true distribution over the vocabulary. Minimising LPT\mathcal{L}_{\text{PT}} is equivalent to maximising the likelihood of the training corpus under the model.

    The reason this objective is so productive is that predicting the next token accurately requires solving an enormous range of implicit sub-problems. To predict the next word in a chemistry paper, the model must understand chemistry. To predict dialogue in a novel, it must model character motivation and narrative consistency. To predict the output of a code snippet, it must simulate execution. All of these capabilities emerge as instrumental sub-goals of the single next-token prediction objective, a phenomenon sometimes called the “bitter lesson” of AI: simple objectives applied at scale consistently outperform hand-crafted inductive biases.

    The training corpus for frontier models is correspondingly vast. GPT-3 was trained on roughly 300 billion tokens drawn from Common Crawl, WebText2, Books, and Wikipedia. Llama 3 used over 15 trillion tokens. Assembling, filtering, deduplicating, and quality-scoring a corpus at this scale is itself a major engineering undertaking, and corpus quality is widely understood to be among the most important determinants of downstream model capability, arguably more important than architectural choices at equivalent parameter counts.

    The Training Loop

    Pre-training proceeds through the standard deep learning training loop, applied at extreme scale:

    Forward pass: A batch of token sequences is sampled from the corpus. Each sequence is processed through the full transformer stack consisting of embedding, NNN transformer blocks, and unembedding. This produces a probability distribution over the vocabulary at each position.

    Loss computation: Cross-entropy loss is computed by comparing the model’s predicted distribution at each position with the true next token.

    Backward pass: Gradients of the loss with respect to all θ\thetaθ parameters are computed via backpropagation through the entire network.

    Parameter update: An optimiser, called Adam or AdamW in virtually all modern LLMs, applies the gradient update:θθηm^t/(v^t+ϵ)\theta \leftarrow \theta – \eta \cdot \hat{m}_t / (\sqrt{\hat{v}_t} + \epsilon)

    where m^t\hat{m}_t​ and v^t\hat{v}_t​ are bias-corrected first and second moment estimates of the gradient, and η\eta is the learning rate. AdamW adds a decoupled weight decay term λθ\lambda \theta directly to the parameter update, separate from the gradient. This is important because standard L2 regularisation interacts badly with Adam’s adaptive scaling, while decoupled weight decay does not.

    The learning rate schedule typically involves a linear warmup phase (to avoid instability at the start of training when gradients are large and parameters are random) followed by a cosine decay to a minimum learning rate of roughly ηmin0.1ηmax\eta_{\text{min}} \approx 0.1 \eta_{\text{max}}​:ηt=ηmin+12(ηmaxηmin)(1+cos ⁣(πtT))\eta_t = \eta_{\text{min}} + \frac{1}{2}(\eta_{\text{max}} – \eta_{\text{min}})\left(1 + \cos\!\left(\frac{\pi t}{T}\right)\right)

    where TT is the total number of training steps. The cosine schedule has become the near-universal choice because it empirically outperforms linear decay and step schedules across model sizes and tasks.

    At frontier scale, training runs on clusters of thousands of GPUs or TPUs, employing a combination of data parallelism (each device processes a different batch, gradients are aggregated), tensor parallelism (each layer’s weight matrices are sharded across devices), and pipeline parallelism (different layers run on different devices simultaneously). GPT-3’s training required approximately 3.14 × 10²³ FLOPs and ran on 10,000 V100 GPUs. A GPT-4-class training run is estimated at well over 10²⁵ FLOPs.

    Scaling Laws and the Chinchilla Result

    How should a fixed compute budget be allocated between model size (number of parameters NN) and training data (number of tokens DD)? This is the central question addressed by neural scaling law research.

    Kaplan et al. (OpenAI, 2020) established that loss scales as a power law in both NN and DD, and derived the now-famous result that, for a fixed compute budget CC, loss is minimised by scaling NN and DD in a roughly fixed ratio, with NN growing considerably faster than DD. This led to the prevailing practice of training very large models on relatively modest amounts of data, exemplified by GPT-3 (175B parameters, 300B tokens).

    Hoffmann et al. (DeepMind, 2022) in the “Chinchilla” paper challenged this conclusion. Using a broader range of model sizes and more careful experimental design, they derived a different optimal allocation:NoptC0.5,DoptC0.5N_{\text{opt}} \propto C^{0.5}, \quad D_{\text{opt}} \propto C^{0.5}

    That is, compute-optimal training requires scaling parameters and tokens in a roughly 1:1 ratio. Their finding: for a given compute budget, the optimal model size is significantly smaller than previously believed, but must be trained on significantly more data. The compute-optimal ratio is approximately 20 training tokens per parameter.

    The practical implication was dramatic. GPT-3, by the Chinchilla analysis, was massively undertrained. A 175B parameter model should be trained on approximately 3.5 trillion tokens to be compute-optimal, not 300 billion. Chinchilla itself (70B parameters, 1.4 trillion tokens) outperformed Gopher (280B parameters) on nearly every benchmark despite using a quarter of the parameters, simply by training longer on more data.

    The Chinchilla result reshaped subsequent model development: Llama 1 and 2 trained smaller models on far more tokens; Llama 3 trained an 8B model on 15 trillion tokens. The scaling law itself takes the form:L(N,D)=E+ANα+BDβL(N, D) = E + \frac{A}{N^\alpha} + \frac{B}{D^\beta}

    where EE is the irreducible entropy of the data distribution (a lower bound on achievable loss), and AA, BB, α\alpha, β\beta are empirically fitted constants. The three terms represent, respectively: the noise floor of the task, the contribution of model capacity, and the contribution of data quantity.

    From Language Model to Assistant: Instruction Tuning and RLHF

    A model trained only on next-token prediction is not a useful assistant. It will complete any prompt in the style of its training distribution and it might respond to “How do I bake bread?” by generating more questions rather than an answer, because question-continuation is a common pattern in web text. Transforming a base language model into a helpful, honest, and harmless assistant requires a second training phase: alignment.

    The alignment pipeline used by OpenAI, Anthropic, Google DeepMind, and most frontier labs follows a three-stage process.

    Stage 1 — Supervised fine-tuning (SFT): Human annotators write demonstrations of ideal assistant behaviour through prompt-response pairs that exhibit the desired properties: helpfulness, accuracy, appropriate refusal of harmful requests, appropriate tone and format. The base model is then fine-tuned on this dataset using standard cross-entropy loss. SFT alone substantially improves instruction-following; InstructGPT’s SFT model already significantly outperformed the raw GPT-3 base in human evaluations.

    Stage 2 — Reward model training: Human annotators rank multiple model responses to the same prompt, from best to worst. A separate reward model RϕR_\phi​, itself a transformer, is trained to predict these rankings. Given a prompt xx and response yy, the reward model produces a scalar score Rϕ(x,y)RR_\phi(x, y) \in \mathbb{R}. The training objective minimises a pairwise ranking loss:LRM=E(x,yw,yl) ⁣[logσ ⁣(Rϕ(x,yw)Rϕ(x,yl))]\mathcal{L}_{\text{RM}} = -\mathbb{E}_{(x, y_w, y_l)}\!\left[\log \sigma\!\left(R_\phi(x, y_w) – R_\phi(x, y_l)\right)\right]

    where ywy_w is the preferred response, yly_l​ is the less preferred response, and σ\sigma is the sigmoid function. This Bradley-Terry loss encourages the reward model to assign higher scores to preferred completions.

    Stage 3 — Reinforcement learning from human feedback (RLHF): The SFT model πθ\pi_\theta​ is further fine-tuned using the reward model as a proxy for human preference. The policy gradient objective maximises expected reward while penalising deviation from the SFT model via a KL divergence constraint:J(θ)=ExD,yπθ(x) ⁣[Rϕ(x,y)βDKL ⁣(πθ(x)πSFT(x))]\mathcal{J}(\theta) = \mathbb{E}_{x \sim \mathcal{D},\, y \sim \pi_\theta(\cdot|x)}\!\left[R_\phi(x, y) – \beta \cdot D_{\text{KL}}\!\left(\pi_\theta(\cdot|x) \,\|\, \pi_{\text{SFT}}(\cdot|x)\right)\right]

    The KL penalty, weighted by coefficient β\beta, is critical. Without it, the policy would rapidly overfit to the reward model’s blind spots, a phenomenon called reward hacking: the model learns to produce outputs that score highly according to RϕR_\phi while being nonsensical or subtly harmful in ways the reward model did not penalise. The KL term keeps the aligned model close to the original SFT distribution, preserving its language modelling capabilities while steering it toward preferred outputs.

    This optimisation problem is solved using the Proximal Policy Optimisation (PPO) algorithm, which clips the policy gradient update to prevent excessively large steps. PPO is not the only approach; Direct Preference Optimisation (DPO), introduced in 2023, reformulates the RLHF objective as a supervised learning problem that bypasses the reward model entirely:LDPO(θ)=E(x,yw,yl) ⁣[logσ ⁣(βlogπθ(ywx)πref(ywx)βlogπθ(ylx)πref(ylx))]\mathcal{L}_{\text{DPO}}(\theta) = -\mathbb{E}_{(x, y_w, y_l)}\!\left[\log \sigma\!\left(\beta \log \frac{\pi_\theta(y_w|x)}{\pi_{\text{ref}}(y_w|x)} – \beta \log \frac{\pi_\theta(y_l|x)}{\pi_{\text{ref}}(y_l|x)}\right)\right]

    DPO has become widely adopted because it is significantly simpler to implement and more stable to train than PPO-based RLHF, while achieving comparable alignment quality on most benchmarks.

    Why InstructGPT Outperformed GPT-3

    The RLHF result that most concisely captures the importance of alignment is this: InstructGPT (1.3B parameters, RLHF-trained) was preferred by human evaluators over GPT-3 (175B parameters, base model) 85% of the time. A model with 100× fewer parameters that is aligned to human preferences consistently produced more useful outputs than its massive unaligned ancestor.

    This result makes precise what “alignment” means in practice. A base model has vast latent capability distributed across its weights, but no particular disposition to deploy that capability in ways that are useful or safe. Alignment is the process of concentrating and directing that capability toward the response distribution humans actually want, without catastrophically degrading the underlying language modelling capability that makes the responses coherent.

    Conclusion

    Pre-training on next-token prediction, at compute-optimal scale guided by Chinchilla’s laws, produces a powerful but raw language model. The alignment pipeline (SFT → reward model → RLHF or DPO) shapes that raw capability into something useful, honest, and controllable. The gap between these two stages is where most of the practical engineering work in deploying frontier models resides.

    Part 5 will close the series with inference: sampling strategies, the mechanics of context window management, emergent capabilities and what they imply, and the open research frontiers such as mechanistic interpretability, reasoning models, and multimodality. These will define the next phase of LLM development.

    Part 5: Inference, Sampling, and Emergent Behaviour — the final instalment of this series.

  • The Science of AI

    How Large Language Models Work — Part 3: The Transformer Block and Architecture

    This is Part 3 of a five-part series on the internal mechanics of large language models. Part 2 derived scaled dot-product attention and the KV cache. Part 3 traces the complete transformer block consisting of feed-forward networks, layer normalisation, and residual streams; it examines the architectural differences between decoder-only and encoder-decoder models.

    From Attention Output to Transformer Block

    At the end of Part 2, self-attention had produced an output matrix ORn×dO \in \mathbb{R}^{n \times d} or one updated vector per token, now containing contextual information drawn from every other position in the sequence. But this is only the first half of a single transformer block. Before the signal moves to the next layer, it passes through three more components: a residual connection, layer normalisation, and a position-wise feed-forward network. Together with multi-head attention, these four elements constitute the repeating unit of every transformer-based LLM, stacked NN times to form the full model.

    Understanding each component precisely is important not just for implementation, but for diagnosing failure modes, interpreting mechanistic interpretability research, and making informed decisions about architectural variants when selecting or fine-tuning models.

    Residual Connections

    The residual connection, introduced in ResNets for computer vision and adopted into transformers from the outset, is deceptively simple. Rather than passing the attention output OO directly to the next component, the original input XX is added back:X=X+MultiHead(X)X’ = X + \text{MultiHead}(X)

    This addition of the residual or skip connection has several important consequences.

    First, it solves the vanishing gradient problem for very deep networks. During backpropagation, gradients flow backward through the network. Without residual connections, multiplying many Jacobians together through NNN sequential non-linear transformations causes gradient magnitudes to decay exponentially, making early layers extremely slow to learn. The residual path provides a direct gradient highway that bypasses each block, so that gradients can flow backward through the addition operation unchanged, regardless of how many layers separate the loss from the input.

    Second, and more subtly, residual connections give the network an inductive bias toward learning incremental transformations. Rather than learning to reconstruct the full representation from scratch at each layer, each block learns only the delta or the correction to add to the existing representation. In mechanistic interpretability, researchers conceptualise the transformer as a residual stream: a dd-dimensional vector that is progressively written to and read from by successive attention heads and feed-forward layers, each contributing small structured updates. This framing, developed extensively by Anthropic, EleutherAI, and Neel Nanda’s research group, has proven highly productive for understanding what specific components of large models actually compute.

    Layer Normalisation

    Before and/or after each sub-component, layer normalisation is applied. For a vector xRd\mathbf{x} \in \mathbb{R}^d:LayerNorm(x)=γxμσ+ϵ+β\text{LayerNorm}(\mathbf{x}) = \gamma \odot \frac{\mathbf{x} – \mu}{\sigma + \epsilon} + \beta

    where μ=1dixi\mu = \frac{1}{d}\sum_i x_i is the mean, σ=1di(xiμ)2\sigma = \sqrt{\frac{1}{d}\sum_i (x_i – \mu)^2} is the standard deviation, ϵ\epsilon is a small constant for numerical stability, and γ,βRd\gamma, \beta \in \mathbb{R}^d are learned scale and shift parameters.

    Layer normalisation stabilises training by preventing the internal covariate shift problem, which is the tendency for the distribution of a layer’s inputs to change as upstream parameters update, forcing each layer to continuously readapt. By normalising each token’s representation independently across the feature dimension (as opposed to batch normalisation, which normalises across the batch dimension), layer norm is compatible with variable-length sequences and works correctly with batch size 1, making it well-suited for autoregressive inference.

    Two conventions exist for where layer norm is placed within the block:

    Post-norm (original Transformer, “Attention Is All You Need”): LayerNorm is applied after the residual addition:X=LayerNorm(X+MultiHead(X))X’ = \text{LayerNorm}(X + \text{MultiHead}(X))

    Pre-norm (GPT-2, GPT-3, most modern LLMs): LayerNorm is applied to the input before the sub-component:X=X+MultiHead(LayerNorm(X))X’ = X + \text{MultiHead}(\text{LayerNorm}(X))

    Pre-norm has become the dominant convention because it produces more stable training dynamics at large scale. Gradients flow more cleanly through the unmodified residual path, and the model is less sensitive to initialisation and learning rate choice. The architectural difference is subtle but has meaningful empirical consequences; models trained with post-norm often require careful learning rate warmup schedules that pre-norm models do not.

    The Feed-Forward Network

    After the attention sub-layer (with its own residual connection and layer norm), each transformer block applies a position-wise feed-forward network (FFN). The term “position-wise” means the same two-layer MLP is applied independently to each token’s vector, and the FFN has no cross-token interactions, unlike attention.

    The standard formulation:FFN(x)=W2σ(W1x+b1)+b2\text{FFN}(\mathbf{x}) = W_2 \cdot \sigma(W_1 \mathbf{x} + \mathbf{b}_1) + \mathbf{b}_2

    where W1Rdff×dW_1 \in \mathbb{R}^{d_{\text{ff}} \times d}, W2Rd×dffW_2 \in \mathbb{R}^{d \times d_{\text{ff}}}​, and dffd_{\text{ff}}​ is the intermediate dimension, typically 4d4d. In GPT-3, d=12288d = 12288 and dff=49152d_{\text{ff}} = 49152, giving each FFN roughly 4×1228826034 \times 12288^2 \approx 603 million parameters, more than the attention sub-layer at that layer.

    The activation function σ\sigmaσ has evolved across generations. The original transformer used ReLU. GPT-2 and GPT-3 used GeLU (Gaussian Error Linear Unit), which approximates ReLU with a smooth, non-zero gradient for slightly negative inputs:GeLU(x)=xΦ(x)0.5x ⁣(1+tanh ⁣(2π(x+0.044715x3)))\text{GeLU}(x) = x \cdot \Phi(x) \approx 0.5x\!\left(1 + \tanh\!\left(\sqrt{\frac{2}{\pi}}\left(x + 0.044715x^3\right)\right)\right)

    where Φ\Phi is the standard normal CDF. More recent models use SwiGLU, a gated variant introduced by Noam Shazeer in 2020 and adopted in PaLM, Llama, and most frontier models:SwiGLU(x)=SiLU(W1x)(W3x)\text{SwiGLU}(\mathbf{x}) = \text{SiLU}(W_1 \mathbf{x}) \odot (W_3 \mathbf{x})

    where SiLU(x)=xσ(x)\text{SiLU}(x) = x \cdot \sigma(x) is the Sigmoid Linear Unit and W3W_3​ is an additional learned gate projection. SwiGLU consistently outperforms GeLU on downstream benchmarks, though the underlying reason remains an active area of research. When using SwiGLU, dffd_{\text{ff}}​ is typically set to 83d\frac{8}{3}d rather than 4d4d to keep parameter counts comparable across architectures.

    What does the FFN actually learn? Mechanistic interpretability work, particularly from Anthropic and the Neel Nanda group, has provided strong evidence that FFN layers function as key-value memories. Each row of W1W_1​ acts as a pattern detector (a “key”), and the corresponding row of W2W_2 stores an associated “value” that gets added to the residual stream when that pattern is detected. This explains why larger FFNs improve factual recall (they have more memory slots) and why deleting specific FFN neurons can surgically remove specific factual associations from a model’s behaviour.

    The Complete Transformer Block

    Assembling all components, the full pre-norm transformer block for a decoder-only model is:a=x+MultiHead(LayerNorm(x))\mathbf{a} = \mathbf{x} + \text{MultiHead}(\text{LayerNorm}(\mathbf{x})) x=a+FFN(LayerNorm(a))\mathbf{x}’ = \mathbf{a} + \text{FFN}(\text{LayerNorm}(\mathbf{a}))

    This two-step computation, attention followed by FFN, each with its own pre-norm and residual, is repeated NN times. In GPT-3, N=96N = 96. In Llama 3 70B, N=80N = 80. In a typical GPT-4-class model, NN is believed to be in the range of 96–120 layers. Each repetition allows the model to build increasingly abstract representations. Early layers handle low-level syntactic patterns, while later layers encode semantic and factual content.

    transformer block structure

    Decoder-Only vs Encoder-Decoder Architecture

    Two principal transformer architectures are in widespread use, differing in how they process input and generate output.

    Decoder-only models (GPT, Llama, Mistral, Gemma, Falcon) use a single stack of transformer blocks with causal (masked) self-attention. Every token can attend only to previous tokens. The entire input prompt and the generated output share the same context window and are processed by the same stack. At inference time, the model autoregressively generates one token at a time, each conditioned on all prior tokens. This architecture is dominant for general-purpose language models because it scales efficiently and the training objective of next-token prediction across the entire sequence is simple, scalable, and empirically powerful.

    Encoder-decoder models (T5, BART, mT5, the original Transformer for machine translation) use two distinct stacks. The encoder processes the full input with bidirectional attention. Every token can attend to every other token simultaneously, with no causal mask. The encoded representation is then passed to the decoder via a cross-attention mechanism: each decoder token’s query attends to the encoder’s key-value pairs in addition to previously generated decoder tokens. The cross-attention block takes the form:CrossAttn(Qdec, Kenc, Venc)=softmax ⁣(QdecKencdk)Venc\text{CrossAttn}(Q_{\text{dec}},\ K_{\text{enc}},\ V_{\text{enc}}) = \text{softmax}\!\left(\frac{Q_{\text{dec}} K_{\text{enc}}^\top}{\sqrt{d_k}}\right)V_{\text{enc}}

    This architecture was originally designed for sequence-to-sequence tasks such as translation, summarisation, or question answering, where the full input is available before generation begins. It has largely been supplanted by decoder-only models for general language tasks, primarily because the instruction-tuned decoder-only paradigm proved more flexible and scalable. However, encoder-decoder models retain advantages for tasks requiring deep understanding of a fixed input, such as structured prediction, constrained generation, and certain retrieval tasks.

    A hybrid, the encoder-only model (BERT, RoBERTa, DeBERTa), uses bidirectional attention with no autoregressive generation. It is optimised for discriminative tasks such as classification, named entity recognition, or semantic similarity, rather than generation, and remains widely used in production embedding pipelines and retrieval systems.

    Depth, Width, and the Scaling Hypothesis

    The transformer block’s design raises a natural question: does it matter whether a model has more layers (depth) or larger hidden dimension (width)? Empirically, the two interact in complex ways, and the optimal allocation of a fixed parameter budget between depth and width is one of the central questions addressed by scaling law research, which is the subject of Part 4.

    What is clear from both theory and experiment is that depth and width serve different functions. Width increases the model’s representational capacity at each layer by the size of the residual stream and the richness of the key-value memory in the FFN. Depth increases the number of sequential computational steps the model can take, which means the number of times attention and FFN transformations can be composed. Tasks requiring multi-step reasoning appear to benefit disproportionately from depth, while factual recall scales more uniformly with total parameter count regardless of how it is distributed between depth and width.

    Conclusion

    The transformer block is elegant in its modularity: a residual stream, two sub-components (attention and FFN), and two layer normalisation steps. The full model is simply this block repeated NN times. But the interactions between these components, including the gradient flow through residual connections, the factual storage in FFN key-value memories, and the progressive abstraction through depth, give rise to capabilities that are not predictable from any single component in isolation.

    Part 4 will move from architecture to training: the next-token prediction objective, loss functions, the Chinchilla scaling laws, and the dramatic effect of RLHF and instruction tuning on model behaviour, explaining why InstructGPT, at a fraction of GPT-3’s parameter count, consistently outperformed it.

    Coming next in the AI Engineering series is Part 4: Training, Scaling Laws, and RLHF.

  • The Science of AI

    How Large Language Models Work — Part 2: The Attention Mechanism

    This is Part 2 of a five-part series on the internal mechanics of large language models. Part 1 covered tokenization, embeddings, and positional encoding. Part 2 derives the self-attention mechanism from first principles, covers multi-head attention, and examines the KV cache.

    The Problem Attention Solves

    At the end of Part 1, we had a matrix XRn×dX \in \mathbb{R}^{n \times d}, which was a one ddd-dimensional vector per token, encoding both semantic identity and position. The first transformer layer receives this matrix and must do something critical: allow each token to incorporate information from every other token in the sequence before passing its updated representation to the feed-forward network.

    This is the problem that self-attention solves. Earlier sequence models such as LSTMs and GRUs processed tokens sequentially, which meant that a word at position 1 had to wait for its influence to propagate through every intermediate hidden state to reach position 512. Long-range dependencies were difficult to learn because the gradient had to flow through hundreds of recurrent steps. Attention eliminates this bottleneck entirely by allowing any token to attend directly to any other token in a single operation, regardless of distance.

    Queries, Keys, and Values

    The first step of self-attention is to project each token’s embedding into three separate representations using learned weight matrices:Q=XWQ,K=XWK,V=XWVQ = XW^Q, \quad K = XW^K, \quad V = XW^Vwhere WQ,WK,WVRd×dkW^Q, W^K, W^V \in \mathbb{R}^{d \times d_k}​ are learned projection matrices, and dkd_k​ is the dimension of the query and key space (typically dk=d/hd_k = d / h where hh is the number of attention heads, more on that shortly).

    The resulting matrices Q,K,VRn×dkQ, K, V \in \mathbb{R}^{n \times d_k} are called the Query, Key, and Value matrices respectively.

    The intuition behind this decomposition is often explained through an analogy: think of each token’s query vector as a question it is asking (“what context do I need?”), each token’s key vector as an advertisement of its content (“here is what I contain”), and each token’s value vector as the actual information it contributes when attended to (“here is what I give you if you attend to me”). The query-key interaction determines how much each token attends to every other; the values are what actually gets aggregated.

    Scaled Dot-Product Attention

    Given QQ, KK, and VV, the attention output is computed as:Attention(Q,K,V)=softmax ⁣(QKdk)V\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right) VLet’s unpack this step by step.

    Step 1 — Dot products: QKRn×nQK^\top \in \mathbb{R}^{n \times n} is a matrix of raw attention scores. Entry (i,j)(i, j) is the dot product between the query vector of token ii and the key vector of token jj:sij=qikjs_{ij} = \mathbf{q}_i \cdot \mathbf{k}_jA high dot product means token ii finds token jj highly relevant. This is the mechanism through which, for example, a pronoun “she” can attend strongly to the noun “Alice” it refers to three sentences earlier.

    Step 2 — Scaling: The dot products are divided by dk\sqrt{d_k}​​. Without this scaling, when dkd_k​ is large, the dot products grow large in magnitude, pushing the softmax into regions where gradients become vanishingly small — a variant of the vanishing gradient problem. The dk\sqrt{d_k}​​ factor keeps the variance of the dot products approximately constant regardless of model dimensionality.

    Step 3 — Causal masking (decoder-only models): In autoregressive models like GPT, token ii must not attend to any token j>ij > i meaning that it cannot look into the future. Before applying softmax, a mask is added:sijsij+mij,mij={0if jiif j>is_{ij} \leftarrow s_{ij} + m_{ij}, \quad m_{ij} = \begin{cases} 0 & \text{if } j \leq i \\ -\infty & \text{if } j > i \end{cases}The -\infty values become zero after softmax, effectively zeroing out future positions.

    Step 4 — Softmax: Each row of the masked score matrix is passed through softmax:αij=exp(sij)k=1nexp(sik)\alpha_{ij} = \frac{\exp(s_{ij})}{\sum_{k=1}^{n} \exp(s_{ik})}The resulting matrix ARn×nA \in \mathbb{R}^{n \times n} is the attention weight matrix. Each row sums to 1 and can be interpreted as a probability distribution over the sequence: the probability that token ii attends to each position.

    Step 5 — Value aggregation: The output for token ii is a weighted sum of all value vectors:oi=j=1nαijvj\mathbf{o}_i = \sum_{j=1}^{n} \alpha_{ij} \mathbf{v}_jIn matrix form: O=AVRn×dkO = AV \in \mathbb{R}^{n \times d_k}​. Each output vector is a contextualised representation of its token, so that the same word “bank” will produce a different output vector in “river bank” versus “central bank” because its attention weights will be distributed differently across the surrounding context.

    scaled dot product attention

    Multi-Head Attention

    A single attention head computes one set of query-key-value interactions. But different aspects of meaning may require different attention patterns simultaneously: a token might need to attend to its syntactic head, its semantic antecedent, and its positional neighbours all at once. Multi-head attention runs hh attention operations in parallel:headi=Attention(QWiQ, KWiK, VWiV)\text{head}_i = \text{Attention}(QW_i^Q,\ KW_i^K,\ VW_i^V) MultiHead(Q,K,V)=Concat(head1,,headh)WO\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \ldots, \text{head}_h)W^Owhere WiQ,WiK,WiVRd×dkW_i^Q, W_i^K, W_i^V \in \mathbb{R}^{d \times d_k}​ are per-head projection matrices, each head operates in a dk=d/hd_k = d/h dimensional subspace, and WORd×dW^O \in \mathbb{R}^{d \times d} is a final output projection that mixes the concatenated heads back into the full dd-dimensional space.

    In GPT-3, d=12288d = 12288 and h=96h = 96, so each head operates in a dk=128d_k = 128 dimensional subspace. The 96 heads learn to specialize: empirical work in mechanistic interpretability has identified heads that track syntactic subject-verb agreement, heads that copy tokens from earlier in context, heads that attend to the most recent noun phrase, and heads that implement induction — recognizing when a pattern seen earlier in the context is repeating.

    The computational cost of full self-attention is O(n2d)O(n^2 d), or quadratic in sequence length. For a 128K-token context window, the attention matrix alone has 128000216128000^2 \approx 16 billion entries, making naive computation prohibitively expensive. Efficient attention variants such as Flash Attention, Sparse Attention, Sliding Window Attention address this scaling problem, which we’ll cover in Part 3 alongside the full transformer block.

    The KV Cache

    During inference, a decoder-only model generates one token at a time. At step tt, the model processes the full sequence [t1,,tt][t_1, \ldots, t_t] and predicts tt+1t_{t+1}​. Without optimization, this would require recomputing the key and value matrices for all previous tokens at every step so thar cost grows as O(t2)O(t^2) per generation.

    The KV cache eliminates this redundancy. Since the key and value representations of tokens t1,,tt1t_1, \ldots, t_{t-1}​do not change between steps (they depend only on those tokens’ positions and embeddings, which are fixed once generated), they can be cached in memory and reused. At step tt, only the new token’s QQ, KK, VV need to be computed; the cached KK and VV matrices from previous steps are concatenated and the attention is computed against the full cached sequence.

    This reduces per-step inference cost from O(t2)O(t^2) to O(t)O(t) in attention computation, but at the cost of memory. A KV cache for a 128K-token context with 96 heads, 128 layers, and FP16 precision occupies on the order of tens of gigabytes. Managing KV cache memory is one of the primary challenges in deploying frontier models efficiently at scale. It is why inference hardware for long-context models requires far more VRAM than a naive parameter count would suggest.

    What Attention Actually Learns

    It is tempting to describe attention as a mechanism that “understands” language. It is more precise, and more useful for engineering purposes, to say that attention is a differentiable, content-based memory retrieval system. The model learns, through gradient descent on the next-token prediction objective, to configure its WQW^Q, WKW^K, WVW^V matrices such that the right values get retrieved for the right queries.

    The mechanism has no built-in notion of syntax, coreference, or meaning. All of that emerges from training dynamics or from the statistical regularities of billions of documents. Understanding this distinction is important for debugging model failures: when an LLM makes a coreference error or loses track of a constraint stated early in a long context, the failure mode is almost always traceable to attention weights that were distributed incorrectly, either because the training distribution underrepresented that pattern, or because the KV cache compression strategy discarded the relevant context.

    Conclusion

    Self-attention is the architectural innovation that made modern LLMs possible. By allowing every token to attend directly to every other token in a single parallelisable matrix operation, it solves the long-range dependency problem that defeated earlier sequential architectures. Multi-head attention extends this by learning multiple independent attention patterns simultaneously, while the KV cache makes autoregressive inference tractable at scale.

    Part 3 will take the attention output ORn×dO \in \mathbb{R}^{n \times d} and trace it through the rest of the transformer block: the feed-forward network, layer normalisation, residual connections, and the architectural choices (decoder-only versus encoder-decoder) that distinguish GPT-style models from BERT-style ones.

    Coming next in the AI Engineering series is Part 3: The Transformer Block and Architecture.

  • The Science of AI

    How Large Language Models Work — Part 1: Tokenization and Embeddings

    This is Part 1 of a five-part deep-dive series on the internal mechanics of large language models. This series is written for engineers, ML practitioners, and technically advanced readers. Part 1 covers tokenization and embeddings — the first two stages through which raw text becomes a mathematical object a neural network can reason over.

    Why Text Must Be Transformed

    Neural networks are, at their core, mathematical functions that operate on tensors, which are multi-dimensional arrays of floating-point numbers. They cannot accept raw text strings as input. Before a language model can do anything useful, it must convert a sequence of characters into a sequence of numbers. This two-step process of tokenization followed by embedding is where all LLM processing begins, and understanding it deeply is prerequisite to understanding everything that follows.

    Stage 1: Tokenization

    What a Tokenizer Does

    A tokenizer breaks a raw string into a sequence of discrete units called tokens, and maps each token to an integer index in a fixed vocabulary. Given the input string:

    "The cat sat on the mat"

    a tokenizer might produce the token sequence: [464, 5171, 7231, 322, 464, 8114]

    Each integer is an index into a vocabulary table of size V|V|, typically between 32,000 and 100,000 entries for modern models. GPT-4 uses a vocabulary of approximately 100,277 tokens. Llama 3 uses 128,256.

    positional encoding comparison
    tokenization bpe diagram

    Byte-Pair Encoding (BPE)

    The dominant tokenization algorithm used in modern LLMs is Byte-Pair Encoding (BPE), originally a data compression algorithm adapted for NLP by Sennrich et al. in 2016.

    BPE builds its vocabulary through an iterative merging process:

    1. Initialise the vocabulary with every individual character (or byte) in the training corpus.
    2. Count all adjacent symbol pairs across the corpus.
    3. Merge the most frequent pair into a single new symbol.
    4. Repeat steps 2–3 until the vocabulary reaches the target size V|V|∣V∣.

    The result is a vocabulary that contains individual characters, common subwords, and frequent whole words. The word “tokenization” might be represented as three tokens: token, ization is further split into iz, ation depending on training corpus frequency.

    This has a critical practical consequence: no word is ever truly unknown to a BPE tokenizer. Any string, including code, URLs, foreign scripts, or novel proper nouns, can be decomposed into its constituent bytes if nothing else matches. This is why BPE-based models generalise to inputs they have never seen verbatim.

    Token Fertility and Efficiency

    Not all languages tokenize equally efficiently. English text typically tokenizes at roughly 0.75 tokens per word. Languages with richer morphology, such as Finnish, Turkish, Arabic, or non-Latin scripts, tokenize less efficiently, sometimes requiring 3–5 tokens per word. This has practical implications: a context window of 128,000 tokens holds far more English prose than it does Thai or Arabic text, a bias baked into the model’s architecture from the vocabulary construction stage.

    The fertility of a tokenizer, or the average number of tokens per word, is a meaningful measure of how well it serves a given language or domain. Code-optimised models like DeepSeek Coder use vocabularies with explicit code tokens to reduce the fertility of common programming constructs.

    WordPiece and SentencePiece

    Two notable alternatives to BPE are worth knowing:

    WordPiece, used in BERT and its derivatives, is similar to BPE but merges pairs that maximise the likelihood of the training data under a language model, rather than simply the most frequent pair. This produces slightly different vocabulary distributions.

    SentencePiece, used in models including Llama and T5, treats the input as a raw unicode byte stream with no pre-tokenization step (no whitespace splitting). This makes it language-agnostic and particularly well-suited for multilingual models.

    Stage 2: Token Embeddings

    The Embedding Matrix

    Once tokenization has produced a sequence of integer indices [t1,t2,,tn][t_1, t_2, \ldots, t_n], each index must be converted into a dense vector. This is done via an embedding matrix WERV×dW_E \in \mathbb{R}^{|V| \times d}, where dd is the model’s hidden dimension (also called the embedding dimension or dmodeld_{\text{model}}​).

    The embedding for token tit_iti​ is simply a row lookup:ei=WE[ti]Rd\mathbf{e}_i = W_E[t_i] \in \mathbb{R}^dIn GPT-3, d=12288d = 12288. In Llama 3 8B, d=4096d = 4096. This single matrix, learned entirely from data during pre-training, is responsible for encoding the semantic relationships between all tokens in the vocabulary.

    The number of parameters in the embedding matrix alone is V×d|V| \times d. For GPT-4’s approximate configuration, that is 100,277×dmodel100{,}277 \times d_{\text{model}} which is often hundreds of millions of parameters just for this one component.

    Why Dense Vectors Work: The Geometry of Meaning

    The remarkable property of learned embeddings is that semantic relationships emerge as geometric relationships in Rd\mathbb{R}^d. The classic demonstration is the linear analogy:

    e(“king”)e(“man”)+e(“woman”)e(“queen”)\mathbf{e}(\text{“king”}) – \mathbf{e}(\text{“man”}) + \mathbf{e}(\text{“woman”}) \approx \mathbf{e}(\text{“queen”})

    This is not programmed. It emerges from the statistical structure of co-occurrence patterns in the training corpus. Words that appear in similar contexts end up with similar embedding vectors, measured by cosine similarity:sim(u,v)=uvuv\text{sim}(\mathbf{u}, \mathbf{v}) = \frac{\mathbf{u} \cdot \mathbf{v}}{\|\mathbf{u}\| \|\mathbf{v}\|}In high-dimensional spaces, this geometry becomes extraordinarily rich. Directions in embedding space can encode syntactic roles, semantic fields, sentiment polarities, and factual associations — all simultaneously, in different orthogonal subspaces of the same Rd\mathbb{R}^d.

    Stage 3: Positional Encoding

    Token embeddings encode what each token is, but they contain no information about where in the sequence each token appears. The sequence "dog bites man" and "man bites dog" would produce identical sets of token embeddings in a different order and would be catastrophic for a model that needs to understand syntax and word order.

    Positional information must therefore be injected explicitly.

    Sinusoidal Positional Encoding (Original Transformer)

    The original transformer paper (Vaswani et al., 2017) proposed adding a fixed sinusoidal signal to each token embedding. For position pospospos and dimension iii:PE(pos,2i)=sin ⁣(pos100002i/d)PE_{(pos, 2i)} = \sin\!\left(\frac{pos}{10000^{2i/d}}\right) PE(pos,2i+1)=cos ⁣(pos100002i/d)PE_{(pos, 2i+1)} = \cos\!\left(\frac{pos}{10000^{2i/d}}\right)

    The input to the first transformer layer is then:xi=ei+PEi\mathbf{x}_i = \mathbf{e}_i + PE_i

    The sinusoidal formulation has a useful property: the positional encoding of position pos+kpos + k can be expressed as a linear function of the encoding at pospospos, which makes it easy for attention heads to learn to attend to tokens at a fixed relative offset.

    Learned Positional Embeddings

    GPT-2 and GPT-3 replaced sinusoidal encodings with learned positional embeddings: a second matrix WPRnmax×dW_P \in \mathbb{R}^{n_{\text{max}} \times d}​, where nmaxn_{\text{max}}​ is the maximum context length. Position pospospos adds the row WP[pos]W_P[pos] to the token embedding. These are learned end-to-end during pre-training and tend to slightly outperform sinusoidal encodings on benchmarks, at the cost of a hard context length ceiling — the model cannot generalise beyond nmaxn_{\text{max}}​ positions it has seen during training.

    Rotary Positional Embedding (RoPE)

    The current state of the art for most frontier models, including Llama, Mistral, GPT-4, and Gemini, is Rotary Positional Embedding (RoPE), introduced by Su et al. in 2021.

    Rather than adding a positional vector to the token embedding, RoPE encodes position by rotating the Query and Key vectors in the attention mechanism (covered in Part 2) by a position-dependent angle. For a vector at position mmm in dimension pair (2i,2i+1)(2i, 2i+1):qm(i)=(q2iq2i+1)(cosmθisinmθisinmθicosmθi)\mathbf{q}_m^{(i)} = \begin{pmatrix} q_{2i} \\ q_{2i+1} \end{pmatrix} \begin{pmatrix} \cos m\theta_i & -\sin m\theta_i \\ \sin m\theta_i & \cos m\theta_i \end{pmatrix}

    where θi=100002i/d\theta_i = 10000^{-2i/d}.

    The critical advantage: the dot product between a query at position mmm and a key at position nnn depends only on their relative offset mnm – n, not their absolute positions. This gives the model a natural inductive bias toward relative position awareness, and with extensions like YaRN makes it possible to extend the effective context window well beyond what the model was trained on.

    RoPE is why modern models can be fine-tuned to handle 128K or even 1M token context windows without retraining the entire model from scratch.

    Putting It Together: The Input Representation

    The final input to the first transformer layer for a sequence of nnn tokens is a matrix XRn×dX \in \mathbb{R}^{n \times d}:X=(e1+p1e2+p2en+pn)X = \begin{pmatrix} \mathbf{e}_1 + \mathbf{p}_1 \\ \mathbf{e}_2 + \mathbf{p}_2 \\ \vdots \\ \mathbf{e}_n + \mathbf{p}_n \end{pmatrix}where pi\mathbf{p}_i is the positional encoding for position ii (sinusoidal, learned, or RoPE-derived). Each row of XX is a dd-dimensional vector carrying both the semantic identity of the token and its position in the sequence. This matrix is what flows into the self-attention mechanism, which is the subject of Part 2.


    Key Numbers to Anchor Your Intuition

    ModelVocabulary V\|V\|dmodeld_{\text{model}}Positional scheme
    GPT-250,257768–1,600Learned
    GPT-350,25712,288Learned
    Llama 3 8B128,2564,096RoPE
    Mistral 7B32,0004,096RoPE
    Gemma 2256,0002,304–3,584RoPE

    Conclusion

    Before a single attention head fires, a large language model has already done substantial mathematical work. A raw string has been segmented into subword tokens by a BPE or SentencePiece algorithm, each token has been projected into a high-dimensional vector space where geometry encodes meaning, and position information has been woven in either additively or, in modern models, rotationally via RoPE. The quality of this input representation has an outsized effect on everything downstream: models with poorly constructed vocabularies or weak embedding initialisations are harder to train and less capable at convergence.

    Part 2 will take this matrix XRn×dX \in \mathbb{R}^{n \times d} and walk through exactly what the self-attention mechanism does with it, including the full mathematical derivation of scaled dot-product attention, multi-head attention, and what different heads actually learn to represent.

    Coming next in the AI Engineering series is Part 2: The Attention Mechanism.

  • AI Foundations

    A History of Artificial Intelligence — Part 3: From Transformers to ChatGPT — and What It Means for the Strong AI Debate

    This is the final part of a three-part series on the history of AI. Part 1 covered AI’s philosophical origins and the Turing Test, Strong AI vs. Weak AI, and Searle’s Chinese Room argument. Part 2 traced the rise of machine learning and deep learning through the founding of OpenAI in 2015. Part 3 picks up the story with the breakthrough that made ChatGPT possible.

    The Paper That Changed Everything

    By 2017, deep learning had already transformed computer vision and game-playing AI, as Part 2 described. But language remained stubbornly difficult. Earlier neural network architectures processed text sequentially, word by word, which made them slow to train and bad at capturing relationships between distant words in a sentence.

    In June 2017, a team of researchers from Google Brain and Google Research published “Attention Is All You Need,” introducing the Transformer architecture. The paper demonstrated that an architecture using only attention mechanisms, with no recurrence or convolutions at all, could outperform existing approaches on machine translation while training significantly faster.

    The key innovation was self-attention. Self-attention allows each word, or token, in a sequence to attend to every other token in that same sequence, enabling efficient parallelization and much better modeling of long-range relationships between words. Because the architecture could process entire sequences of text at once rather than one word at a time, it enabled the training of dramatically larger and more sophisticated models than had previously been practical.

    Few people, including the paper’s own authors, anticipated just how far-reaching this idea would become. Within a few years, researchers had adapted the Transformer architecture to tasks far beyond language translation, including image classification, image generation, and even protein folding.

    GPT-1 to GPT-3: Teaching Machines to Predict the Next Word

    The original 2017 Transformer had two halves: an encoder for reading text and a decoder for generating it. OpenAI was the first to apply generative pre-training specifically to the decoder half of this architecture, introducing the GPT-1 model in 2018. While other researchers, such as the team behind Google’s BERT, pursued clever training objectives, OpenAI took a more deceptively simple path: training models to predict the next word in a sequence, an approach now called language modeling. GPT pioneered the idea of pre-training language models on vast amounts of unlabeled text before fine-tuning them on specific downstream tasks.

    The first GPT model had 117 million parameters and meaningfully advanced state-of-the-art results across many language tasks, but it was not GPT-2, with its 1.5 billion parameters, that began capturing genuine public attention. Each generation scaled up dramatically. GPT-2 followed in February 2019, and GPT-3 arrived in June 2020 with 175 billion parameters, demonstrating striking emergent capabilities that simply hadn’t been visible in smaller models. GPT-3 was the first model OpenAI commercialized broadly, through a private beta of the OpenAI API in June 2020. Meaning that for the first time, developers anywhere could build applications on top of a frontier language model without training one themselves.

    But GPT-3, for all its scale, had a problem: it was powerful but not particularly easy to work with. Interacting with raw GPT-3 could be hit-or-miss; the model sometimes gave irrelevant answers or followed instructions only loosely. It was capable, but not especially helpful or safe by default.

    Teaching the Model to Listen: RLHF and InstructGPT

    The solution OpenAI developed would prove just as important as the scaling breakthroughs that preceded it: Reinforcement Learning from Human Feedback, or RLHF. The technique worked in stages: human AI trainers had conversations with the model and provided examples of good responses; the model then generated multiple possible answers to the same questions; human reviewers ranked these answers from best to worst; and the model learned to produce responses more like the highly ranked ones. arxiv

    This fine-tuning stage, layered on top of GPT-3’s existing pre-training, became known as reinforcement learning with human feedback. OpenAI released the resulting model, InstructGPT, in early 2022, and the results were striking: human evaluators preferred InstructGPT’s outputs over raw GPT-3’s outputs 85% of the time, even though InstructGPT used far fewer parameters. That finding reframed the entire scaling debate: a smaller, better-aligned model could outperform a larger, unaligned one on the metrics that actually mattered to users.

    RLHF didn’t just make models safer; it made them more useful in practical settings, because their responses became more predictable, more direct, and less prone to drifting into irrelevant territory.

    November 30, 2022: ChatGPT Arrives

    This period of refinement directly produced ChatGPT, which applied RLHF to a GPT-3.5 base model and packaged it inside a simple, conversational interface. OpenAI released ChatGPT on November 30, 2022, as a free research preview.

    The public response was immediate and unprecedented. Within five days of launch, ChatGPT reached one million users, and an estimated 100 million monthly users within roughly two months, making it the fastest-adopted consumer product in history at that time.

    What made ChatGPT spread so quickly wasn’t necessarily a leap in raw capability over what came before. The technical capabilities of InstructGPT and ChatGPT were almost identical — the primary changes OpenAI made were adding conversational training data and further tuning the training process. What changed was accessibility: for the first time, a frontier AI model was wrapped in an interface anyone could use, for free, with no technical knowledge required. The gap between “powerful research model” and “tool my grandmother can use” had finally closed.

    From there, the pace of iteration accelerated further. GPT-4 arrived in March 2023 with image input and substantially stronger reasoning, followed by GPT-4 Turbo, then GPT-4o in May 2024, which combined text, audio, and image processing into a single model. A parallel “reasoning” lineage (the o-series, beginning with o1 in 2024) introduced models trained to work through an internal chain of thought before answering, particularly strengthening performance on math, coding, and science tasks. ChatGPT itself evolved from a simple chat box into a far broader platform capable of browsing, file analysis, and increasingly autonomous task execution.

    Returning to the Question We Started With

    This brings us back to where Part 1 began: Turing’s question of whether machines can think, and Searle’s challenge to the idea that they ever truly could.

    Modern language models like ChatGPT are, at their technical core, exactly the kind of system Searle’s Chinese Room argument was built to describe: a process that manipulates symbols or tokens according to learned statistical patterns, without any claimed inner experience of meaning. Searle’s argument was never meant to deny that such a machine could produce remarkably intelligent-seeming behavior; it was aimed specifically at the philosophical claim that symbol manipulation alone is sufficient to produce genuine understanding. By that standard, today’s most advanced chatbots remain, in the strictest philosophical sense, firmly in weak AI territory. They are extraordinarily capable simulators of conversation, whatever may or may not be happening “underneath.”

    Even ChatGPT itself is best understood as an advanced form of narrow AI, rather than a step toward the kind of general intelligence imagined at Dartmouth in 1956. It cannot reason about domains outside its training in the way a human professional moves fluidly between unrelated fields of expertise. It does not possess goals, desires, or self-awareness in any sense most philosophers would recognize as minds typically do.

    And yet, six decades after Turing’s original 1950 paper, the Turing Test feels almost quaint. Millions of people now hold conversations daily with systems that, for stretches at a time, are functionally indistinguishable from a knowledgeable human correspondent. The technical bar Turing imagined has, in many everyday contexts, been cleared, even as the philosophical question he set out to sidestep remains as unresolved as ever.

    What today’s AI does prove, decisively, is something Turing himself anticipated: that behavior, not metaphysics, is what changes the world. Whether or not ChatGPT “understands” anything in Searle’s sense, it has already reshaped how hundreds of millions of people write, code, research, and learn. The history traced across these three articles, from Turing’s question, through symbolic AI and its winters, through the rise of neural networks and deep learning, to the Transformer and RLHF, is ultimately the story of a field that kept building useful tools, even while the deepest question that started it all remains open.

    how an llm works 1

    Here’s the full end-to-end LLM pipeline in one diagram. It walks through five stages:

    ① Tokenization — raw text is split into token IDs (shown as pills with their vocabulary numbers).

    ② Embedding — each token ID is converted to a high-dimensional vector, plus a positional vector so the model knows word order.

    ③ Transformer layers — the heart of the model: self-attention (where each token “looks at” every other token, with amber lines showing attention weights from “sat”), a feed-forward network per token, and layer normalisation — repeated N times (96 layers in GPT-4).

    ④ Output projection — the final hidden state is mapped back across the entire vocabulary using a softmax to produce probabilities.

    ⑤ Sampling — a token is selected from the distribution (here “floor” wins at 42.1%), appended to the context, and the whole process repeats — shown by the dashed feedback arrow on the right.

    This concludes our three-part series on the history of artificial intelligence. Explore more in our AI Foundations category, including beginner-friendly guides to AI tools, prompt engineering, and AI productivity.