<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>AI Foundations on Brice's Blog</title><link>https://brice6.pages.dev/tags/ai-foundations/</link><description>Recent content in AI Foundations on Brice's Blog</description><image><title>Brice's Blog</title><url>https://brice6.pages.dev/images/avatar-320.webp</url><link>https://brice6.pages.dev/images/avatar-320.webp</link></image><generator>Hugo -- 0.161.1</generator><language>en</language><lastBuildDate>Thu, 26 Nov 2026 18:50:06 +1300</lastBuildDate><atom:link href="https://brice6.pages.dev/tags/ai-foundations/index.xml" rel="self" type="application/rss+xml"/><item><title>Classical AI, Systematically: Logic, Knowledge Representation, Soft Computing, and Learning Systems</title><link>https://brice6.pages.dev/posts/mai/compsci-713/midterm-summary/</link><pubDate>Tue, 28 Apr 2026 00:00:00 +0000</pubDate><guid>https://brice6.pages.dev/posts/mai/compsci-713/midterm-summary/</guid><description>A systematic overview of classical AI: knowledge representation, symbolic logic, expert systems, decision trees, ensembles, soft computing, LNNs, and NEAT — and how they connect.</description><content:encoded><![CDATA[<p>This overview is organized around one central question:</p>
<blockquote>
<p>How do AI systems represent knowledge, reason with it, and still make useful decisions when the world is uncertain, vague, noisy, or too complex for hand-written rules?</p>
</blockquote>
<p>The material moves from symbolic knowledge and rule-based reasoning to statistical and learning-based systems. The important part is not remembering definitions, but understanding what each method represents, how it performs inference, when it works well, and where it fails.</p>
<p><img alt="Overview: MYCIN, decision trees, and ensembles" loading="lazy" src="/images/compsci713-midterm/01-mycin-decision-trees-ensembles-overview.webp"></p>
<h2 id="1-knowledge-representation">1. Knowledge Representation</h2>
<p>Knowledge Representation, or KR, is the foundation of everything that follows. Its purpose is to turn raw information into a structure that an AI system can store, query, update, and reason over.</p>
<p>A good representation should balance five requirements:</p>
<ul>
<li><strong>Expressiveness</strong>: can it represent the knowledge needed by the domain?</li>
<li><strong>Computational efficiency</strong>: can inference be done at a practical cost?</li>
<li><strong>Scalability</strong>: does it still work as the knowledge base grows?</li>
<li><strong>Interpretability</strong>: can humans understand why the system made a decision?</li>
<li><strong>Modifiability</strong>: can the system be updated when the world changes?</li>
</ul>
<p>The main KR methods include symbolic logic, semantic networks, frames, rule-based systems, expert systems, and knowledge graphs. Structured knowledge, such as tables, ontologies, and RDF triples, is easier to query and reason over. Unstructured knowledge, such as text and images, usually needs NLP, deep learning, or retrieval-augmented generation before it can support reliable reasoning.</p>
<p><img alt="Knowledge representation cheat sheet" loading="lazy" src="/images/compsci713-midterm/16-knowledge-representation.webp"></p>
<h2 id="2-symbolic-logic">2. Symbolic Logic</h2>
<p>Symbolic logic gives AI systems a formal language for representing claims and checking whether conclusions follow from premises.</p>
<p>In propositional logic, the basic unit is an atomic proposition with a truth value. Common connectives include negation, conjunction, disjunction, implication, and biconditional. The highest-yield rule is implication:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>P</mi><mo>→</mo><mi>Q</mi></mrow><annotation encoding="application/x-tex">
P \to Q
</annotation></semantics></math></span><p>This implication is false only when <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi></mrow><annotation encoding="application/x-tex">P</annotation></semantics></math></span> is true and <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>Q</mi></mrow><annotation encoding="application/x-tex">Q</annotation></semantics></math></span> is false. It does <strong>not</strong> allow us to infer <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi></mrow><annotation encoding="application/x-tex">P</annotation></semantics></math></span> from <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>Q</mi></mrow><annotation encoding="application/x-tex">Q</annotation></semantics></math></span>. That mistake is the fallacy of affirming the consequent.</p>
<p>Core valid inference rules:</p>
<ul>
<li><strong>Modus Ponens</strong>: from <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi></mrow><annotation encoding="application/x-tex">P</annotation></semantics></math></span> and <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo>→</mo><mi>Q</mi></mrow><annotation encoding="application/x-tex">P \to Q</annotation></semantics></math></span>, infer <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>Q</mi></mrow><annotation encoding="application/x-tex">Q</annotation></semantics></math></span>.</li>
<li><strong>Modus Tollens</strong>: from <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="normal">¬</mi><mi>Q</mi></mrow><annotation encoding="application/x-tex">\neg Q</annotation></semantics></math></span> and <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo>→</mo><mi>Q</mi></mrow><annotation encoding="application/x-tex">P \to Q</annotation></semantics></math></span>, infer <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="normal">¬</mi><mi>P</mi></mrow><annotation encoding="application/x-tex">\neg P</annotation></semantics></math></span>.</li>
<li><strong>Hypothetical Syllogism</strong>: from <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo>→</mo><mi>Q</mi></mrow><annotation encoding="application/x-tex">P \to Q</annotation></semantics></math></span> and <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>Q</mi><mo>→</mo><mi>R</mi></mrow><annotation encoding="application/x-tex">Q \to R</annotation></semantics></math></span>, infer <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo>→</mo><mi>R</mi></mrow><annotation encoding="application/x-tex">P \to R</annotation></semantics></math></span>.</li>
</ul>
<p><img alt="Symbolic logic: propositional logic core" loading="lazy" src="/images/compsci713-midterm/06-symbolic-logic-propositional-core.webp"></p>
<p>First-Order Logic extends propositional logic with objects, predicates, functions, variables, and quantifiers. It is more expressive because it can describe relationships among objects rather than only isolated true-or-false statements.</p>
<p>Common pitfalls:</p>
<ul>
<li>Do not reverse implications.</li>
<li>Check whether variables are free or bound.</li>
<li>Quantify only what the question states.</li>
<li>Distinguish terms, formulas, and sentences.</li>
<li>Remember that predicates return truth values, while functions return objects.</li>
</ul>
<p><img alt="First-order logic and semantics" loading="lazy" src="/images/compsci713-midterm/09-symbolic-logic-fol-semantics.webp"></p>
<h2 id="3-wumpus-world">3. Wumpus World</h2>
<p>Wumpus World is a compact example of logical reasoning from observations. The agent receives local percepts, such as breeze or stench, and uses rules to infer which squares may contain pits, the Wumpus, or safe moves.</p>
<p>The key idea is:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>World knowledge</mtext><mo>+</mo><mtext>observations</mtext><mo>⇒</mo><mtext>inferred safety or danger</mtext></mrow><annotation encoding="application/x-tex">
\text{World knowledge} + \text{observations} \Rightarrow \text{inferred safety or danger}
</annotation></semantics></math></span><p>For example, a breeze at a square means at least one neighboring square has a pit. It does not identify exactly which one. No breeze is stronger evidence: it means none of the neighboring squares has a pit.</p>
<p>This distinction is easy to get wrong. &quot;At least one&quot;, &quot;none&quot;, and &quot;exactly one&quot; are logically different claims.</p>
<p><img alt="Wumpus World and logical reasoning" loading="lazy" src="/images/compsci713-midterm/10-symbolic-logic-wumpus-world.webp"></p>
<h2 id="4-mycin-and-expert-systems">4. MYCIN and Expert Systems</h2>
<p>MYCIN is an early rule-based expert system for bacterial infection diagnosis and treatment support. It is important because it shows the structure of a classical symbolic AI system:</p>
<ul>
<li>a <strong>knowledge base</strong> containing long-term rules and facts</li>
<li>a <strong>working memory</strong> containing case-specific data</li>
<li>an <strong>inference engine</strong> that applies rules</li>
<li>a <strong>rule acquisition system</strong> for editing expert knowledge</li>
<li>an <strong>explanation system</strong> that answers WHY and HOW questions</li>
</ul>
<p>MYCIN used production rules of the form:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">IF premise
</span></span><span class="line"><span class="cl">THEN conclusion
</span></span></code></pre></div><p>It also used confidence factors to handle uncertain evidence:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>CF</mtext><mo stretchy="false">(</mo><mtext>conclusion</mtext><mo stretchy="false">)</mo><mo>=</mo><mtext>CF</mtext><mo stretchy="false">(</mo><mtext>premise</mtext><mo stretchy="false">)</mo><mo>×</mo><mtext>CF</mtext><mo stretchy="false">(</mo><mtext>rule</mtext><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">
\text{CF}(\text{conclusion}) = \text{CF}(\text{premise}) \times \text{CF}(\text{rule})
</annotation></semantics></math></span><p>For AND premises:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>CF</mtext><mo stretchy="false">(</mo><mi>A</mi><mo>∧</mo><mi>B</mi><mo>∧</mo><mi>C</mi><mo stretchy="false">)</mo><mo>=</mo><mi>min</mi><mo>⁡</mo><mo stretchy="false">(</mo><mtext>CF</mtext><mo stretchy="false">(</mo><mi>A</mi><mo stretchy="false">)</mo><mo separator="true">,</mo><mtext>CF</mtext><mo stretchy="false">(</mo><mi>B</mi><mo stretchy="false">)</mo><mo separator="true">,</mo><mtext>CF</mtext><mo stretchy="false">(</mo><mi>C</mi><mo stretchy="false">)</mo><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">
\text{CF}(A \land B \land C) = \min(\text{CF}(A), \text{CF}(B), \text{CF}(C))
</annotation></semantics></math></span><p>The WHY/HOW distinction matters:</p>
<ul>
<li><strong>WHY</strong> explains why the system is asking a question.</li>
<li><strong>HOW</strong> explains how the system reached a conclusion.</li>
</ul>
<p>MYCIN mattered because it separated knowledge from inference and made explanations part of the system. Its limits were also clear: knowledge acquisition was expensive, rules were hard to maintain, medical knowledge changed quickly, and deployment raised legal and ethical concerns.</p>
<p><img alt="MYCIN and expert systems" loading="lazy" src="/images/compsci713-midterm/14-mycin-expert-systems.webp"></p>
<h2 id="5-decision-trees">5. Decision Trees</h2>
<p>Decision trees are interpretable, non-parametric supervised learning models. They recursively split data using feature tests until each leaf can make a prediction.</p>
<p>For classification trees, a leaf usually predicts the majority class. For regression trees, a leaf predicts the mean target value. Each root-to-leaf path can be rewritten as an IF-THEN rule, which connects decision trees back to symbolic rule-based systems.</p>
<p>The learning process is usually greedy:</p>
<ol>
<li>Choose the best feature or threshold to split on.</li>
<li>Split the data into subsets.</li>
<li>Repeat recursively on each subset.</li>
<li>Stop when the data is pure, no features remain, or a stopping rule is met.</li>
</ol>
<p>The key point is that accuracy alone is not a good split criterion. A split may not improve immediate accuracy but may reduce uncertainty and make later splits better. That is why impurity measures are used.</p>
<p>Entropy:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>H</mi><mo stretchy="false">(</mo><mi>X</mi><mo stretchy="false">)</mo><mo>=</mo><mo>−</mo><munder><mo>∑</mo><mi>x</mi></munder><mi>p</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><msub><mrow><mi>log</mi><mo>⁡</mo></mrow><mn>2</mn></msub><mi>p</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">
H(X) = -\sum_x p(x)\log_2 p(x)
</annotation></semantics></math></span><p>Information gain:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>IG</mtext><mo stretchy="false">(</mo><mi>Y</mi><mo>∣</mo><mi>X</mi><mo stretchy="false">)</mo><mo>=</mo><mi>H</mi><mo stretchy="false">(</mo><mi>Y</mi><mo stretchy="false">)</mo><mo>−</mo><mi>H</mi><mo stretchy="false">(</mo><mi>Y</mi><mo>∣</mo><mi>X</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">
\text{IG}(Y \mid X) = H(Y) - H(Y \mid X)
</annotation></semantics></math></span><p>Gini impurity:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>Gini</mtext><mo stretchy="false">(</mo><mi>D</mi><mo stretchy="false">)</mo><mo>=</mo><mn>1</mn><mo>−</mo><munder><mo>∑</mo><mi>i</mi></munder><msubsup><mi>p</mi><mi>i</mi><mn>2</mn></msubsup></mrow><annotation encoding="application/x-tex">
\text{Gini}(D) = 1 - \sum_i p_i^2
</annotation></semantics></math></span><p>ID3 uses information gain, C4.5 extends ID3 to continuous features and uses gain ratio, and CART uses binary trees with Gini for classification or squared error for regression.</p>
<p><img alt="Decision tree foundations" loading="lazy" src="/images/compsci713-midterm/12-decision-trees-foundations.webp"></p>
<h2 id="6-ensembles-bagging-random-forests-and-boosting">6. Ensembles: Bagging, Random Forests, and Boosting</h2>
<p>Ensemble learning combines multiple predictors. The motivation is simple: many imperfect models can be more reliable than one unstable model.</p>
<p>Bagging trains models independently on bootstrap samples and aggregates predictions by voting or averaging. It mainly reduces variance. Random forests extend bagging by choosing only a random subset of features at each split, which decorrelates trees and improves averaging.</p>
<p>Boosting is sequential. Each new learner focuses more on the mistakes of previous learners. This often reduces bias and improves the final model step by step.</p>
<p>AdaBoost trains weak learners, reweights misclassified samples, and combines learners with weighted votes. Gradient boosting fits residuals or gradients of the loss function. XGBoost is an efficient, regularized implementation of gradient-boosted trees with shrinkage, column sampling, and scalable training.</p>
<p>High-yield comparison:</p>
<table>
  <thead>
      <tr>
          <th>Method</th>
          <th>Training Style</th>
          <th>Main Effect</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>Bagging</td>
          <td>Independent models on bootstrap samples</td>
          <td>Reduces variance</td>
      </tr>
      <tr>
          <td>Random forest</td>
          <td>Bagging plus random feature subsets</td>
          <td>Reduces correlation and variance</td>
      </tr>
      <tr>
          <td>AdaBoost</td>
          <td>Sequential reweighting of errors</td>
          <td>Reduces bias and focuses on hard cases</td>
      </tr>
      <tr>
          <td>Gradient boosting / XGBoost</td>
          <td>Sequential fitting of residuals or gradients</td>
          <td>Optimizes loss with regularization</td>
      </tr>
  </tbody>
</table>
<p><img alt="Ensembles, bagging, random forests, and boosting" loading="lazy" src="/images/compsci713-midterm/18-ensembles-bagging-boosting.webp"></p>
<h2 id="7-soft-computing">7. Soft Computing</h2>
<p>Soft computing is a family of methods that tolerate uncertainty, partial truth, inaccuracy, and approximation. The goal is not weak computation. The goal is robust decision-making in messy real-world settings.</p>
<p>Hard computing asks for exact truth. Soft computing asks for useful, stable, interpretable decisions when exact truth is unavailable or too brittle.</p>
<p>The most important distinction is:</p>
<ul>
<li><strong>Uncertainty</strong>: we do not know which state of the world is true.</li>
<li><strong>Vagueness</strong>: the concept itself has blurry boundaries.</li>
</ul>
<p>Probability asks: <strong>How likely is it?</strong></p>
<p>Fuzzy logic asks: <strong>To what degree is it true?</strong></p>
<p><img alt="Soft computing foundations and fuzzy logic" loading="lazy" src="/images/compsci713-midterm/15-soft-computing-foundations.webp"></p>
<h2 id="8-fuzzy-logic-and-bayesian-reasoning">8. Fuzzy Logic and Bayesian Reasoning</h2>
<p>Fuzzy logic maps truth values to the interval <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">[</mo><mn>0</mn><mo separator="true">,</mo><mn>1</mn><mo stretchy="false">]</mo></mrow><annotation encoding="application/x-tex">[0,1]</annotation></semantics></math></span>. A membership function measures how strongly an object belongs to a fuzzy set:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>μ</mi><mi>A</mi></msub><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>∈</mo><mo stretchy="false">[</mo><mn>0</mn><mo separator="true">,</mo><mn>1</mn><mo stretchy="false">]</mo></mrow><annotation encoding="application/x-tex">
\mu_A(x) \in [0,1]
</annotation></semantics></math></span><p>For example, <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>μ</mi><mtext>Tall</mtext></msub><mo stretchy="false">(</mo><mn>183</mn><mtext> </mtext><mtext>cm</mtext><mo stretchy="false">)</mo><mo>=</mo><mn>0.6</mn></mrow><annotation encoding="application/x-tex">\mu_{\text{Tall}}(183\,\text{cm}) = 0.6</annotation></semantics></math></span> does not mean a 60 percent chance of being tall. It means degree 0.6 membership in the concept Tall.</p>
<p>Common fuzzy operators:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi mathvariant="normal">¬</mi><mi>A</mi><mo>=</mo><mn>1</mn><mo>−</mo><mi>A</mi></mrow><annotation encoding="application/x-tex">
\neg A = 1 - A
</annotation></semantics></math></span><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>A</mi><mo>∧</mo><mi>B</mi><mo>=</mo><mi>min</mi><mo>⁡</mo><mo stretchy="false">(</mo><mi>A</mi><mo separator="true">,</mo><mi>B</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">
A \land B = \min(A, B)
</annotation></semantics></math></span><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>A</mi><mo>∨</mo><mi>B</mi><mo>=</mo><mi>max</mi><mo>⁡</mo><mo stretchy="false">(</mo><mi>A</mi><mo separator="true">,</mo><mi>B</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">
A \lor B = \max(A, B)
</annotation></semantics></math></span><p>Bayesian reasoning updates belief after observing evidence:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mi>H</mi><mi mathvariant="normal">∣</mi><mi>e</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mrow><mi>P</mi><mo stretchy="false">(</mo><mi>e</mi><mi mathvariant="normal">∣</mi><mi>H</mi><mo stretchy="false">)</mo><mi>P</mi><mo stretchy="false">(</mo><mi>H</mi><mo stretchy="false">)</mo></mrow><mrow><mi>P</mi><mo stretchy="false">(</mo><mi>e</mi><mo stretchy="false">)</mo></mrow></mfrac></mrow><annotation encoding="application/x-tex">
P(H|e) = \frac{P(e|H)P(H)}{P(e)}
</annotation></semantics></math></span><p>Naive Bayes is a probabilistic classifier that assumes features are conditionally independent given the class:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mi>x</mi><mi mathvariant="normal">∣</mi><mi>C</mi><mo>=</mo><mi>c</mi><mo stretchy="false">)</mo><mo>≈</mo><munder><mo>∏</mo><mi>i</mi></munder><mi>P</mi><mo stretchy="false">(</mo><msub><mi>x</mi><mi>i</mi></msub><mi mathvariant="normal">∣</mi><mi>C</mi><mo>=</mo><mi>c</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">
P(x|C=c) \approx \prod_i P(x_i|C=c)
</annotation></semantics></math></span><p>The assumption is often not perfectly true, but the method is simple, fast, scalable, and frequently strong as a baseline.</p>
<p><img alt="Fuzzy inference, Bayesian reasoning, and Naive Bayes" loading="lazy" src="/images/compsci713-midterm/13-soft-computing-fuzzy-bayes.webp"></p>
<p><img alt="Soft computing: a reasoning guide" loading="lazy" src="/images/compsci713-midterm/11-soft-computing-exam-guide.webp"></p>
<h2 id="9-logic-neural-networks">9. Logic Neural Networks</h2>
<p>Logic Neural Networks, or LNNs, combine neural learning with logical reasoning. Neural networks are strong at pattern recognition but weak at consistency and explainability. Symbolic logic is interpretable and precise but brittle under noise and hard to scale manually. LNNs try to blend these strengths.</p>
<p>The main idea is to convert logical formulas into syntax-tree neural structures. Each logical neuron corresponds to a sub-formula or logical operator. Instead of assigning only one truth value, LNNs often reason with truth bounds:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mn>0</mn><mo>≤</mo><mi>L</mi><mo>≤</mo><mi>U</mi><mo>≤</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">
0 \le L \le U \le 1
</annotation></semantics></math></span><p>The workflow is:</p>
<ol>
<li>Initialize bounds for atomic facts.</li>
<li>Propagate upward through logical operators.</li>
<li>Propagate downward from parent formulas to child constraints.</li>
<li>Iterate until convergence.</li>
<li>Inspect target bounds and classify the result.</li>
</ol>
<p>Common classifications:</p>
<table>
  <thead>
      <tr>
          <th>Bound Condition</th>
          <th>Interpretation</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>L</mi><mo>≥</mo><mi>α</mi></mrow><annotation encoding="application/x-tex">L \ge \alpha</annotation></semantics></math></span></td>
          <td>Definitely true</td>
      </tr>
      <tr>
          <td><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>U</mi><mo>&lt;</mo><mi>α</mi></mrow><annotation encoding="application/x-tex">U &lt; \alpha</annotation></semantics></math></span></td>
          <td>Definitely false</td>
      </tr>
      <tr>
          <td><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>L</mi><mo>&lt;</mo><mi>α</mi><mo>&lt;</mo><mi>U</mi></mrow><annotation encoding="application/x-tex">L &lt; \alpha &lt; U</annotation></semantics></math></span></td>
          <td>Uncertain</td>
      </tr>
      <tr>
          <td><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>L</mi><mo>&gt;</mo><mi>U</mi></mrow><annotation encoding="application/x-tex">L &gt; U</annotation></semantics></math></span></td>
          <td>Contradiction</td>
      </tr>
  </tbody>
</table>
<p>The most important caution is to classify bounds first, then reason. Do not treat fuzzy truth or LNN bounds as ordinary probability.</p>
<p><img alt="Logic Neural Networks core concepts" loading="lazy" src="/images/compsci713-midterm/08-lnn-core-concepts.webp"></p>
<p><img alt="Logic Neural Networks question forms" loading="lazy" src="/images/compsci713-midterm/07-lnn-question-forms.webp"></p>
<p><img alt="Logic Neural Networks answer strategy" loading="lazy" src="/images/compsci713-midterm/05-lnn-answer-strategy.webp"></p>
<h2 id="10-neat">10. NEAT</h2>
<p>NEAT stands for NeuroEvolution of Augmenting Topologies. It is a genetic algorithm that evolves both neural network weights and neural network topology.</p>
<p>NEAT starts simple and adds complexity only when useful. This is a major design idea: instead of beginning with a large network, the algorithm begins with a minimal structure and gradually evolves nodes, connections, and recurrent links.</p>
<p>Key mechanisms:</p>
<ul>
<li><strong>Weight mutation</strong> changes connection weights.</li>
<li><strong>Add-connection mutation</strong> adds a new connection.</li>
<li><strong>Add-node mutation</strong> splits an existing connection by inserting a new node.</li>
<li><strong>Innovation numbers</strong> record the historical origin of genes.</li>
<li><strong>Crossover</strong> aligns genes by innovation number.</li>
<li><strong>Speciation</strong> protects new structures from being eliminated too early.</li>
<li><strong>Fitness sharing</strong> prevents large species from dominating the population.</li>
</ul>
<p>The compatibility distance is commonly written as:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>δ</mi><mo>=</mo><msub><mi>c</mi><mn>1</mn></msub><mfrac><mi>E</mi><mi>N</mi></mfrac><mo>+</mo><msub><mi>c</mi><mn>2</mn></msub><mfrac><mi>D</mi><mi>N</mi></mfrac><mo>+</mo><msub><mi>c</mi><mn>3</mn></msub><mi>W</mi></mrow><annotation encoding="application/x-tex">
\delta = c_1 \frac{E}{N} + c_2 \frac{D}{N} + c_3 W
</annotation></semantics></math></span><p>where <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>E</mi></mrow><annotation encoding="application/x-tex">E</annotation></semantics></math></span> is excess genes, <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>D</mi></mrow><annotation encoding="application/x-tex">D</annotation></semantics></math></span> is disjoint genes, <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>W</mi></mrow><annotation encoding="application/x-tex">W</annotation></semantics></math></span> is average weight difference of matching genes, and <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>N</mi></mrow><annotation encoding="application/x-tex">N</annotation></semantics></math></span> normalizes genome size.</p>
<p>The adjusted fitness is:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>Adjusted Fitness</mtext><mo>=</mo><mfrac><mtext>Individual Fitness</mtext><mtext>Species Size</mtext></mfrac></mrow><annotation encoding="application/x-tex">
\text{Adjusted Fitness} = \frac{\text{Individual Fitness}}{\text{Species Size}}
</annotation></semantics></math></span><p>NEAT's strength comes from combining evolutionary search, topology growth, historical markings, and protected innovation.</p>
<p><img alt="NEAT cheat sheet" loading="lazy" src="/images/compsci713-midterm/04-neat-cheatsheet.webp"></p>
<p><img alt="NEAT: key questions and answers" loading="lazy" src="/images/compsci713-midterm/03-neat-exam-answers.webp"></p>
<h2 id="11-a-reasoning-checklist">11. A Reasoning Checklist</h2>
<p>Most clear explanations follow a simple structure:</p>
<ol>
<li>Define the term clearly.</li>
<li>State the mechanism or formula.</li>
<li>Apply it to the given scenario.</li>
<li>Interpret the result in plain English.</li>
<li>Mention one strength, limitation, or assumption if relevant.</li>
</ol>
<p>When comparing methods, compare along stable dimensions: representation, inference method, strengths, weaknesses, and use cases.</p>
<p>When working through a calculation, write the formula first, substitute values carefully, compute step by step, and finish with a sentence explaining what the number means.</p>
<p>When applying a method to a real scenario, do not dump formulas. Name the method, explain why it fits the setting, state one caveat, and connect the answer back to the problem.</p>
<p><img alt="Scenarios and reasoning templates" loading="lazy" src="/images/compsci713-midterm/17-scenario-answer-templates.webp"></p>
<h2 id="12-how-it-all-connects">12. How It All Connects</h2>
<p>The topics connect naturally:</p>
<ul>
<li><strong>KR</strong> explains how knowledge is represented.</li>
<li><strong>Logic</strong> explains how conclusions follow from rules.</li>
<li><strong>MYCIN</strong> shows rule-based reasoning in a practical expert system.</li>
<li><strong>Decision trees</strong> learn rule-like structures from data.</li>
<li><strong>Ensembles</strong> improve unstable learners by combining many models.</li>
<li><strong>Soft computing</strong> handles uncertainty, vagueness, and approximation.</li>
<li><strong>LNNs</strong> combine neural learning with logical consistency.</li>
<li><strong>NEAT</strong> evolves both neural weights and neural structures.</li>
</ul>
<p>The habit that ties it together: define precisely, reason step by step, interpret formulas in words, and always state the assumptions behind a method.</p>
]]></content:encoded></item><item><title>Soft Computing Explained: Fuzzy Logic, Bayesian Methods, and Neural Networks</title><link>https://brice6.pages.dev/posts/mai/compsci-713/softcomputing/</link><pubDate>Mon, 30 Mar 2026 00:00:00 +0000</pubDate><guid>https://brice6.pages.dev/posts/mai/compsci-713/softcomputing/</guid><description>An introduction to soft computing, covering fuzzy logic, Bayesian reasoning, neural networks, and the shift away from rigid rule-based systems.</description><content:encoded><![CDATA[<h2 id="overview">Overview</h2>
<p>Classical symbolic AI works best when the world can be described using <strong>clean rules</strong>:</p>
<ul>
<li>inputs are well defined</li>
<li>categories are crisp</li>
<li>expert knowledge can be written explicitly</li>
</ul>
<p>Real systems are rarely that tidy. Sensor readings are noisy, labels are ambiguous, and many decision boundaries are not sharp. <strong>Soft computing</strong> is the family of methods designed for exactly this setting: instead of forcing rigid precision everywhere, it accepts approximation, uncertainty, and partial truth as part of the computation.</p>
<p>The goal is not to be &quot;less correct&quot;. The goal is to be <strong>robust when exact reasoning is either impossible or too expensive</strong>.</p>
<p>In practice, soft computing usually refers to four major ideas:</p>
<ol>
<li><strong>Fuzzy logic</strong> for reasoning with graded truth.</li>
<li><strong>Probabilistic / Bayesian methods</strong> for reasoning under uncertainty.</li>
<li><strong>Neural networks</strong> for learning patterns directly from data.</li>
<li><strong>Evolutionary algorithms</strong> for search in difficult, non-convex spaces.</li>
</ol>
<hr>
<h2 id="hard-vs-soft-computing">Hard vs. Soft Computing</h2>
<p>The difference is easiest to see through the kind of assumptions each approach makes.</p>
<table>
  <thead>
      <tr>
          <th>Aspect</th>
          <th>Hard Computing</th>
          <th>Soft Computing</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>Logic</td>
          <td>Exact, binary</td>
          <td>Approximate, graded</td>
      </tr>
      <tr>
          <td>Input assumptions</td>
          <td>Clean and precise</td>
          <td>Noisy and uncertain</td>
      </tr>
      <tr>
          <td>Knowledge source</td>
          <td>Hand-written rules</td>
          <td>Rules, data, or both</td>
      </tr>
      <tr>
          <td>Output</td>
          <td>Deterministic</td>
          <td>Probabilistic or approximate</td>
      </tr>
      <tr>
          <td>Typical strength</td>
          <td>Correctness under strict models</td>
          <td>Robustness in messy environments</td>
      </tr>
  </tbody>
</table>
<p>Hard computing asks:</p>
<blockquote>
<p>Is this statement true or false?</p>
</blockquote>
<p>Soft computing asks:</p>
<blockquote>
<p>How true is it, how uncertain is it, and what decision is best under that uncertainty?</p>
</blockquote>
<p>That shift matters in tasks such as speech recognition, forecasting, medical diagnosis, autonomous control, and recommendation systems.</p>
<hr>
<h2 id="why-soft-computing-matters">Why Soft Computing Matters</h2>
<p>There are three recurring reasons soft computing appears in AI:</p>
<h3 id="1-the-world-is-noisy">1. The world is noisy</h3>
<p>Measurements are imperfect. A temperature sensor can drift, a camera can be blurry, and a biological signal can be incomplete. Exact symbolic rules often break under that noise.</p>
<h3 id="2-human-concepts-are-vague">2. Human concepts are vague</h3>
<p>Words such as &quot;hot&quot;, &quot;safe&quot;, &quot;similar&quot;, and &quot;high risk&quot; do not have perfectly sharp boundaries. Human reasoning often works with gradual categories rather than strict thresholds.</p>
<h3 id="3-many-useful-functions-are-too-hard-to-write-manually">3. Many useful functions are too hard to write manually</h3>
<p>We may not know the correct rule set for image classification, protein folding, or market prediction. In those cases we prefer models that can <strong>learn approximations from data</strong>.</p>
<hr>
<h2 id="fuzzy-logic-truth-as-a-degree">Fuzzy Logic: Truth as a Degree</h2>
<p>In Boolean logic, a proposition is either <code>0</code> or <code>1</code>. In fuzzy logic, truth can take any value in <code>[0,1]</code>.</p>
<p>For example, instead of saying:</p>
<ul>
<li>temperature is hot = <code>true</code></li>
<li>temperature is hot = <code>false</code></li>
</ul>
<p>we can say:</p>
<ul>
<li>temperature is hot = <code>0.2</code></li>
<li>temperature is hot = <code>0.7</code></li>
<li>temperature is hot = <code>0.95</code></li>
</ul>
<p>This is expressed through a <strong>membership function</strong>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>μ</mi><mi>A</mi></msub><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>∈</mo><mo stretchy="false">[</mo><mn>0</mn><mo separator="true">,</mo><mn>1</mn><mo stretchy="false">]</mo></mrow><annotation encoding="application/x-tex">
\mu_A(x) \in [0,1]
</annotation></semantics></math></span><p>where <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>μ</mi><mi>A</mi></msub><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mu_A(x)</annotation></semantics></math></span> measures how strongly input <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi></mrow><annotation encoding="application/x-tex">x</annotation></semantics></math></span> belongs to fuzzy set <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>A</mi></mrow><annotation encoding="application/x-tex">A</annotation></semantics></math></span>.</p>
<h3 id="example">Example</h3>
<p>Let <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>A</mi></mrow><annotation encoding="application/x-tex">A</annotation></semantics></math></span> be the fuzzy set &quot;warm temperature&quot;. Then:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>μ</mi><mi>A</mi></msub><mo stretchy="false">(</mo><msup><mn>18</mn><mo>∘</mo></msup><mtext>C</mtext><mo stretchy="false">)</mo><mo>=</mo><mn>0.2</mn><mo separator="true">,</mo><mspace width="1em"/><msub><mi>μ</mi><mi>A</mi></msub><mo stretchy="false">(</mo><msup><mn>24</mn><mo>∘</mo></msup><mtext>C</mtext><mo stretchy="false">)</mo><mo>=</mo><mn>0.8</mn></mrow><annotation encoding="application/x-tex">
\mu_A(18^\circ\text{C})=0.2, \quad \mu_A(24^\circ\text{C})=0.8
</annotation></semantics></math></span><p>The important point is that fuzzy logic models <strong>vagueness</strong>, not randomness. It is about partial truth, not probability.</p>
<h3 id="fuzzy-rule-systems">Fuzzy Rule Systems</h3>
<p>A typical fuzzy controller has three stages:</p>
<ol>
<li><strong>Fuzzification</strong><br>
Convert crisp inputs into membership degrees.</li>
<li><strong>Rule evaluation</strong><br>
Apply expert rules such as:
<code>IF temperature is high AND humidity is medium THEN fan speed is fast</code></li>
<li><strong>Defuzzification</strong><br>
Convert the fuzzy output back into a usable numeric decision.</li>
</ol>
<p>This makes fuzzy systems attractive when domain experts can describe behavior qualitatively, but exact equations are hard to specify.</p>
<h3 id="strengths-and-limits">Strengths and Limits</h3>
<p>Strengths:</p>
<ul>
<li>interpretable rule base</li>
<li>handles vague linguistic concepts well</li>
<li>useful in control systems and decision support</li>
</ul>
<p>Limits:</p>
<ul>
<li>membership functions are often hand-designed</li>
<li>scaling to high-dimensional data is difficult</li>
<li>pure fuzzy systems do not learn rich representations by themselves</li>
</ul>
<hr>
<h2 id="bayesian-methods-uncertainty-as-probability">Bayesian Methods: Uncertainty as Probability</h2>
<p>If fuzzy logic handles <strong>vagueness</strong>, Bayesian methods handle <strong>uncertainty about the world</strong>.</p>
<p>The central equation is Bayes' theorem:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mi>H</mi><mo>∣</mo><mi>D</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mrow><mi>P</mi><mo stretchy="false">(</mo><mi>D</mi><mo>∣</mo><mi>H</mi><mo stretchy="false">)</mo><mi>P</mi><mo stretchy="false">(</mo><mi>H</mi><mo stretchy="false">)</mo></mrow><mrow><mi>P</mi><mo stretchy="false">(</mo><mi>D</mi><mo stretchy="false">)</mo></mrow></mfrac></mrow><annotation encoding="application/x-tex">
P(H \mid D) = \frac{P(D \mid H)P(H)}{P(D)}
</annotation></semantics></math></span><p>where:</p>
<ul>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>H</mi></mrow><annotation encoding="application/x-tex">H</annotation></semantics></math></span> is a hypothesis</li>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>D</mi></mrow><annotation encoding="application/x-tex">D</annotation></semantics></math></span> is observed data</li>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mi>H</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P(H)</annotation></semantics></math></span> is the prior belief</li>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mi>H</mi><mo>∣</mo><mi>D</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P(H \mid D)</annotation></semantics></math></span> is the updated belief after seeing data</li>
</ul>
<p>This provides a principled way to revise beliefs when new evidence arrives.</p>
<h3 id="example-1">Example</h3>
<p>Suppose a medical test is noisy. A positive result does not guarantee disease; it only changes the probability. Bayesian reasoning combines:</p>
<ul>
<li>prior prevalence</li>
<li>test reliability</li>
<li>observed evidence</li>
</ul>
<p>to produce a posterior belief.</p>
<h3 id="why-it-matters-in-ai">Why It Matters in AI</h3>
<p>Bayesian reasoning appears in:</p>
<ul>
<li>probabilistic graphical models</li>
<li>filtering and tracking</li>
<li>uncertainty-aware prediction</li>
<li>active learning</li>
<li>generative modeling</li>
</ul>
<p>In modern ML, Bayesian thinking also appears implicitly in regularization, variational inference, and uncertainty calibration.</p>
<h3 id="fuzzy-vs-bayesian">Fuzzy vs Bayesian</h3>
<p>These two are often confused, but they solve different problems:</p>
<table>
  <thead>
      <tr>
          <th>Question</th>
          <th>Fuzzy Logic</th>
          <th>Bayesian Methods</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>What does the number mean?</td>
          <td>Degree of truth</td>
          <td>Degree of belief</td>
      </tr>
      <tr>
          <td>Source of ambiguity</td>
          <td>Vagueness</td>
          <td>Uncertainty</td>
      </tr>
      <tr>
          <td>Example</td>
          <td>&quot;How hot is hot?&quot;</td>
          <td>&quot;How likely is rain?&quot;</td>
      </tr>
  </tbody>
</table>
<hr>
<h2 id="neural-networks-learning-the-mapping">Neural Networks: Learning the Mapping</h2>
<p>Neural networks represent another branch of soft computing. Instead of writing rules directly, we define a parameterized function and learn it from data.</p>
<p>For a simple layer:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>h</mi><mo>=</mo><mi>σ</mi><mo stretchy="false">(</mo><mi>W</mi><mi>x</mi><mo>+</mo><mi>b</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">
h = \sigma(Wx + b)
</annotation></semantics></math></span><p>and for supervised learning we optimize parameters by minimizing a loss:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msup><mi>θ</mi><mo>∗</mo></msup><mo>=</mo><mi>arg</mi><mo>⁡</mo><munder><mrow><mi>min</mi><mo>⁡</mo></mrow><mi>θ</mi></munder><mi mathvariant="script">L</mi><mo stretchy="false">(</mo><msub><mi>f</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo separator="true">,</mo><mi>y</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">
\theta^* = \arg\min_\theta \mathcal{L}(f_\theta(x), y)
</annotation></semantics></math></span><p>This framework is powerful because it can approximate highly complex nonlinear mappings.</p>
<h3 id="why-neural-networks-fit-soft-computing">Why Neural Networks Fit Soft Computing</h3>
<p>Neural networks:</p>
<ul>
<li>tolerate noisy inputs</li>
<li>learn approximate decision boundaries</li>
<li>generalize from examples rather than explicit rules</li>
<li>work well even when the true underlying mechanism is unknown</li>
</ul>
<p>They are therefore a natural soft-computing tool for perception problems such as:</p>
<ul>
<li>image recognition</li>
<li>speech processing</li>
<li>language modeling</li>
<li>biological sequence modeling</li>
</ul>
<h3 id="tradeoff">Tradeoff</h3>
<p>Compared with fuzzy systems, neural networks are usually:</p>
<ul>
<li>more scalable</li>
<li>better at representation learning</li>
<li>less interpretable</li>
</ul>
<p>That tradeoff explains why many hybrid systems try to combine both.</p>
<hr>
<h2 id="evolutionary-algorithms-search-without-gradients">Evolutionary Algorithms: Search Without Gradients</h2>
<p>Another major component of soft computing is <strong>evolutionary computation</strong>. Instead of optimizing parameters through gradients, it evolves a population of candidate solutions.</p>
<p>The basic loop is:</p>
<ol>
<li>initialize a population</li>
<li>evaluate fitness</li>
<li>select stronger candidates</li>
<li>mutate / recombine</li>
<li>repeat</li>
</ol>
<p>This is useful when:</p>
<ul>
<li>gradients are unavailable</li>
<li>the search space is discrete</li>
<li>the objective is noisy or multi-modal</li>
</ul>
<p>Examples include:</p>
<ul>
<li>architecture search</li>
<li>scheduling</li>
<li>rule optimization</li>
<li>control policy search</li>
</ul>
<p>Evolutionary methods are usually less sample-efficient than gradient-based deep learning, but they are more flexible in irregular optimization landscapes.</p>
<hr>
<h2 id="hybrid-systems">Hybrid Systems</h2>
<p>One of the most practical ideas in soft computing is that these methods can be <strong>combined</strong>.</p>
<p>Common combinations include:</p>
<ul>
<li><strong>Neuro-fuzzy systems</strong><br>
Neural networks learn parameters for fuzzy rules or membership functions.</li>
<li><strong>Bayesian neural networks</strong><br>
Neural models with uncertainty estimates on parameters or outputs.</li>
<li><strong>Evolutionary neural optimization</strong><br>
Evolutionary algorithms search over architectures or hyperparameters.</li>
</ul>
<p>This hybrid view is important because real systems often need several properties at once:</p>
<ul>
<li>adaptability</li>
<li>uncertainty handling</li>
<li>interpretability</li>
<li>robust search</li>
</ul>
<p>No single method gives all of them equally well.</p>
<hr>
<h2 id="soft-computing-in-modern-ai">Soft Computing in Modern AI</h2>
<p>Although the phrase &quot;soft computing&quot; is older than today's deep learning boom, the underlying philosophy remains highly relevant.</p>
<p>Modern AI systems still rely on soft-computing principles:</p>
<ul>
<li><strong>LLMs</strong> learn approximate distributions over language</li>
<li><strong>diffusion models</strong> model uncertainty through stochastic processes</li>
<li><strong>probabilistic classifiers</strong> express confidence rather than only labels</li>
<li><strong>reinforcement learning</strong> often deals with noisy, partial, and delayed feedback</li>
</ul>
<p>So even when the terminology changes, the core idea remains:</p>
<blockquote>
<p>useful intelligence often requires approximation, uncertainty management, and flexible optimization</p>
</blockquote>
<hr>
<h2 id="when-to-use-which-tool">When to Use Which Tool</h2>
<p>Use <strong>fuzzy logic</strong> when:</p>
<ul>
<li>expert knowledge is available</li>
<li>concepts are linguistic and vague</li>
<li>interpretability matters</li>
</ul>
<p>Use <strong>Bayesian methods</strong> when:</p>
<ul>
<li>uncertainty must be quantified</li>
<li>sequential evidence updates are important</li>
<li>decisions depend on calibrated belief</li>
</ul>
<p>Use <strong>neural networks</strong> when:</p>
<ul>
<li>large datasets are available</li>
<li>the mapping from input to output is complex</li>
<li>representation learning is essential</li>
</ul>
<p>Use <strong>evolutionary methods</strong> when:</p>
<ul>
<li>the search space is irregular</li>
<li>gradients are unavailable or unreliable</li>
<li>exploration matters more than local optimization</li>
</ul>
<hr>
<h2 id="final-intuition">Final Intuition</h2>
<p>Soft computing is best seen as a response to the limits of rigid symbolic reasoning.</p>
<p>It does not reject mathematics or structure. Instead, it expands the toolkit by admitting that many real-world problems involve:</p>
<ul>
<li>incomplete information</li>
<li>graded concepts</li>
<li>uncertain evidence</li>
<li>hard-to-model dynamics</li>
</ul>
<p>That is why soft computing still matters. It provides the conceptual bridge between classical AI, probabilistic reasoning, and modern machine learning.</p>
]]></content:encoded></item><item><title>Build GPT-2 from Scratch: Architecture, Tokenization, and Training</title><link>https://brice6.pages.dev/posts/mai/compsci-714/build_gpt2/</link><pubDate>Sat, 28 Mar 2026 00:00:00 +0000</pubDate><guid>https://brice6.pages.dev/posts/mai/compsci-714/build_gpt2/</guid><description>A step-by-step GPT-2 walkthrough covering BPE tokenization, transformer blocks, masked self-attention, and training.</description><content:encoded><![CDATA[<h2 id="architecture">Architecture</h2>
<p>GPT-2 is a <strong>decoder-only Transformer</strong> trained to predict the next token in a sequence.</p>
<p>Its high-level structure is:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>Tokens</mtext><mo>→</mo><mtext>Token Embedding</mtext><mo>+</mo><mtext>Position Embedding</mtext><mo>→</mo><mi>N</mi><mo>×</mo><mtext>Transformer Block</mtext><mo>→</mo><mtext>LayerNorm</mtext><mo>→</mo><mtext>Linear Head</mtext></mrow><annotation encoding="application/x-tex">
\text{Tokens} \rightarrow \text{Token Embedding} + \text{Position Embedding}
\rightarrow N \times \text{Transformer Block}
\rightarrow \text{LayerNorm}
\rightarrow \text{Linear Head}
</annotation></semantics></math></span><p>Each Transformer block contains:</p>
<ol>
<li>masked self-attention</li>
<li>a feed-forward MLP</li>
<li>residual connections</li>
<li>layer normalization</li>
</ol>
<p>If the hidden size is <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>d</mi><mtext>model</mtext></msub></mrow><annotation encoding="application/x-tex">d_{\text{model}}</annotation></semantics></math></span> and the sequence length is <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>T</mi></mrow><annotation encoding="application/x-tex">T</annotation></semantics></math></span>, then the hidden state has shape:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>X</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>T</mi><mo>×</mo><msub><mi>d</mi><mtext>model</mtext></msub></mrow></msup></mrow><annotation encoding="application/x-tex">
X \in \mathbb{R}^{T \times d_{\text{model}}}
</annotation></semantics></math></span><p>For GPT-2 small:</p>
<ul>
<li>number of layers: <code>12</code></li>
<li>number of heads: <code>12</code></li>
<li>hidden size: <code>768</code></li>
<li>context window: <code>1024</code></li>
</ul>
<p>The key design choice is causal generation: token <code>t</code> can only attend to tokens <code>1..t</code>, never to future tokens.</p>
<hr>
<h2 id="tokenization-and-raw-data">Tokenization and Raw Data</h2>
<p>Neural networks do not operate directly on strings. We first convert text into <strong>tokens</strong>, then map tokens to integer IDs, and finally map IDs to vectors.</p>
<p>The basic unit is not a word and not a single character. GPT-2 uses <strong>Byte Pair Encoding (BPE)</strong>, which merges frequent byte patterns into reusable subword units.</p>
<p>That gives a practical compromise:</p>
<ul>
<li>character-level tokens are too long</li>
<li>word-level vocabularies are too brittle</li>
<li>subword tokens balance compression and flexibility</li>
</ul>
<p>Using <code>tiktoken</code>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">uv add tiktoken
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">tiktoken</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">enc</span> <span class="o">=</span> <span class="n">tiktoken</span><span class="o">.</span><span class="n">get_encoding</span><span class="p">(</span><span class="s2">&#34;gpt2&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">ids</span> <span class="o">=</span> <span class="n">enc</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s2">&#34;Transformers model conditional distributions over tokens.&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="nb">print</span><span class="p">(</span><span class="n">ids</span><span class="p">)</span>
</span></span></code></pre></div><p>Once token IDs are produced, the embedding table converts them into vectors:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>E</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>V</mi><mo>×</mo><msub><mi>d</mi><mtext>model</mtext></msub></mrow></msup></mrow><annotation encoding="application/x-tex">
E \in \mathbb{R}^{V \times d_{\text{model}}}
</annotation></semantics></math></span><p>where <code>V</code> is the vocabulary size. Looking up a token ID <code>i</code> returns row <code>E_i</code>.</p>
<p>GPT-2 also adds a learned positional embedding so the model can distinguish the order of tokens.</p>
<hr>
<h2 id="language-modeling-objective">Language Modeling Objective</h2>
<p>GPT-2 is trained with the next-token prediction objective:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><msub><mi>x</mi><mn>1</mn></msub><mo separator="true">,</mo><msub><mi>x</mi><mn>2</mn></msub><mo separator="true">,</mo><mo>…</mo><mo separator="true">,</mo><msub><mi>x</mi><mi>T</mi></msub><mo stretchy="false">)</mo><mo>=</mo><munderover><mo>∏</mo><mrow><mi>t</mi><mo>=</mo><mn>1</mn></mrow><mi>T</mi></munderover><mi>P</mi><mo stretchy="false">(</mo><msub><mi>x</mi><mi>t</mi></msub><mo>∣</mo><msub><mi>x</mi><mrow><mo>&lt;</mo><mi>t</mi></mrow></msub><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">
P(x_1, x_2, \dots, x_T) = \prod_{t=1}^{T} P(x_t \mid x_{&lt;t})
</annotation></semantics></math></span><p>In words, the model learns a conditional probability distribution over the next token given the prefix.</p>
<p>Training minimizes cross-entropy:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi mathvariant="script">L</mi><mo>=</mo><mo>−</mo><munderover><mo>∑</mo><mrow><mi>t</mi><mo>=</mo><mn>1</mn></mrow><mi>T</mi></munderover><mi>log</mi><mo>⁡</mo><mi>P</mi><mo stretchy="false">(</mo><msub><mi>x</mi><mi>t</mi></msub><mo>∣</mo><msub><mi>x</mi><mrow><mo>&lt;</mo><mi>t</mi></mrow></msub><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">
\mathcal{L} = - \sum_{t=1}^{T} \log P(x_t \mid x_{&lt;t})
</annotation></semantics></math></span><p>This objective is simple, but it scales extremely well. The entire model is built around estimating that factorization efficiently.</p>
<hr>
<h2 id="masked-self-attention">Masked Self-Attention</h2>
<p>The central operation in GPT-2 is self-attention. From hidden states <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>X</mi></mrow><annotation encoding="application/x-tex">X</annotation></semantics></math></span>, we compute:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>Q</mi><mo>=</mo><mi>X</mi><msub><mi>W</mi><mi>Q</mi></msub><mo separator="true">,</mo><mspace width="1em"/><mi>K</mi><mo>=</mo><mi>X</mi><msub><mi>W</mi><mi>K</mi></msub><mo separator="true">,</mo><mspace width="1em"/><mi>V</mi><mo>=</mo><mi>X</mi><msub><mi>W</mi><mi>V</mi></msub></mrow><annotation encoding="application/x-tex">
Q = XW_Q,\quad K = XW_K,\quad V = XW_V
</annotation></semantics></math></span><p>Then attention is:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>Attention</mtext><mo stretchy="false">(</mo><mi>Q</mi><mo separator="true">,</mo><mi>K</mi><mo separator="true">,</mo><mi>V</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>softmax</mtext><mrow><mo fence="true">(</mo><mfrac><mrow><mi>Q</mi><msup><mi>K</mi><mi>T</mi></msup></mrow><msqrt><msub><mi>d</mi><mi>k</mi></msub></msqrt></mfrac><mo>+</mo><mi>M</mi><mo fence="true">)</mo></mrow><mi>V</mi></mrow><annotation encoding="application/x-tex">
\text{Attention}(Q,K,V) =
\text{softmax}\left(\frac{QK^T}{\sqrt{d_k}} + M\right)V
</annotation></semantics></math></span><p>where <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>M</mi></mrow><annotation encoding="application/x-tex">M</annotation></semantics></math></span> is the <strong>causal mask</strong>. Entries corresponding to future positions are set to <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo>−</mo><mi mathvariant="normal">∞</mi></mrow><annotation encoding="application/x-tex">-\infty</annotation></semantics></math></span> before the softmax.</p>
<p>This ensures:</p>
<ul>
<li>token 5 can attend to 1,2,3,4,5</li>
<li>token 5 cannot attend to 6,7,...</li>
</ul>
<p>In PyTorch, a minimal version looks like:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">math</span>
</span></span><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">torch</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">masked_attention</span><span class="p">(</span><span class="n">q</span><span class="p">,</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="n">T</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">size</span><span class="p">(</span><span class="o">-</span><span class="mi">2</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">scores</span> <span class="o">=</span> <span class="n">q</span> <span class="o">@</span> <span class="n">k</span><span class="o">.</span><span class="n">transpose</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">2</span><span class="p">)</span> <span class="o">/</span> <span class="n">math</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">q</span><span class="o">.</span><span class="n">size</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">    <span class="n">mask</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">triu</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">ones</span><span class="p">(</span><span class="n">T</span><span class="p">,</span> <span class="n">T</span><span class="p">,</span> <span class="n">device</span><span class="o">=</span><span class="n">q</span><span class="o">.</span><span class="n">device</span><span class="p">),</span> <span class="n">diagonal</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">bool</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">    <span class="n">scores</span> <span class="o">=</span> <span class="n">scores</span><span class="o">.</span><span class="n">masked_fill</span><span class="p">(</span><span class="n">mask</span><span class="p">,</span> <span class="nb">float</span><span class="p">(</span><span class="s2">&#34;-inf&#34;</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">    <span class="n">weights</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">softmax</span><span class="p">(</span><span class="n">scores</span><span class="p">,</span> <span class="n">dim</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">weights</span> <span class="o">@</span> <span class="n">v</span>
</span></span></code></pre></div><p>This is the mechanism that lets every token build a context-aware representation of the prefix.</p>
<hr>
<h2 id="multi-head-attention">Multi-Head Attention</h2>
<p>A single attention map is often too limited. GPT-2 uses <strong>multi-head attention</strong>, which splits the hidden dimension across several heads:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>MHA</mtext><mo stretchy="false">(</mo><mi>X</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>Concat</mtext><mo stretchy="false">(</mo><msub><mtext>head</mtext><mn>1</mn></msub><mo separator="true">,</mo><mo>…</mo><mo separator="true">,</mo><msub><mtext>head</mtext><mi>h</mi></msub><mo stretchy="false">)</mo><msub><mi>W</mi><mi>O</mi></msub></mrow><annotation encoding="application/x-tex">
\text{MHA}(X) = \text{Concat}(\text{head}_1, \dots, \text{head}_h)W_O
</annotation></semantics></math></span><p>Each head can specialize differently. For example, one head may focus on:</p>
<ul>
<li>local syntax</li>
<li>long-range dependencies</li>
<li>delimiter structure</li>
<li>repeated entities</li>
</ul>
<p>The point is not that heads correspond cleanly to human-defined roles, but that multiple heads allow the model to represent several relational patterns in parallel.</p>
<hr>
<h2 id="the-feed-forward-block">The Feed-Forward Block</h2>
<p>After attention, each token independently passes through an MLP:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>MLP</mtext><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><msub><mi>W</mi><mn>2</mn></msub><mi>ϕ</mi><mo stretchy="false">(</mo><msub><mi>W</mi><mn>1</mn></msub><mi>x</mi><mo>+</mo><msub><mi>b</mi><mn>1</mn></msub><mo stretchy="false">)</mo><mo>+</mo><msub><mi>b</mi><mn>2</mn></msub></mrow><annotation encoding="application/x-tex">
\text{MLP}(x) = W_2 \phi(W_1 x + b_1) + b_2
</annotation></semantics></math></span><p>In GPT-2, this block expands the hidden dimension and then projects it back down. This lets the model perform nonlinear feature transformation after the context-mixing step.</p>
<p>You can think of the division of labor as:</p>
<ul>
<li>attention mixes information across positions</li>
<li>the MLP transforms features at each position</li>
</ul>
<p>Both are necessary.</p>
<hr>
<h2 id="a-minimal-transformer-block">A Minimal Transformer Block</h2>
<p>Putting the pieces together:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">torch</span>
</span></span><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">torch.nn</span> <span class="k">as</span> <span class="nn">nn</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">class</span> <span class="nc">Block</span><span class="p">(</span><span class="n">nn</span><span class="o">.</span><span class="n">Module</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">d_model</span><span class="p">,</span> <span class="n">n_heads</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">ln1</span> <span class="o">=</span> <span class="n">nn</span><span class="o">.</span><span class="n">LayerNorm</span><span class="p">(</span><span class="n">d_model</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">attn</span> <span class="o">=</span> <span class="n">CausalSelfAttention</span><span class="p">(</span><span class="n">d_model</span><span class="p">,</span> <span class="n">n_heads</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">ln2</span> <span class="o">=</span> <span class="n">nn</span><span class="o">.</span><span class="n">LayerNorm</span><span class="p">(</span><span class="n">d_model</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        <span class="bp">self</span><span class="o">.</span><span class="n">mlp</span> <span class="o">=</span> <span class="n">nn</span><span class="o">.</span><span class="n">Sequential</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">            <span class="n">nn</span><span class="o">.</span><span class="n">Linear</span><span class="p">(</span><span class="n">d_model</span><span class="p">,</span> <span class="mi">4</span> <span class="o">*</span> <span class="n">d_model</span><span class="p">),</span>
</span></span><span class="line"><span class="cl">            <span class="n">nn</span><span class="o">.</span><span class="n">GELU</span><span class="p">(),</span>
</span></span><span class="line"><span class="cl">            <span class="n">nn</span><span class="o">.</span><span class="n">Linear</span><span class="p">(</span><span class="mi">4</span> <span class="o">*</span> <span class="n">d_model</span><span class="p">,</span> <span class="n">d_model</span><span class="p">),</span>
</span></span><span class="line"><span class="cl">        <span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">def</span> <span class="nf">forward</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">attn</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">ln1</span><span class="p">(</span><span class="n">x</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">        <span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">mlp</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">ln2</span><span class="p">(</span><span class="n">x</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="n">x</span>
</span></span></code></pre></div><p>Two implementation details matter:</p>
<ul>
<li><strong>residual connections</strong> stabilize deep optimization</li>
<li><strong>pre-layernorm</strong> helps gradient flow in practice</li>
</ul>
<p>Repeated stacking of this block is what gives GPT-2 its modeling capacity.</p>
<hr>
<h2 id="build-gpt-from-the-beginning">Build GPT from the Beginning</h2>
<p>A small educational GPT can be built in the following order:</p>
<ol>
<li>write the tokenizer pipeline</li>
<li>create token and position embeddings</li>
<li>implement causal self-attention</li>
<li>implement the MLP and transformer block</li>
<li>stack multiple blocks</li>
<li>add the output projection to vocabulary logits</li>
<li>write the training loop</li>
</ol>
<p>A minimal forward pass is:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="n">tok</span> <span class="o">=</span> <span class="n">token_embedding</span><span class="p">(</span><span class="n">idx</span><span class="p">)</span>          <span class="c1"># [B, T, d]</span>
</span></span><span class="line"><span class="cl"><span class="n">pos</span> <span class="o">=</span> <span class="n">position_embedding</span><span class="p">(</span><span class="n">pos_ids</span><span class="p">)</span>   <span class="c1"># [T, d]</span>
</span></span><span class="line"><span class="cl"><span class="n">x</span> <span class="o">=</span> <span class="n">tok</span> <span class="o">+</span> <span class="n">pos</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">for</span> <span class="n">block</span> <span class="ow">in</span> <span class="n">blocks</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="n">x</span> <span class="o">=</span> <span class="n">block</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">x</span> <span class="o">=</span> <span class="n">final_ln</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">logits</span> <span class="o">=</span> <span class="n">lm_head</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>                 <span class="c1"># [B, T, vocab_size]</span>
</span></span></code></pre></div><p>The logits are then compared with shifted targets using cross-entropy.</p>
<hr>
<h2 id="training-on-an-unlabeled-dataset">Training on an Unlabeled Dataset</h2>
<p>Training data for GPT-2 does not need class labels. Plain text is enough.</p>
<p>From a sequence:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">the cat sat on the mat
</span></span></code></pre></div><p>we create:</p>
<ul>
<li>input: <code>the cat sat on the</code></li>
<li>target: <code>cat sat on the mat</code></li>
</ul>
<p>More precisely, if <code>idx[:, :-1]</code> is the input sequence, then <code>idx[:, 1:]</code> is the target sequence.</p>
<p>In PyTorch:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="n">logits</span> <span class="o">=</span> <span class="n">model</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>                   <span class="c1"># [B, T, V]</span>
</span></span><span class="line"><span class="cl"><span class="n">loss</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">nn</span><span class="o">.</span><span class="n">functional</span><span class="o">.</span><span class="n">cross_entropy</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="n">logits</span><span class="p">[:,</span> <span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="n">logits</span><span class="o">.</span><span class="n">size</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)),</span>
</span></span><span class="line"><span class="cl">    <span class="n">x</span><span class="p">[:,</span> <span class="mi">1</span><span class="p">:]</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">),</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span>
</span></span></code></pre></div><p>This teaches the model to compress statistical regularities from text into its parameters.</p>
<p>Important training considerations:</p>
<ul>
<li>large batch size improves throughput</li>
<li>AdamW is commonly used</li>
<li>learning-rate warmup helps early stability</li>
<li>gradient clipping can prevent exploding updates</li>
<li>context length strongly affects memory cost</li>
</ul>
<p>Because attention has roughly quadratic cost in sequence length, longer contexts are much more expensive.</p>
<hr>
<h2 id="sampling-and-inference">Sampling and Inference</h2>
<p>Once trained, GPT-2 generates text autoregressively:</p>
<ol>
<li>feed a prompt</li>
<li>get logits for the next token</li>
<li>sample or choose the next token</li>
<li>append it to the prompt</li>
<li>repeat</li>
</ol>
<p>Sampling is controlled by strategies such as:</p>
<ul>
<li><strong>temperature</strong>: rescales logits</li>
<li><strong>top-k</strong>: keep only the <code>k</code> highest-probability tokens</li>
<li><strong>top-p</strong>: keep the smallest set whose cumulative probability exceeds <code>p</code></li>
</ul>
<p>These do not change the model itself; they change how we draw from its learned distribution.</p>
<hr>
<h2 id="fine-tuning-for-classification">Fine-Tuning for Classification</h2>
<p>A pretrained GPT model can also be adapted to downstream tasks such as sentiment classification, topic labeling, or spam detection.</p>
<p>There are two common strategies:</p>
<ol>
<li><strong>Add a task-specific head</strong><br>
Use the final hidden state to predict a label.</li>
<li><strong>Prompt the model generatively</strong><br>
Reframe classification as text generation.</li>
</ol>
<p>The first approach is more direct in a standard ML pipeline. The second is closer to modern instruction-style use.</p>
<p>The reason fine-tuning works is that pretraining already teaches the model:</p>
<ul>
<li>syntax</li>
<li>semantics</li>
<li>long-range dependencies</li>
<li>broad world regularities in text</li>
</ul>
<p>Downstream tasks then only need to reshape that knowledge.</p>
<hr>
<h2 id="instruction-fine-tuning-with-human-feedback">Instruction Fine-Tuning with Human Feedback</h2>
<p>Base GPT-2 learns to continue text. It does <strong>not</strong> automatically learn to follow instructions helpfully.</p>
<p>Instruction tuning typically adds supervised examples like:</p>
<ul>
<li>prompt: &quot;Summarize this article&quot;</li>
<li>response: a good summary</li>
</ul>
<p>Human-feedback-based alignment adds another layer by preferring some responses over others.</p>
<p>Conceptually, the pipeline is:</p>
<ol>
<li>pretrain on next-token prediction</li>
<li>supervised fine-tune on instruction-response pairs</li>
<li>apply preference optimization or RL-style alignment</li>
</ol>
<p>This is the difference between a raw language model and an assistant-like system.</p>
<p>GPT-2 historically predates much of the alignment stack used in modern chat models, but understanding GPT-2 is still the cleanest way to understand the foundation.</p>
<hr>
<h2 id="final-intuition">Final Intuition</h2>
<p>If you strip away the scale, GPT-2 is conceptually elegant:</p>
<ul>
<li>tokenization turns text into discrete units</li>
<li>embeddings turn units into vectors</li>
<li>masked attention lets tokens read the prefix</li>
<li>MLP blocks transform those contextual features</li>
<li>training on next-token prediction teaches the model a distribution over text</li>
</ul>
<p>That is why rebuilding GPT-2 from scratch is such a useful exercise. It exposes the core mechanics behind modern large language models without hiding them behind framework magic.</p>
]]></content:encoded></item><item><title>Deep Learning Explained with Mathematics: From Linear Regression to LLMs</title><link>https://brice6.pages.dev/posts/mai/compsci-714/llm_concept/</link><pubDate>Sun, 08 Mar 2026 00:00:00 +0000</pubDate><guid>https://brice6.pages.dev/posts/mai/compsci-714/llm_concept/</guid><description>A mathematical deep learning roadmap covering probability, optimization, neural networks, transformers, generative models, and multimodal AI.</description><content:encoded><![CDATA[<h2 id="probability--statistics-foundations">Probability &amp; Statistics Foundations</h2>
<h3 id="gaussian-distribution">Gaussian Distribution</h3>
<p>The most important distribution in deep learning. A random variable <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>X</mi><mo>∼</mo><mi mathvariant="script">N</mi><mo stretchy="false">(</mo><mi>μ</mi><mo separator="true">,</mo><msup><mi>σ</mi><mn>2</mn></msup><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">X \sim \mathcal{N}(\mu, \sigma^2)</annotation></semantics></math></span> has density:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>p</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mn>1</mn><msqrt><mrow><mn>2</mn><mi>π</mi><msup><mi>σ</mi><mn>2</mn></msup></mrow></msqrt></mfrac><mi>exp</mi><mo>⁡</mo><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><mo>−</mo><mfrac><mrow><mo stretchy="false">(</mo><mi>x</mi><mo>−</mo><mi>μ</mi><msup><mo stretchy="false">)</mo><mn>2</mn></msup></mrow><mrow><mn>2</mn><msup><mi>σ</mi><mn>2</mn></msup></mrow></mfrac><mo fence="true">)</mo></mrow></mrow><annotation encoding="application/x-tex">p(x) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\!\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)</annotation></semantics></math></span><ul>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>μ</mi></mrow><annotation encoding="application/x-tex">\mu</annotation></semantics></math></span>: mean (centre of the bell curve)</li>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msup><mi>σ</mi><mn>2</mn></msup></mrow><annotation encoding="application/x-tex">\sigma^2</annotation></semantics></math></span>: variance (spread); <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>σ</mi></mrow><annotation encoding="application/x-tex">\sigma</annotation></semantics></math></span> is the standard deviation</li>
</ul>
<p><strong>Multivariate Gaussian</strong> <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="bold">x</mi><mo>∼</mo><mi mathvariant="script">N</mi><mo stretchy="false">(</mo><mi mathvariant="bold-italic">μ</mi><mo separator="true">,</mo><mi mathvariant="normal">Σ</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathbf{x} \sim \mathcal{N}(\boldsymbol{\mu}, \Sigma)</annotation></semantics></math></span>, <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="normal">Σ</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>d</mi><mo>×</mo><mi>d</mi></mrow></msup></mrow><annotation encoding="application/x-tex">\Sigma \in \mathbb{R}^{d\times d}</annotation></semantics></math></span> covariance matrix:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>p</mi><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mn>1</mn><mrow><mo stretchy="false">(</mo><mn>2</mn><mi>π</mi><msup><mo stretchy="false">)</mo><mrow><mi>d</mi><mi mathvariant="normal">/</mi><mn>2</mn></mrow></msup><mi mathvariant="normal">∣</mi><mi mathvariant="normal">Σ</mi><msup><mi mathvariant="normal">∣</mi><mrow><mn>1</mn><mi mathvariant="normal">/</mi><mn>2</mn></mrow></msup></mrow></mfrac><mi>exp</mi><mo>⁡</mo><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><mo>−</mo><mfrac><mn>1</mn><mn>2</mn></mfrac><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo>−</mo><mi mathvariant="bold-italic">μ</mi><msup><mo stretchy="false">)</mo><mi mathvariant="normal">⊤</mi></msup><msup><mi mathvariant="normal">Σ</mi><mrow><mo>−</mo><mn>1</mn></mrow></msup><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo>−</mo><mi mathvariant="bold-italic">μ</mi><mo stretchy="false">)</mo><mo fence="true">)</mo></mrow></mrow><annotation encoding="application/x-tex">p(\mathbf{x}) = \frac{1}{(2\pi)^{d/2}|\Sigma|^{1/2}} \exp\!\left(-\frac{1}{2}(\mathbf{x}-\boldsymbol{\mu})^\top \Sigma^{-1}(\mathbf{x}-\boldsymbol{\mu})\right)</annotation></semantics></math></span><h3 id="expectation--variance">Expectation &amp; Variance</h3>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi mathvariant="double-struck">E</mi><mo stretchy="false">[</mo><mi>X</mi><mo stretchy="false">]</mo><mo>=</mo><mo>∫</mo><mi>x</mi><mtext> </mtext><mi>p</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mtext> </mtext><mi>d</mi><mi>x</mi><mo separator="true">,</mo><mspace width="2em"/><mi mathvariant="double-struck">E</mi><mo stretchy="false">[</mo><mi>f</mi><mo stretchy="false">(</mo><mi>X</mi><mo stretchy="false">)</mo><mo stretchy="false">]</mo><mo>=</mo><mo>∫</mo><mi>f</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mtext> </mtext><mi>p</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mtext> </mtext><mi>d</mi><mi>x</mi></mrow><annotation encoding="application/x-tex">\mathbb{E}[X] = \int x\, p(x)\, dx, \qquad \mathbb{E}[f(X)] = \int f(x)\, p(x)\, dx</annotation></semantics></math></span><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>Var</mtext><mo stretchy="false">(</mo><mi>X</mi><mo stretchy="false">)</mo><mo>=</mo><mi mathvariant="double-struck">E</mi><mo stretchy="false">[</mo><mo stretchy="false">(</mo><mi>X</mi><mo>−</mo><mi mathvariant="double-struck">E</mi><mo stretchy="false">[</mo><mi>X</mi><mo stretchy="false">]</mo><msup><mo stretchy="false">)</mo><mn>2</mn></msup><mo stretchy="false">]</mo><mo>=</mo><mi mathvariant="double-struck">E</mi><mo stretchy="false">[</mo><msup><mi>X</mi><mn>2</mn></msup><mo stretchy="false">]</mo><mo>−</mo><mo stretchy="false">(</mo><mi mathvariant="double-struck">E</mi><mo stretchy="false">[</mo><mi>X</mi><mo stretchy="false">]</mo><msup><mo stretchy="false">)</mo><mn>2</mn></msup></mrow><annotation encoding="application/x-tex">\text{Var}(X) = \mathbb{E}[(X - \mathbb{E}[X])^2] = \mathbb{E}[X^2] - (\mathbb{E}[X])^2</annotation></semantics></math></span><h3 id="entropy--kl-divergence">Entropy &amp; KL Divergence</h3>
<p><strong>Entropy</strong> — measures uncertainty of distribution <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi></mrow><annotation encoding="application/x-tex">p</annotation></semantics></math></span>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>H</mi><mo stretchy="false">(</mo><mi>p</mi><mo stretchy="false">)</mo><mo>=</mo><mo>−</mo><munder><mo>∑</mo><mi>x</mi></munder><mi>p</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mi>log</mi><mo>⁡</mo><mi>p</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mspace width="2em"/><mo stretchy="false">(</mo><mtext>discrete</mtext><mo stretchy="false">)</mo><mo separator="true">,</mo><mspace width="1em"/><mi>H</mi><mo stretchy="false">(</mo><mi>p</mi><mo stretchy="false">)</mo><mo>=</mo><mo>−</mo><mo>∫</mo><mi>p</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mi>log</mi><mo>⁡</mo><mi>p</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mtext> </mtext><mi>d</mi><mi>x</mi><mspace width="1em"/><mo stretchy="false">(</mo><mtext>continuous</mtext><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">H(p) = -\sum_x p(x)\log p(x) \qquad (\text{discrete}), \quad H(p) = -\int p(x)\log p(x)\,dx \quad (\text{continuous})</annotation></semantics></math></span><p><strong>KL Divergence</strong> — measures how much <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>q</mi></mrow><annotation encoding="application/x-tex">q</annotation></semantics></math></span> differs from <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi></mrow><annotation encoding="application/x-tex">p</annotation></semantics></math></span> (not a distance — asymmetric):</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>D</mi><mtext>KL</mtext></msub><mo stretchy="false">(</mo><mi>p</mi><mi mathvariant="normal">∥</mi><mi>q</mi><mo stretchy="false">)</mo><mo>=</mo><munder><mo>∑</mo><mi>x</mi></munder><mi>p</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mi>log</mi><mo>⁡</mo><mfrac><mrow><mi>p</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow><mrow><mi>q</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow></mfrac><mo>≥</mo><mn>0</mn><mo separator="true">,</mo><mspace width="1em"/><mo>=</mo><mn>0</mn><mtext>  </mtext><mo>⟺</mo><mtext>  </mtext><mi>p</mi><mo>=</mo><mi>q</mi></mrow><annotation encoding="application/x-tex">D_{\text{KL}}(p \| q) = \sum_x p(x)\log\frac{p(x)}{q(x)} \geq 0, \quad = 0 \iff p = q</annotation></semantics></math></span><p>Cross-entropy loss is directly related: <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="script">L</mi><mtext>CE</mtext></msub><mo>=</mo><mi>H</mi><mo stretchy="false">(</mo><mi>p</mi><mo stretchy="false">)</mo><mo>+</mo><msub><mi>D</mi><mtext>KL</mtext></msub><mo stretchy="false">(</mo><mi>p</mi><mi mathvariant="normal">∥</mi><mi>q</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathcal{L}_{\text{CE}} = H(p) + D_{\text{KL}}(p\|q)</annotation></semantics></math></span> where <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi></mrow><annotation encoding="application/x-tex">p</annotation></semantics></math></span> is the true label distribution.</p>
<h3 id="bayes-theorem">Bayes' Theorem</h3>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mi>θ</mi><mo>∣</mo><mi mathvariant="script">D</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mrow><mi>P</mi><mo stretchy="false">(</mo><mi mathvariant="script">D</mi><mo>∣</mo><mi>θ</mi><mo stretchy="false">)</mo><mtext>  </mtext><mi>P</mi><mo stretchy="false">(</mo><mi>θ</mi><mo stretchy="false">)</mo></mrow><mrow><mi>P</mi><mo stretchy="false">(</mo><mi mathvariant="script">D</mi><mo stretchy="false">)</mo></mrow></mfrac></mrow><annotation encoding="application/x-tex">P(\theta \mid \mathcal{D}) = \frac{P(\mathcal{D} \mid \theta)\; P(\theta)}{P(\mathcal{D})}</annotation></semantics></math></span><ul>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mi>θ</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P(\theta)</annotation></semantics></math></span>: <strong>prior</strong> — belief about parameters before seeing data</li>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mi mathvariant="script">D</mi><mo>∣</mo><mi>θ</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P(\mathcal{D}\mid\theta)</annotation></semantics></math></span>: <strong>likelihood</strong> — how well <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>θ</mi></mrow><annotation encoding="application/x-tex">\theta</annotation></semantics></math></span> explains data</li>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mi>θ</mi><mo>∣</mo><mi mathvariant="script">D</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P(\theta\mid\mathcal{D})</annotation></semantics></math></span>: <strong>posterior</strong> — updated belief after data</li>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mi mathvariant="script">D</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P(\mathcal{D})</annotation></semantics></math></span>: <strong>evidence</strong> — normalisation constant</li>
</ul>
<p>MLE (Maximum Likelihood Estimation) maximises <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mi mathvariant="script">D</mi><mo>∣</mo><mi>θ</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P(\mathcal{D}\mid\theta)</annotation></semantics></math></span>; MAP adds a prior regulariser.</p>
<hr>
<h2 id="core-ml-concepts-mathematically">Core ML Concepts, Mathematically</h2>
<h3 id="linear-regression-lr">Linear Regression (LR)</h3>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>f</mi><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mo>=</mo><msup><mi mathvariant="bold">w</mi><mi mathvariant="normal">⊤</mi></msup><mi mathvariant="bold">x</mi><mo>+</mo><mi>b</mi><mo>=</mo><munderover><mo>∑</mo><mrow><mi>j</mi><mo>=</mo><mn>1</mn></mrow><mi>d</mi></munderover><msub><mi>w</mi><mi>j</mi></msub><msub><mi>x</mi><mi>j</mi></msub><mo>+</mo><mi>b</mi></mrow><annotation encoding="application/x-tex">f(\mathbf{x}) = \mathbf{w}^\top \mathbf{x} + b = \sum_{j=1}^{d} w_j x_j + b</annotation></semantics></math></span><p>In matrix form over <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi></mrow><annotation encoding="application/x-tex">n</annotation></semantics></math></span> samples: <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mover accent="true"><mi mathvariant="bold">y</mi><mo>^</mo></mover><mo>=</mo><mi>X</mi><mi mathvariant="bold">w</mi><mo>+</mo><mi>b</mi><mn mathvariant="bold">1</mn><mo separator="true">,</mo><mspace width="1em"/><mi>X</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>n</mi><mo>×</mo><mi>d</mi></mrow></msup></mrow><annotation encoding="application/x-tex">\hat{\mathbf{y}} = X\mathbf{w} + b\mathbf{1},\quad X \in \mathbb{R}^{n \times d}</annotation></semantics></math></span></p>
<h3 id="squared-error-se">Squared Error (SE)</h3>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>SE</mtext><mo stretchy="false">(</mo><mover accent="true"><mi>y</mi><mo>^</mo></mover><mo separator="true">,</mo><mi>y</mi><mo stretchy="false">)</mo><mo>=</mo><mo stretchy="false">(</mo><mover accent="true"><mi>y</mi><mo>^</mo></mover><mo>−</mo><mi>y</mi><msup><mo stretchy="false">)</mo><mn>2</mn></msup></mrow><annotation encoding="application/x-tex">\text{SE}(\hat{y}, y) = (\hat{y} - y)^2</annotation></semantics></math></span><h3 id="mean-squared-error-mse">Mean Squared Error (MSE)</h3>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="script">L</mi><mtext>MSE</mtext></msub><mo stretchy="false">(</mo><mi>θ</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mn>1</mn><mi>n</mi></mfrac><munderover><mo>∑</mo><mrow><mi>i</mi><mo>=</mo><mn>1</mn></mrow><mi>n</mi></munderover><msup><mrow><mo fence="true">(</mo><msub><mi>f</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msup><mi mathvariant="bold">x</mi><mrow><mo stretchy="false">(</mo><mi>i</mi><mo stretchy="false">)</mo></mrow></msup><mo stretchy="false">)</mo><mo>−</mo><msup><mi>y</mi><mrow><mo stretchy="false">(</mo><mi>i</mi><mo stretchy="false">)</mo></mrow></msup><mo fence="true">)</mo></mrow><mn>2</mn></msup></mrow><annotation encoding="application/x-tex">\mathcal{L}_{\text{MSE}}(\theta) = \frac{1}{n} \sum_{i=1}^{n} \left( f_\theta(\mathbf{x}^{(i)}) - y^{(i)} \right)^2</annotation></semantics></math></span><h3 id="cross-entropy-loss-ce">Cross-Entropy Loss (CE)</h3>
<p>Used for classification. For a one-hot label <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="bold">y</mi><mo>∈</mo><mo stretchy="false">{</mo><mn>0</mn><mo separator="true">,</mo><mn>1</mn><msup><mo stretchy="false">}</mo><mi>K</mi></msup></mrow><annotation encoding="application/x-tex">\mathbf{y} \in \{0,1\}^K</annotation></semantics></math></span> over <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>K</mi></mrow><annotation encoding="application/x-tex">K</annotation></semantics></math></span> classes and predicted probability vector <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mover accent="true"><mi mathvariant="bold">p</mi><mo>^</mo></mover><mo>=</mo><mtext>softmax</mtext><mo stretchy="false">(</mo><mi mathvariant="bold">z</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\hat{\mathbf{p}} = \text{softmax}(\mathbf{z})</annotation></semantics></math></span>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="script">L</mi><mtext>CE</mtext></msub><mo>=</mo><mo>−</mo><munderover><mo>∑</mo><mrow><mi>k</mi><mo>=</mo><mn>1</mn></mrow><mi>K</mi></munderover><msub><mi>y</mi><mi>k</mi></msub><mi>log</mi><mo>⁡</mo><msub><mover accent="true"><mi>p</mi><mo>^</mo></mover><mi>k</mi></msub></mrow><annotation encoding="application/x-tex">\mathcal{L}_{\text{CE}} = -\sum_{k=1}^{K} y_k \log \hat{p}_k</annotation></semantics></math></span><p>For binary classification (<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>K</mi><mo>=</mo><mn>2</mn></mrow><annotation encoding="application/x-tex">K=2</annotation></semantics></math></span>):</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="script">L</mi><mtext>BCE</mtext></msub><mo>=</mo><mo>−</mo><mrow><mo fence="true">[</mo><mi>y</mi><mi>log</mi><mo>⁡</mo><mover accent="true"><mi>p</mi><mo>^</mo></mover><mo>+</mo><mo stretchy="false">(</mo><mn>1</mn><mo>−</mo><mi>y</mi><mo stretchy="false">)</mo><mi>log</mi><mo>⁡</mo><mo stretchy="false">(</mo><mn>1</mn><mo>−</mo><mover accent="true"><mi>p</mi><mo>^</mo></mover><mo stretchy="false">)</mo><mo fence="true">]</mo></mrow></mrow><annotation encoding="application/x-tex">\mathcal{L}_{\text{BCE}} = -\left[y \log \hat{p} + (1-y)\log(1-\hat{p})\right]</annotation></semantics></math></span><p>Over <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi></mrow><annotation encoding="application/x-tex">n</annotation></semantics></math></span> samples (multiclass):</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="script">L</mi><mtext>CE</mtext></msub><mo stretchy="false">(</mo><mi>θ</mi><mo stretchy="false">)</mo><mo>=</mo><mo>−</mo><mfrac><mn>1</mn><mi>n</mi></mfrac><munderover><mo>∑</mo><mrow><mi>i</mi><mo>=</mo><mn>1</mn></mrow><mi>n</mi></munderover><mi>log</mi><mo>⁡</mo><msubsup><mover accent="true"><mi>p</mi><mo>^</mo></mover><msup><mi>y</mi><mrow><mo stretchy="false">(</mo><mi>i</mi><mo stretchy="false">)</mo></mrow></msup><mrow><mo stretchy="false">(</mo><mi>i</mi><mo stretchy="false">)</mo></mrow></msubsup></mrow><annotation encoding="application/x-tex">\mathcal{L}_{\text{CE}}(\theta) = -\frac{1}{n}\sum_{i=1}^{n} \log \hat{p}_{y^{(i)}}^{(i)}</annotation></semantics></math></span><h3 id="derivatives">Derivatives</h3>
<p><strong>Derivative</strong> — instantaneous rate of change:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msup><mi>f</mi><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mrow><mi>d</mi><mi>f</mi></mrow><mrow><mi>d</mi><mi>x</mi></mrow></mfrac><mo>=</mo><munder><mrow><mi>lim</mi><mo>⁡</mo></mrow><mrow><mi>h</mi><mo>→</mo><mn>0</mn></mrow></munder><mfrac><mrow><mi>f</mi><mo stretchy="false">(</mo><mi>x</mi><mo>+</mo><mi>h</mi><mo stretchy="false">)</mo><mo>−</mo><mi>f</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow><mi>h</mi></mfrac></mrow><annotation encoding="application/x-tex">f&#x27;(x) = \frac{df}{dx} = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}</annotation></semantics></math></span><p><strong>Gradient</strong> — multivariate generalisation <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>f</mi><mo>:</mo><msup><mi mathvariant="double-struck">R</mi><mi>d</mi></msup><mo>→</mo><mi mathvariant="double-struck">R</mi></mrow><annotation encoding="application/x-tex">f : \mathbb{R}^d \to \mathbb{R}</annotation></semantics></math></span>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="normal">∇</mi><mi>θ</mi></msub><mi mathvariant="script">L</mi><mo>=</mo><mrow><mo fence="true">[</mo><mtable rowspacing="0.16em" columnalign="center" columnspacing="1em"><mtr><mtd><mstyle scriptlevel="0" displaystyle="false"><mrow><mi mathvariant="normal">∂</mi><mi mathvariant="script">L</mi><mi mathvariant="normal">/</mi><mi mathvariant="normal">∂</mi><msub><mi>θ</mi><mn>1</mn></msub></mrow></mstyle></mtd></mtr><mtr><mtd><mstyle scriptlevel="0" displaystyle="false"><mrow><mi mathvariant="normal">⋮</mi><mpadded height="0em" voffset="0em"><mspace mathbackground="black" width="0em" height="1.5em"></mspace></mpadded></mrow></mstyle></mtd></mtr><mtr><mtd><mstyle scriptlevel="0" displaystyle="false"><mrow><mi mathvariant="normal">∂</mi><mi mathvariant="script">L</mi><mi mathvariant="normal">/</mi><mi mathvariant="normal">∂</mi><msub><mi>θ</mi><mi>d</mi></msub></mrow></mstyle></mtd></mtr></mtable><mo fence="true">]</mo></mrow><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mi>d</mi></msup></mrow><annotation encoding="application/x-tex">\nabla_\theta \mathcal{L} = \begin{bmatrix} \partial \mathcal{L}/\partial \theta_1 \\ \vdots \\ \partial \mathcal{L}/\partial \theta_d \end{bmatrix} \in \mathbb{R}^d</annotation></semantics></math></span><p><strong>Chain Rule</strong> — for <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>z</mi><mo>=</mo><mi>g</mi><mo stretchy="false">(</mo><mi>f</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">z = g(f(x))</annotation></semantics></math></span>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mfrac><mrow><mi>d</mi><mi>z</mi></mrow><mrow><mi>d</mi><mi>x</mi></mrow></mfrac><mo>=</mo><mfrac><mrow><mi>d</mi><mi>z</mi></mrow><mrow><mi>d</mi><mi>f</mi></mrow></mfrac><mo>⋅</mo><mfrac><mrow><mi>d</mi><mi>f</mi></mrow><mrow><mi>d</mi><mi>x</mi></mrow></mfrac></mrow><annotation encoding="application/x-tex">\frac{dz}{dx} = \frac{dz}{df} \cdot \frac{df}{dx}</annotation></semantics></math></span><p>For deep compositions <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>z</mi><mo>=</mo><mi>h</mi><mo stretchy="false">(</mo><mi>g</mi><mo stretchy="false">(</mo><mi>f</mi><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mo stretchy="false">)</mo><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">z = h(g(f(\mathbf{x})))</annotation></semantics></math></span>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mfrac><mrow><mi mathvariant="normal">∂</mi><mi>z</mi></mrow><mrow><mi mathvariant="normal">∂</mi><mi mathvariant="bold">x</mi></mrow></mfrac><mo>=</mo><mfrac><mrow><mi mathvariant="normal">∂</mi><mi>z</mi></mrow><mrow><mi mathvariant="normal">∂</mi><mi>g</mi></mrow></mfrac><mo>⋅</mo><mfrac><mrow><mi mathvariant="normal">∂</mi><mi>g</mi></mrow><mrow><mi mathvariant="normal">∂</mi><mi>f</mi></mrow></mfrac><mo>⋅</mo><mfrac><mrow><mi mathvariant="normal">∂</mi><mi>f</mi></mrow><mrow><mi mathvariant="normal">∂</mi><mi mathvariant="bold">x</mi></mrow></mfrac></mrow><annotation encoding="application/x-tex">\frac{\partial z}{\partial \mathbf{x}} = \frac{\partial z}{\partial g} \cdot \frac{\partial g}{\partial f} \cdot \frac{\partial f}{\partial \mathbf{x}}</annotation></semantics></math></span><p><strong>Gradient Descent</strong> — minimise <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="script">L</mi><mo stretchy="false">(</mo><mi>θ</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathcal{L}(\theta)</annotation></semantics></math></span> by stepping opposite the gradient:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>θ</mi><mrow><mi>t</mi><mo>+</mo><mn>1</mn></mrow></msub><mo>=</mo><msub><mi>θ</mi><mi>t</mi></msub><mo>−</mo><mi>η</mi><mo>⋅</mo><msub><mi mathvariant="normal">∇</mi><mi>θ</mi></msub><mi mathvariant="script">L</mi><mo stretchy="false">(</mo><msub><mi>θ</mi><mi>t</mi></msub><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\theta_{t+1} = \theta_t - \eta \cdot \nabla_\theta \mathcal{L}(\theta_t)</annotation></semantics></math></span><h3 id="the-four-step-recipe-of-machine-learning">The Four-Step Recipe of Machine Learning</h3>
<ol>
<li>Collect the data</li>
<li>Define the model's structure</li>
<li>Define the loss function</li>
<li>Minimise the loss</li>
</ol>
<h3 id="vectors-are-all-you-need">Vectors Are All You Need</h3>
<p>A vector <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="bold">x</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mi>d</mi></msup></mrow><annotation encoding="application/x-tex">\mathbf{x} \in \mathbb{R}^d</annotation></semantics></math></span> encodes a data point with <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>d</mi></mrow><annotation encoding="application/x-tex">d</annotation></semantics></math></span> features.</p>
<p>Operations:</p>
<ul>
<li><strong>Add:</strong> <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">(</mo><mi mathvariant="bold">u</mi><mo>+</mo><mi mathvariant="bold">v</mi><msub><mo stretchy="false">)</mo><mi>i</mi></msub><mo>=</mo><msub><mi>u</mi><mi>i</mi></msub><mo>+</mo><msub><mi>v</mi><mi>i</mi></msub></mrow><annotation encoding="application/x-tex">(\mathbf{u} + \mathbf{v})_i = u_i + v_i</annotation></semantics></math></span></li>
<li><strong>Dot product:</strong> <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="bold">u</mi><mo>⋅</mo><mi mathvariant="bold">v</mi><mo>=</mo><msup><mi mathvariant="bold">u</mi><mi mathvariant="normal">⊤</mi></msup><mi mathvariant="bold">v</mi><mo>=</mo><msub><mo>∑</mo><mi>i</mi></msub><msub><mi>u</mi><mi>i</mi></msub><msub><mi>v</mi><mi>i</mi></msub></mrow><annotation encoding="application/x-tex">\mathbf{u} \cdot \mathbf{v} = \mathbf{u}^\top \mathbf{v} = \sum_i u_i v_i</annotation></semantics></math></span></li>
<li><strong><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="normal">ℓ</mi><mn>2</mn></msub></mrow><annotation encoding="application/x-tex">\ell_2</annotation></semantics></math></span> Norm:</strong> <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="normal">∥</mi><mi mathvariant="bold">x</mi><msub><mi mathvariant="normal">∥</mi><mn>2</mn></msub><mo>=</mo><msqrt><mrow><msub><mo>∑</mo><mi>i</mi></msub><msubsup><mi>x</mi><mi>i</mi><mn>2</mn></msubsup></mrow></msqrt></mrow><annotation encoding="application/x-tex">\|\mathbf{x}\|_2 = \sqrt{\sum_i x_i^2}</annotation></semantics></math></span></li>
<li><strong>Cosine similarity:</strong> <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>cos</mi><mo>⁡</mo><mo stretchy="false">(</mo><mi mathvariant="bold">u</mi><mo separator="true">,</mo><mi mathvariant="bold">v</mi><mo stretchy="false">)</mo><mo>=</mo><mstyle displaystyle="true" scriptlevel="0"><mfrac><mrow><msup><mi mathvariant="bold">u</mi><mi mathvariant="normal">⊤</mi></msup><mi mathvariant="bold">v</mi></mrow><mrow><mi mathvariant="normal">∥</mi><mi mathvariant="bold">u</mi><mi mathvariant="normal">∥</mi><mi mathvariant="normal">∥</mi><mi mathvariant="bold">v</mi><mi mathvariant="normal">∥</mi></mrow></mfrac></mstyle></mrow><annotation encoding="application/x-tex">\cos(\mathbf{u},\mathbf{v}) = \dfrac{\mathbf{u}^\top \mathbf{v}}{\|\mathbf{u}\|\|\mathbf{v}\|}</annotation></semantics></math></span></li>
</ul>
<h3 id="matrices">Matrices</h3>
<p>A matrix <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>W</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>m</mi><mo>×</mo><mi>n</mi></mrow></msup></mrow><annotation encoding="application/x-tex">W \in \mathbb{R}^{m \times n}</annotation></semantics></math></span> represents a linear transformation <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msup><mi mathvariant="double-struck">R</mi><mi>n</mi></msup><mo>→</mo><msup><mi mathvariant="double-struck">R</mi><mi>m</mi></msup></mrow><annotation encoding="application/x-tex">\mathbb{R}^n \to \mathbb{R}^m</annotation></semantics></math></span>.</p>
<p>Operations:</p>
<ul>
<li><strong>Add:</strong> <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">(</mo><mi>A</mi><mo>+</mo><mi>B</mi><msub><mo stretchy="false">)</mo><mrow><mi>i</mi><mi>j</mi></mrow></msub><mo>=</mo><msub><mi>A</mi><mrow><mi>i</mi><mi>j</mi></mrow></msub><mo>+</mo><msub><mi>B</mi><mrow><mi>i</mi><mi>j</mi></mrow></msub></mrow><annotation encoding="application/x-tex">(A+B)_{ij} = A_{ij}+B_{ij}</annotation></semantics></math></span></li>
<li><strong>Mul (matrix product):</strong> <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">(</mo><mi>A</mi><mi>B</mi><msub><mo stretchy="false">)</mo><mrow><mi>i</mi><mi>j</mi></mrow></msub><mo>=</mo><msub><mo>∑</mo><mi>k</mi></msub><msub><mi>A</mi><mrow><mi>i</mi><mi>k</mi></mrow></msub><msub><mi>B</mi><mrow><mi>k</mi><mi>j</mi></mrow></msub></mrow><annotation encoding="application/x-tex">(AB)_{ij} = \sum_k A_{ik}B_{kj}</annotation></semantics></math></span></li>
<li><strong>Broadcast:</strong> scalar/vector ops extend across batch dimensions</li>
<li><strong>Transpose:</strong> <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">(</mo><msup><mi>A</mi><mi mathvariant="normal">⊤</mi></msup><msub><mo stretchy="false">)</mo><mrow><mi>i</mi><mi>j</mi></mrow></msub><mo>=</mo><msub><mi>A</mi><mrow><mi>j</mi><mi>i</mi></mrow></msub></mrow><annotation encoding="application/x-tex">(A^\top)_{ij} = A_{ji}</annotation></semantics></math></span></li>
</ul>
<h3 id="neural-networks">Neural Networks</h3>
<p><strong>Single neuron:</strong></p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>a</mi><mo>=</mo><mi>ϕ</mi><mo stretchy="false">(</mo><msup><mi mathvariant="bold">w</mi><mi mathvariant="normal">⊤</mi></msup><mi mathvariant="bold">x</mi><mo>+</mo><mi>b</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">a = \phi(\mathbf{w}^\top \mathbf{x} + b)</annotation></semantics></math></span><p><strong>MLP — layer <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="normal">ℓ</mi></mrow><annotation encoding="application/x-tex">\ell</annotation></semantics></math></span> forward pass:</strong></p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msup><mi mathvariant="bold">z</mi><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">ℓ</mi><mo stretchy="false">)</mo></mrow></msup><mo>=</mo><msup><mi>W</mi><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">ℓ</mi><mo stretchy="false">)</mo></mrow></msup><msup><mi mathvariant="bold">a</mi><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">ℓ</mi><mo>−</mo><mn>1</mn><mo stretchy="false">)</mo></mrow></msup><mo>+</mo><msup><mi mathvariant="bold">b</mi><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">ℓ</mi><mo stretchy="false">)</mo></mrow></msup><mo separator="true">,</mo><mspace width="2em"/><msup><mi mathvariant="bold">a</mi><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">ℓ</mi><mo stretchy="false">)</mo></mrow></msup><mo>=</mo><mi>ϕ</mi><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><msup><mi mathvariant="bold">z</mi><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">ℓ</mi><mo stretchy="false">)</mo></mrow></msup><mo fence="true">)</mo></mrow></mrow><annotation encoding="application/x-tex">\mathbf{z}^{(\ell)} = W^{(\ell)}\mathbf{a}^{(\ell-1)} + \mathbf{b}^{(\ell)}, \qquad \mathbf{a}^{(\ell)} = \phi\!\left(\mathbf{z}^{(\ell)}\right)</annotation></semantics></math></span><p><strong>Backpropagation</strong> (chain rule applied layer by layer):</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msup><mi mathvariant="bold-italic">δ</mi><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">ℓ</mi><mo stretchy="false">)</mo></mrow></msup><mo>=</mo><mrow><mo fence="true">(</mo><msup><mi>W</mi><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">ℓ</mi><mo>+</mo><mn>1</mn><mo stretchy="false">)</mo><mi mathvariant="normal">⊤</mi></mrow></msup><msup><mi mathvariant="bold-italic">δ</mi><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">ℓ</mi><mo>+</mo><mn>1</mn><mo stretchy="false">)</mo></mrow></msup><mo fence="true">)</mo></mrow><mo>⊙</mo><msup><mi>ϕ</mi><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><msup><mi mathvariant="bold">z</mi><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">ℓ</mi><mo stretchy="false">)</mo></mrow></msup><mo fence="true">)</mo></mrow></mrow><annotation encoding="application/x-tex">\boldsymbol{\delta}^{(\ell)} = \left(W^{(\ell+1)\top}\boldsymbol{\delta}^{(\ell+1)}\right) \odot \phi&#x27;\!\left(\mathbf{z}^{(\ell)}\right)</annotation></semantics></math></span><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mfrac><mrow><mi mathvariant="normal">∂</mi><mi mathvariant="script">L</mi></mrow><mrow><mi mathvariant="normal">∂</mi><msup><mi>W</mi><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">ℓ</mi><mo stretchy="false">)</mo></mrow></msup></mrow></mfrac><mo>=</mo><msup><mi mathvariant="bold-italic">δ</mi><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">ℓ</mi><mo stretchy="false">)</mo></mrow></msup><msup><mi mathvariant="bold">a</mi><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">ℓ</mi><mo>−</mo><mn>1</mn><mo stretchy="false">)</mo><mi mathvariant="normal">⊤</mi></mrow></msup></mrow><annotation encoding="application/x-tex">\frac{\partial \mathcal{L}}{\partial W^{(\ell)}} = \boldsymbol{\delta}^{(\ell)}\mathbf{a}^{(\ell-1)\top}</annotation></semantics></math></span><p><strong>Activation functions:</strong></p>
<p><strong>ReLU:</strong>
</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>ReLU</mtext><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mi>max</mi><mo>⁡</mo><mo stretchy="false">(</mo><mn>0</mn><mo separator="true">,</mo><mi>x</mi><mo stretchy="false">)</mo><mo separator="true">,</mo><mspace width="2em"/><msup><mtext>ReLU</mtext><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mn mathvariant="bold">1</mn><mo stretchy="false">[</mo><mi>x</mi><mo>&gt;</mo><mn>0</mn><mo stretchy="false">]</mo></mrow><annotation encoding="application/x-tex">\text{ReLU}(x) = \max(0,x), \qquad \text{ReLU}&#x27;(x) = \mathbf{1}[x&gt;0]</annotation></semantics></math></span><p><strong>Sigmoid:</strong>
</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>σ</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mn>1</mn><mrow><mn>1</mn><mo>+</mo><msup><mi>e</mi><mrow><mo>−</mo><mi>x</mi></mrow></msup></mrow></mfrac><mo separator="true">,</mo><mspace width="2em"/><msup><mi>σ</mi><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mi>σ</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo stretchy="false">(</mo><mn>1</mn><mo>−</mo><mi>σ</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\sigma(x) = \frac{1}{1+e^{-x}}, \qquad \sigma&#x27;(x) = \sigma(x)(1-\sigma(x))</annotation></semantics></math></span><p><strong>Tanh:</strong>
</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>tanh</mi><mo>⁡</mo><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mrow><msup><mi>e</mi><mi>x</mi></msup><mo>−</mo><msup><mi>e</mi><mrow><mo>−</mo><mi>x</mi></mrow></msup></mrow><mrow><msup><mi>e</mi><mi>x</mi></msup><mo>+</mo><msup><mi>e</mi><mrow><mo>−</mo><mi>x</mi></mrow></msup></mrow></mfrac><mo separator="true">,</mo><mspace width="2em"/><msup><mrow><mi>tanh</mi><mo>⁡</mo></mrow><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mn>1</mn><mo>−</mo><msup><mrow><mi>tanh</mi><mo>⁡</mo></mrow><mn>2</mn></msup><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\tanh(x) = \frac{e^x - e^{-x}}{e^x + e^{-x}}, \qquad \tanh&#x27;(x) = 1 - \tanh^2(x)</annotation></semantics></math></span><p><strong>Softmax:</strong>
</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>softmax</mtext><mo stretchy="false">(</mo><mi mathvariant="bold">z</mi><msub><mo stretchy="false">)</mo><mi>k</mi></msub><mo>=</mo><mfrac><msup><mi>e</mi><msub><mi>z</mi><mi>k</mi></msub></msup><mrow><munder><mo>∑</mo><mi>j</mi></munder><msup><mi>e</mi><msub><mi>z</mi><mi>j</mi></msub></msup></mrow></mfrac></mrow><annotation encoding="application/x-tex">\text{softmax}(\mathbf{z})_k = \frac{e^{z_k}}{\sum_j e^{z_j}}</annotation></semantics></math></span><p><strong>GELU</strong> (Gaussian Error Linear Unit) — used in BERT, GPT-2, and many modern Transformers:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>GELU</mtext><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mi>x</mi><mo>⋅</mo><mi mathvariant="normal">Φ</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mi>x</mi><mo>⋅</mo><mfrac><mn>1</mn><mn>2</mn></mfrac><mrow><mo fence="true">[</mo><mn>1</mn><mo>+</mo><mtext>erf</mtext><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><mfrac><mi>x</mi><msqrt><mn>2</mn></msqrt></mfrac><mo fence="true">)</mo></mrow><mo fence="true">]</mo></mrow></mrow><annotation encoding="application/x-tex">\text{GELU}(x) = x \cdot \Phi(x) = x \cdot \frac{1}{2}\left[1 + \text{erf}\!\left(\frac{x}{\sqrt{2}}\right)\right]</annotation></semantics></math></span><p>where <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="normal">Φ</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\Phi(x)</annotation></semantics></math></span> is the standard Gaussian CDF. Practical approximation:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>GELU</mtext><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>≈</mo><mn>0.5</mn><mi>x</mi><mrow><mo fence="true">(</mo><mn>1</mn><mo>+</mo><mi>tanh</mi><mo>⁡</mo><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><msqrt><mfrac><mn>2</mn><mi>π</mi></mfrac></msqrt><mtext> </mtext><mo stretchy="false">(</mo><mi>x</mi><mo>+</mo><mn>0.044715</mn><mtext> </mtext><msup><mi>x</mi><mn>3</mn></msup><mo stretchy="false">)</mo><mo fence="true">)</mo></mrow><mo fence="true">)</mo></mrow></mrow><annotation encoding="application/x-tex">\text{GELU}(x) \approx 0.5x\left(1 + \tanh\!\left(\sqrt{\frac{2}{\pi}}\,(x + 0.044715\,x^3)\right)\right)</annotation></semantics></math></span><p>Unlike ReLU, GELU is smooth everywhere and lets small negative values through for <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>x</mi><mo>&lt;</mo><mn>0</mn></mrow><annotation encoding="application/x-tex">x &lt; 0</annotation></semantics></math></span>, which helps gradient flow.</p>
<h3 id="training-details">Training Details</h3>
<ul>
<li><strong>Parameters</strong> <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>θ</mi><mo>=</mo><mo stretchy="false">{</mo><msup><mi>W</mi><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">ℓ</mi><mo stretchy="false">)</mo></mrow></msup><mo separator="true">,</mo><msup><mi mathvariant="bold">b</mi><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">ℓ</mi><mo stretchy="false">)</mo></mrow></msup><mo stretchy="false">}</mo></mrow><annotation encoding="application/x-tex">\theta = \{W^{(\ell)}, \mathbf{b}^{(\ell)}\}</annotation></semantics></math></span>: learned by gradient descent.</li>
<li><strong>Hyperparameters</strong>: learning rate <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>η</mi></mrow><annotation encoding="application/x-tex">\eta</annotation></semantics></math></span>, batch size <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>B</mi></mrow><annotation encoding="application/x-tex">B</annotation></semantics></math></span>, layers <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>L</mi></mrow><annotation encoding="application/x-tex">L</annotation></semantics></math></span>, hidden dim <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>d</mi></mrow><annotation encoding="application/x-tex">d</annotation></semantics></math></span> — set before training.</li>
</ul>
<p><strong><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="normal">ℓ</mi><mn>2</mn></msub></mrow><annotation encoding="application/x-tex">\ell_2</annotation></semantics></math></span> Regularisation</strong> (weight decay):</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="script">L</mi><mtext>reg</mtext></msub><mo stretchy="false">(</mo><mi>θ</mi><mo stretchy="false">)</mo><mo>=</mo><mi mathvariant="script">L</mi><mo stretchy="false">(</mo><mi>θ</mi><mo stretchy="false">)</mo><mo>+</mo><mfrac><mi>λ</mi><mn>2</mn></mfrac><mi mathvariant="normal">∥</mi><mi>θ</mi><msubsup><mi mathvariant="normal">∥</mi><mn>2</mn><mn>2</mn></msubsup></mrow><annotation encoding="application/x-tex">\mathcal{L}_{\text{reg}}(\theta) = \mathcal{L}(\theta) + \frac{\lambda}{2}\|\theta\|_2^2</annotation></semantics></math></span><p><strong>Dropout</strong> — randomly zero out neurons during training with probability <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi></mrow><annotation encoding="application/x-tex">p</annotation></semantics></math></span>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mover accent="true"><mi mathvariant="bold">a</mi><mo>~</mo></mover><mo>=</mo><mi mathvariant="bold">m</mi><mo>⊙</mo><mi mathvariant="bold">a</mi><mo>⋅</mo><mfrac><mn>1</mn><mrow><mn>1</mn><mo>−</mo><mi>p</mi></mrow></mfrac><mo separator="true">,</mo><mspace width="1em"/><msub><mi mathvariant="bold">m</mi><mi>i</mi></msub><mo>∼</mo><mtext>Bernoulli</mtext><mo stretchy="false">(</mo><mn>1</mn><mo>−</mo><mi>p</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\tilde{\mathbf{a}} = \mathbf{m} \odot \mathbf{a} \cdot \frac{1}{1-p}, \quad \mathbf{m}_i \sim \text{Bernoulli}(1-p)</annotation></semantics></math></span><p>At inference, no dropout is applied: activations were already scaled by <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mn>1</mn><mi mathvariant="normal">/</mi><mo stretchy="false">(</mo><mn>1</mn><mo>−</mo><mi>p</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">1/(1-p)</annotation></semantics></math></span> during training (<strong>inverted dropout</strong>), so the expected output matches.</p>
<p><strong>Batch Normalisation (BN)</strong> — normalise activations across the batch dimension, then scale and shift:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mover accent="true"><mi>x</mi><mo>^</mo></mover><mi>i</mi></msub><mo>=</mo><mfrac><mrow><msub><mi>x</mi><mi>i</mi></msub><mo>−</mo><msub><mi>μ</mi><mi mathvariant="script">B</mi></msub></mrow><msqrt><mrow><msubsup><mi>σ</mi><mi mathvariant="script">B</mi><mn>2</mn></msubsup><mo>+</mo><mi>ϵ</mi></mrow></msqrt></mfrac><mo separator="true">,</mo><mspace width="2em"/><msub><mi>y</mi><mi>i</mi></msub><mo>=</mo><mi>γ</mi><msub><mover accent="true"><mi>x</mi><mo>^</mo></mover><mi>i</mi></msub><mo>+</mo><mi>β</mi></mrow><annotation encoding="application/x-tex">\hat{x}_i = \frac{x_i - \mu_\mathcal{B}}{\sqrt{\sigma_\mathcal{B}^2 + \epsilon}}, \qquad y_i = \gamma\hat{x}_i + \beta</annotation></semantics></math></span><p>where <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>μ</mi><mi mathvariant="script">B</mi></msub><mo separator="true">,</mo><msubsup><mi>σ</mi><mi mathvariant="script">B</mi><mn>2</mn></msubsup></mrow><annotation encoding="application/x-tex">\mu_\mathcal{B}, \sigma_\mathcal{B}^2</annotation></semantics></math></span> are batch mean/variance; <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>γ</mi><mo separator="true">,</mo><mi>β</mi></mrow><annotation encoding="application/x-tex">\gamma,\beta</annotation></semantics></math></span> are learned parameters.</p>
<p><strong>Layer Normalisation (LN)</strong> — same formula but normalise across the <em>feature</em> dimension (not batch). Preferred in Transformers because it is batch-size independent:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mover accent="true"><mi mathvariant="bold">x</mi><mo>^</mo></mover><mo>=</mo><mfrac><mrow><mi mathvariant="bold">x</mi><mo>−</mo><msub><mi>μ</mi><mi mathvariant="bold">x</mi></msub></mrow><msqrt><mrow><msubsup><mi>σ</mi><mi mathvariant="bold">x</mi><mn>2</mn></msubsup><mo>+</mo><mi>ϵ</mi></mrow></msqrt></mfrac><mo>⋅</mo><mi mathvariant="bold-italic">γ</mi><mo>+</mo><mi mathvariant="bold-italic">β</mi><mo separator="true">,</mo><mspace width="1em"/><msub><mi>μ</mi><mi mathvariant="bold">x</mi></msub><mo>=</mo><mfrac><mn>1</mn><mi>d</mi></mfrac><munder><mo>∑</mo><mi>j</mi></munder><msub><mi>x</mi><mi>j</mi></msub></mrow><annotation encoding="application/x-tex">\hat{\mathbf{x}} = \frac{\mathbf{x} - \mu_\mathbf{x}}{\sqrt{\sigma_\mathbf{x}^2 + \epsilon}} \cdot \boldsymbol{\gamma} + \boldsymbol{\beta}, \quad \mu_\mathbf{x} = \frac{1}{d}\sum_j x_j</annotation></semantics></math></span><p><strong>Adam optimiser</strong> — bias-corrected moment estimates:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>m</mi><mi>t</mi></msub><mo>=</mo><msub><mi>β</mi><mn>1</mn></msub><msub><mi>m</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><mo>+</mo><mo stretchy="false">(</mo><mn>1</mn><mo>−</mo><msub><mi>β</mi><mn>1</mn></msub><mo stretchy="false">)</mo><msub><mi>g</mi><mi>t</mi></msub><mo separator="true">,</mo><mspace width="1em"/><msub><mi>v</mi><mi>t</mi></msub><mo>=</mo><msub><mi>β</mi><mn>2</mn></msub><msub><mi>v</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><mo>+</mo><mo stretchy="false">(</mo><mn>1</mn><mo>−</mo><msub><mi>β</mi><mn>2</mn></msub><mo stretchy="false">)</mo><msubsup><mi>g</mi><mi>t</mi><mn>2</mn></msubsup></mrow><annotation encoding="application/x-tex">m_t = \beta_1 m_{t-1} + (1-\beta_1)g_t, \quad v_t = \beta_2 v_{t-1} + (1-\beta_2)g_t^2</annotation></semantics></math></span><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>θ</mi><mrow><mi>t</mi><mo>+</mo><mn>1</mn></mrow></msub><mo>=</mo><msub><mi>θ</mi><mi>t</mi></msub><mo>−</mo><mi>η</mi><mfrac><msub><mover accent="true"><mi>m</mi><mo>^</mo></mover><mi>t</mi></msub><mrow><msqrt><msub><mover accent="true"><mi>v</mi><mo>^</mo></mover><mi>t</mi></msub></msqrt><mo>+</mo><mi>ϵ</mi></mrow></mfrac><mo separator="true">,</mo><mspace width="1em"/><msub><mover accent="true"><mi>m</mi><mo>^</mo></mover><mi>t</mi></msub><mo>=</mo><mfrac><msub><mi>m</mi><mi>t</mi></msub><mrow><mn>1</mn><mo>−</mo><msubsup><mi>β</mi><mn>1</mn><mi>t</mi></msubsup></mrow></mfrac><mo separator="true">,</mo><mtext>  </mtext><msub><mover accent="true"><mi>v</mi><mo>^</mo></mover><mi>t</mi></msub><mo>=</mo><mfrac><msub><mi>v</mi><mi>t</mi></msub><mrow><mn>1</mn><mo>−</mo><msubsup><mi>β</mi><mn>2</mn><mi>t</mi></msubsup></mrow></mfrac></mrow><annotation encoding="application/x-tex">\theta_{t+1} = \theta_t - \eta\frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\epsilon}, \quad \hat{m}_t = \frac{m_t}{1-\beta_1^t},\; \hat{v}_t = \frac{v_t}{1-\beta_2^t}</annotation></semantics></math></span><h3 id="vanishing--exploding-gradients">Vanishing &amp; Exploding Gradients</h3>
<p>In a deep network with <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>L</mi></mrow><annotation encoding="application/x-tex">L</annotation></semantics></math></span> layers, the gradient flowing back to layer <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="normal">ℓ</mi></mrow><annotation encoding="application/x-tex">\ell</annotation></semantics></math></span> is a product of Jacobians:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mfrac><mrow><mi mathvariant="normal">∂</mi><mi mathvariant="script">L</mi></mrow><mrow><mi mathvariant="normal">∂</mi><msup><mi mathvariant="bold">a</mi><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">ℓ</mi><mo stretchy="false">)</mo></mrow></msup></mrow></mfrac><mo>=</mo><mfrac><mrow><mi mathvariant="normal">∂</mi><mi mathvariant="script">L</mi></mrow><mrow><mi mathvariant="normal">∂</mi><msup><mi mathvariant="bold">a</mi><mrow><mo stretchy="false">(</mo><mi>L</mi><mo stretchy="false">)</mo></mrow></msup></mrow></mfrac><munderover><mo>∏</mo><mrow><mi>k</mi><mo>=</mo><mi mathvariant="normal">ℓ</mi></mrow><mrow><mi>L</mi><mo>−</mo><mn>1</mn></mrow></munderover><mfrac><mrow><mi mathvariant="normal">∂</mi><msup><mi mathvariant="bold">a</mi><mrow><mo stretchy="false">(</mo><mi>k</mi><mo>+</mo><mn>1</mn><mo stretchy="false">)</mo></mrow></msup></mrow><mrow><mi mathvariant="normal">∂</mi><msup><mi mathvariant="bold">a</mi><mrow><mo stretchy="false">(</mo><mi>k</mi><mo stretchy="false">)</mo></mrow></msup></mrow></mfrac></mrow><annotation encoding="application/x-tex">\frac{\partial \mathcal{L}}{\partial \mathbf{a}^{(\ell)}} = \frac{\partial \mathcal{L}}{\partial \mathbf{a}^{(L)}} \prod_{k=\ell}^{L-1} \frac{\partial \mathbf{a}^{(k+1)}}{\partial \mathbf{a}^{(k)}}</annotation></semantics></math></span><p>Each factor <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo>≈</mo><msup><mi>W</mi><mrow><mo stretchy="false">(</mo><mi>k</mi><mo stretchy="false">)</mo></mrow></msup><mo>⋅</mo><mtext>diag</mtext><mo stretchy="false">(</mo><msup><mi>ϕ</mi><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mo stretchy="false">(</mo><msup><mi mathvariant="bold">z</mi><mrow><mo stretchy="false">(</mo><mi>k</mi><mo stretchy="false">)</mo></mrow></msup><mo stretchy="false">)</mo><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\approx W^{(k)} \cdot \text{diag}(\phi&#x27;(\mathbf{z}^{(k)}))</annotation></semantics></math></span>. If the spectral norm <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="normal">∥</mi><mi>W</mi><mi mathvariant="normal">∥</mi><mo>&lt;</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">\|W\| &lt; 1</annotation></semantics></math></span> repeatedly, gradients <strong>vanish</strong> exponentially; if <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="normal">∥</mi><mi>W</mi><mi mathvariant="normal">∥</mi><mo>&gt;</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">\|W\| &gt; 1</annotation></semantics></math></span>, they <strong>explode</strong>.</p>
<ul>
<li><strong>Vanishing</strong>: gradients <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo>→</mo><mn>0</mn></mrow><annotation encoding="application/x-tex">\to 0</annotation></semantics></math></span>, early layers learn nothing. Caused by sigmoid/tanh saturation (<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msup><mi>σ</mi><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mo>≤</mo><mn>0.25</mn></mrow><annotation encoding="application/x-tex">\sigma&#x27; \leq 0.25</annotation></semantics></math></span>) + many layers.</li>
<li><strong>Exploding</strong>: parameter updates become huge, training diverges.</li>
</ul>
<p><strong>Fixes</strong>: ReLU (gradient = 1 in positive region), residual connections, LayerNorm, gradient clipping:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>g</mi><mi>t</mi></msub><mo>←</mo><msub><mi>g</mi><mi>t</mi></msub><mo>⋅</mo><mi>min</mi><mo>⁡</mo><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><mn>1</mn><mo separator="true">,</mo><mtext>  </mtext><mfrac><mi>τ</mi><mrow><mi mathvariant="normal">∥</mi><msub><mi>g</mi><mi>t</mi></msub><mi mathvariant="normal">∥</mi></mrow></mfrac><mo fence="true">)</mo></mrow><mo separator="true">,</mo><mspace width="1em"/><mi>τ</mi><mtext> is the clip threshold</mtext></mrow><annotation encoding="application/x-tex">g_t \leftarrow g_t \cdot \min\!\left(1,\; \frac{\tau}{\|g_t\|}\right), \quad \tau \text{ is the clip threshold}</annotation></semantics></math></span><h3 id="zigzag-in-gradient-descent">Zigzag in Gradient Descent</h3>
<p>Vanilla SGD with a fixed learning rate <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>η</mi></mrow><annotation encoding="application/x-tex">\eta</annotation></semantics></math></span> oscillates (<strong>zigzags</strong>) when the loss surface has different curvatures along different directions — it overshoots in high-curvature directions and undershoots in low-curvature ones:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msubsup><mi>θ</mi><mrow><mi>t</mi><mo>+</mo><mn>1</mn></mrow><mrow><mo stretchy="false">(</mo><mi>i</mi><mo stretchy="false">)</mo></mrow></msubsup><mo>=</mo><msubsup><mi>θ</mi><mi>t</mi><mrow><mo stretchy="false">(</mo><mi>i</mi><mo stretchy="false">)</mo></mrow></msubsup><mo>−</mo><mi>η</mi><mtext> </mtext><mfrac><mrow><mi mathvariant="normal">∂</mi><mi mathvariant="script">L</mi></mrow><mrow><mi mathvariant="normal">∂</mi><msup><mi>θ</mi><mrow><mo stretchy="false">(</mo><mi>i</mi><mo stretchy="false">)</mo></mrow></msup></mrow></mfrac></mrow><annotation encoding="application/x-tex">\theta_{t+1}^{(i)} = \theta_t^{(i)} - \eta\, \frac{\partial \mathcal{L}}{\partial \theta^{(i)}}</annotation></semantics></math></span><p>If <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>η</mi></mrow><annotation encoding="application/x-tex">\eta</annotation></semantics></math></span> is large enough to make progress along the flat direction, it overshoots along the steep direction → zigzag trajectory.</p>
<p><strong>Momentum</strong> damps oscillations by accumulating a velocity vector:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="bold">v</mi><mrow><mi>t</mi><mo>+</mo><mn>1</mn></mrow></msub><mo>=</mo><mi>γ</mi><msub><mi mathvariant="bold">v</mi><mi>t</mi></msub><mo>+</mo><mi>η</mi><msub><mi mathvariant="normal">∇</mi><mi>θ</mi></msub><mi mathvariant="script">L</mi><mo separator="true">,</mo><mspace width="2em"/><msub><mi>θ</mi><mrow><mi>t</mi><mo>+</mo><mn>1</mn></mrow></msub><mo>=</mo><msub><mi>θ</mi><mi>t</mi></msub><mo>−</mo><msub><mi mathvariant="bold">v</mi><mrow><mi>t</mi><mo>+</mo><mn>1</mn></mrow></msub></mrow><annotation encoding="application/x-tex">\mathbf{v}_{t+1} = \gamma \mathbf{v}_t + \eta \nabla_\theta \mathcal{L}, \qquad \theta_{t+1} = \theta_t - \mathbf{v}_{t+1}</annotation></semantics></math></span><p>The exponential moving average of gradients cancels out oscillating components while reinforcing consistent directions. Adam further applies <strong>per-parameter</strong> adaptive learning rates via <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mover accent="true"><mi>v</mi><mo>^</mo></mover><mi>t</mi></msub></mrow><annotation encoding="application/x-tex">\hat{v}_t</annotation></semantics></math></span> (second moment), which is why it often converges faster than plain SGD on non-convex landscapes.</p>
<h3 id="resnet--residual-connections">ResNet — Residual Connections</h3>
<p>Add a <strong>skip connection</strong> that bypasses one or more layers, letting gradients flow directly to earlier layers:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi mathvariant="bold">y</mi><mo>=</mo><mi mathvariant="script">F</mi><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo separator="true">,</mo><mtext> </mtext><mo stretchy="false">{</mo><msub><mi>W</mi><mi>i</mi></msub><mo stretchy="false">}</mo><mo stretchy="false">)</mo><mo>+</mo><mi mathvariant="bold">x</mi></mrow><annotation encoding="application/x-tex">\mathbf{y} = \mathcal{F}(\mathbf{x},\,\{W_i\}) + \mathbf{x}</annotation></semantics></math></span><ul>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="script">F</mi><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathcal{F}(\mathbf{x})</annotation></semantics></math></span>: the residual to learn (e.g. two conv layers)</li>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="bold">x</mi></mrow><annotation encoding="application/x-tex">\mathbf{x}</annotation></semantics></math></span>: identity shortcut</li>
</ul>
<p><strong>Why it works:</strong> the gradient through the skip path is exactly <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mn>1</mn></mrow><annotation encoding="application/x-tex">1</annotation></semantics></math></span> — no matter how deep, the chain rule always has a direct path with gradient <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mfrac><mrow><mi mathvariant="normal">∂</mi><mi mathvariant="bold">y</mi></mrow><mrow><mi mathvariant="normal">∂</mi><mi mathvariant="bold">x</mi></mrow></mfrac><mo>=</mo><mfrac><mrow><mi mathvariant="normal">∂</mi><mi mathvariant="script">F</mi></mrow><mrow><mi mathvariant="normal">∂</mi><mi mathvariant="bold">x</mi></mrow></mfrac><mo>+</mo><mi>I</mi></mrow><annotation encoding="application/x-tex">\frac{\partial \mathbf{y}}{\partial \mathbf{x}} = \frac{\partial \mathcal{F}}{\partial \mathbf{x}} + I</annotation></semantics></math></span>. This prevents vanishing gradients in very deep networks (ResNet-152, Transformers).</p>
<h3 id="cnn">CNN</h3>
<p>2D convolution — kernel <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>K</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>k</mi><mo>×</mo><mi>k</mi></mrow></msup></mrow><annotation encoding="application/x-tex">K \in \mathbb{R}^{k\times k}</annotation></semantics></math></span> slides over image <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>X</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>H</mi><mo>×</mo><mi>W</mi></mrow></msup></mrow><annotation encoding="application/x-tex">X \in \mathbb{R}^{H\times W}</annotation></semantics></math></span>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mo stretchy="false">(</mo><mi>X</mi><mo>∗</mo><mi>K</mi><msub><mo stretchy="false">)</mo><mrow><mi>i</mi><mo separator="true">,</mo><mi>j</mi></mrow></msub><mo>=</mo><munderover><mo>∑</mo><mrow><mi>m</mi><mo>=</mo><mn>0</mn></mrow><mrow><mi>k</mi><mo>−</mo><mn>1</mn></mrow></munderover><munderover><mo>∑</mo><mrow><mi>n</mi><mo>=</mo><mn>0</mn></mrow><mrow><mi>k</mi><mo>−</mo><mn>1</mn></mrow></munderover><msub><mi>K</mi><mrow><mi>m</mi><mo separator="true">,</mo><mi>n</mi></mrow></msub><mo>⋅</mo><msub><mi>X</mi><mrow><mi>i</mi><mo>+</mo><mi>m</mi><mo separator="true">,</mo><mtext> </mtext><mi>j</mi><mo>+</mo><mi>n</mi></mrow></msub></mrow><annotation encoding="application/x-tex">(X * K)_{i,j} = \sum_{m=0}^{k-1}\sum_{n=0}^{k-1} K_{m,n} \cdot X_{i+m,\,j+n}</annotation></semantics></math></span><p>Each layer applies <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>C</mi><mtext>out</mtext></msub></mrow><annotation encoding="application/x-tex">C_{\text{out}}</annotation></semantics></math></span> kernels → feature map <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><msub><mi>C</mi><mtext>out</mtext></msub><mo>×</mo><msup><mi>H</mi><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mo>×</mo><msup><mi>W</mi><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup></mrow></msup></mrow><annotation encoding="application/x-tex">\in \mathbb{R}^{C_{\text{out}}\times H&#x27;\times W&#x27;}</annotation></semantics></math></span>.</p>
<p><strong>Pooling</strong> — downsample spatial dimensions to reduce computation and add translation invariance:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>MaxPool</mtext><mo stretchy="false">(</mo><mi>X</mi><msub><mo stretchy="false">)</mo><mrow><mi>i</mi><mo separator="true">,</mo><mi>j</mi></mrow></msub><mo>=</mo><munder><mrow><mi>max</mi><mo>⁡</mo></mrow><mrow><mo stretchy="false">(</mo><mi>m</mi><mo separator="true">,</mo><mi>n</mi><mo stretchy="false">)</mo><mo>∈</mo><mtext>window</mtext></mrow></munder><msub><mi>X</mi><mrow><mi>i</mi><mo>⋅</mo><mi>s</mi><mo>+</mo><mi>m</mi><mo separator="true">,</mo><mtext> </mtext><mi>j</mi><mo>⋅</mo><mi>s</mi><mo>+</mo><mi>n</mi></mrow></msub></mrow><annotation encoding="application/x-tex">\text{MaxPool}(X)_{i,j} = \max_{(m,n)\in\text{window}} X_{i\cdot s+m,\,j\cdot s+n}</annotation></semantics></math></span><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>AvgPool</mtext><mo stretchy="false">(</mo><mi>X</mi><msub><mo stretchy="false">)</mo><mrow><mi>i</mi><mo separator="true">,</mo><mi>j</mi></mrow></msub><mo>=</mo><mfrac><mn>1</mn><msup><mi>k</mi><mn>2</mn></msup></mfrac><munder><mo>∑</mo><mrow><mo stretchy="false">(</mo><mi>m</mi><mo separator="true">,</mo><mi>n</mi><mo stretchy="false">)</mo><mo>∈</mo><mtext>window</mtext></mrow></munder><msub><mi>X</mi><mrow><mi>i</mi><mo>⋅</mo><mi>s</mi><mo>+</mo><mi>m</mi><mo separator="true">,</mo><mtext> </mtext><mi>j</mi><mo>⋅</mo><mi>s</mi><mo>+</mo><mi>n</mi></mrow></msub></mrow><annotation encoding="application/x-tex">\text{AvgPool}(X)_{i,j} = \frac{1}{k^2}\sum_{(m,n)\in\text{window}} X_{i\cdot s+m,\,j\cdot s+n}</annotation></semantics></math></span><p>where <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>k</mi></mrow><annotation encoding="application/x-tex">k</annotation></semantics></math></span> is the pool size and <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>s</mi></mrow><annotation encoding="application/x-tex">s</annotation></semantics></math></span> is the stride.</p>
<h3 id="rnn">RNN</h3>
<p><strong>Vanilla RNN</strong> — hidden state recurrence:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="bold">h</mi><mi>t</mi></msub><mo>=</mo><mi>tanh</mi><mo>⁡</mo><mo stretchy="false">(</mo><msub><mi>W</mi><mi>h</mi></msub><msub><mi mathvariant="bold">h</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><mo>+</mo><msub><mi>W</mi><mi>x</mi></msub><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo>+</mo><mi mathvariant="bold">b</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathbf{h}_t = \tanh(W_h \mathbf{h}_{t-1} + W_x \mathbf{x}_t + \mathbf{b})</annotation></semantics></math></span><p><strong>LSTM</strong> — gated memory cell <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">(</mo><mi>i</mi><mo separator="true">,</mo><mi>f</mi><mo separator="true">,</mo><mi>o</mi></mrow><annotation encoding="application/x-tex">(i,f,o</annotation></semantics></math></span>: input/forget/output gates<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">)</annotation></semantics></math></span>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="bold">f</mi><mi>t</mi></msub><mo>=</mo><mi>σ</mi><mo stretchy="false">(</mo><msub><mi>W</mi><mi>f</mi></msub><mo stretchy="false">[</mo><msub><mi mathvariant="bold">h</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><mo separator="true">;</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo stretchy="false">]</mo><mo>+</mo><msub><mi mathvariant="bold">b</mi><mi>f</mi></msub><mo stretchy="false">)</mo><mo separator="true">,</mo><mspace width="1em"/><msub><mi mathvariant="bold">i</mi><mi>t</mi></msub><mo>=</mo><mi>σ</mi><mo stretchy="false">(</mo><msub><mi>W</mi><mi>i</mi></msub><mo stretchy="false">[</mo><msub><mi mathvariant="bold">h</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><mo separator="true">;</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo stretchy="false">]</mo><mo>+</mo><msub><mi mathvariant="bold">b</mi><mi>i</mi></msub><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathbf{f}_t = \sigma(W_f[\mathbf{h}_{t-1};\mathbf{x}_t]+\mathbf{b}_f), \quad \mathbf{i}_t = \sigma(W_i[\mathbf{h}_{t-1};\mathbf{x}_t]+\mathbf{b}_i)</annotation></semantics></math></span><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="bold">c</mi><mi>t</mi></msub><mo>=</mo><msub><mi mathvariant="bold">f</mi><mi>t</mi></msub><mo>⊙</mo><msub><mi mathvariant="bold">c</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><mo>+</mo><msub><mi mathvariant="bold">i</mi><mi>t</mi></msub><mo>⊙</mo><mi>tanh</mi><mo>⁡</mo><mo stretchy="false">(</mo><msub><mi>W</mi><mi>c</mi></msub><mo stretchy="false">[</mo><msub><mi mathvariant="bold">h</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><mo separator="true">;</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo stretchy="false">]</mo><mo>+</mo><msub><mi mathvariant="bold">b</mi><mi>c</mi></msub><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tanh(W_c[\mathbf{h}_{t-1};\mathbf{x}_t]+\mathbf{b}_c)</annotation></semantics></math></span><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="bold">o</mi><mi>t</mi></msub><mo>=</mo><mi>σ</mi><mo stretchy="false">(</mo><msub><mi>W</mi><mi>o</mi></msub><mo stretchy="false">[</mo><msub><mi mathvariant="bold">h</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><mo separator="true">;</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo stretchy="false">]</mo><mo>+</mo><msub><mi mathvariant="bold">b</mi><mi>o</mi></msub><mo stretchy="false">)</mo><mo separator="true">,</mo><mspace width="1em"/><msub><mi mathvariant="bold">h</mi><mi>t</mi></msub><mo>=</mo><msub><mi mathvariant="bold">o</mi><mi>t</mi></msub><mo>⊙</mo><mi>tanh</mi><mo>⁡</mo><mo stretchy="false">(</mo><msub><mi mathvariant="bold">c</mi><mi>t</mi></msub><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathbf{o}_t = \sigma(W_o[\mathbf{h}_{t-1};\mathbf{x}_t]+\mathbf{b}_o), \quad \mathbf{h}_t = \mathbf{o}_t \odot \tanh(\mathbf{c}_t)</annotation></semantics></math></span><p><strong>GRU</strong> — simplified gating (reset <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="bold">r</mi><mi>t</mi></msub></mrow><annotation encoding="application/x-tex">\mathbf{r}_t</annotation></semantics></math></span>, update <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="bold">z</mi><mi>t</mi></msub></mrow><annotation encoding="application/x-tex">\mathbf{z}_t</annotation></semantics></math></span>):</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="bold">z</mi><mi>t</mi></msub><mo>=</mo><mi>σ</mi><mo stretchy="false">(</mo><msub><mi>W</mi><mi>z</mi></msub><mo stretchy="false">[</mo><msub><mi mathvariant="bold">h</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><mo separator="true">;</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo stretchy="false">]</mo><mo stretchy="false">)</mo><mo separator="true">,</mo><mspace width="1em"/><msub><mi mathvariant="bold">r</mi><mi>t</mi></msub><mo>=</mo><mi>σ</mi><mo stretchy="false">(</mo><msub><mi>W</mi><mi>r</mi></msub><mo stretchy="false">[</mo><msub><mi mathvariant="bold">h</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><mo separator="true">;</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo stretchy="false">]</mo><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathbf{z}_t = \sigma(W_z[\mathbf{h}_{t-1};\mathbf{x}_t]), \quad \mathbf{r}_t = \sigma(W_r[\mathbf{h}_{t-1};\mathbf{x}_t])</annotation></semantics></math></span><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="bold">h</mi><mi>t</mi></msub><mo>=</mo><mo stretchy="false">(</mo><mn>1</mn><mo>−</mo><msub><mi mathvariant="bold">z</mi><mi>t</mi></msub><mo stretchy="false">)</mo><mo>⊙</mo><msub><mi mathvariant="bold">h</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><mo>+</mo><msub><mi mathvariant="bold">z</mi><mi>t</mi></msub><mo>⊙</mo><mi>tanh</mi><mo>⁡</mo><mo stretchy="false">(</mo><msub><mi>W</mi><mi>h</mi></msub><mo stretchy="false">[</mo><msub><mi mathvariant="bold">r</mi><mi>t</mi></msub><mo>⊙</mo><msub><mi mathvariant="bold">h</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><mo separator="true">;</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo stretchy="false">]</mo><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathbf{h}_t = (1-\mathbf{z}_t)\odot\mathbf{h}_{t-1} + \mathbf{z}_t\odot\tanh(W_h[\mathbf{r}_t\odot\mathbf{h}_{t-1};\mathbf{x}_t])</annotation></semantics></math></span><h3 id="attention">Attention</h3>
<p><strong>Scaled Dot-Product Attention</strong> — <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>Q</mi><mo separator="true">,</mo><mi>K</mi><mo separator="true">,</mo><mi>V</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>n</mi><mo>×</mo><msub><mi>d</mi><mi>k</mi></msub></mrow></msup></mrow><annotation encoding="application/x-tex">Q,K,V \in \mathbb{R}^{n\times d_k}</annotation></semantics></math></span>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>Attention</mtext><mo stretchy="false">(</mo><mi>Q</mi><mo separator="true">,</mo><mi>K</mi><mo separator="true">,</mo><mi>V</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>softmax</mtext><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><mfrac><mrow><mi>Q</mi><msup><mi>K</mi><mi mathvariant="normal">⊤</mi></msup></mrow><msqrt><msub><mi>d</mi><mi>k</mi></msub></msqrt></mfrac><mo fence="true">)</mo></mrow><mi>V</mi></mrow><annotation encoding="application/x-tex">\text{Attention}(Q,K,V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V</annotation></semantics></math></span><p><strong>Multi-Head Attention</strong> — <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>h</mi></mrow><annotation encoding="application/x-tex">h</annotation></semantics></math></span> parallel heads, then project:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mtext>head</mtext><mi>i</mi></msub><mo>=</mo><mtext>Attention</mtext><mo stretchy="false">(</mo><mi>Q</mi><msubsup><mi>W</mi><mi>i</mi><mi>Q</mi></msubsup><mo separator="true">,</mo><mtext> </mtext><mi>K</mi><msubsup><mi>W</mi><mi>i</mi><mi>K</mi></msubsup><mo separator="true">,</mo><mtext> </mtext><mi>V</mi><msubsup><mi>W</mi><mi>i</mi><mi>V</mi></msubsup><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\text{head}_i = \text{Attention}(QW_i^Q,\,KW_i^K,\,VW_i^V)</annotation></semantics></math></span><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>MultiHead</mtext><mo stretchy="false">(</mo><mi>Q</mi><mo separator="true">,</mo><mi>K</mi><mo separator="true">,</mo><mi>V</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>Concat</mtext><mo stretchy="false">(</mo><msub><mtext>head</mtext><mn>1</mn></msub><mo separator="true">,</mo><mo>…</mo><mo separator="true">,</mo><msub><mtext>head</mtext><mi>h</mi></msub><mo stretchy="false">)</mo><mtext> </mtext><msup><mi>W</mi><mi>O</mi></msup></mrow><annotation encoding="application/x-tex">\text{MultiHead}(Q,K,V) = \text{Concat}(\text{head}_1,\ldots,\text{head}_h)\,W^O</annotation></semantics></math></span><p><strong>Positional Encoding</strong> (sinusoidal):</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mtext>PE</mtext><mrow><mo stretchy="false">(</mo><mi>p</mi><mi>o</mi><mi>s</mi><mo separator="true">,</mo><mn>2</mn><mi>i</mi><mo stretchy="false">)</mo></mrow></msub><mo>=</mo><mi>sin</mi><mo>⁡</mo><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><mfrac><mrow><mi>p</mi><mi>o</mi><mi>s</mi></mrow><msup><mn>10000</mn><mrow><mn>2</mn><mi>i</mi><mi mathvariant="normal">/</mi><mi>d</mi></mrow></msup></mfrac><mo fence="true">)</mo></mrow><mo separator="true">,</mo><mspace width="1em"/><msub><mtext>PE</mtext><mrow><mo stretchy="false">(</mo><mi>p</mi><mi>o</mi><mi>s</mi><mo separator="true">,</mo><mn>2</mn><mi>i</mi><mo>+</mo><mn>1</mn><mo stretchy="false">)</mo></mrow></msub><mo>=</mo><mi>cos</mi><mo>⁡</mo><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><mfrac><mrow><mi>p</mi><mi>o</mi><mi>s</mi></mrow><msup><mn>10000</mn><mrow><mn>2</mn><mi>i</mi><mi mathvariant="normal">/</mi><mi>d</mi></mrow></msup></mfrac><mo fence="true">)</mo></mrow></mrow><annotation encoding="application/x-tex">\text{PE}_{(pos,2i)} = \sin\!\left(\frac{pos}{10000^{2i/d}}\right), \quad \text{PE}_{(pos,2i+1)} = \cos\!\left(\frac{pos}{10000^{2i/d}}\right)</annotation></semantics></math></span><p><strong>Transformer block</strong> (with residual + LayerNorm):</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msup><mi mathvariant="bold">h</mi><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mo>=</mo><mtext>LayerNorm</mtext><mo stretchy="false">(</mo><mi mathvariant="bold">h</mi><mo>+</mo><mtext>MultiHead</mtext><mo stretchy="false">(</mo><mi mathvariant="bold">h</mi><mo separator="true">,</mo><mi mathvariant="bold">h</mi><mo separator="true">,</mo><mi mathvariant="bold">h</mi><mo stretchy="false">)</mo><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathbf{h}&#x27; = \text{LayerNorm}(\mathbf{h} + \text{MultiHead}(\mathbf{h},\mathbf{h},\mathbf{h}))</annotation></semantics></math></span><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msup><mi mathvariant="bold">h</mi><mrow><mo mathvariant="normal">′</mo><mo mathvariant="normal">′</mo></mrow></msup><mo>=</mo><mtext>LayerNorm</mtext><mo stretchy="false">(</mo><msup><mi mathvariant="bold">h</mi><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mo>+</mo><mtext>FFN</mtext><mo stretchy="false">(</mo><msup><mi mathvariant="bold">h</mi><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mo stretchy="false">)</mo><mo stretchy="false">)</mo><mo separator="true">,</mo><mspace width="1em"/><mtext>FFN</mtext><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mo>=</mo><msub><mi>W</mi><mn>2</mn></msub><mtext> </mtext><mtext>ReLU</mtext><mo stretchy="false">(</mo><msub><mi>W</mi><mn>1</mn></msub><mi mathvariant="bold">x</mi><mo>+</mo><msub><mi mathvariant="bold">b</mi><mn>1</mn></msub><mo stretchy="false">)</mo><mo>+</mo><msub><mi mathvariant="bold">b</mi><mn>2</mn></msub></mrow><annotation encoding="application/x-tex">\mathbf{h}&#x27;&#x27; = \text{LayerNorm}(\mathbf{h}&#x27; + \text{FFN}(\mathbf{h}&#x27;)), \quad \text{FFN}(\mathbf{x})=W_2\,\text{ReLU}(W_1\mathbf{x}+\mathbf{b}_1)+\mathbf{b}_2</annotation></semantics></math></span><p><strong>Language Modelling Objective</strong> — minimise the negative log-likelihood of the token sequence:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi mathvariant="script">L</mi><mo>=</mo><mo>−</mo><mfrac><mn>1</mn><mi>T</mi></mfrac><munderover><mo>∑</mo><mrow><mi>t</mi><mo>=</mo><mn>1</mn></mrow><mi>T</mi></munderover><mi>log</mi><mo>⁡</mo><msub><mi>P</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi>t</mi><mi>t</mi></msub><mo>∣</mo><msub><mi>t</mi><mrow><mo>&lt;</mo><mi>t</mi></mrow></msub><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathcal{L} = -\frac{1}{T}\sum_{t=1}^T \log P_\theta(t_t \mid t_{\lt t})</annotation></semantics></math></span><p><strong>ViT</strong> — split image into <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>N</mi></mrow><annotation encoding="application/x-tex">N</annotation></semantics></math></span> patches <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="bold">p</mi><mi>i</mi></msub><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><msup><mi>P</mi><mn>2</mn></msup><mi>C</mi></mrow></msup></mrow><annotation encoding="application/x-tex">\mathbf{p}_i \in \mathbb{R}^{P^2 C}</annotation></semantics></math></span>, linearly project to token embeddings, then apply Transformer encoder:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="bold">z</mi><mn>0</mn></msub><mo>=</mo><mo stretchy="false">[</mo><msub><mi mathvariant="bold">x</mi><mtext>cls</mtext></msub><mo separator="true">;</mo><mtext> </mtext><mi>E</mi><msub><mi mathvariant="bold">p</mi><mn>1</mn></msub><mo separator="true">;</mo><mtext> </mtext><mo>…</mo><mo separator="true">;</mo><mtext> </mtext><mi>E</mi><msub><mi mathvariant="bold">p</mi><mi>N</mi></msub><mo stretchy="false">]</mo><mo>+</mo><msub><mi mathvariant="bold">E</mi><mtext>pos</mtext></msub></mrow><annotation encoding="application/x-tex">\mathbf{z}_0 = [\mathbf{x}_{\text{cls}};\, E\mathbf{p}_1;\,\ldots;\,E\mathbf{p}_N] + \mathbf{E}_{\text{pos}}</annotation></semantics></math></span><p><strong>Encoder-Decoder Transformer</strong> (original seq2seq, e.g. T5, BART) — encoder processes source sequence bidirectionally; decoder generates target tokens autoregressively with <strong>cross-attention</strong> over encoder outputs:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msubsup><mtext>head</mtext><mi>i</mi><mtext>cross</mtext></msubsup><mo>=</mo><mtext>Attention</mtext><mo stretchy="false">(</mo><msub><mi>Q</mi><mtext>dec</mtext></msub><mtext> </mtext><msubsup><mi>W</mi><mi>i</mi><mi>Q</mi></msubsup><mo separator="true">,</mo><mtext>  </mtext><msub><mi>K</mi><mtext>enc</mtext></msub><mtext> </mtext><msubsup><mi>W</mi><mi>i</mi><mi>K</mi></msubsup><mo separator="true">,</mo><mtext>  </mtext><msub><mi>V</mi><mtext>enc</mtext></msub><mtext> </mtext><msubsup><mi>W</mi><mi>i</mi><mi>V</mi></msubsup><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\text{head}_i^{\text{cross}} = \text{Attention}(Q_{\text{dec}}\,W_i^Q,\; K_{\text{enc}}\,W_i^K,\; V_{\text{enc}}\,W_i^V)</annotation></semantics></math></span><p>Decoder block = (causal self-attention) → (cross-attention to encoder) → (FFN), each with residual + LayerNorm.</p>
<h3 id="bert--bidirectional-encoder">BERT — Bidirectional Encoder</h3>
<p>BERT uses the <strong>encoder-only</strong> Transformer and pre-trains on two objectives:</p>
<p><strong>1. Masked Language Model (MLM)</strong> — randomly mask 15 % of tokens, predict them from full bidirectional context:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="script">L</mi><mtext>MLM</mtext></msub><mo>=</mo><mo>−</mo><munder><mo>∑</mo><mrow><mi>i</mi><mo>∈</mo><mi mathvariant="script">M</mi></mrow></munder><mi>log</mi><mo>⁡</mo><msub><mi>P</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi>t</mi><mi>i</mi></msub><mo>∣</mo><msub><mi mathvariant="bold">t</mi><mrow><mi mathvariant="normal">\</mi><mi mathvariant="script">M</mi></mrow></msub><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathcal{L}_{\text{MLM}} = -\sum_{i \in \mathcal{M}} \log P_\theta(t_i \mid \mathbf{t}_{\backslash \mathcal{M}})</annotation></semantics></math></span><ul>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="script">M</mi></mrow><annotation encoding="application/x-tex">\mathcal{M}</annotation></semantics></math></span>: set of masked positions</li>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="bold">t</mi><mrow><mi mathvariant="normal">\</mi><mi mathvariant="script">M</mi></mrow></msub></mrow><annotation encoding="application/x-tex">\mathbf{t}_{\backslash \mathcal{M}}</annotation></semantics></math></span>: all tokens except the masked ones</li>
</ul>
<p>Because attention is <strong>bidirectional</strong> (no causal mask), every token can attend to every other token — unlike GPT which only sees past context.</p>
<p><strong>2. Next Sentence Prediction (NSP)</strong> — binary classification: does sentence B follow sentence A?</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="script">L</mi><mtext>NSP</mtext></msub><mo>=</mo><mo>−</mo><mi>log</mi><mo>⁡</mo><msub><mi>P</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><mtext>IsNext</mtext><mo>∣</mo><mo stretchy="false">[</mo><mtext>CLS</mtext><mo stretchy="false">]</mo><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathcal{L}_{\text{NSP}} = -\log P_\theta(\text{IsNext} \mid [\text{CLS}])</annotation></semantics></math></span><p><strong>GPT vs BERT comparison:</strong></p>
<table>
  <thead>
      <tr>
          <th></th>
          <th>GPT (decoder-only)</th>
          <th>BERT (encoder-only)</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>Attention</td>
          <td>Causal (left-to-right)</td>
          <td>Bidirectional (full)</td>
      </tr>
      <tr>
          <td>Pre-training</td>
          <td>Next-token prediction</td>
          <td>MLM + NSP</td>
      </tr>
      <tr>
          <td>Strength</td>
          <td>Generation</td>
          <td>Understanding / Classification</td>
      </tr>
      <tr>
          <td>Representation</td>
          <td><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="bold">h</mi><mi>i</mi></msub></mrow><annotation encoding="application/x-tex">\mathbf{h}_i</annotation></semantics></math></span> sees only <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>t</mi><mn>1</mn></msub><mo separator="true">,</mo><mo>…</mo><mo separator="true">,</mo><msub><mi>t</mi><mi>i</mi></msub></mrow><annotation encoding="application/x-tex">t_1,\ldots,t_i</annotation></semantics></math></span></td>
          <td><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="bold">h</mi><mi>i</mi></msub></mrow><annotation encoding="application/x-tex">\mathbf{h}_i</annotation></semantics></math></span> sees all tokens</td>
      </tr>
  </tbody>
</table>
<h3 id="transfer-learning">Transfer Learning</h3>
<p>Pre-train on large corpus <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="script">D</mi><mtext>pre</mtext></msub></mrow><annotation encoding="application/x-tex">\mathcal{D}_{\text{pre}}</annotation></semantics></math></span> to get <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msup><mi>θ</mi><mo>∗</mo></msup></mrow><annotation encoding="application/x-tex">\theta^*</annotation></semantics></math></span>, then fine-tune on target task <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="script">D</mi><mtext>ft</mtext></msub></mrow><annotation encoding="application/x-tex">\mathcal{D}_{\text{ft}}</annotation></semantics></math></span>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>θ</mi><mtext>ft</mtext></msub><mo>=</mo><mi>arg</mi><mo>⁡</mo><munder><mrow><mi>min</mi><mo>⁡</mo></mrow><mi>θ</mi></munder><msub><mi mathvariant="script">L</mi><mtext>ft</mtext></msub><mo stretchy="false">(</mo><mi>θ</mi><mo separator="true">;</mo><mtext> </mtext><msub><mi mathvariant="script">D</mi><mtext>ft</mtext></msub><mo stretchy="false">)</mo><mo separator="true">,</mo><mspace width="1em"/><mi>θ</mi><mo>←</mo><msup><mi>θ</mi><mo>∗</mo></msup><mtext> (initialised)</mtext></mrow><annotation encoding="application/x-tex">\theta_{\text{ft}} = \arg\min_\theta \mathcal{L}_{\text{ft}}(\theta;\,\mathcal{D}_{\text{ft}}), \quad \theta \leftarrow \theta^* \text{ (initialised)}</annotation></semantics></math></span><p><strong>LoRA</strong> — freeze <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>W</mi><mn>0</mn></msub></mrow><annotation encoding="application/x-tex">W_0</annotation></semantics></math></span>, inject low-rank update <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="normal">Δ</mi><mi>W</mi><mo>=</mo><mi>B</mi><mi>A</mi></mrow><annotation encoding="application/x-tex">\Delta W = BA</annotation></semantics></math></span> (<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>B</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>d</mi><mo>×</mo><mi>r</mi></mrow></msup><mo separator="true">,</mo><mtext> </mtext><mi>A</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>r</mi><mo>×</mo><mi>k</mi></mrow></msup><mo separator="true">,</mo><mtext> </mtext><mi>r</mi><mo>≪</mo><mi>min</mi><mo>⁡</mo><mo stretchy="false">(</mo><mi>d</mi><mo separator="true">,</mo><mi>k</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">B\in\mathbb{R}^{d\times r},\,A\in\mathbb{R}^{r\times k},\,r\ll\min(d,k)</annotation></semantics></math></span>):</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>W</mi><mo>=</mo><msub><mi>W</mi><mn>0</mn></msub><mo>+</mo><mi mathvariant="normal">Δ</mi><mi>W</mi><mo>=</mo><msub><mi>W</mi><mn>0</mn></msub><mo>+</mo><mi>B</mi><mi>A</mi></mrow><annotation encoding="application/x-tex">W = W_0 + \Delta W = W_0 + BA</annotation></semantics></math></span><hr>
<h2 id="generative-ai">Generative AI</h2>
<p>Generative models learn the data distribution <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">p(\mathbf{x})</annotation></semantics></math></span> and can <strong>sample new data</strong> from it.</p>
<p>The core distinction from discriminative models:</p>
<table>
  <thead>
      <tr>
          <th></th>
          <th>Discriminative</th>
          <th>Generative</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><strong>Goal</strong></td>
          <td><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi><mo stretchy="false">(</mo><mi>y</mi><mi mathvariant="normal">∥</mi><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">p(y\|\mathbf{x})</annotation></semantics></math></span></td>
          <td><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">p(\mathbf{x})</annotation></semantics></math></span> or <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo separator="true">,</mo><mi>y</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">p(\mathbf{x},y)</annotation></semantics></math></span></td>
      </tr>
      <tr>
          <td><strong>Output</strong></td>
          <td>Label / decision</td>
          <td>New data sample</td>
      </tr>
      <tr>
          <td><strong>Examples</strong></td>
          <td>Classifier, Regression</td>
          <td>VAE, GAN, Diffusion, LLM</td>
      </tr>
  </tbody>
</table>
<h3 id="variational-autoencoder-vae">Variational Autoencoder (VAE)</h3>
<p>Encode data <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="bold">x</mi></mrow><annotation encoding="application/x-tex">\mathbf{x}</annotation></semantics></math></span> into a latent variable <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="bold">z</mi></mrow><annotation encoding="application/x-tex">\mathbf{z}</annotation></semantics></math></span>, then decode back.</p>
<p><strong>Encoder</strong> — approximate posterior <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>q</mi><mi>ϕ</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">z</mi><mi mathvariant="normal">∣</mi><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mo>≈</mo><mi>p</mi><mo stretchy="false">(</mo><mi mathvariant="bold">z</mi><mi mathvariant="normal">∣</mi><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">q_\phi(\mathbf{z}|\mathbf{x}) \approx p(\mathbf{z}|\mathbf{x})</annotation></semantics></math></span>, parameterised as Gaussian:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>q</mi><mi>ϕ</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">z</mi><mi mathvariant="normal">∣</mi><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mo>=</mo><mi mathvariant="script">N</mi><mo stretchy="false">(</mo><mi mathvariant="bold">z</mi><mo separator="true">;</mo><mtext> </mtext><msub><mi mathvariant="bold-italic">μ</mi><mi>ϕ</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mo separator="true">,</mo><mtext> </mtext><mtext>diag</mtext><mo stretchy="false">(</mo><msubsup><mi mathvariant="bold-italic">σ</mi><mi>ϕ</mi><mn>2</mn></msubsup><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mo stretchy="false">)</mo><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">q_\phi(\mathbf{z}|\mathbf{x}) = \mathcal{N}(\mathbf{z};\,\boldsymbol{\mu}_\phi(\mathbf{x}),\,\text{diag}(\boldsymbol{\sigma}^2_\phi(\mathbf{x})))</annotation></semantics></math></span><p><strong>Decoder</strong> — likelihood <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>p</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mi mathvariant="normal">∣</mi><mi mathvariant="bold">z</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">p_\theta(\mathbf{x}|\mathbf{z})</annotation></semantics></math></span>.</p>
<p><strong>ELBO objective</strong> (Evidence Lower Bound, maximise):</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="script">L</mi><mtext>VAE</mtext></msub><mo stretchy="false">(</mo><mi>θ</mi><mo separator="true">,</mo><mi>ϕ</mi><mo stretchy="false">)</mo><mo>=</mo><msub><mi mathvariant="double-struck">E</mi><mrow><msub><mi>q</mi><mi>ϕ</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">z</mi><mi mathvariant="normal">∣</mi><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo></mrow></msub><mtext> ⁣</mtext><mrow><mo fence="true">[</mo><mi>log</mi><mo>⁡</mo><msub><mi>p</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mi mathvariant="normal">∣</mi><mi mathvariant="bold">z</mi><mo stretchy="false">)</mo><mo fence="true">]</mo></mrow><mo>−</mo><msub><mi>D</mi><mtext>KL</mtext></msub><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><msub><mi>q</mi><mi>ϕ</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">z</mi><mi mathvariant="normal">∣</mi><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mtext>  </mtext><mi mathvariant="normal">∥</mi><mtext>  </mtext><mi>p</mi><mo stretchy="false">(</mo><mi mathvariant="bold">z</mi><mo stretchy="false">)</mo><mo fence="true">)</mo></mrow></mrow><annotation encoding="application/x-tex">\mathcal{L}_{\text{VAE}}(\theta,\phi) = \mathbb{E}_{q_\phi(\mathbf{z}|\mathbf{x})}\!\left[\log p_\theta(\mathbf{x}|\mathbf{z})\right] - D_{\text{KL}}\!\left(q_\phi(\mathbf{z}|\mathbf{x})\;\|\;p(\mathbf{z})\right)</annotation></semantics></math></span><p><strong>KL divergence</strong> between two Gaussians:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>D</mi><mtext>KL</mtext></msub><mo stretchy="false">(</mo><mi mathvariant="script">N</mi><mo stretchy="false">(</mo><mi mathvariant="bold-italic">μ</mi><mo separator="true">,</mo><msup><mi mathvariant="bold-italic">σ</mi><mn>2</mn></msup><mo stretchy="false">)</mo><mtext>  </mtext><mi mathvariant="normal">∥</mi><mtext>  </mtext><mi mathvariant="script">N</mi><mo stretchy="false">(</mo><mn mathvariant="bold">0</mn><mo separator="true">,</mo><mi>I</mi><mo stretchy="false">)</mo><mo stretchy="false">)</mo><mo>=</mo><mfrac><mn>1</mn><mn>2</mn></mfrac><munder><mo>∑</mo><mi>j</mi></munder><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><msubsup><mi>σ</mi><mi>j</mi><mn>2</mn></msubsup><mo>+</mo><msubsup><mi>μ</mi><mi>j</mi><mn>2</mn></msubsup><mo>−</mo><mn>1</mn><mo>−</mo><mi>log</mi><mo>⁡</mo><msubsup><mi>σ</mi><mi>j</mi><mn>2</mn></msubsup><mo fence="true">)</mo></mrow></mrow><annotation encoding="application/x-tex">D_{\text{KL}}(\mathcal{N}(\boldsymbol{\mu},\boldsymbol{\sigma}^2)\;\|\;\mathcal{N}(\mathbf{0},I)) = \frac{1}{2}\sum_j\!\left(\sigma_j^2 + \mu_j^2 - 1 - \log\sigma_j^2\right)</annotation></semantics></math></span><p><strong>Reparameterisation trick</strong> — make sampling differentiable:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi mathvariant="bold">z</mi><mo>=</mo><msub><mi mathvariant="bold-italic">μ</mi><mi>ϕ</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mo>+</mo><msub><mi mathvariant="bold-italic">σ</mi><mi>ϕ</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mo>⊙</mo><mi mathvariant="bold-italic">ϵ</mi><mo separator="true">,</mo><mspace width="2em"/><mi mathvariant="bold-italic">ϵ</mi><mo>∼</mo><mi mathvariant="script">N</mi><mo stretchy="false">(</mo><mn mathvariant="bold">0</mn><mo separator="true">,</mo><mi>I</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathbf{z} = \boldsymbol{\mu}_\phi(\mathbf{x}) + \boldsymbol{\sigma}_\phi(\mathbf{x}) \odot \boldsymbol{\epsilon}, \qquad \boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, I)</annotation></semantics></math></span><hr>
<h3 id="generative-adversarial-network-gan">Generative Adversarial Network (GAN)</h3>
<p>Two networks compete: <strong>Generator</strong> <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>G</mi><mi>θ</mi></msub></mrow><annotation encoding="application/x-tex">G_\theta</annotation></semantics></math></span> tries to fool <strong>Discriminator</strong> <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>D</mi><mi>ϕ</mi></msub></mrow><annotation encoding="application/x-tex">D_\phi</annotation></semantics></math></span>.</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><munder><mrow><mi>min</mi><mo>⁡</mo></mrow><mi>θ</mi></munder><munder><mrow><mi>max</mi><mo>⁡</mo></mrow><mi>ϕ</mi></munder><mtext>  </mtext><msub><mi mathvariant="double-struck">E</mi><mrow><mi mathvariant="bold">x</mi><mo>∼</mo><msub><mi>p</mi><mtext>data</mtext></msub></mrow></msub><mtext> ⁣</mtext><mrow><mo fence="true">[</mo><mi>log</mi><mo>⁡</mo><msub><mi>D</mi><mi>ϕ</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mo fence="true">]</mo></mrow><mo>+</mo><msub><mi mathvariant="double-struck">E</mi><mrow><mi mathvariant="bold">z</mi><mo>∼</mo><mi>p</mi><mo stretchy="false">(</mo><mi mathvariant="bold">z</mi><mo stretchy="false">)</mo></mrow></msub><mtext> ⁣</mtext><mrow><mo fence="true">[</mo><mi>log</mi><mo>⁡</mo><mo stretchy="false">(</mo><mn>1</mn><mo>−</mo><msub><mi>D</mi><mi>ϕ</mi></msub><mo stretchy="false">(</mo><msub><mi>G</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">z</mi><mo stretchy="false">)</mo><mo stretchy="false">)</mo><mo stretchy="false">)</mo><mo fence="true">]</mo></mrow></mrow><annotation encoding="application/x-tex">\min_\theta \max_\phi\; \mathbb{E}_{\mathbf{x}\sim p_{\text{data}}}\!\left[\log D_\phi(\mathbf{x})\right] + \mathbb{E}_{\mathbf{z}\sim p(\mathbf{z})}\!\left[\log(1 - D_\phi(G_\theta(\mathbf{z})))\right]</annotation></semantics></math></span><ul>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>G</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">z</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">G_\theta(\mathbf{z})</annotation></semantics></math></span>: maps noise <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="bold">z</mi><mo>∼</mo><mi mathvariant="script">N</mi><mo stretchy="false">(</mo><mn mathvariant="bold">0</mn><mo separator="true">,</mo><mi>I</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathbf{z}\sim\mathcal{N}(\mathbf{0},I)</annotation></semantics></math></span> to fake samples.</li>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>D</mi><mi>ϕ</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mo>∈</mo><mo stretchy="false">(</mo><mn>0</mn><mo separator="true">,</mo><mn>1</mn><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">D_\phi(\mathbf{x})\in(0,1)</annotation></semantics></math></span>: probability that <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="bold">x</mi></mrow><annotation encoding="application/x-tex">\mathbf{x}</annotation></semantics></math></span> is real.</li>
<li>At equilibrium: <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>D</mi><mi>ϕ</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mn>1</mn><mn>2</mn></mfrac></mrow><annotation encoding="application/x-tex">D_\phi(\mathbf{x}) = \tfrac{1}{2}</annotation></semantics></math></span> everywhere — generator perfectly mimics data.</li>
</ul>
<hr>
<h3 id="diffusion-models-ddpm">Diffusion Models (DDPM)</h3>
<p>Gradually add Gaussian noise over <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>T</mi></mrow><annotation encoding="application/x-tex">T</annotation></semantics></math></span> steps (<strong>forward process</strong>), then learn to reverse it (<strong>reverse process</strong>).</p>
<p><strong>Forward process</strong> — fixed Markov chain:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>q</mi><mo stretchy="false">(</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mi mathvariant="normal">∣</mi><msub><mi mathvariant="bold">x</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><mo stretchy="false">)</mo><mo>=</mo><mi mathvariant="script">N</mi><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo separator="true">;</mo><mtext> </mtext><msqrt><mrow><mn>1</mn><mo>−</mo><msub><mi>β</mi><mi>t</mi></msub></mrow></msqrt><mtext> </mtext><msub><mi mathvariant="bold">x</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><mo separator="true">,</mo><mtext> </mtext><msub><mi>β</mi><mi>t</mi></msub><mi>I</mi><mo fence="true">)</mo></mrow></mrow><annotation encoding="application/x-tex">q(\mathbf{x}_t|\mathbf{x}_{t-1}) = \mathcal{N}\!\left(\mathbf{x}_t;\,\sqrt{1-\beta_t}\,\mathbf{x}_{t-1},\,\beta_t I\right)</annotation></semantics></math></span><p><strong>Closed-form sampling</strong> at any step <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>t</mi></mrow><annotation encoding="application/x-tex">t</annotation></semantics></math></span> (let <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mover accent="true"><mi>α</mi><mo>ˉ</mo></mover><mi>t</mi></msub><mo>=</mo><msubsup><mo>∏</mo><mrow><mi>s</mi><mo>=</mo><mn>1</mn></mrow><mi>t</mi></msubsup><mo stretchy="false">(</mo><mn>1</mn><mo>−</mo><msub><mi>β</mi><mi>s</mi></msub><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\bar\alpha_t = \prod_{s=1}^t(1-\beta_s)</annotation></semantics></math></span>):</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo>=</mo><msqrt><msub><mover accent="true"><mi>α</mi><mo>ˉ</mo></mover><mi>t</mi></msub></msqrt><mtext> </mtext><msub><mi mathvariant="bold">x</mi><mn>0</mn></msub><mo>+</mo><msqrt><mrow><mn>1</mn><mo>−</mo><msub><mover accent="true"><mi>α</mi><mo>ˉ</mo></mover><mi>t</mi></msub></mrow></msqrt><mtext> </mtext><mi mathvariant="bold-italic">ϵ</mi><mo separator="true">,</mo><mspace width="2em"/><mi mathvariant="bold-italic">ϵ</mi><mo>∼</mo><mi mathvariant="script">N</mi><mo stretchy="false">(</mo><mn mathvariant="bold">0</mn><mo separator="true">,</mo><mi>I</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathbf{x}_t = \sqrt{\bar\alpha_t}\,\mathbf{x}_0 + \sqrt{1-\bar\alpha_t}\,\boldsymbol{\epsilon}, \qquad \boldsymbol{\epsilon}\sim\mathcal{N}(\mathbf{0},I)</annotation></semantics></math></span><p><strong>Reverse process</strong> — learned denoiser <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="bold-italic">ϵ</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo separator="true">,</mo><mi>t</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t)</annotation></semantics></math></span>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>p</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi mathvariant="bold">x</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><mi mathvariant="normal">∣</mi><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo stretchy="false">)</mo><mo>=</mo><mi mathvariant="script">N</mi><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><msub><mi mathvariant="bold">x</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><mo separator="true">;</mo><mtext> </mtext><msub><mi mathvariant="bold-italic">μ</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo separator="true">,</mo><mi>t</mi><mo stretchy="false">)</mo><mo separator="true">,</mo><mtext> </mtext><msub><mover accent="true"><mi>β</mi><mo>~</mo></mover><mi>t</mi></msub><mi>I</mi><mo fence="true">)</mo></mrow></mrow><annotation encoding="application/x-tex">p_\theta(\mathbf{x}_{t-1}|\mathbf{x}_t) = \mathcal{N}\!\left(\mathbf{x}_{t-1};\,\boldsymbol{\mu}_\theta(\mathbf{x}_t,t),\,\tilde\beta_t I\right)</annotation></semantics></math></span><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="bold-italic">μ</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo separator="true">,</mo><mi>t</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mn>1</mn><msqrt><msub><mi>α</mi><mi>t</mi></msub></msqrt></mfrac><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo>−</mo><mfrac><msub><mi>β</mi><mi>t</mi></msub><msqrt><mrow><mn>1</mn><mo>−</mo><msub><mover accent="true"><mi>α</mi><mo>ˉ</mo></mover><mi>t</mi></msub></mrow></msqrt></mfrac><mtext> </mtext><msub><mi mathvariant="bold-italic">ϵ</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo separator="true">,</mo><mi>t</mi><mo stretchy="false">)</mo><mo fence="true">)</mo></mrow></mrow><annotation encoding="application/x-tex">\boldsymbol{\mu}_\theta(\mathbf{x}_t,t) = \frac{1}{\sqrt{\alpha_t}}\!\left(\mathbf{x}_t - \frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\boldsymbol{\epsilon}_\theta(\mathbf{x}_t,t)\right)</annotation></semantics></math></span><p><strong>Training objective</strong> — predict the noise:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="script">L</mi><mtext>DDPM</mtext></msub><mo>=</mo><msub><mi mathvariant="double-struck">E</mi><mrow><mi>t</mi><mo separator="true">,</mo><msub><mi mathvariant="bold">x</mi><mn>0</mn></msub><mo separator="true">,</mo><mi mathvariant="bold-italic">ϵ</mi></mrow></msub><mtext> ⁣</mtext><mrow><mo fence="true">[</mo><mi mathvariant="normal">∥</mi><mi mathvariant="bold-italic">ϵ</mi><mo>−</mo><msub><mi mathvariant="bold-italic">ϵ</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo separator="true">,</mo><mi>t</mi><mo stretchy="false">)</mo><msup><mi mathvariant="normal">∥</mi><mn>2</mn></msup><mo fence="true">]</mo></mrow></mrow><annotation encoding="application/x-tex">\mathcal{L}_{\text{DDPM}} = \mathbb{E}_{t,\mathbf{x}_0,\boldsymbol{\epsilon}}\!\left[\|\boldsymbol{\epsilon} - \boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t)\|^2\right]</annotation></semantics></math></span><hr>
<h3 id="autoregressive-generation-llm-decoding">Autoregressive Generation (LLM Decoding)</h3>
<p>Given a prompt <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">(</mo><msub><mi>t</mi><mn>1</mn></msub><mo separator="true">,</mo><mo>…</mo><mo separator="true">,</mo><msub><mi>t</mi><mi>k</mi></msub><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">(t_1,\ldots,t_k)</annotation></semantics></math></span>, generate token-by-token:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>t</mi><mrow><mi>k</mi><mo>+</mo><mi>i</mi></mrow></msub><mo>∼</mo><msub><mi>P</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><mo>⋅</mo><mo>∣</mo><msub><mi>t</mi><mn>1</mn></msub><mo separator="true">,</mo><mo>…</mo><mo separator="true">,</mo><msub><mi>t</mi><mrow><mi>k</mi><mo>+</mo><mi>i</mi><mo>−</mo><mn>1</mn></mrow></msub><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">t_{k+i} \sim P_\theta(\cdot \mid t_1,\ldots,t_{k+i-1})</annotation></semantics></math></span><p><strong>Temperature scaling</strong> — control sharpness of distribution:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>P</mi><mi>τ</mi></msub><mo stretchy="false">(</mo><mi>t</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mrow><mi>exp</mi><mo>⁡</mo><mo stretchy="false">(</mo><msub><mi>z</mi><mi>t</mi></msub><mi mathvariant="normal">/</mi><mi>τ</mi><mo stretchy="false">)</mo></mrow><mrow><munder><mo>∑</mo><mi>j</mi></munder><mi>exp</mi><mo>⁡</mo><mo stretchy="false">(</mo><msub><mi>z</mi><mi>j</mi></msub><mi mathvariant="normal">/</mi><mi>τ</mi><mo stretchy="false">)</mo></mrow></mfrac></mrow><annotation encoding="application/x-tex">P_\tau(t) = \frac{\exp(z_t / \tau)}{\sum_j \exp(z_j / \tau)}</annotation></semantics></math></span><ul>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>τ</mi><mo>→</mo><mn>0</mn></mrow><annotation encoding="application/x-tex">\tau \to 0</annotation></semantics></math></span>: greedy (deterministic); <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>τ</mi><mo>=</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">\tau = 1</annotation></semantics></math></span>: standard softmax; <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>τ</mi><mo>&gt;</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">\tau &gt; 1</annotation></semantics></math></span>: more random.</li>
</ul>
<p><strong>Top-<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi></mrow><annotation encoding="application/x-tex">p</annotation></semantics></math></span> (nucleus) sampling</strong> — sample from smallest set <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="script">V</mi></mrow><annotation encoding="application/x-tex">\mathcal{V}</annotation></semantics></math></span> s.t.:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><munder><mo>∑</mo><mrow><mi>t</mi><mo>∈</mo><mi mathvariant="script">V</mi></mrow></munder><mi>P</mi><mo stretchy="false">(</mo><mi>t</mi><mo stretchy="false">)</mo><mo>≥</mo><mi>p</mi></mrow><annotation encoding="application/x-tex">\sum_{t \in \mathcal{V}} P(t) \geq p</annotation></semantics></math></span><hr>
<h3 id="reinforcement-learning-from-human-feedback-rlhf">Reinforcement Learning from Human Feedback (RLHF)</h3>
<p><strong>Step 1 — Supervised Fine-Tuning (SFT):</strong> fine-tune LLM on human demonstrations.</p>
<p><strong>Step 2 — Reward Model:</strong> train <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>r</mi><mi>ϕ</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo separator="true">,</mo><mi mathvariant="bold">y</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">r_\phi(\mathbf{x}, \mathbf{y})</annotation></semantics></math></span> from preference pairs <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">(</mo><msub><mi>y</mi><mi>w</mi></msub><mo>≻</mo><msub><mi>y</mi><mi>l</mi></msub><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">(y_w \succ y_l)</annotation></semantics></math></span>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="script">L</mi><mtext>RM</mtext></msub><mo>=</mo><mo>−</mo><msub><mi mathvariant="double-struck">E</mi><mrow><mo stretchy="false">(</mo><mi>x</mi><mo separator="true">,</mo><msub><mi>y</mi><mi>w</mi></msub><mo separator="true">,</mo><msub><mi>y</mi><mi>l</mi></msub><mo stretchy="false">)</mo></mrow></msub><mtext> ⁣</mtext><mrow><mo fence="true">[</mo><mi>log</mi><mo>⁡</mo><mi>σ</mi><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><msub><mi>r</mi><mi>ϕ</mi></msub><mo stretchy="false">(</mo><mi>x</mi><mo separator="true">,</mo><msub><mi>y</mi><mi>w</mi></msub><mo stretchy="false">)</mo><mo>−</mo><msub><mi>r</mi><mi>ϕ</mi></msub><mo stretchy="false">(</mo><mi>x</mi><mo separator="true">,</mo><msub><mi>y</mi><mi>l</mi></msub><mo stretchy="false">)</mo><mo fence="true">)</mo></mrow><mo fence="true">]</mo></mrow></mrow><annotation encoding="application/x-tex">\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]</annotation></semantics></math></span><p><strong>Step 3 — PPO fine-tuning</strong> — maximise reward while staying close to SFT policy <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>π</mi><mtext>ref</mtext></msub></mrow><annotation encoding="application/x-tex">\pi_{\text{ref}}</annotation></semantics></math></span>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="script">L</mi><mtext>RLHF</mtext></msub><mo stretchy="false">(</mo><mi>θ</mi><mo stretchy="false">)</mo><mo>=</mo><msub><mi mathvariant="double-struck">E</mi><mrow><mi>x</mi><mo>∼</mo><mi mathvariant="script">D</mi><mo separator="true">,</mo><mtext> </mtext><mi>y</mi><mo>∼</mo><msub><mi>π</mi><mi>θ</mi></msub></mrow></msub><mtext> ⁣</mtext><mrow><mo fence="true">[</mo><msub><mi>r</mi><mi>ϕ</mi></msub><mo stretchy="false">(</mo><mi>x</mi><mo separator="true">,</mo><mi>y</mi><mo stretchy="false">)</mo><mo fence="true">]</mo></mrow><mo>−</mo><mi>β</mi><mtext> </mtext><msub><mi>D</mi><mtext>KL</mtext></msub><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><msub><mi>π</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><mo>⋅</mo><mi mathvariant="normal">∣</mi><mi>x</mi><mo stretchy="false">)</mo><mtext>  </mtext><mi mathvariant="normal">∥</mi><mtext>  </mtext><msub><mi>π</mi><mtext>ref</mtext></msub><mo stretchy="false">(</mo><mo>⋅</mo><mi mathvariant="normal">∣</mi><mi>x</mi><mo stretchy="false">)</mo><mo fence="true">)</mo></mrow></mrow><annotation encoding="application/x-tex">\mathcal{L}_{\text{RLHF}}(\theta) = \mathbb{E}_{x\sim\mathcal{D},\,y\sim\pi_\theta}\!\left[r_\phi(x,y)\right] - \beta\,D_{\text{KL}}\!\left(\pi_\theta(\cdot|x)\;\|\;\pi_{\text{ref}}(\cdot|x)\right)</annotation></semantics></math></span><p><strong>DPO</strong> (Direct Preference Optimisation) — skips reward model, optimise preferences directly:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="script">L</mi><mtext>DPO</mtext></msub><mo stretchy="false">(</mo><mi>θ</mi><mo stretchy="false">)</mo><mo>=</mo><mo>−</mo><msub><mi mathvariant="double-struck">E</mi><mrow><mo stretchy="false">(</mo><mi>x</mi><mo separator="true">,</mo><msub><mi>y</mi><mi>w</mi></msub><mo separator="true">,</mo><msub><mi>y</mi><mi>l</mi></msub><mo stretchy="false">)</mo></mrow></msub><mtext> ⁣</mtext><mrow><mo fence="true">[</mo><mi>log</mi><mo>⁡</mo><mi>σ</mi><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><mi>β</mi><mi>log</mi><mo>⁡</mo><mfrac><mrow><msub><mi>π</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi>y</mi><mi>w</mi></msub><mi mathvariant="normal">∣</mi><mi>x</mi><mo stretchy="false">)</mo></mrow><mrow><msub><mi>π</mi><mtext>ref</mtext></msub><mo stretchy="false">(</mo><msub><mi>y</mi><mi>w</mi></msub><mi mathvariant="normal">∣</mi><mi>x</mi><mo stretchy="false">)</mo></mrow></mfrac><mo>−</mo><mi>β</mi><mi>log</mi><mo>⁡</mo><mfrac><mrow><msub><mi>π</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi>y</mi><mi>l</mi></msub><mi mathvariant="normal">∣</mi><mi>x</mi><mo stretchy="false">)</mo></mrow><mrow><msub><mi>π</mi><mtext>ref</mtext></msub><mo stretchy="false">(</mo><msub><mi>y</mi><mi>l</mi></msub><mi mathvariant="normal">∣</mi><mi>x</mi><mo stretchy="false">)</mo></mrow></mfrac><mo fence="true">)</mo></mrow><mo fence="true">]</mo></mrow></mrow><annotation encoding="application/x-tex">\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]</annotation></semantics></math></span><hr>
<h2 id="large-language-models-llm">Large Language Models (LLM)</h2>
<h3 id="architecture-overview">Architecture Overview</h3>
<p>A decoder-only Transformer stacks <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>L</mi></mrow><annotation encoding="application/x-tex">L</annotation></semantics></math></span> blocks. Given token sequence <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">(</mo><msub><mi>t</mi><mn>1</mn></msub><mo separator="true">,</mo><mo>…</mo><mo separator="true">,</mo><msub><mi>t</mi><mi>n</mi></msub><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">(t_1,\ldots,t_n)</annotation></semantics></math></span>:</p>
<ol>
<li><strong>Tokenisation</strong> — map text to integer IDs via vocabulary <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="script">V</mi></mrow><annotation encoding="application/x-tex">\mathcal{V}</annotation></semantics></math></span>, <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="normal">∣</mi><mi mathvariant="script">V</mi><mi mathvariant="normal">∣</mi><mo>∼</mo><mn>50</mn><mtext>k</mtext></mrow><annotation encoding="application/x-tex">|\mathcal{V}|\sim 50\text{k}</annotation></semantics></math></span>–<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mn>200</mn><mtext>k</mtext></mrow><annotation encoding="application/x-tex">200\text{k}</annotation></semantics></math></span>.</li>
<li><strong>Embedding</strong> — <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="bold">E</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi mathvariant="normal">∣</mi><mi mathvariant="script">V</mi><mi mathvariant="normal">∣</mi><mo>×</mo><mi>d</mi></mrow></msup></mrow><annotation encoding="application/x-tex">\mathbf{E} \in \mathbb{R}^{|\mathcal{V}|\times d}</annotation></semantics></math></span>, look up row <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>t</mi><mi>i</mi></msub></mrow><annotation encoding="application/x-tex">t_i</annotation></semantics></math></span>: <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msubsup><mi mathvariant="bold">h</mi><mi>i</mi><mrow><mo stretchy="false">(</mo><mn>0</mn><mo stretchy="false">)</mo></mrow></msubsup><mo>=</mo><msub><mi mathvariant="bold">E</mi><msub><mi>t</mi><mi>i</mi></msub></msub><mo>+</mo><msub><mrow><mi mathvariant="bold">P</mi><mi mathvariant="bold">E</mi></mrow><mi>i</mi></msub></mrow><annotation encoding="application/x-tex">\mathbf{h}_i^{(0)} = \mathbf{E}_{t_i} + \mathbf{PE}_i</annotation></semantics></math></span></li>
<li><strong><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>L</mi></mrow><annotation encoding="application/x-tex">L</annotation></semantics></math></span> Transformer blocks</strong> (causal masked attention + FFN).</li>
<li><strong>Unembedding</strong> — project to logits and apply softmax: <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="bold">l</mi><mi>i</mi></msub><mo>=</mo><mi mathvariant="bold">E</mi><mtext> </mtext><msubsup><mi mathvariant="bold">h</mi><mi>i</mi><mrow><mo stretchy="false">(</mo><mi>L</mi><mo stretchy="false">)</mo></mrow></msubsup><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi mathvariant="normal">∣</mi><mi mathvariant="script">V</mi><mi mathvariant="normal">∣</mi></mrow></msup></mrow><annotation encoding="application/x-tex">\mathbf{l}_i = \mathbf{E}\,\mathbf{h}_i^{(L)} \in \mathbb{R}^{|\mathcal{V}|}</annotation></semantics></math></span></li>
</ol>
<p><strong>Causal (masked) self-attention</strong> — token <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>i</mi></mrow><annotation encoding="application/x-tex">i</annotation></semantics></math></span> can only attend to positions <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>j</mi><mo>≤</mo><mi>i</mi></mrow><annotation encoding="application/x-tex">j \leq i</annotation></semantics></math></span>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>Attention</mtext><mo stretchy="false">(</mo><mi>Q</mi><mo separator="true">,</mo><mi>K</mi><mo separator="true">,</mo><mi>V</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>softmax</mtext><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><mfrac><mrow><mi>Q</mi><msup><mi>K</mi><mi mathvariant="normal">⊤</mi></msup></mrow><msqrt><msub><mi>d</mi><mi>k</mi></msub></msqrt></mfrac><mo>+</mo><mi>M</mi><mo fence="true">)</mo></mrow><mi>V</mi><mo separator="true">,</mo><mspace width="1em"/><msub><mi>M</mi><mrow><mi>i</mi><mi>j</mi></mrow></msub><mo>=</mo><mrow><mo fence="true">{</mo><mtable rowspacing="0.36em" columnalign="left left" columnspacing="1em"><mtr><mtd><mstyle scriptlevel="0" displaystyle="false"><mn>0</mn></mstyle></mtd><mtd><mstyle scriptlevel="0" displaystyle="false"><mrow><mi>j</mi><mo>≤</mo><mi>i</mi></mrow></mstyle></mtd></mtr><mtr><mtd><mstyle scriptlevel="0" displaystyle="false"><mrow><mo>−</mo><mi mathvariant="normal">∞</mi></mrow></mstyle></mtd><mtd><mstyle scriptlevel="0" displaystyle="false"><mrow><mi>j</mi><mo>&gt;</mo><mi>i</mi></mrow></mstyle></mtd></mtr></mtable></mrow></mrow><annotation encoding="application/x-tex">\text{Attention}(Q,K,V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V, \quad M_{ij} = \begin{cases}0 &amp; j\leq i\\-\infty &amp; j&gt;i\end{cases}</annotation></semantics></math></span><hr>
<h3 id="tokenisation--embedding">Tokenisation &amp; Embedding</h3>
<p><strong>Byte-Pair Encoding (BPE)</strong> — iteratively merge the most frequent adjacent pair until vocabulary size <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="normal">∣</mi><mi mathvariant="script">V</mi><mi mathvariant="normal">∣</mi></mrow><annotation encoding="application/x-tex">|\mathcal{V}|</annotation></semantics></math></span> is reached.</p>
<p><strong>Token embedding</strong> + <strong>positional encoding</strong> → input representation:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="bold">h</mi><mi>i</mi></msub><mo>=</mo><msub><mi mathvariant="bold">E</mi><msub><mi>t</mi><mi>i</mi></msub></msub><mo>+</mo><msub><mrow><mi mathvariant="bold">P</mi><mi mathvariant="bold">E</mi></mrow><mi>i</mi></msub><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mi>d</mi></msup></mrow><annotation encoding="application/x-tex">\mathbf{h}_i = \mathbf{E}_{t_i} + \mathbf{PE}_i \in \mathbb{R}^d</annotation></semantics></math></span><p><strong>RoPE</strong> (Rotary Positional Embedding) — encode position by rotating query/key vectors:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="bold">q</mi><mi>m</mi></msub><mo>=</mo><msub><mi>R</mi><mi>m</mi></msub><mi mathvariant="bold">q</mi><mo separator="true">,</mo><mspace width="1em"/><msub><mi mathvariant="bold">k</mi><mi>n</mi></msub><mo>=</mo><msub><mi>R</mi><mi>n</mi></msub><mi mathvariant="bold">k</mi><mo separator="true">,</mo><mspace width="1em"/><msubsup><mi mathvariant="bold">q</mi><mi>m</mi><mi mathvariant="normal">⊤</mi></msubsup><msub><mi mathvariant="bold">k</mi><mi>n</mi></msub><mo>=</mo><msup><mi mathvariant="bold">q</mi><mi mathvariant="normal">⊤</mi></msup><msub><mi>R</mi><mrow><mi>n</mi><mo>−</mo><mi>m</mi></mrow></msub><mi mathvariant="bold">k</mi></mrow><annotation encoding="application/x-tex">\mathbf{q}_m = R_m \mathbf{q}, \quad \mathbf{k}_n = R_n \mathbf{k}, \quad \mathbf{q}_m^\top \mathbf{k}_n = \mathbf{q}^\top R_{n-m} \mathbf{k}</annotation></semantics></math></span><p>where <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>R</mi><mi>m</mi></msub></mrow><annotation encoding="application/x-tex">R_m</annotation></semantics></math></span> is a block-diagonal rotation matrix at angle <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>m</mi><msub><mi>θ</mi><mi>i</mi></msub></mrow><annotation encoding="application/x-tex">m\theta_i</annotation></semantics></math></span>.</p>
<hr>
<h3 id="perplexity-ppl">Perplexity (PPL)</h3>
<p>The standard intrinsic evaluation metric for language models — how &quot;surprised&quot; the model is by the test set:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>PPL</mtext><mo stretchy="false">(</mo><mi>T</mi><mo stretchy="false">)</mo><mo>=</mo><mi>exp</mi><mo>⁡</mo><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><mo>−</mo><mfrac><mn>1</mn><mi>T</mi></mfrac><munderover><mo>∑</mo><mrow><mi>t</mi><mo>=</mo><mn>1</mn></mrow><mi>T</mi></munderover><mi>log</mi><mo>⁡</mo><msub><mi>P</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi>t</mi><mi>t</mi></msub><mo>∣</mo><msub><mi>t</mi><mrow><mo>&lt;</mo><mi>t</mi></mrow></msub><mo stretchy="false">)</mo><mo fence="true">)</mo></mrow><mo>=</mo><mi>exp</mi><mo>⁡</mo><mo stretchy="false">(</mo><mi mathvariant="script">L</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\text{PPL}(T) = \exp\!\left(-\frac{1}{T}\sum_{t=1}^{T} \log P_\theta(t_t \mid t_{\lt t})\right) = \exp(\mathcal{L})</annotation></semantics></math></span><ul>
<li>Lower PPL = model assigns higher probability to real text = better.</li>
<li>PPL is simply the exponential of the cross-entropy loss <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="script">L</mi></mrow><annotation encoding="application/x-tex">\mathcal{L}</annotation></semantics></math></span>.</li>
<li>PPL <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo>=</mo><mi>k</mi></mrow><annotation encoding="application/x-tex">= k</annotation></semantics></math></span> means the model is as uncertain as choosing uniformly among <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>k</mi></mrow><annotation encoding="application/x-tex">k</annotation></semantics></math></span> tokens.</li>
<li>GPT-2 zero-shot on WikiText-103: PPL ≈ 37.5 (117M) → ≈ 17.5 (1.5B) — scale alone cuts it in half.</li>
</ul>
<p><strong>Bits-per-character (BPC)</strong> — alternative unit used for character-level models:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>BPC</mtext><mo>=</mo><mfrac><mi mathvariant="script">L</mi><mrow><mi>ln</mi><mo>⁡</mo><mn>2</mn></mrow></mfrac></mrow><annotation encoding="application/x-tex">\text{BPC} = \frac{\mathcal{L}}{\ln 2}</annotation></semantics></math></span><hr>
<h3 id="scaling-laws">Scaling Laws</h3>
<p>Model performance scales predictably with compute <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>C</mi></mrow><annotation encoding="application/x-tex">C</annotation></semantics></math></span>, data <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>D</mi></mrow><annotation encoding="application/x-tex">D</annotation></semantics></math></span>, and parameters <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>N</mi></mrow><annotation encoding="application/x-tex">N</annotation></semantics></math></span> (Chinchilla):</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi mathvariant="script">L</mi><mo stretchy="false">(</mo><mi>N</mi><mo separator="true">,</mo><mi>D</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mi>A</mi><msup><mi>N</mi><mi>α</mi></msup></mfrac><mo>+</mo><mfrac><mi>B</mi><msup><mi>D</mi><mi>β</mi></msup></mfrac><mo>+</mo><msub><mi mathvariant="script">L</mi><mi mathvariant="normal">∞</mi></msub></mrow><annotation encoding="application/x-tex">\mathcal{L}(N, D) = \frac{A}{N^\alpha} + \frac{B}{D^\beta} + \mathcal{L}_\infty</annotation></semantics></math></span><p>Optimal allocation for a compute budget <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>C</mi><mo>=</mo><mn>6</mn><mi>N</mi><mi>D</mi></mrow><annotation encoding="application/x-tex">C = 6ND</annotation></semantics></math></span>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>N</mi><mtext>opt</mtext></msub><mo>∝</mo><msup><mi>C</mi><mn>0.5</mn></msup><mo separator="true">,</mo><mspace width="2em"/><msub><mi>D</mi><mtext>opt</mtext></msub><mo>∝</mo><msup><mi>C</mi><mn>0.5</mn></msup></mrow><annotation encoding="application/x-tex">N_{\text{opt}} \propto C^{0.5}, \qquad D_{\text{opt}} \propto C^{0.5}</annotation></semantics></math></span><p>i.e. <strong>tokens and parameters should scale equally</strong>.</p>
<hr>
<h3 id="in-context-learning-icl--prompting">In-Context Learning (ICL) &amp; Prompting</h3>
<p>LLMs can learn from examples in the prompt <strong>without updating weights</strong>.</p>
<p><strong><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>k</mi></mrow><annotation encoding="application/x-tex">k</annotation></semantics></math></span>-shot prompting</strong> — prepend <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>k</mi></mrow><annotation encoding="application/x-tex">k</annotation></semantics></math></span> (input, output) examples:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>P</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><mi>y</mi><mo>∣</mo><mi>x</mi><mo separator="true">,</mo><mo stretchy="false">(</mo><msub><mi>x</mi><mn>1</mn></msub><mo separator="true">,</mo><msub><mi>y</mi><mn>1</mn></msub><mo stretchy="false">)</mo><mo separator="true">,</mo><mo>…</mo><mo separator="true">,</mo><mo stretchy="false">(</mo><msub><mi>x</mi><mi>k</mi></msub><mo separator="true">,</mo><msub><mi>y</mi><mi>k</mi></msub><mo stretchy="false">)</mo><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P_\theta(y \mid x, (x_1,y_1),\ldots,(x_k,y_k))</annotation></semantics></math></span><p><strong>Chain-of-Thought (CoT)</strong> — include reasoning steps <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi></mrow><annotation encoding="application/x-tex">r</annotation></semantics></math></span> before answer <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>a</mi></mrow><annotation encoding="application/x-tex">a</annotation></semantics></math></span>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>P</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><mi>r</mi><mo separator="true">,</mo><mi>a</mi><mo>∣</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><msub><mi>P</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><mi>r</mi><mo>∣</mo><mi>x</mi><mo stretchy="false">)</mo><mo>⋅</mo><msub><mi>P</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><mi>a</mi><mo>∣</mo><mi>x</mi><mo separator="true">,</mo><mi>r</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P_\theta(r, a \mid x) = P_\theta(r \mid x) \cdot P_\theta(a \mid x, r)</annotation></semantics></math></span><p><strong>Self-consistency</strong> — sample <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>M</mi></mrow><annotation encoding="application/x-tex">M</annotation></semantics></math></span> reasoning paths, take majority vote:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mover accent="true"><mi>a</mi><mo>^</mo></mover><mo>=</mo><mi>arg</mi><mo>⁡</mo><munder><mrow><mi>max</mi><mo>⁡</mo></mrow><mi>a</mi></munder><munderover><mo>∑</mo><mrow><mi>m</mi><mo>=</mo><mn>1</mn></mrow><mi>M</mi></munderover><mn mathvariant="bold">1</mn><mo stretchy="false">[</mo><msub><mi>a</mi><mi>m</mi></msub><mo>=</mo><mi>a</mi><mo stretchy="false">]</mo></mrow><annotation encoding="application/x-tex">\hat{a} = \arg\max_a \sum_{m=1}^{M} \mathbf{1}[a_m = a]</annotation></semantics></math></span><hr>
<h3 id="retrieval-augmented-generation-rag">Retrieval-Augmented Generation (RAG)</h3>
<p>Augment generation with retrieved documents <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="script">D</mi><mi>r</mi></msub></mrow><annotation encoding="application/x-tex">\mathcal{D}_r</annotation></semantics></math></span> from an external knowledge base:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>P</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><mi>y</mi><mo>∣</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><munder><mo>∑</mo><mrow><mi>d</mi><mo>∈</mo><msub><mi mathvariant="script">D</mi><mi>r</mi></msub></mrow></munder><msub><mi>P</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><mi>y</mi><mo>∣</mo><mi>x</mi><mo separator="true">,</mo><mi>d</mi><mo stretchy="false">)</mo><mtext> </mtext><msub><mi>P</mi><mtext>ret</mtext></msub><mo stretchy="false">(</mo><mi>d</mi><mo>∣</mo><mi>x</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P_\theta(y \mid x) = \sum_{d \in \mathcal{D}_r} P_\theta(y \mid x, d)\, P_{\text{ret}}(d \mid x)</annotation></semantics></math></span><p><strong>Retrieval</strong> — encode query and documents, fetch top-<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>k</mi></mrow><annotation encoding="application/x-tex">k</annotation></semantics></math></span> by cosine similarity:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>score</mtext><mo stretchy="false">(</mo><mi>x</mi><mo separator="true">,</mo><mi>d</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mrow><mi>f</mi><mo stretchy="false">(</mo><mi>x</mi><msup><mo stretchy="false">)</mo><mi mathvariant="normal">⊤</mi></msup><mi>g</mi><mo stretchy="false">(</mo><mi>d</mi><mo stretchy="false">)</mo></mrow><mrow><mi mathvariant="normal">∥</mi><mi>f</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mi mathvariant="normal">∥</mi><mi mathvariant="normal">∥</mi><mi>g</mi><mo stretchy="false">(</mo><mi>d</mi><mo stretchy="false">)</mo><mi mathvariant="normal">∥</mi></mrow></mfrac></mrow><annotation encoding="application/x-tex">\text{score}(x, d) = \frac{f(x)^\top g(d)}{\|f(x)\|\|g(d)\|}</annotation></semantics></math></span><hr>
<h3 id="kv-cache">KV Cache</h3>
<p>During autoregressive inference, keys and values for all past tokens are cached — avoid recomputing on each new token:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>K</mi><mrow><mo>≤</mo><mi>t</mi></mrow></msub><mo>=</mo><mo stretchy="false">[</mo><msub><mi>k</mi><mn>1</mn></msub><mo separator="true">,</mo><mo>…</mo><mo separator="true">,</mo><msub><mi>k</mi><mi>t</mi></msub><mo stretchy="false">]</mo><mo separator="true">,</mo><mspace width="1em"/><msub><mi>V</mi><mrow><mo>≤</mo><mi>t</mi></mrow></msub><mo>=</mo><mo stretchy="false">[</mo><msub><mi>v</mi><mn>1</mn></msub><mo separator="true">,</mo><mo>…</mo><mo separator="true">,</mo><msub><mi>v</mi><mi>t</mi></msub><mo stretchy="false">]</mo></mrow><annotation encoding="application/x-tex">K_{\leq t} = [k_1,\ldots,k_t], \quad V_{\leq t} = [v_1,\ldots,v_t]</annotation></semantics></math></span><p>New token <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>t</mi><mo>+</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">t+1</annotation></semantics></math></span> only computes <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>q</mi><mrow><mi>t</mi><mo>+</mo><mn>1</mn></mrow></msub></mrow><annotation encoding="application/x-tex">q_{t+1}</annotation></semantics></math></span>, then attends over cached <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>K</mi><mrow><mo>≤</mo><mi>t</mi></mrow></msub><mo separator="true">,</mo><msub><mi>V</mi><mrow><mo>≤</mo><mi>t</mi></mrow></msub></mrow><annotation encoding="application/x-tex">K_{\leq t}, V_{\leq t}</annotation></semantics></math></span>. Reduces per-step cost from <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="script">O</mi><mo stretchy="false">(</mo><msup><mi>t</mi><mn>2</mn></msup><mi>d</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathcal{O}(t^2 d)</annotation></semantics></math></span> to <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="script">O</mi><mo stretchy="false">(</mo><mi>t</mi><mi>d</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathcal{O}(t d)</annotation></semantics></math></span>; memory grows linearly with sequence length.</p>
<hr>
<h3 id="mixture-of-experts-moe">Mixture of Experts (MoE)</h3>
<p>Replace the dense FFN in each Transformer block with <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>E</mi></mrow><annotation encoding="application/x-tex">E</annotation></semantics></math></span> expert FFNs. A learned <strong>router</strong> selects top-<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>k</mi></mrow><annotation encoding="application/x-tex">k</annotation></semantics></math></span> experts per token:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>MoE</mtext><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mo>=</mo><munderover><mo>∑</mo><mrow><mi>i</mi><mo>=</mo><mn>1</mn></mrow><mi>k</mi></munderover><msub><mi>g</mi><mi>i</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mtext>  </mtext><msub><mtext>FFN</mtext><mi>i</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\text{MoE}(\mathbf{x}) = \sum_{i=1}^{k} g_i(\mathbf{x})\; \text{FFN}_i(\mathbf{x})</annotation></semantics></math></span><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>g</mi><mi>i</mi></msub><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>softmax</mtext><mtext> ⁣</mtext><msub><mrow><mo fence="true">(</mo><mtext>TopK</mtext><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><msub><mi>W</mi><mi>g</mi></msub><mi mathvariant="bold">x</mi><mo separator="true">,</mo><mtext>  </mtext><mi>k</mi><mo fence="true">)</mo></mrow><mo fence="true">)</mo></mrow><mi>i</mi></msub></mrow><annotation encoding="application/x-tex">g_i(\mathbf{x}) = \text{softmax}\!\left(\text{TopK}\!\left(W_g\mathbf{x},\; k\right)\right)_i</annotation></semantics></math></span><ul>
<li><strong>Activated params</strong> per token: <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo>∼</mo><mi>k</mi><mi mathvariant="normal">/</mi><mi>E</mi></mrow><annotation encoding="application/x-tex">\sim k/E</annotation></semantics></math></span> of total params → same inference cost as a smaller dense model.</li>
<li><strong>Load balancing loss</strong> encourages uniform expert utilisation: <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="script">L</mi><mtext>bal</mtext></msub><mo>=</mo><mi>E</mi><msub><mo>∑</mo><mi>i</mi></msub><msub><mi>f</mi><mi>i</mi></msub><mo>⋅</mo><msub><mi>p</mi><mi>i</mi></msub></mrow><annotation encoding="application/x-tex">\mathcal{L}_{\text{bal}} = E \sum_i f_i \cdot p_i</annotation></semantics></math></span> where <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>f</mi><mi>i</mi></msub></mrow><annotation encoding="application/x-tex">f_i</annotation></semantics></math></span> is fraction of tokens routed to expert <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>i</mi></mrow><annotation encoding="application/x-tex">i</annotation></semantics></math></span> and <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>p</mi><mi>i</mi></msub></mrow><annotation encoding="application/x-tex">p_i</annotation></semantics></math></span> is mean router probability.</li>
</ul>
<p>Used in <strong>Switch Transformer</strong>, <strong>Mixtral</strong>, and <strong>DeepSeek-V3</strong>.</p>
<hr>
<h3 id="key-llm-concepts-summary">Key LLM Concepts Summary</h3>
<table>
  <thead>
      <tr>
          <th>Concept</th>
          <th>What it does</th>
          <th>Key formula / idea</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><strong>Tokenisation (BPE)</strong></td>
          <td>Text → integer IDs</td>
          <td>Merge most-frequent pairs</td>
      </tr>
      <tr>
          <td><strong>Causal Attention</strong></td>
          <td>Each token sees only past</td>
          <td>Mask <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>M</mi><mrow><mi>i</mi><mi>j</mi></mrow></msub><mo>=</mo><mo>−</mo><mi mathvariant="normal">∞</mi></mrow><annotation encoding="application/x-tex">M_{ij}=-\infty</annotation></semantics></math></span> for <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>j</mi><mo>&gt;</mo><mi>i</mi></mrow><annotation encoding="application/x-tex">j&gt;i</annotation></semantics></math></span></td>
      </tr>
      <tr>
          <td><strong>Scaling Law</strong></td>
          <td>Predict loss from <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>N</mi><mo separator="true">,</mo><mi>D</mi><mo separator="true">,</mo><mi>C</mi></mrow><annotation encoding="application/x-tex">N,D,C</annotation></semantics></math></span></td>
          <td><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="script">L</mi><mo>∝</mo><msup><mi>N</mi><mrow><mo>−</mo><mi>α</mi></mrow></msup><mo>+</mo><msup><mi>D</mi><mrow><mo>−</mo><mi>β</mi></mrow></msup></mrow><annotation encoding="application/x-tex">\mathcal{L} \propto N^{-\alpha} + D^{-\beta}</annotation></semantics></math></span></td>
      </tr>
      <tr>
          <td><strong>SFT</strong></td>
          <td>Align model to instructions</td>
          <td>Cross-entropy on demonstrations</td>
      </tr>
      <tr>
          <td><strong>RLHF / DPO</strong></td>
          <td>Align to human preferences</td>
          <td>Reward signal or preference pairs</td>
      </tr>
      <tr>
          <td><strong>CoT Prompting</strong></td>
          <td>Elicit step-by-step reasoning</td>
          <td><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>P</mi><mo stretchy="false">(</mo><mi>r</mi><mo separator="true">,</mo><mi>a</mi><mi mathvariant="normal">∥</mi><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo><mi>P</mi><mo stretchy="false">(</mo><mi>r</mi><mi mathvariant="normal">∥</mi><mi>x</mi><mo stretchy="false">)</mo><mi>P</mi><mo stretchy="false">(</mo><mi>a</mi><mi mathvariant="normal">∥</mi><mi>x</mi><mo separator="true">,</mo><mi>r</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">P(r,a\|x) = P(r\|x)P(a\|x,r)</annotation></semantics></math></span></td>
      </tr>
      <tr>
          <td><strong>RAG</strong></td>
          <td>Ground generation in facts</td>
          <td>Retrieve then generate</td>
      </tr>
      <tr>
          <td><strong>LoRA</strong></td>
          <td>Parameter-efficient fine-tuning</td>
          <td><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>W</mi><mo>=</mo><msub><mi>W</mi><mn>0</mn></msub><mo>+</mo><mi>B</mi><mi>A</mi></mrow><annotation encoding="application/x-tex">W = W_0 + BA</annotation></semantics></math></span>, <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mo>≪</mo><mi>d</mi></mrow><annotation encoding="application/x-tex">r \ll d</annotation></semantics></math></span></td>
      </tr>
  </tbody>
</table>
<hr>
<h2 id="multimodal-ai">Multimodal AI</h2>
<p>Multimodal models process and generate <strong>more than one modality</strong> (text, image, audio, video) within a unified framework.</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>f</mi><mi>θ</mi></msub><mo>:</mo><msub><mi mathvariant="script">M</mi><mn>1</mn></msub><mo>×</mo><msub><mi mathvariant="script">M</mi><mn>2</mn></msub><mo>×</mo><mo>⋯</mo><mo>→</mo><mi mathvariant="script">Y</mi></mrow><annotation encoding="application/x-tex">f_\theta : \mathcal{M}_1 \times \mathcal{M}_2 \times \cdots \to \mathcal{Y}</annotation></semantics></math></span><h3 id="modality-encoding">Modality Encoding</h3>
<p>Each modality is first encoded into a shared embedding space <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msup><mi mathvariant="double-struck">R</mi><mi>d</mi></msup></mrow><annotation encoding="application/x-tex">\mathbb{R}^d</annotation></semantics></math></span>:</p>
<table>
  <thead>
      <tr>
          <th>Modality</th>
          <th>Encoder</th>
          <th>Output</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>Text</td>
          <td>Tokeniser + Embedding</td>
          <td><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="bold">h</mi><mi>t</mi></msub><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>L</mi><mo>×</mo><mi>d</mi></mrow></msup></mrow><annotation encoding="application/x-tex">\mathbf{h}_t \in \mathbb{R}^{L\times d}</annotation></semantics></math></span></td>
      </tr>
      <tr>
          <td>Image</td>
          <td>ViT / CNN patch encoder</td>
          <td><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="bold">h</mi><mi>v</mi></msub><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>N</mi><mo>×</mo><mi>d</mi></mrow></msup></mrow><annotation encoding="application/x-tex">\mathbf{h}_v \in \mathbb{R}^{N\times d}</annotation></semantics></math></span></td>
      </tr>
      <tr>
          <td>Audio</td>
          <td>Spectrogram + Conv / Whisper</td>
          <td><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="bold">h</mi><mi>a</mi></msub><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>S</mi><mo>×</mo><mi>d</mi></mrow></msup></mrow><annotation encoding="application/x-tex">\mathbf{h}_a \in \mathbb{R}^{S\times d}</annotation></semantics></math></span></td>
      </tr>
      <tr>
          <td>Video</td>
          <td>Frame-level ViT + temporal attention</td>
          <td><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="bold">h</mi><mi>f</mi></msub><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>T</mi><mo>×</mo><mi>N</mi><mo>×</mo><mi>d</mi></mrow></msup></mrow><annotation encoding="application/x-tex">\mathbf{h}_f \in \mathbb{R}^{T\times N\times d}</annotation></semantics></math></span></td>
      </tr>
  </tbody>
</table>
<hr>
<h3 id="clip--contrastive-vision-language-pre-training">CLIP — Contrastive Vision-Language Pre-training</h3>
<p>Learn aligned image and text embeddings by maximising agreement between matched pairs.</p>
<p>Given a batch of <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>N</mi></mrow><annotation encoding="application/x-tex">N</annotation></semantics></math></span> (image <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="bold">v</mi><mi>i</mi></msub></mrow><annotation encoding="application/x-tex">\mathbf{v}_i</annotation></semantics></math></span>, text <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi mathvariant="bold">t</mi><mi>i</mi></msub></mrow><annotation encoding="application/x-tex">\mathbf{t}_i</annotation></semantics></math></span>) pairs, compute cosine similarities:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>s</mi><mrow><mi>i</mi><mi>j</mi></mrow></msub><mo>=</mo><mfrac><mrow><mi>f</mi><mo stretchy="false">(</mo><msub><mi mathvariant="bold">v</mi><mi>i</mi></msub><msup><mo stretchy="false">)</mo><mi mathvariant="normal">⊤</mi></msup><mi>g</mi><mo stretchy="false">(</mo><msub><mi mathvariant="bold">t</mi><mi>j</mi></msub><mo stretchy="false">)</mo></mrow><mrow><mi mathvariant="normal">∥</mi><mi>f</mi><mo stretchy="false">(</mo><msub><mi mathvariant="bold">v</mi><mi>i</mi></msub><mo stretchy="false">)</mo><mi mathvariant="normal">∥</mi><mi mathvariant="normal">∥</mi><mi>g</mi><mo stretchy="false">(</mo><msub><mi mathvariant="bold">t</mi><mi>j</mi></msub><mo stretchy="false">)</mo><mi mathvariant="normal">∥</mi></mrow></mfrac><mo>⋅</mo><mi>exp</mi><mo>⁡</mo><mo stretchy="false">(</mo><mi>τ</mi><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">s_{ij} = \frac{f(\mathbf{v}_i)^\top g(\mathbf{t}_j)}{\|f(\mathbf{v}_i)\|\|g(\mathbf{t}_j)\|} \cdot \exp(\tau)</annotation></semantics></math></span><p><strong>Symmetric InfoNCE loss</strong> (maximise diagonal, minimise off-diagonal):</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="script">L</mi><mtext>CLIP</mtext></msub><mo>=</mo><mo>−</mo><mfrac><mn>1</mn><mrow><mn>2</mn><mi>N</mi></mrow></mfrac><munderover><mo>∑</mo><mrow><mi>i</mi><mo>=</mo><mn>1</mn></mrow><mi>N</mi></munderover><mrow><mo fence="true">[</mo><mi>log</mi><mo>⁡</mo><mfrac><msup><mi>e</mi><msub><mi>s</mi><mrow><mi>i</mi><mi>i</mi></mrow></msub></msup><mrow><munder><mo>∑</mo><mi>j</mi></munder><msup><mi>e</mi><msub><mi>s</mi><mrow><mi>i</mi><mi>j</mi></mrow></msub></msup></mrow></mfrac><mo>+</mo><mi>log</mi><mo>⁡</mo><mfrac><msup><mi>e</mi><msub><mi>s</mi><mrow><mi>i</mi><mi>i</mi></mrow></msub></msup><mrow><munder><mo>∑</mo><mi>j</mi></munder><msup><mi>e</mi><msub><mi>s</mi><mrow><mi>j</mi><mi>i</mi></mrow></msub></msup></mrow></mfrac><mo fence="true">]</mo></mrow></mrow><annotation encoding="application/x-tex">\mathcal{L}_{\text{CLIP}} = -\frac{1}{2N}\sum_{i=1}^N \left[\log\frac{e^{s_{ii}}}{\sum_j e^{s_{ij}}} + \log\frac{e^{s_{ii}}}{\sum_j e^{s_{ji}}}\right]</annotation></semantics></math></span><p>At test time: zero-shot classification by picking the text prompt with highest cosine similarity to the image.</p>
<hr>
<h3 id="vision-language-models-vlm">Vision-Language Models (VLM)</h3>
<p>Connect a <strong>vision encoder</strong> to an <strong>LLM</strong> via a projection layer.</p>
<p><strong>Architecture:</strong></p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="bold">h</mi><mi>v</mi></msub><mo>=</mo><mtext>VisualEncoder</mtext><mo stretchy="false">(</mo><mi mathvariant="bold">I</mi><mo stretchy="false">)</mo><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>N</mi><mo>×</mo><msub><mi>d</mi><mi>v</mi></msub></mrow></msup></mrow><annotation encoding="application/x-tex">\mathbf{h}_v = \text{VisualEncoder}(\mathbf{I}) \in \mathbb{R}^{N\times d_v}</annotation></semantics></math></span><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mover accent="true"><mi mathvariant="bold">h</mi><mo>~</mo></mover><mi>v</mi></msub><mo>=</mo><msub><mi>W</mi><mtext>proj</mtext></msub><mtext> </mtext><msub><mi mathvariant="bold">h</mi><mi>v</mi></msub><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>N</mi><mo>×</mo><mi>d</mi></mrow></msup><mo separator="true">,</mo><mspace width="1em"/><msub><mi>W</mi><mtext>proj</mtext></msub><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>d</mi><mo>×</mo><msub><mi>d</mi><mi>v</mi></msub></mrow></msup></mrow><annotation encoding="application/x-tex">\tilde{\mathbf{h}}_v = W_{\text{proj}}\,\mathbf{h}_v \in \mathbb{R}^{N\times d}, \quad W_{\text{proj}} \in \mathbb{R}^{d\times d_v}</annotation></semantics></math></span><p>Visual tokens <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mover accent="true"><mi mathvariant="bold">h</mi><mo>~</mo></mover><mi>v</mi></msub></mrow><annotation encoding="application/x-tex">\tilde{\mathbf{h}}_v</annotation></semantics></math></span> are prepended (or interleaved) with text tokens and fed into the LLM:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>input</mtext><mo>=</mo><mo stretchy="false">[</mo><msub><mover accent="true"><mi mathvariant="bold">h</mi><mo>~</mo></mover><mi>v</mi></msub><mo separator="true">;</mo><mtext> </mtext><msub><mi mathvariant="bold">h</mi><mtext>text</mtext></msub><mo stretchy="false">]</mo></mrow><annotation encoding="application/x-tex">\text{input} = [\tilde{\mathbf{h}}_v;\, \mathbf{h}_{\text{text}}]</annotation></semantics></math></span><p><strong>LLaVA-style training</strong> — two stages:</p>
<ol>
<li>Pre-train projection only (freeze encoder + LLM): learn <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>W</mi><mtext>proj</mtext></msub></mrow><annotation encoding="application/x-tex">W_{\text{proj}}</annotation></semantics></math></span></li>
<li>Instruction fine-tuning: unfreeze LLM, train on (image, instruction, response) triplets</li>
</ol>
<p><strong>Objective</strong> — standard next-token prediction on response tokens only:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi mathvariant="script">L</mi><mo>=</mo><mo>−</mo><munder><mo>∑</mo><mi>t</mi></munder><mi>log</mi><mo>⁡</mo><msub><mi>P</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi>y</mi><mi>t</mi></msub><mo>∣</mo><mi mathvariant="bold">I</mi><mo separator="true">,</mo><mtext> </mtext><mi mathvariant="bold">x</mi><mo separator="true">,</mo><mtext> </mtext><msub><mi>y</mi><mrow><mo>&lt;</mo><mi>t</mi></mrow></msub><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathcal{L} = -\sum_{t} \log P_\theta(y_t \mid \mathbf{I},\, \mathbf{x},\, y_{\lt t})</annotation></semantics></math></span><hr>
<h3 id="cross-modal-attention">Cross-Modal Attention</h3>
<p>Allow one modality to attend over another. Text queries attend to visual keys/values:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msubsup><mi mathvariant="bold">h</mi><mtext>text</mtext><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msubsup><mo>=</mo><mtext>Attention</mtext><mo stretchy="false">(</mo><msub><mi>Q</mi><mtext>text</mtext></msub><mo separator="true">,</mo><mtext>  </mtext><msub><mi>K</mi><mtext>vision</mtext></msub><mo separator="true">,</mo><mtext>  </mtext><msub><mi>V</mi><mtext>vision</mtext></msub><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathbf{h}&#x27;_{\text{text}} = \text{Attention}(Q_{\text{text}},\; K_{\text{vision}},\; V_{\text{vision}})</annotation></semantics></math></span><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mo>=</mo><mtext>softmax</mtext><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><mfrac><mrow><msub><mi>Q</mi><mtext>text</mtext></msub><msubsup><mi>K</mi><mtext>vision</mtext><mi mathvariant="normal">⊤</mi></msubsup></mrow><msqrt><msub><mi>d</mi><mi>k</mi></msub></msqrt></mfrac><mo fence="true">)</mo></mrow><msub><mi>V</mi><mtext>vision</mtext></msub></mrow><annotation encoding="application/x-tex">= \text{softmax}\!\left(\frac{Q_{\text{text}} K_{\text{vision}}^\top}{\sqrt{d_k}}\right) V_{\text{vision}}</annotation></semantics></math></span><p>Used in <strong>Flamingo</strong>, whose gated cross-attention layers read visual tokens from a Perceiver Resampler.</p>
<hr>
<h3 id="image-generation--text-to-image">Image Generation — Text-to-Image</h3>
<p>Condition a diffusion model on a text embedding <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi mathvariant="bold">c</mi><mo>=</mo><msub><mi>g</mi><mi>ϕ</mi></msub><mo stretchy="false">(</mo><mtext>prompt</mtext><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">\mathbf{c} = g_\phi(\text{prompt})</annotation></semantics></math></span>.</p>
<p><strong>Classifier-Free Guidance (CFG)</strong> — blend conditional and unconditional score:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mover accent="true"><mi mathvariant="bold-italic">ϵ</mi><mo>~</mo></mover><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo separator="true">,</mo><mi mathvariant="bold">c</mi><mo stretchy="false">)</mo><mo>=</mo><msub><mi mathvariant="bold-italic">ϵ</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo separator="true">,</mo><mi mathvariant="normal">∅</mi><mo stretchy="false">)</mo><mo>+</mo><mi>w</mi><mtext> ⁣</mtext><mrow><mo fence="true">(</mo><msub><mi mathvariant="bold-italic">ϵ</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo separator="true">,</mo><mi mathvariant="bold">c</mi><mo stretchy="false">)</mo><mo>−</mo><msub><mi mathvariant="bold-italic">ϵ</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi mathvariant="bold">x</mi><mi>t</mi></msub><mo separator="true">,</mo><mi mathvariant="normal">∅</mi><mo stretchy="false">)</mo><mo fence="true">)</mo></mrow></mrow><annotation encoding="application/x-tex">\tilde{\boldsymbol{\epsilon}}_\theta(\mathbf{x}_t, \mathbf{c}) = \boldsymbol{\epsilon}_\theta(\mathbf{x}_t, \emptyset) + w\!\left(\boldsymbol{\epsilon}_\theta(\mathbf{x}_t, \mathbf{c}) - \boldsymbol{\epsilon}_\theta(\mathbf{x}_t, \emptyset)\right)</annotation></semantics></math></span><ul>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>w</mi><mo>&gt;</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">w &gt; 1</annotation></semantics></math></span>: stronger text conditioning (higher fidelity to prompt, less diversity).</li>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>w</mi><mo>=</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">w = 1</annotation></semantics></math></span>: standard conditional generation.</li>
<li><span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>w</mi><mo>=</mo><mn>0</mn></mrow><annotation encoding="application/x-tex">w = 0</annotation></semantics></math></span>: unconditional generation.</li>
</ul>
<p><strong>Latent Diffusion (Stable Diffusion)</strong> — run diffusion in a compressed latent space:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi mathvariant="bold">z</mi><mo>=</mo><mi mathvariant="script">E</mi><mo stretchy="false">(</mo><mi mathvariant="bold">x</mi><mo stretchy="false">)</mo><mo separator="true">,</mo><mspace width="1em"/><mover accent="true"><mi mathvariant="bold">x</mi><mo>^</mo></mover><mo>=</mo><mi mathvariant="script">D</mi><mo stretchy="false">(</mo><mi mathvariant="bold">z</mi><mo stretchy="false">)</mo><mo separator="true">,</mo><mspace width="1em"/><mi mathvariant="script">L</mi><mo>=</mo><msub><mi mathvariant="double-struck">E</mi><mrow><mi>t</mi><mo separator="true">,</mo><msub><mi mathvariant="bold">z</mi><mn>0</mn></msub><mo separator="true">,</mo><mi mathvariant="bold-italic">ϵ</mi></mrow></msub><mtext> ⁣</mtext><mrow><mo fence="true">[</mo><mi mathvariant="normal">∥</mi><mi mathvariant="bold-italic">ϵ</mi><mo>−</mo><msub><mi mathvariant="bold-italic">ϵ</mi><mi>θ</mi></msub><mo stretchy="false">(</mo><msub><mi mathvariant="bold">z</mi><mi>t</mi></msub><mo separator="true">,</mo><mi>t</mi><mo separator="true">,</mo><mi mathvariant="bold">c</mi><mo stretchy="false">)</mo><msup><mi mathvariant="normal">∥</mi><mn>2</mn></msup><mo fence="true">]</mo></mrow></mrow><annotation encoding="application/x-tex">\mathbf{z} = \mathcal{E}(\mathbf{x}), \quad \hat{\mathbf{x}} = \mathcal{D}(\mathbf{z}), \quad \mathcal{L} = \mathbb{E}_{t,\mathbf{z}_0,\boldsymbol{\epsilon}}\!\left[\|\boldsymbol{\epsilon} - \boldsymbol{\epsilon}_\theta(\mathbf{z}_t, t, \mathbf{c})\|^2\right]</annotation></semantics></math></span><hr>
<h3 id="multimodal-summary">Multimodal Summary</h3>
<table>
  <thead>
      <tr>
          <th>Model / Concept</th>
          <th>Modalities</th>
          <th>Key idea</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><strong>CLIP</strong></td>
          <td>Image + Text</td>
          <td>Contrastive alignment, InfoNCE</td>
      </tr>
      <tr>
          <td><strong>LLaVA / InternVL</strong></td>
          <td>Image + Text</td>
          <td>Visual tokens → LLM via projection</td>
      </tr>
      <tr>
          <td><strong>Flamingo</strong></td>
          <td>Image + Text</td>
          <td>Cross-modal attention layers</td>
      </tr>
      <tr>
          <td><strong>Stable Diffusion</strong></td>
          <td>Text → Image</td>
          <td>Latent diffusion + CFG</td>
      </tr>
      <tr>
          <td><strong>Whisper</strong></td>
          <td>Audio → Text</td>
          <td>Spectrogram encoder + decoder</td>
      </tr>
      <tr>
          <td><strong>GPT-4o</strong></td>
          <td>Image/Audio/Text</td>
          <td>Unified multimodal autoregressive LLM</td>
      </tr>
  </tbody>
</table>
]]></content:encoded></item><item><title>AlphaFold Explained: Learning the Basics with PyTorch</title><link>https://brice6.pages.dev/posts/mai/compsci-713/alphafold/</link><pubDate>Thu, 05 Mar 2026 00:00:00 +0000</pubDate><guid>https://brice6.pages.dev/posts/mai/compsci-713/alphafold/</guid><description>A beginner-friendly AlphaFold introduction that uses PyTorch, tensors, and attention to build intuition from first principles.</description><content:encoded><![CDATA[<blockquote>
<p>This note is <strong>not</strong> a full reproduction of AlphaFold. The goal is to build the right mental model: what problem AlphaFold solves, what tensors it operates on, and why attention-based geometry reasoning makes sense for proteins.</p>
</blockquote>
<h2 id="setup">Setup</h2>
<p>If you want to experiment locally, a lightweight Python environment is enough for the tensor-level ideas in this article.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">brew install uv
</span></span><span class="line"><span class="cl">mkdir alpha_fold <span class="o">&amp;&amp;</span> <span class="nb">cd</span> alpha_fold
</span></span><span class="line"><span class="cl">uv init .
</span></span><span class="line"><span class="cl">uv add torch numpy matplotlib jupyterlab
</span></span></code></pre></div><p>This is enough to prototype shapes, attention maps, distance matrices, and toy structure predictors in notebooks.</p>
<hr>
<h2 id="what-problem-does-alphafold-solve">What Problem Does AlphaFold Solve?</h2>
<p>A protein is a sequence of amino acids:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mo stretchy="false">(</mo><msub><mi>a</mi><mn>1</mn></msub><mo separator="true">,</mo><msub><mi>a</mi><mn>2</mn></msub><mo separator="true">,</mo><mo>…</mo><mo separator="true">,</mo><msub><mi>a</mi><mi>n</mi></msub><mo stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">
(a_1, a_2, \dots, a_n)
</annotation></semantics></math></span><p>but its function depends heavily on its <strong>3D structure</strong>, not only its 1D sequence.</p>
<p>The hard problem is:</p>
<blockquote>
<p>Given the amino-acid sequence, predict the final spatial arrangement of atoms.</p>
</blockquote>
<p>This is difficult because:</p>
<ul>
<li>the number of possible conformations is enormous</li>
<li>interactions are long-range</li>
<li>local sequence neighbors are not the only important neighbors in 3D space</li>
</ul>
<p>AlphaFold's key contribution is that it turns structure prediction into a learning problem over <strong>representations of residues and residue pairs</strong>, then repeatedly refines those representations using attention-style updates.</p>
<hr>
<h2 id="why-pytorch-is-a-good-learning-tool">Why PyTorch Is a Good Learning Tool</h2>
<p>Before thinking about proteins, it helps to think in terms of tensors.</p>
<p>In PyTorch, a tensor is simply a multidimensional array with efficient numerical operations and automatic differentiation:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">torch</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">x</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">tensor</span><span class="p">([[</span><span class="mf">1.0</span><span class="p">,</span> <span class="mf">2.0</span><span class="p">],</span> <span class="p">[</span><span class="mf">3.0</span><span class="p">,</span> <span class="mf">4.0</span><span class="p">]])</span>
</span></span><span class="line"><span class="cl"><span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span>  <span class="c1"># torch.Size([2, 2])</span>
</span></span></code></pre></div><p>AlphaFold is fundamentally a tensor program:</p>
<ul>
<li>sequence features become tensors</li>
<li>pairwise residue relationships become tensors</li>
<li>attention updates those tensors</li>
<li>losses compare predicted geometry with known structures</li>
</ul>
<p>Once you understand the shapes, the architecture becomes much less mysterious.</p>
<hr>
<h2 id="the-core-representations">The Core Representations</h2>
<p>A useful simplification is to think of AlphaFold as operating on two main objects.</p>
<h3 id="1-sequence--residue-representation">1. Sequence / residue representation</h3>
<p>For a protein with <code>N</code> residues, we keep a feature vector for each residue:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>R</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>N</mi><mo>×</mo><msub><mi>d</mi><mi>r</mi></msub></mrow></msup></mrow><annotation encoding="application/x-tex">
R \in \mathbb{R}^{N \times d_r}
</annotation></semantics></math></span><p>This stores per-residue information such as:</p>
<ul>
<li>amino-acid identity</li>
<li>evolutionary context</li>
<li>learned hidden features</li>
</ul>
<h3 id="2-pair-representation">2. Pair representation</h3>
<p>We also keep a feature vector for each residue pair <code>(i, j)</code>:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>P</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>N</mi><mo>×</mo><mi>N</mi><mo>×</mo><msub><mi>d</mi><mi>p</mi></msub></mrow></msup></mrow><annotation encoding="application/x-tex">
P \in \mathbb{R}^{N \times N \times d_p}
</annotation></semantics></math></span><p>This is the crucial idea. Protein geometry is relational, so we need a representation for questions like:</p>
<ul>
<li>are residues <code>i</code> and <code>j</code> likely to be close?</li>
<li>what orientation might they have?</li>
<li>does evidence suggest a contact or constraint?</li>
</ul>
<p>In many ways, the pair tensor acts like a learned geometric memory.</p>
<hr>
<h2 id="why-pairwise-reasoning-matters">Why Pairwise Reasoning Matters</h2>
<p>A protein chain is local in sequence but not local in space.</p>
<p>Residues that are far apart in index may become neighbors after folding. So a model that only looks at nearby tokens in 1D will miss important interactions.</p>
<p>This is where AlphaFold departs from simpler sequence models. It explicitly models <strong>residue-residue interactions</strong> rather than hoping they emerge implicitly.</p>
<p>If we define a crude distance matrix from coordinates:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi>D</mi><mrow><mi>i</mi><mi>j</mi></mrow></msub><mo>=</mo><mi mathvariant="normal">∥</mi><msub><mi>x</mi><mi>i</mi></msub><mo>−</mo><msub><mi>x</mi><mi>j</mi></msub><msub><mi mathvariant="normal">∥</mi><mn>2</mn></msub></mrow><annotation encoding="application/x-tex">
D_{ij} = \|x_i - x_j\|_2
</annotation></semantics></math></span><p>then the folding problem is deeply related to recovering a geometrically consistent version of this pairwise structure.</p>
<hr>
<h2 id="evolutionary-information-and-msa-intuition">Evolutionary Information and MSA Intuition</h2>
<p>One major source of signal in protein prediction is the <strong>multiple sequence alignment (MSA)</strong>.</p>
<p>The intuition is:</p>
<ul>
<li>related proteins evolve over time</li>
<li>positions that mutate together often reflect structural dependence</li>
<li>co-evolution gives clues about spatial constraints</li>
</ul>
<p>You do not need to implement a full MSA pipeline to understand the idea. Conceptually, the MSA gives the model a tensor like:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>M</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>S</mi><mo>×</mo><mi>N</mi><mo>×</mo><msub><mi>d</mi><mi>m</mi></msub></mrow></msup></mrow><annotation encoding="application/x-tex">
M \in \mathbb{R}^{S \times N \times d_m}
</annotation></semantics></math></span><p>where:</p>
<ul>
<li><code>S</code> = number of aligned sequences</li>
<li><code>N</code> = protein length</li>
<li><code>d_m</code> = feature dimension</li>
</ul>
<p>AlphaFold uses attention to move information:</p>
<ul>
<li>across positions inside a sequence</li>
<li>across related sequences at the same position</li>
<li>from MSA features into pair features</li>
</ul>
<p>This lets the network infer which residues likely constrain each other.</p>
<hr>
<h2 id="attention-but-for-structure">Attention, but for Structure</h2>
<p>Attention is useful because it lets every element selectively gather information from other elements.</p>
<p>The standard scaled dot-product attention is:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mtext>Attention</mtext><mo stretchy="false">(</mo><mi>Q</mi><mo separator="true">,</mo><mi>K</mi><mo separator="true">,</mo><mi>V</mi><mo stretchy="false">)</mo><mo>=</mo><mtext>softmax</mtext><mrow><mo fence="true">(</mo><mfrac><mrow><mi>Q</mi><msup><mi>K</mi><mi>T</mi></msup></mrow><msqrt><msub><mi>d</mi><mi>k</mi></msub></msqrt></mfrac><mo fence="true">)</mo></mrow><mi>V</mi></mrow><annotation encoding="application/x-tex">
\text{Attention}(Q,K,V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V
</annotation></semantics></math></span><p>In NLP, tokens attend to other tokens. In protein modeling, residues or MSA positions attend to other residues or aligned positions.</p>
<p>A minimal PyTorch example:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">math</span>
</span></span><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">torch</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">attention</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">Wq</span><span class="p">,</span> <span class="n">Wk</span><span class="p">,</span> <span class="n">Wv</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="n">q</span> <span class="o">=</span> <span class="n">x</span> <span class="o">@</span> <span class="n">Wq</span>
</span></span><span class="line"><span class="cl">    <span class="n">k</span> <span class="o">=</span> <span class="n">x</span> <span class="o">@</span> <span class="n">Wk</span>
</span></span><span class="line"><span class="cl">    <span class="n">v</span> <span class="o">=</span> <span class="n">x</span> <span class="o">@</span> <span class="n">Wv</span>
</span></span><span class="line"><span class="cl">    <span class="n">scores</span> <span class="o">=</span> <span class="n">q</span> <span class="o">@</span> <span class="n">k</span><span class="o">.</span><span class="n">transpose</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">2</span><span class="p">)</span> <span class="o">/</span> <span class="n">math</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">q</span><span class="o">.</span><span class="n">size</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">    <span class="n">weights</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">softmax</span><span class="p">(</span><span class="n">scores</span><span class="p">,</span> <span class="n">dim</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">weights</span> <span class="o">@</span> <span class="n">v</span>
</span></span></code></pre></div><p>The important idea is not the code itself. It is that attention gives the model a mechanism for learning:</p>
<ul>
<li>long-range dependencies</li>
<li>context-dependent interactions</li>
<li>relational patterns that are hard to encode by hand</li>
</ul>
<p>That is exactly what protein folding needs.</p>
<hr>
<h2 id="a-toy-residue-pair-pipeline-in-pytorch">A Toy Residue-Pair Pipeline in PyTorch</h2>
<p>A simple educational prototype is:</p>
<ol>
<li>embed the amino-acid sequence</li>
<li>build pair features by combining residue features</li>
<li>refine pair features with attention or MLP blocks</li>
<li>predict distances or contacts</li>
</ol>
<p>For example:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">torch</span>
</span></span><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">torch.nn</span> <span class="k">as</span> <span class="nn">nn</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">N</span> <span class="o">=</span> <span class="mi">128</span>
</span></span><span class="line"><span class="cl"><span class="n">d</span> <span class="o">=</span> <span class="mi">64</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">seq</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">randint</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="p">(</span><span class="n">N</span><span class="p">,))</span>
</span></span><span class="line"><span class="cl"><span class="n">embed</span> <span class="o">=</span> <span class="n">nn</span><span class="o">.</span><span class="n">Embedding</span><span class="p">(</span><span class="mi">20</span><span class="p">,</span> <span class="n">d</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">r</span> <span class="o">=</span> <span class="n">embed</span><span class="p">(</span><span class="n">seq</span><span class="p">)</span>                      <span class="c1"># [N, d]</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">ri</span> <span class="o">=</span> <span class="n">r</span><span class="o">.</span><span class="n">unsqueeze</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">expand</span><span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">N</span><span class="p">,</span> <span class="n">d</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">rj</span> <span class="o">=</span> <span class="n">r</span><span class="o">.</span><span class="n">unsqueeze</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span><span class="o">.</span><span class="n">expand</span><span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">N</span><span class="p">,</span> <span class="n">d</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">pair</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">cat</span><span class="p">([</span><span class="n">ri</span><span class="p">,</span> <span class="n">rj</span><span class="p">],</span> <span class="n">dim</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span>  <span class="c1"># [N, N, 2d]</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">pair_mlp</span> <span class="o">=</span> <span class="n">nn</span><span class="o">.</span><span class="n">Sequential</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="n">nn</span><span class="o">.</span><span class="n">Linear</span><span class="p">(</span><span class="mi">2</span> <span class="o">*</span> <span class="n">d</span><span class="p">,</span> <span class="n">d</span><span class="p">),</span>
</span></span><span class="line"><span class="cl">    <span class="n">nn</span><span class="o">.</span><span class="n">ReLU</span><span class="p">(),</span>
</span></span><span class="line"><span class="cl">    <span class="n">nn</span><span class="o">.</span><span class="n">Linear</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">d</span><span class="p">),</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">pair_features</span> <span class="o">=</span> <span class="n">pair_mlp</span><span class="p">(</span><span class="n">pair</span><span class="p">)</span>      <span class="c1"># [N, N, d]</span>
</span></span><span class="line"><span class="cl"><span class="n">dist_head</span> <span class="o">=</span> <span class="n">nn</span><span class="o">.</span><span class="n">Linear</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">pred_dist</span> <span class="o">=</span> <span class="n">dist_head</span><span class="p">(</span><span class="n">pair_features</span><span class="p">)</span><span class="o">.</span><span class="n">squeeze</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>  <span class="c1"># [N, N]</span>
</span></span></code></pre></div><p>This is still far from AlphaFold, but it already captures a central idea:</p>
<blockquote>
<p>structure prediction benefits from explicitly learning a feature for each residue pair</p>
</blockquote>
<hr>
<h2 id="geometry-is-more-than-distances">Geometry Is More Than Distances</h2>
<p>Distances alone are not enough. A valid protein structure must satisfy consistent geometry:</p>
<ul>
<li>bond lengths</li>
<li>bond angles</li>
<li>torsion angles</li>
<li>rigid-body constraints</li>
</ul>
<p>That is why modern structure predictors go beyond contact maps. They learn richer geometric signals and refine them iteratively until the output becomes physically plausible.</p>
<p>One intuition is to think of the model as repeatedly asking:</p>
<ul>
<li>what should residue <code>i</code> know about residue <code>j</code>?</li>
<li>what geometric relation is plausible?</li>
<li>is the current global structure self-consistent?</li>
</ul>
<hr>
<h2 id="from-hidden-states-to-coordinates">From Hidden States to Coordinates</h2>
<p>A useful abstraction is:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mo stretchy="false">(</mo><mtext>sequence features</mtext><mo separator="true">,</mo><mtext>pair features</mtext><mo stretchy="false">)</mo><mo>→</mo><mtext>geometric reasoning</mtext><mo>→</mo><mtext>3D coordinates</mtext></mrow><annotation encoding="application/x-tex">
(\text{sequence features}, \text{pair features}) \rightarrow \text{geometric reasoning} \rightarrow \text{3D coordinates}
</annotation></semantics></math></span><p>The final output can be represented as coordinates:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><mi>X</mi><mo>∈</mo><msup><mi mathvariant="double-struck">R</mi><mrow><mi>N</mi><mo>×</mo><mn>3</mn></mrow></msup></mrow><annotation encoding="application/x-tex">
X \in \mathbb{R}^{N \times 3}
</annotation></semantics></math></span><p>for backbone atoms or residue-level positions, depending on the level of simplification.</p>
<p>During training, predicted structures are compared with target structures using geometry-aware losses. In a toy setting, you might start with a distance loss such as:</p>
<span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msub><mi mathvariant="script">L</mi><mtext>dist</mtext></msub><mo>=</mo><mfrac><mn>1</mn><msup><mi>N</mi><mn>2</mn></msup></mfrac><munder><mo>∑</mo><mrow><mi>i</mi><mo separator="true">,</mo><mi>j</mi></mrow></munder><msup><mrow><mo fence="true">(</mo><msub><mover accent="true"><mi>D</mi><mo>^</mo></mover><mrow><mi>i</mi><mi>j</mi></mrow></msub><mo>−</mo><msub><mi>D</mi><mrow><mi>i</mi><mi>j</mi></mrow></msub><mo fence="true">)</mo></mrow><mn>2</mn></msup></mrow><annotation encoding="application/x-tex">
\mathcal{L}_{\text{dist}} = \frac{1}{N^2}\sum_{i,j}\left(\hat{D}_{ij} - D_{ij}\right)^2
</annotation></semantics></math></span><p>where <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mover accent="true"><mi>D</mi><mo>^</mo></mover><mrow><mi>i</mi><mi>j</mi></mrow></msub></mrow><annotation encoding="application/x-tex">\hat{D}_{ij}</annotation></semantics></math></span> is the predicted distance and <span class="katex"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><msub><mi>D</mi><mrow><mi>i</mi><mi>j</mi></mrow></msub></mrow><annotation encoding="application/x-tex">D_{ij}</annotation></semantics></math></span> is the ground truth.</p>
<p>Real systems use richer objectives, but this simplified loss is enough to understand how a model can learn geometry from supervision.</p>
<hr>
<h2 id="what-makes-alphafold-different-from-a-plain-transformer">What Makes AlphaFold Different from a Plain Transformer?</h2>
<p>A plain transformer over the amino-acid sequence is not enough because folding is not just sequence modeling.</p>
<p>AlphaFold-like systems are distinctive because they:</p>
<ul>
<li>maintain <strong>pair representations</strong></li>
<li>incorporate <strong>evolutionary evidence</strong></li>
<li>use <strong>geometry-aware refinement</strong></li>
<li>enforce stronger <strong>structural consistency</strong></li>
</ul>
<p>So the architecture is not merely &quot;attention on proteins&quot;. It is an architecture designed specifically for <strong>relational geometry</strong>.</p>
<hr>
<h2 id="a-good-learning-path">A Good Learning Path</h2>
<p>If you want to study AlphaFold seriously, the order below is practical:</p>
<ol>
<li>understand PyTorch tensors and broadcasting</li>
<li>learn attention thoroughly</li>
<li>study pairwise feature construction</li>
<li>implement contact-map or distance-matrix prediction</li>
<li>add simple geometric losses</li>
<li>only then read the full AlphaFold architecture</li>
</ol>
<p>This order matters. Without strong intuition for tensors and attention, the full model is easy to memorize but hard to really understand.</p>
<hr>
<h2 id="final-intuition">Final Intuition</h2>
<p>The most useful mental model is this:</p>
<blockquote>
<p>AlphaFold is a learned system for turning sequence information and evolutionary constraints into a consistent geometric representation of a protein.</p>
</blockquote>
<p>PyTorch helps because it makes the machinery concrete:</p>
<ul>
<li>residue embeddings are tensors</li>
<li>pair relationships are tensors</li>
<li>attention updates those tensors</li>
<li>losses push them toward valid structure</li>
</ul>
<p>Once you see the problem through that lens, AlphaFold stops looking like magic and starts looking like a very sophisticated, geometry-aware deep learning system.</p>
]]></content:encoded></item></channel></rss>