Efficient AI

Importance Sampling

\[\mathbb{E}_f[w(x)]\]

Aditya Desai

Why importance sampling?

Example 1

\[ \mathbb{E}_f[w(x)] = \frac{1}{n}\sum_{i=1}^{n}w(x_i), \qquad x_i\sim f(x) \]

but we cannot sample from \(f(x)\).

Why importance sampling?

Example 2

Sometimes we may want to purposefully choose a different distribution,

even if we can sample from \(f(x)\).

Consider an example

\[ S=(x_1+x_2+\cdots+x_n), \qquad x_i\in\mathbb{R} \]

attention output \(=a_1v_1+a_2v_2+\cdots+a_nv_n,\quad v_i\in\mathbb{R}^d\)

goal is to sample and estimate \(S\)

A uniform estimator

\[ S=n\,\mathbb{E}_p[x_i] \]

where

\[ p(i)=\mathrm{Uniform}\{1,\ldots,n\} \]
\[ \hat S = n\cdot\frac{1}{k}\sum_{j=1}^{k}x_{i_j} \]

When is uniform sampling undesirable?

Q. What are the cases in which this is not desirable sampling

Example: values of \(x_i\)

\[ \{10^6,\ 1,\ 1,\ 1,\ \ldots,\ 1\}, \qquad n=100 \]
\[ \mathbb{E}(\hat S)=S \qquad \text{it is still unbiased,} \]

but variance will be high?

What should be a good distribution?

Q. What should be a good distribution?

→ A distribution that samples \(x_1\) with high probability (very close to 1)

* This condition is actually the case in attention computation.

The attention connection

\[ o=\sum_i a_i\vec v_i, \qquad \|v_i\|=\mathrm{Constant} \]
\[ a_i = \frac{e^{\langle q,k_i\rangle}} {\sum_j e^{\langle q,k_j\rangle}} \]

depending on dot products subsequent keys far from query \(q\) get exponentially small!

→ Random Sampling will not work!

Formalise this idea

Formalise this idea in importance Sampling.

  • \(X\): Random variable
  • \(w(x)\): function of interest
  • \(\mathbb{E}[w(x)]\): Quantity of interest
  • \(f(x)\): "true distribution"
  • \(g(x)\): proposed distribution.
\[ \mathbb{E}_f[w(x)] = \mathbb{E}_g\big[\;??\;\big] \]

Change the distribution

\[ \int w(x)f(x)\,dx \]
\[ = \int \frac{w(x)f(x)}{g(x)}\cdot g(x)\,dx \]
\[ = \mathbb{E}_g\!\left[ \frac{w(x)f(x)}{g(x)} \right] \]

The estimator

Estimator (left-hand side labeled \(\hat\mu\)):

\[ \underbrace{\mathbb{E}_f[w(x)]}_{\hat\mu} = \frac{1}{n}\sum_{i=1}^{n} \frac{w(x_i)f(x_i)}{g(x_i)}, \qquad x_i\sim g(x) \]

* Unbiased?

Is it unbiased?

\[ \mathbb{E}_g[\hat\mu] = \frac{1}{n}\sum_{i=1}^{n} \mathbb{E}_g\!\left[ \frac{w(x_i)f(x_i)}{g(x_i)} \right] \]
\[ = \frac{1}{n}\cdot n\cdot\mathbb{E}_f[w(x)] \]
\[ = \mathbb{E}_f[w(x)] \]

* Unbiased? Yes.

Which proposal should we use?

So this works for any proposal \(g(x)\)

What's a good \(g(x)\)?

→ One with least variance!!

\[ \hat\mu = \frac{1}{n}\sum_{i=1}^{n} \frac{w(x_i)f(x_i)}{g(x_i)} \]

Variance of the estimator

\[ \mathrm{Var}(\hat\mu) = \frac{1}{n^2}\cdot n\cdot \mathrm{Var}_g\!\left( \frac{w(x_i)f(x_i)}{g(x_i)} \right) \]
\[ = \frac{1}{n}\left[ \mathbb{E}_g\!\left( \frac{w^2(x)f^2(x)}{g^2(x)} \right)-\mu^2 \right] \]

Problem: Which \(g\) minimises this?

The optimization problem

\[ \underset{ \substack{ g\\ \int g(x)\,dx=1\\ g(x)>0 } }{\arg\min} \; \mathbb{E}_g\!\left[ \frac{w^2(x)f^2(x)}{g^2(x)} \right] \]
\[ \int \frac{w^2(x)f^2(x)}{g^2(x)} \cdot g(x)\,dx \]
\[ = \int\frac{w^2(x)f^2(x)}{g(x)}\,dx \]

Choose a \(g(x)\) which minimises this.

How do we proceed?

Simplicity Consider discrete case

\[ \min_{g(x)} \sum_i\frac{w^2(x_i)f^2(x_i)}{g(x_i)} \]
\[ \sum_i g(x_i)=1, \qquad g(x)>0 \]

rewrite:

\[ \sum_i \frac{w^2(x_i)f^2(x_i)} {\left(\sqrt{g(x_i)}\right)^2}, \qquad \sum_i\left(\sqrt{g(x_i)}\right)^2=1 \]

See a vector problem

If every "\(i\)" is a dimension

\[ \min.\quad \left\| \frac{w(x_i)f(x_i)}{\sqrt{g(x_i)}} \right\|_2^2 * \left\|\sqrt g\right\|_2^2, \qquad \left\|\sqrt g\right\|_2^2=1 \]
\[ \|a\|_2^2\,\|b\|_2^2\ge ? \]

Cauchy Schwartz

\[ \|a\|_2\,\|b\|_2\ge\langle a,b\rangle \]

The integral version

There is a integral version of this

\[ \int\left( \frac{|w(x)|f(x)}{\sqrt{g(x)}} \right)^2dx \cdot \int\left(\sqrt{g(x)}\right)^2dx \]
\[ \ge \left(\int|w(x)|\cdot f(x)\,dx\right)^2 \]
\[ = \mathbb{E}_f\!\left[|w(x)|\right] \]

minimum value

When is the bound tight?

is Cauchy Schwartz tight?

Yes!

When is minimum achieved?

\[ \sqrt{g(x)} \propto \frac{|w(x)|f(x)}{\sqrt{g(x)}} \]
\[ g(x)\propto |w(x)|f(x) \]

The best proposal distribution

\[ g(x) = \frac{|w(x)|f(x)} {\int|w(x)|f(x)\,dx} \]
\[ g(x) = \frac{|w(x)|f(x)} {\mathbb{E}_f[|w(x)|]} \]

This is the best proposal distribution.

Does it make sense?

Does it make sense?

\(|w(x)\cdot f(x)|\) is exactly the "contribution"

of \(i\)th term to the expectation.

\(w(x)>0\ \forall x\), then what is the variance?

What happens when \(w(x)>0\)?

\[ g(x) = \frac{w(x)f(x)}{\mathbb{E}_f(w(x))} \]
\[ \mathrm{Var}(\hat\mu) = \frac{1}{n}\left[ \int\frac{w^2f^2}{g^2}\,g\,dx - \mathbb{E}_f(w(x))^2 \right] \]
\[ = \frac{1}{n}\left[ \mathbb{E}_f(w(x))^2 - \mathbb{E}_f(w(x))^2 \right] \]
\[=0\ !!\]

Something Wrong?

Something Wrong?

No. \(g(x)\) needs you to know \(\mathbb{E}_f(w(x))\)!

In practice, we will be trying to cheaply get a proposal \(g(x)\)

that is close to \(f(x)|w(x)|\).

Attention example

\[ o=\sum_{i=1}^{n}a_iv_i \]

How should we sample terms?

Best distribution \(=\)

\[ g(x)=[g(1),\ldots,g(n)] \]
\[ g(i)\propto a_i\|v_i\|_2 \qquad [\text{Exercise}] \]

But can we compute it cheaply?

\(a_i\) computation will need entire KV Cache reading.

→ What is a good \(g(x)\)?

[Think] that is cheaply computable

we will answer this question partially in the Seminar

and hopefully in some future class.

Efficient AI

Rejection Sampling

Aditya Desai

From expectations to samples

So importance sampling lets us compute \(\mathbb{E}_f[w(x)]\)

but what if we want to get samples from \(f(x)\)

but cannot sample directly from it.

Example: uniform in a circle

Example: Get a point \(x\) in 2D

sampled uniformly at random from a circle of radius \(r\)

using only \(U[0,1]\) variables.

Solution

Solution:

\[x,y\in U[0,1]\]

Reject outside the circle

* Sample uniformly in square

→ Reject if outside the circle

The generic case

Now consider the generic case

\(f(x)\): target distribution

\(g(x)\): distribution to be used.

\[a\sim g(x)\]

How do we make sure that probability of getting \(x\) is actually \(f(x)\)?

If \(g(a) > f(a)\)

if \(\underline{g(a) > f(a)}\)

→ Reduce the probability.

→ start rejecting the sample!

\[ \text{accept with prb.}\left(\frac{f(a)}{g(a)}\right) \]

Algo till now

Sample \(a \sim g(x)\)

if \(g(a) \ge f(a)\):

\(r = \mathrm{Uniform}[0,1]\)

if \(r > f(a)/g(a)\)

Reject and go sample again

otherwise

Accept, return \(a\)

else ??

What if \(f(a) > g(a)\)?

What about if \(f(a) > g(a)\)

→ we need to increase the probability of \(a\)

But how?

⇒ Decrease probability of other "\(x\)" enough so that we can relatively use \(g(a)\)

Envelope

Envelope: Choose an \(M\) s.t. \(Mg(x) > f(x)\ \forall x\)

Algo:

Sample \(a \sim g(x)\)

\(r = U[0,1]\)

if \(r < \dfrac{f(a)}{Mg(a)}\): Accept

else: Reject and Sample again

Where to use rejection sampling

Example of where to use the Rejection Sampling (Cooked up)

Consider Attention Computation.

Attention computation

\[ \mathrm{Att}(K,V,q) = \frac{\sum_{i=1}^{n} e^{\langle k_i,q\rangle}\, v_i} {\sum_{i=1}^{n} e^{\langle k_i,q\rangle}} \]

Approximate the denominator

Let us say you wanted to approximate the denominator with a sample

\[ S=\sum_{i=1}^{n} e^{\langle k_i,q\rangle} \]

What is the best sampling distribution?

What is the best sampling probability distribution?

→ Importance Sampling say

\[ p(i)\propto e^{\langle k_i,q\rangle} \]

Note \(q\) is not available beforehand in decode.

A representative query

Say somehow we have obtained the sample proportional to

\[ \phi(\langle k_i,\bar q\rangle) \]

where \(\bar q\) is some "representative" query.

A subset from \(\bar q\)

\[ [i_1,i_2,\ldots,i_n] \]
\[ p(i_j)\propto \phi(\langle k_{i_j},\bar q\rangle ) \]

Now can you get a sample from this subset that is s.t.

\[ p(i_{j_k})\propto \phi(\langle k_{i_{j_k}}, q\rangle) \]

where \(q\) is the actual query?

→ Can use Rejection Sampling!!

Efficient AI

Reservoir Sampling

Aditya Desai

Previous cooked up example

Previous Cooked up example:

Assumed that we had a sample of KV

\[ p(i)\propto \phi(\langle k_i,\bar q\rangle) \]

But in a auto-regressive generation total KV tokens keep on increasing

How do we maintain a sample?

Q. How do we "maintain" a sample in that case?

A. Reservoir Sampling.

Maintaining a sample of size \(k\)

Consider a stream of data

\[ \{x_1,x_2,\ldots,x_t,\ldots\} \]

at each point \(t\), we want to keep a sample of size \(k\)

\[ \{x_{i_1},x_{i_2},\ldots,x_{i_k}\} \]

such that

\[ P(x_i\text{ is in sample})=\frac{k}{t} \qquad\forall t \]

What does "stream" mean?

"Stream": we process the data point only once and "throw" it away.

At time \(t\) we look at \(x_t\)

"Build a streaming algorithm for sampling"

State at time \(t\)

A.

let us say we have a sample

\[ \{x_{i_1},\ldots,x_{i_k}\} \quad\text{at time }t \]
\[ P(i)=\frac{k}{t}. \]

At time \((t+1)\), we got \(x_{t+1}\)

With what probability do we choose \(x_{t+1}\)?

Q. Choose \(x_{t+1}\) with Prob?

\[ \left(\frac{k}{t+1}\right) \]
\[ \left\{ \begin{array}{l} \text{check }r\sim U[0,1]\\ r\le \dfrac{k}{t+1} \end{array} \right. \]

Q. If chosen, throw one of the other sampled data with uniform probability

Why does it work?

\[ P(x_{t+1}\text{ is in sample at }(t+1))=\frac{k}{t+1} \]

Why does it work?

\[ P(x_i\text{ is in sample at }(t+1)) \]
\[ = P(x_i\text{ is in sample at }t) \times P(x_i\text{ is not thrown}) \]
\[ =\frac{k}{t}\big[\;\cdots\;\big] \]

Why does it work?

\[ =\frac{k}{t}\left[ \frac{1+t-k}{1+t}\cdot 1 +\cdots \right] \]
\[ =\frac{k}{t}\left[ \frac{1+t-k}{1+t} + \frac{k}{1+t}\cdot\frac{k-1}{k} \right] \]
\[ =\frac{k}{t}\left[ \frac{1+t-k+k-1}{1+t} \right] \]

Thus the algorithm (Algorithm 1) works

\[ =\frac{k}{t}\cdot\frac{t}{1+t} \]
\[ =\frac{k}{1+t} \]

Thus the algorithm works.

Another simple algorithm

Another simple algorithm: Random Key algorithm.

→ Every \(x_i\) is assigned a random value \(r_i\sim U[0,1]\)

→ At each point \(t\), the sample is the \(x_i\)s with

Highest \(k\) values.

Why random keys work

→ random key assignment gives a permutation.

→ probability that any key is chosen is \(k/t\) at all times \(t\).

→ At each time you only have to keep track of top \(k\) \(x_i\)s and their scores

At \(t+1\)

\[ S=\{x_{i_1},\ldots,x_{i_k}\} \]
\[ R=\{r_{i_1},\ldots,r_{i_k}\} \]
\[ r_{t+1}=U[0,1] \]

If \(r_{t+1} \lt \min R\):

discard \(x_{t+1}\)

Else

Add \((x_{t+1},r_{t+1})\) and discard the min

Efficient AI

Weighted Reservoir Sampling

Aditya Desai

Problem setup

Problem setup:

Stream

\[ \{(x_1,w_1),(x_2,w_2),\ldots\} \]

At time \(t\gt k\), \(k\) sample size.

\[ \Pr(x_i\text{ in Sample})\propto w_i \]
  • Different interpretations:
  • Do we want to maintain the sample with or without replacement?
  • Do we want to achieve marginal probabilities proportional to the weights in the final sample?

WRS without "Replacement"

WRS without "Replacement" \([P\text{-}WRS\text{-}w/o]\)

Maintain a sample \(k\). s.t at each point in time \(t\gt k\), the probabilities of inclusion match the following procedure

"If you construct \(k\) sample iteratively the probability that \(i\) is sampled at step \(t\) is \(\propto w_i\)"

Note that under this the marginal probabilities of \(x_i\) in \(k\)-sample is NOT proportional to \(w_i\)

eg. \(\{w_1,w_2,w_3\}\), \(k=2\)

Marginals are not \(\propto w_i\)

\[ \Pr(w_i\text{ in sample}) = \frac{w_i}{w_i+w_j+w_k} \left[ 1 + \frac{w_j}{w_i+w_k} + \frac{w_k}{w_i+w_j} \right] \]
\[ \text{Thus }\Pr(w_i\text{ in sample})\not\propto w_i \]

A random key algorithm

How do we design a random key algorithm?

\[ r_i=U[0,1] \]
\[ X_i=\mathcal{F}(r_i) \]

Sort \(X_i\) and pick top-\(k\).

so that

\[ \Pr(X_i\text{ in Sample})=\text{P-WRS-w/o}(i) \]

How should we pick \(\mathcal{F}\)??

[Intuition Not a Proof ] How to pick \(\mathcal{F}\)

Simplicity: let us only look at \(k=1\)

I want probability that \(i\) lies at right most to be \(\propto w_i\)

What should density of \(X\) look like??

Density at 1

If \(w_1\gt w_2\gt w_3\) then \(\leftarrow\)

\[ \Pr(x_i\text{ lies in }\Delta)\propto w_i \]
\[ f(X_i)=f_i(x)\propto w_i \quad\text{at }1 \]
\[ f_i(x)=w\cdot g(x) \quad\text{where }g(1)=1 \]

Do we know such \(g(x)\)?

\[ f_i(x)=w\cdot g(x) \]
\[ \int f_i(x)=1 \implies \int_{0}^{1} g(x)=\frac{1}{w} \]

do we know such \(g(x)\)?

\[ g(x)=[\;\cdots\;] \]

A candidate \(g\)

\[ g(x)=x^{w-1} \qquad (g(1)=1) \]
\[ f_i(x)=w_i\cdot x^{w_i-1} \]

Then density should be such that

\[ f_i(x)=w_i\cdot x^{w_i-1} \]
\[ F_i(x)=x^{w_i} =\int_{0}^{x} w_i\cdot u^{w_i-1}\,du \]

The key map

\[ F(X_i = \mathcal{F}(r_i) \le x) = x^{w_i} \]
\[ F(r_i \lt \mathcal{F}^{-1}(x)) = x^{w_j} \]
\[ \mathcal{F}^{-1}(x) = x^{w_j} \]
\[ \mathcal{F}(x) = x^{1/w_j} \]
\[ X_i = \mathcal{F}(r_i) = r_i^{1/w_j} \]

A potential proposal

Thus "Potentially" \(\mathcal{F}(r_i)=r_i^{1/w_i}\) can work.

→ We have not proved anything yet. We have just come up with "a potential" proposal that "might" work.

Proof: Full proof is out of scope. But we can prove a lemma.

Lemma

lemma:

If \(r_1\) and \(r_2\) are \(U[0,1]\),

\[ x_1=r_1^{1/w_1},\qquad x_2=r_2^{1/w_2} \]
\[ w_i\gt 0 \]
\[ \Pr(x_1\le x_2)=\frac{w_2}{w_1+w_2} \]

Proof

Proof:

\[ \Pr(X_1\le X_2) \]
\[ = \Pr\!\left(r_1^{1/w_1}\lt r_2^{1/w_2}\right) \]
\[ = \Pr\!\left(r_1\lt r_2^{w_1/w_2}\right) \]

Proof (contd.)

\[ = \int_{r_2=0}^{1} \int_{r_1=0}^{r_2^{w_1/w_2}} \,dr_1\,dr_2 \]
\[ = \int_{0}^{1} r_2^{w_1/w_2}\,dr_2 \]
\[ = \left. \frac{r_2^{w_1/w_2+1}}{\frac{w_1}{w_2}+1} \right|_{0}^{1} \]
\[ = \frac{w_2}{w_1+w_2} \qquad\square \]

Exercise

Can you extend "non-random-key" algo to WRS. [Exercise]