LabHub

Blog

Math + LaTeX/KaTeX Complete Guide for Reading AI/ML Papers

한국어English日本語中文

Introduction

Open an AI/ML paper for the first time and the thing that feels most like a wall is the formulas. A developer who can read and write code can usually follow the algorithm itself, but without knowing the notation you get stuck on page one.

This article pulls together, in one place, "the minimum math you need in order to read papers" and "the LaTeX/KaTeX syntax that expresses that math". The goal is not to study a textbook cover to cover — it is to pick up quickly the patterns that show up over and over in real papers.


1. A Math Roadmap for Papers

1.1 Linear Algebra

Vectors and Matrices

In papers, data is almost always represented as a vector or a matrix.

% Vector (boldface)
\mathbf{x} = \begin{bmatrix} x_1 \\ x_2 \\ \vdots \\ x_n \end{bmatrix}

% Matrix
\mathbf{W} = \begin{bmatrix}
  w_{11} & w_{12} & \cdots & w_{1n} \\
  w_{21} & w_{22} & \cdots & w_{2n} \\
  \vdots & \vdots & \ddots & \vdots \\
  w_{m1} & w_{m2} & \cdots & w_{mn}
\end{bmatrix}

Core operation:

y=Wx+b\mathbf{y} = \mathbf{W}\mathbf{x} + \mathbf{b}

That single line is one layer of a neural network. W\mathbf{W} is the weights, b\mathbf{b} the bias.

Dot Product

The most basic operation for measuring the similarity of two vectors.

ab=ab=i=1naibi\mathbf{a} \cdot \mathbf{b} = \mathbf{a}^\top \mathbf{b} = \sum_{i=1}^{n} a_i b_i
\mathbf{a}^\top \mathbf{b} = \sum_{i=1}^{n} a_i b_i

Eigendecomposition

For a matrix A\mathbf{A}, this means finding the λ\lambda (eigenvalue) and v\mathbf{v} (eigenvector) that satisfy Av=λv\mathbf{A}\mathbf{v} = \lambda \mathbf{v}. It shows up as a core ingredient in PCA, spectral clustering, and similar methods.

Singular Value Decomposition (SVD)

Decomposes an arbitrary matrix ARm×n\mathbf{A} \in \mathbb{R}^{m \times n} into a product of three matrices.

A=UΣV\mathbf{A} = \mathbf{U} \boldsymbol{\Sigma} \mathbf{V}^\top

It turns up constantly in dimensionality reduction, recommender systems, LoRA, and more.

\mathbf{A} = \mathbf{U} \boldsymbol{\Sigma} \mathbf{V}^\top

Norms

Measure the "size" of a vector.

NormFormulaMeaningUse in papers
L1L_1x1=ixi\lVert \mathbf{x} \rVert_1 = \sum_i \lvert x_i \rvertSum of absolute valuesLasso regularization, sparsity
L2L_2x2=ixi2\lVert \mathbf{x} \rVert_2 = \sqrt{\sum_i x_i^2}Euclidean distanceRidge regularization, weight decay
LL_\inftyx=maxixi\lVert \mathbf{x} \rVert_\infty = \max_i \lvert x_i \rvertLargest absolute valueadversarial attack bound
FrobeniusAF=i,jaij2\lVert \mathbf{A} \rVert_F = \sqrt{\sum_{i,j} a_{ij}^2}Root of the summed squared entriesMatrix approximation error

1.2 Calculus

Partial Derivatives

Differentiating a multivariable function with respect to one variable only.

fxi\frac{\partial f}{\partial x_i}

It tells you how much each parameter of a network influences the loss.

Gradient (the vector of partial derivatives)

All the partial derivatives collected into a vector.

θL=[Lθ1Lθ2Lθn]\nabla_{\boldsymbol{\theta}} \mathcal{L} = \begin{bmatrix} \frac{\partial \mathcal{L}}{\partial \theta_1} \\ \frac{\partial \mathcal{L}}{\partial \theta_2} \\ \vdots \\ \frac{\partial \mathcal{L}}{\partial \theta_n} \end{bmatrix}
\nabla_{\boldsymbol{\theta}} \mathcal{L} = \begin{bmatrix}
  \frac{\partial \mathcal{L}}{\partial \theta_1} \\
  \frac{\partial \mathcal{L}}{\partial \theta_2} \\
  \vdots \\
  \frac{\partial \mathcal{L}}{\partial \theta_n}
\end{bmatrix}

Chain Rule

The differentiation rule for composite functions, and the mathematical basis of backpropagation.

Lx=Lyyx\frac{\partial \mathcal{L}}{\partial \mathbf{x}} = \frac{\partial \mathcal{L}}{\partial \mathbf{y}} \cdot \frac{\partial \mathbf{y}}{\partial \mathbf{x}}

A 3-layer network example:

LW1=Ly^y^h2h2h1h1W1\frac{\partial \mathcal{L}}{\partial \mathbf{W}_1} = \frac{\partial \mathcal{L}}{\partial \hat{\mathbf{y}}} \cdot \frac{\partial \hat{\mathbf{y}}}{\partial \mathbf{h}_2} \cdot \frac{\partial \mathbf{h}_2}{\partial \mathbf{h}_1} \cdot \frac{\partial \mathbf{h}_1}{\partial \mathbf{W}_1}

Jacobian and Hessian

The Hessian carries curvature information, so it is used in second-order optimization (Newton's method).

\mathbf{J} = \begin{bmatrix}
  \frac{\partial f_1}{\partial x_1} & \cdots & \frac{\partial f_1}{\partial x_n} \\
  \vdots & \ddots & \vdots \\
  \frac{\partial f_m}{\partial x_1} & \cdots & \frac{\partial f_m}{\partial x_n}
\end{bmatrix}

1.3 Probability and Statistics

Probability Distributions

DistributionFormulaUse in papers
BernoulliP(x)=px(1p)1xP(x) = p^x (1-p)^{1-x}Binary classification
CategoricalP(x=k)=πkP(x=k) = \pi_kMulti-class classification
GaussianN(xμ,σ2)=12πσ2exp ⁣((xμ)22σ2)\mathcal{N}(x \mid \mu, \sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\!\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)VAE latent space, noise modeling
Multivariate GaussianN(xμ,Σ)\mathcal{N}(\mathbf{x} \mid \boldsymbol{\mu}, \boldsymbol{\Sigma})Continuous latent variables

Expectation and Variance

E[X]=xxP(x)(discrete),E[X]=xp(x)dx(continuous)\mathbb{E}[X] = \sum_x x \, P(x) \quad \text{(discrete)}, \qquad \mathbb{E}[X] = \int x \, p(x) \, dx \quad \text{(continuous)} Var(X)=E[(XE[X])2]=E[X2](E[X])2\text{Var}(X) = \mathbb{E}[(X - \mathbb{E}[X])^2] = \mathbb{E}[X^2] - (\mathbb{E}[X])^2
\mathbb{E}[X] = \sum_x x \, P(x)
\text{Var}(X) = \mathbb{E}[X^2] - (\mathbb{E}[X])^2

Conditional Probability and Bayes' Theorem

P(AB)=P(BA)P(A)P(B)P(A \mid B) = \frac{P(B \mid A) \, P(A)}{P(B)}

MLE and MAP

Maximum Likelihood Estimation (MLE):

θ^MLE=argmaxθi=1Np(xiθ)=argmaxθi=1Nlogp(xiθ)\hat{\boldsymbol{\theta}}_{\text{MLE}} = \arg\max_{\boldsymbol{\theta}} \prod_{i=1}^{N} p(\mathbf{x}_i \mid \boldsymbol{\theta}) = \arg\max_{\boldsymbol{\theta}} \sum_{i=1}^{N} \log p(\mathbf{x}_i \mid \boldsymbol{\theta})

Maximum A Posteriori (MAP):

θ^MAP=argmaxθ[i=1Nlogp(xiθ)+logp(θ)]\hat{\boldsymbol{\theta}}_{\text{MAP}} = \arg\max_{\boldsymbol{\theta}} \left[ \sum_{i=1}^{N} \log p(\mathbf{x}_i \mid \boldsymbol{\theta}) + \log p(\boldsymbol{\theta}) \right]

MAP is MLE with a prior distribution p(θ)p(\boldsymbol{\theta}) added. L2 regularization is equivalent to MAP under a Gaussian prior.


1.4 Optimization

Gradient Descent

θt+1=θtηθL(θt)\boldsymbol{\theta}_{t+1} = \boldsymbol{\theta}_t - \eta \nabla_{\boldsymbol{\theta}} \mathcal{L}(\boldsymbol{\theta}_t)

η\eta is the learning rate. Use mini-batches and it becomes SGD.

Adam Optimizer

The most widely used optimizer. It uses moving averages of the first moment (mean) and the second moment (variance).

mt=β1mt1+(1β1)gtvt=β2vt1+(1β2)gt2m^t=mt1β1t,v^t=vt1β2tθt+1=θtηv^t+ϵm^t\begin{aligned} m_t &= \beta_1 m_{t-1} + (1-\beta_1) g_t \\ v_t &= \beta_2 v_{t-1} + (1-\beta_2) g_t^2 \\ \hat{m}_t &= \frac{m_t}{1-\beta_1^t}, \quad \hat{v}_t = \frac{v_t}{1-\beta_2^t} \\ \boldsymbol{\theta}_{t+1} &= \boldsymbol{\theta}_t - \frac{\eta}{\sqrt{\hat{v}_t} + \epsilon} \hat{m}_t \end{aligned}
\begin{aligned}
m_t &= \beta_1 m_{t-1} + (1-\beta_1) g_t \\
v_t &= \beta_2 v_{t-1} + (1-\beta_2) g_t^2 \\
\hat{m}_t &= \frac{m_t}{1-\beta_1^t}, \quad
\hat{v}_t &= \frac{v_t}{1-\beta_2^t} \\
\theta_{t+1} &= \theta_t
  - \frac{\eta}{\sqrt{\hat{v}_t} + \epsilon} \hat{m}_t
\end{aligned}

Regularization

Adds a penalty term to the loss function to prevent overfitting.

Lreg=Ldata+λθ22\mathcal{L}_{\text{reg}} = \mathcal{L}_{\text{data}} + \lambda \lVert \boldsymbol{\theta} \rVert_2^2

Convex vs Non-Convex

When a paper says "non-convex optimization", it means there is no guarantee of reaching the global optimum.


2. Formula Patterns That Recur in Papers

2.1 Softmax and Cross-Entropy

Softmax: converts a logit vector into a probability distribution.

softmax(zi)=ezij=1Kezj\text{softmax}(z_i) = \frac{e^{z_i}}{\sum_{j=1}^{K} e^{z_j}}

Cross-Entropy Loss: the standard loss function for classification.

LCE=i=1Kyilog(y^i)\mathcal{L}_{\text{CE}} = -\sum_{i=1}^{K} y_i \log(\hat{y}_i)

Here yiy_i is the one-hot label and y^i\hat{y}_i is the softmax output.

\text{softmax}(z_i) = \frac{e^{z_i}}{\sum_{j=1}^{K} e^{z_j}}

\mathcal{L}_{\text{CE}} = -\sum_{i=1}^{K} y_i \log(\hat{y}_i)

2.2 Attention Score and Scaled Dot-Product

Scaled Dot-Product Attention, the heart of the Transformer:

Attention(Q,K,V)=softmax ⁣(QKdk)V\text{Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\right)\mathbf{V}

Multi-Head Attention:

MultiHead(Q,K,V)=Concat(head1,,headh)WO\text{MultiHead}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{Concat}(\text{head}_1, \ldots, \text{head}_h)\mathbf{W}^O where headi=Attention(QWiQ,KWiK,VWiV)\text{where } \text{head}_i = \text{Attention}(\mathbf{Q}\mathbf{W}_i^Q, \mathbf{K}\mathbf{W}_i^K, \mathbf{V}\mathbf{W}_i^V)
\text{Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V})
  = \text{softmax}\!\left(
    \frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}
  \right)\mathbf{V}

2.3 KL Divergence and ELBO

KL Divergence: measures the "distance" (asymmetric) between two probability distributions.

DKL(qp)=xq(x)logq(x)p(x)=Eq ⁣[logq(x)p(x)]D_{\text{KL}}(q \,\|\, p) = \sum_x q(x) \log \frac{q(x)}{p(x)} = \mathbb{E}_{q}\!\left[\log \frac{q(x)}{p(x)}\right]

Properties:

ELBO (Evidence Lower Bound): the core objective function of the VAE.

logp(x)Eq(zx)[logp(xz)]reconstructionDKL(q(zx)p(z))regularization=ELBO\log p(\mathbf{x}) \geq \underbrace{\mathbb{E}_{q(\mathbf{z}|\mathbf{x})}[\log p(\mathbf{x}|\mathbf{z})]}_{\text{reconstruction}} - \underbrace{D_{\text{KL}}(q(\mathbf{z}|\mathbf{x}) \,\|\, p(\mathbf{z}))}_{\text{regularization}} = \text{ELBO}
\log p(\mathbf{x}) \geq
  \underbrace{\mathbb{E}_{q(\mathbf{z}|\mathbf{x})}
  [\log p(\mathbf{x}|\mathbf{z})]}_{\text{reconstruction}}
  - \underbrace{D_{\text{KL}}(q(\mathbf{z}|\mathbf{x})
  \,\|\, p(\mathbf{z}))}_{\text{regularization}}

2.4 Normalization and Loss Notation

Layer Normalization:

LayerNorm(x)=xμσ2+ϵγ+β\text{LayerNorm}(\mathbf{x}) = \frac{\mathbf{x} - \mu}{\sqrt{\sigma^2 + \epsilon}} \odot \boldsymbol{\gamma} + \boldsymbol{\beta}

Here μ=1di=1dxi\mu = \frac{1}{d}\sum_{i=1}^d x_i and σ2=1di=1d(xiμ)2\sigma^2 = \frac{1}{d}\sum_{i=1}^d (x_i - \mu)^2, while γ\boldsymbol{\gamma} and β\boldsymbol{\beta} are learnable parameters and \odot is element-wise multiplication.

Batch Normalization:

x^i=xiμBσB2+ϵ\hat{x}_i = \frac{x_i - \mu_B}{\sqrt{\sigma_B^2 + \epsilon}}

μB\mu_B and σB2\sigma_B^2 are computed per mini-batch.

RMSNorm (used in LLaMA and others):

RMSNorm(x)=xRMS(x)γ,RMS(x)=1di=1dxi2\text{RMSNorm}(\mathbf{x}) = \frac{\mathbf{x}}{\text{RMS}(\mathbf{x})} \odot \boldsymbol{\gamma}, \quad \text{RMS}(\mathbf{x}) = \sqrt{\frac{1}{d}\sum_{i=1}^d x_i^2}

Loss notation conventions:


3. The Essentials of Reading and Writing LaTeX

3.1 Basic Formula Syntax

Fractions, Sums, Integrals

% Fraction
\frac{a}{b}            % → a/b
\dfrac{a}{b}           % → large fraction (display style)

% Sum
\sum_{i=1}^{N} x_i     % → Σ from i=1 to N
\prod_{j=1}^{M} p_j    % → Π from j=1 to M

% Integral
\int_{a}^{b} f(x)\,dx           % → definite integral
\iint_D f(x,y)\,dx\,dy          % → double integral
\oint_C \mathbf{F}\cdot d\mathbf{r}  % → line integral

Rendered result:

ab,i=1Nxi,abf(x)dx\frac{a}{b}, \quad \sum_{i=1}^{N} x_i, \quad \int_{a}^{b} f(x)\,dx

Subscripts and Superscripts

x_i           % subscript
x^2           % superscript (square)
x_i^{(j)}    % combined: the j-th iteration of the i-th element
\hat{y}       % y-hat (prediction)
\bar{x}       % x-bar (mean)
\tilde{x}     % x-tilde (transformed value)
\dot{x}       % time derivative
\mathbf{W}    % bold (matrix/vector)
\mathcal{L}   % calligraphic (loss function)
\mathbb{R}    % blackboard bold (number systems)

Patterns you see very often in papers:

y^,xˉ,x~,x˙,W,L,Rn\hat{y}, \quad \bar{x}, \quad \tilde{x}, \quad \dot{x}, \quad \mathbf{W}, \quad \mathcal{L}, \quad \mathbb{R}^n

Matrices

% Parenthesis matrix
\begin{pmatrix} a & b \\ c & d \end{pmatrix}

% Bracket matrix
\begin{bmatrix} a & b \\ c & d \end{bmatrix}

% Determinant
\begin{vmatrix} a & b \\ c & d \end{vmatrix}
(abcd),[abcd],abcd\begin{pmatrix} a & b \\ c & d \end{pmatrix}, \quad \begin{bmatrix} a & b \\ c & d \end{bmatrix}, \quad \begin{vmatrix} a & b \\ c & d \end{vmatrix}

3.2 Alignment Environments

aligned (aligning multi-line formulas)

$$
\begin{aligned}
  f(x) &= ax^2 + bx + c \\
       &= a(x - h)^2 + k \\
       &= a(x - r_1)(x - r_2)
\end{aligned}
$$
f(x)=ax2+bx+c=a(xh)2+k=a(xr1)(xr2)\begin{aligned} f(x) &= ax^2 + bx + c \\ &= a(x - h)^2 + k \\ &= a(x - r_1)(x - r_2) \end{aligned}

The & symbol sets the alignment point, and \\ breaks the line.

cases (conditional branches)

$$
f(x) = \begin{cases}
  1 & \text{if } x > 0 \\
  0 & \text{if } x = 0 \\
  -1 & \text{if } x < 0
\end{cases}
$$
f(x)={1if x>00if x=01if x<0f(x) = \begin{cases} 1 & \text{if } x > 0 \\ 0 & \text{if } x = 0 \\ -1 & \text{if } x < 0 \end{cases}

You see it often in definitions of activation functions such as ReLU:

ReLU(x)=max(0,x)={xif x>00otherwise\text{ReLU}(x) = \max(0, x) = \begin{cases} x & \text{if } x > 0 \\ 0 & \text{otherwise} \end{cases}

3.3 How to Read the Macros Papers Commonly Use

You rarely look at LaTeX source directly from a paper PDF, but when you pull the arXiv source or write a blog post, certain macros come up again and again.

% Common user-defined macros
\newcommand{\E}{\mathbb{E}}           % expectation
\newcommand{\R}{\mathbb{R}}           % the reals
\newcommand{\KL}{D_{\text{KL}}}       % KL divergence
\newcommand{\norm}[1]{\lVert #1 \rVert}  % norm
\newcommand{\inner}[2]{\langle #1, #2 \rangle}  % inner product

% Usage examples
\E_{x \sim p}[f(x)]     % → 𝔼_{x~p}[f(x)]
\norm{\mathbf{x}}_2     % → ‖x‖₂
\inner{\mathbf{a}}{\mathbf{b}}  % → ⟨a, b⟩

Tip: to see the source of an arXiv paper, change abs to e-prints in the URL, or click "Download source" to get the .tex file. Checking the \newcommand definitions first makes decoding the formulas in the body far easier.


4. KaTeX in Practice

4.1 Rendering KaTeX in an MDX Blog

To use KaTeX on a Next.js + Contentlayer + MDX stack like this blog, you need two plugins.

npm install remark-math rehype-katex

An example Contentlayer configuration:

// contentlayer.config.ts
import remarkMath from 'remark-math'
import rehypeKatex from 'rehype-katex'

export default makeSource({
  mdx: {
    remarkPlugins: [remarkMath],
    rehypePlugins: [rehypeKatex],
  },
})

Then add the KaTeX CSS to your layout:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.css" />

4.2 When to Use Inline vs Block Formulas

Inline formulas ($...$): when the math flows naturally inside a sentence.

Differentiating the loss function $\mathcal{L}$ with respect to $\boldsymbol{\theta}$ gives...

→ Differentiating the loss function L\mathcal{L} with respect to θ\boldsymbol{\theta} gives...

Block formulas ($$...$$): when a standalone formula deserves emphasis.

$$
\nabla_{\boldsymbol{\theta}} \mathcal{L} = \frac{1}{N} \sum_{i=1}^{N} \nabla_{\boldsymbol{\theta}} \ell(f(\mathbf{x}_i; \boldsymbol{\theta}), y_i)
$$
θL=1Ni=1Nθ(f(xi;θ),yi)\nabla_{\boldsymbol{\theta}} \mathcal{L} = \frac{1}{N} \sum_{i=1}^{N} \nabla_{\boldsymbol{\theta}} \ell(f(\mathbf{x}_i; \boldsymbol{\theta}), y_i)

How to decide:

4.3 Common Rendering Errors and Fixes

1) Special-character errors inside a \text{} block

% Error
\text{cross-entropy}    % the hyphen may be read as a minus sign

% Fix
\text{cross\text{-}entropy}
% or simply drop the hyphen
\text{cross entropy}

2) \\ line breaks do not work

In KaTeX, \\ works only inside environments such as aligned, cases, and bmatrix. To break a line in a plain block formula, use a separate $$ block or wrap it in aligned.

% Error: breaking a line directly in a block formula
$$
a = b \\
c = d
$$

% Fix: use aligned
$$
\begin{aligned}
a &= b \\
c &= d
\end{aligned}
$$

3) \boldsymbol vs. \mathbf: which to use

\mathbf{W}              % matrix W (upright bold) ✅
\mathbf{\theta}         % ❌ not recommended for Greek letters
\boldsymbol{\theta}     % ✅ bold Greek letters

4) A $$ block needs blank lines around it

This is the most common reason a $$ block formula fails to render in MDX.

<!-- Error: no blank lines -->

This is a formula:

$$
x = y
$$

The next sentence.

<!-- Fix: add blank lines before and after -->

This is a formula:

$$
x = y
$$

The next sentence.

5) Commands KaTeX does not support

KaTeX supports only a subset of LaTeX. Unsupported commands you hit often:

LaTeX commandKaTeX statusAlternative
\DeclareMathOperatorNot supported\operatorname{name}
\newcommandNot supportedWrite it out in the formula
\eqrefNot supportedNumber the equations manually
\substackSupported-
\xleftarrowSupported-

5. How to Practise in Real Life

5.1 A Checklist for Reading a Single Paper

  1. Abstract → grasp the purpose: state in one sentence the problem the paper is trying to solve
  2. Skim figures and tables first: Figure 1 is usually a summary of the whole architecture
  3. Find the notation table: normally laid out on page 2 or 3
  4. Identify the core formulas: usually 3 to 5. Focus on the numbered equations
  5. Translate the formulas into plain language: unpack each one as an "input → operation → output" flow
  6. Check the experimental results: read the improvement over the baseline off the tables and graphs
  7. Interpret the ablation study: work out which component contributes to the performance
  8. Look at the code: cross-check the published GitHub implementation against the formulas

5.2 How to Back-Trace When a Formula Stops You

Build a symbol dictionary

When you meet a symbol you do not know while reading, write it into your notes immediately.

## Symbol dictionary (Paper: Attention Is All You Need)

| Symbol                               | Meaning                    | Dimension                                  | Notes                  |
| ------------------------------------ | -------------------------- | ------------------------------------------ | ---------------------- |
| $d_{\text{model}}$                   | Model hidden dimension     | scalar                                     | 512                    |
| $d_k$                                | Key/Query dimension        | scalar                                     | $d_{\text{model}} / h$ |
| $d_v$                                | Value dimension            | scalar                                     | $d_{\text{model}} / h$ |
| $h$                                  | Number of heads            | scalar                                     | 8                      |
| $\mathbf{Q}, \mathbf{K}, \mathbf{V}$ | Query, Key, Value          | matrix                                     |                        |
| $\mathbf{W}^Q_i$                     | Query projection of head i | $\mathbb{R}^{d_{\text{model}} \times d_k}$ |                        |

Back-tracing in 3 steps:

  1. Find where the symbol is defined: search the text above and below the formula for "where" or "here"
  2. Back out the dimensions: for a matrix product to be valid the inner dimensions must agree — use that to infer the dimension of an unknown symbol
  3. Cross-check the code: confirm what the formula means from code such as attention_scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_k)

5.3 Example: Scaled Dot-Product Attention Worked Step by Step

Attention(Q,K,V)=softmax ⁣(QKdk)V\text{Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\right)\mathbf{V}

Step 1: check the inputs

Step 2: compute the QK\mathbf{Q}\mathbf{K}^\top product

QKRn×m\mathbf{Q}\mathbf{K}^\top \in \mathbb{R}^{n \times m}

Element (i,j)(i, j) is the dot product of the ii-th query and the jj-th key → a similarity score

Step 3: divide by the dk\sqrt{d_k} factor

The larger dkd_k is, the larger the dot products get in absolute value. Dividing by dk\sqrt{d_k} keeps softmax from saturating. That is what "scaled" means.

QKdkRn×m\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}} \in \mathbb{R}^{n \times m}

Step 4: apply softmax

Apply softmax over each row (each query) to produce the attention weights (a probability distribution).

αij=exp(sij)l=1mexp(sil),where sij=(QK)ijdk\alpha_{ij} = \frac{\exp(s_{ij})}{\sum_{l=1}^m \exp(s_{il})}, \quad \text{where } s_{ij} = \frac{(\mathbf{Q}\mathbf{K}^\top)_{ij}}{\sqrt{d_k}}

Step 5: take the weighted sum over Value

Sum the Value vectors, weighted by the attention weights.

outputi=j=1mαijvj\text{output}_i = \sum_{j=1}^{m} \alpha_{ij} \mathbf{v}_j

Result: outputRn×dv\text{output} \in \mathbb{R}^{n \times d_v}

One-line summary: "each query measures its similarity to every key, then uses those similarities as weights to output a weighted average of the values."

The matching PyTorch code:

import torch
import torch.nn.functional as F
import math

def scaled_dot_product_attention(Q, K, V):
    d_k = Q.size(-1)
    scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_k)
    attn_weights = F.softmax(scores, dim=-1)
    output = torch.matmul(attn_weights, V)
    return output, attn_weights

6. Appendix

6.1 Symbol Cheat Sheet

SymbolLaTeXHow to read itMeaning
\nabla\nablanabla / gradientVector differential operator
\partial\partialpartialPartial-derivative symbol
\sum\sumsigma / sumSummation
\prod\prodpi / productMultiplication
\int\intintegralIntegration
\lVert \cdot \rVert\lVert \cdot \rVertnormSize of a vector or matrix
\lvert \cdot \rvert\lvert \cdot \rvertabsolute valueAbsolute value of a scalar, or set size
E\mathbb{E}\mathbb{E}expectationMean of a random variable
Var\text{Var}\text{Var}varianceVariance of a random variable
argmax\arg\max\arg\maxargmaxThe argument that maximizes
argmin\arg\min\arg\minargminThe argument that minimizes
\propto\proptoproportionalIs proportional to
\sim\simtilde / is drawn fromxpx \sim p: xx follows distribution pp
\in\inbelongs toSet membership
\subset\subsetsubsetSubset relation
\forall\forallfor allUniversal quantifier
\exists\existsthere existsExistential quantifier
\infty\inftyinfinityInfinity
\approx\approxapproximately equalsApproximately equal
\triangleq\triangleqis defined asDefined to be (definition)
\odot\odotHadamard productElement-wise multiplication
\otimes\otimesKronecker / tensor productTensor multiplication
\oplus\oplusdirect sumDirect sum
,\langle \cdot, \cdot \rangle\langle \cdot, \cdot \rangleinner productInner product
O\mathcal{O}\mathcal{O}big-OTime/space complexity
θ,θ\theta, \boldsymbol{\theta}\theta, \boldsymbol{\theta}thetaModel parameters
η\eta\etaetaLearning rate
λ\lambda\lambdalambdaRegularization coefficient, eigenvalue
ϵ\epsilon\epsilonepsilonA very small value, noise
σ\sigma\sigmasigmaStandard deviation, sigmoid function
ϕ,φ\phi, \varphi\phi, \varphiphiModel parameters (auxiliary)
ψ\psi\psipsiParameters, functions
α,β,γ\alpha, \beta, \gamma\alpha, \beta, \gammaalpha, beta, gammaHyperparameters
μ\mu\mumuMean
Rn\mathbb{R}^n\mathbb{R}^nreal n-spacen-dimensional real space
Z\mathbb{Z}\mathbb{Z}the integersSet of integers
\top\toptransposeMatrix transpose

Textbooks

  1. Mathematics for Machine Learning (Deisenroth et al.) — Free PDF available. Focuses only on the math ML actually needs
  2. Deep Learning (Goodfellow, Bengio, Courville) — Part I is the math foundation. Free to read at deeplearningbook.org
  3. Pattern Recognition and Machine Learning (Bishop) — Reaches as far as probabilistic graphical models. A textbook from the Bayesian viewpoint
  4. Linear Algebra Done Right (Axler) — Theory-centred linear algebra. Proof-based, suited to a deep understanding

Online courses

  1. 3Blue1Brown — Essence of Linear Algebra (YouTube) — A visualization-driven series that builds linear-algebra intuition
  2. 3Blue1Brown — Essence of Calculus (YouTube) — Visual understanding of the core calculus concepts
  3. Stanford CS229 — Machine Learning — Andrew Ng's ML course. Mathematically solid
  4. MIT 18.06 — Linear Algebra (Gilbert Strang) — A celebrated linear-algebra course from an engineering perspective

Tools and references

  1. KaTeX official docs (katex.org) — The complete list of supported functions and symbols
  2. Detexify (detexify.kirelabs.org) — Draw a symbol by hand and it finds the LaTeX command for you
  3. Mathpix Snip — An OCR tool that turns a photo of a formula into LaTeX code
  4. Overleaf (overleaf.com) — An online LaTeX editor with live preview
  5. arXiv Vanity — Converts arXiv papers into web pages so the formulas are comfortable to read
  6. Papers with Code (paperswithcode.com) — Papers and their implementations side by side. Ideal for matching formulas against code

Conclusion

A paper's formulas are, in the end, a compressed expression of "how the data gets transformed". Every symbol feels unfamiliar at first, but the patterns collected above cover more than 80% of the formulas you will meet across papers.

The most effective learning order is:

  1. Keep this article's symbol cheat sheet beside you
  2. Pick one paper you are interested in
  3. Write out just the 3 to 5 core formulas in plain language
  4. Cross-check them against the matching code (PyTorch/JAX)

Once you can translate formulas into code and code back into formulas, your reading speed goes up dramatically.

Comments

No comments yet.

Sign in to leave a comment