TExcelTAD
Home › Math for Deep Learning & LLMs › Probability for Deep Learning

Probability for Deep Learning

A classifier outputs a probability distribution, dropout is a random variable, a language model is a chain of conditional distributions, and training minimizes an expectation estimated from samples. This lesson collects the probability a deep-learning practitioner uses daily; the full treatment is in Math for ML: Probability and Probability Theory.

Distributions networks output

Output Distribution Network head
binary label Bernoulli(μ\mu) one logit zz, μ=σ(z)\mu = \sigma(z)
one of KK classes or tokens categorical(p\mathbf{p}) KK logits, p=softmax⁡(z)\mathbf{p} = \operatorname{softmax}(\mathbf{z})
real value Gaussian(μ\mu, σ2\sigma^2) a mean (and sometimes a log-variance)
sequence product of conditionals one categorical per position

The logistic sigmoid σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}} squashes a real number into (0,1)(0, 1); its inverse is the logit log⁡μ1−μ\log\frac{\mu}{1 - \mu}. The softmax generalizes it to KK classes, and the softmax of two logits (z,0)(z, 0) is exactly (σ(z),1−σ(z))(\sigma(z), 1 - \sigma(z)).

The chain rule of probability

Any joint distribution factors as a product of conditionals:

p(x1,…,xT)=∏t=1Tp(xt∣x1,…,xt−1)p(x_1, \ldots, x_T) = \prod_{t=1}^{T} p(x_t \mid x_1, \ldots, x_{t-1})

An autoregressive language model learns each factor with one network that reads the prefix (Language Modeling as Next-Token Prediction). No independence assumption is made; the factorization is exact.

python · try it yourself
import numpy as np

# A toy "language" over {a, b} with a hand-made next-token model
def next_probs(prefix):
    if not prefix: return {"a": 0.7, "b": 0.3}
    return {"a": 0.2, "b": 0.8} if prefix[-1] == "a" else {"a": 0.6, "b": 0.4}
def seq_prob(s):
    p = 1.0
    for t in range(len(s)):
        p *= next_probs(s[:t])[s[t]]
    return p
from itertools import product
seqs = ["".join(s) for s in product("ab", repeat=3)]
probs = {s: seq_prob(s) for s in seqs}
for s in seqs: print(s, round(probs[s], 4))
print("total over all length-3 sequences:", round(sum(probs.values()), 10))
aaa 0.028
aab 0.112
aba 0.336
abb 0.224
baa 0.036
bab 0.144
bba 0.072
bbb 0.048
total over all length-3 sequences: 1.0

Expectations, samples and dropout

Training minimizes the expected loss E(x,y)[ℓ]\mathbb{E}_{(\mathbf{x}, y)}[\ell], estimated by mini-batch averages. Dropout multiplies each activation by an independent Bernoulli mask mi∼Bernoulli⁡(1−p)m_i \sim \operatorname{Bernoulli}(1 - p) and rescales by 11−p\frac{1}{1 - p} ("inverted dropout") so that the expected activation is unchanged:

E[mi1−phi]=1−p1−phi=hi\mathbb{E}\left[\frac{m_i}{1 - p}h_i\right] = \frac{1 - p}{1 - p}h_i = h_i

At test time dropout is switched off, and thanks to the rescaling no correction is needed.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
h = np.array([1.0, 2.0, 3.0, 4.0])
p = 0.5
samples = np.array([(rng.uniform(size=4) > p) / (1 - p) * h for _ in range(100000)])
print("one dropout sample:", samples[0])
print("average over samples:", np.round(samples.mean(axis=0), 3), " original:", h)
print("variance added per unit:", np.round(samples.var(axis=0), 3), " theory h^2 p/(1-p):", h**2 * p / (1 - p))
one dropout sample: [2. 0. 0. 0.]
average over samples: [1.002 1.994 2.983 4.001]  original: [1. 2. 3. 4.]
variance added per unit: [ 1.  4.  9. 16.]  theory h^2 p/(1-p): [ 1.  4.  9. 16.]

Bayes in deep learning

Bayes' theorem p(θ∣D)∝p(D∣θ) p(θ)p(\boldsymbol{\theta} \mid \mathcal{D}) \propto p(\mathcal{D} \mid \boldsymbol{\theta})\,p(\boldsymbol{\theta}) underlies weight decay (a Gaussian prior, see MAP Estimation), and calibrated probabilities matter whenever a model's confidence is acted on: a classifier that says 90% should be right about 90% of the time.

In software

  • torch.distributions (and jax.random) provide Bernoulli, Categorical, Normal with sample, log_prob and entropy.
  • nn.Dropout(p) implements inverted dropout and is disabled by model.eval().
  • Generation with an LLM is repeated sampling from the categorical next-token distribution (Sampling).

Exercises

Exercise 1: Sigmoid and softmax

Show that softmax⁡(z,0)1=σ(z)\operatorname{softmax}(z, 0)_1 = \sigma(z).

Answer

ezez+e0=11+e−z\frac{e^z}{e^z + e^0} = \frac{1}{1 + e^{-z}}.

Solution

Divide numerator and denominator by eze^z: ezez+1=11+e−z=σ(z)\frac{e^z}{e^z + 1} = \frac{1}{1 + e^{-z}} = \sigma(z). A binary classifier with one logit is a 2-class softmax with the second logit fixed at 0.

Exercise 2: Sequence probability

Using the toy model of the first example, compute p("ab")p(\text{"ab"}) by hand.

Answer

0.560.56.

Solution

p(a)⋅p(b∣a)=0.7⋅0.8=0.56p(\text{a}) \cdot p(\text{b} \mid \text{a}) = 0.7 \cdot 0.8 = 0.56.

Exercise 3: Dropout at test time (code)

A layer was trained with dropout p=0.2p = 0.2 without inverted scaling. What factor must test-time activations be multiplied by? Check by simulation.

Answer

0.80.8.

Solution

Without rescaling, the training-time expected activation is (1−p)h=0.8h(1 - p)h = 0.8h, so test-time activations must be scaled by 0.80.8 to match.

python · try it yourself
import numpy as np
rng = np.random.default_rng(1)
h = 5.0
print(round(np.mean((rng.uniform(size=200000) > 0.2) * h) / h, 3))
0.801

Test yourself

A KK-class classifier's output distribution is usually…

  1. Gaussian
  2. categorical, via a softmax over KK logits
  3. uniform
  4. Poisson

Inverted dropout divides kept activations by 1−p1 - p so that…

  1. the variance is zero
  2. the expected activation equals the original activation
  3. more units are dropped
  4. test time needs dropout too

The factorization p(x1,…,xT)=∏tp(xt∣x<t)p(x_1, \ldots, x_T) = \prod_t p(x_t \mid x_{<t}) requires…

  1. independent tokens
  2. no assumption; it is the chain rule of probability
  3. a Gaussian model
  4. fixed-length sequences of length 2