Skip to content
ResAI

USAAIO 2025

Round 2

Three long problems on modern deep learning, each mixing derivations with PyTorch implementation: physics-informed neural networks, multi-head attention and its efficient variants, and CLIP.
Problems
3
Parts
46
Total points
300

Problem 1Physics-informed neural networks

100 pts

SummaryProve the analytical solution of a 1-D heat equation, then train a PINN whose loss combines PDE residual, initial-condition and boundary-condition terms, using torch.autograd.grad for derivatives and mini-batch training.

    AI for sciencePDEsAutograd

Many physics systems are governed by the following type of partial differential equations (PDEs)

F(t,r,u,ut,utt,∇r u,∇r2 u)=0, ∀ t∈[0,T], r∈SF \left( t, \mathbf{r}, u, u_t, u_{tt}, \nabla_{\mathbf{r}} \ u, \nabla^2_{\mathbf{r}} \ u \right) = 0 , \ \forall \ t \in \left[ 0 , T \right], \ \mathbf{r} \in \mathcal S

where

  • t∈Rt \in \Bbb R: Time.

  • r∈R3\mathbf{r} \in \Bbb R^3: Position.

  • u(t,r)∈Ru \left( t, \mathbf{r} \right) \in \Bbb R: A function of tt and r\mathbf{r} that is differentiable.

  • utu_t: ∂u∂t\frac{\partial u}{\partial t}.

  • uttu_{tt}: ∂2u∂t2\frac{\partial^2 u}{\partial t^2}.

  • S\mathcal S: A convex set in R3\Bbb R^3.

For such a physics system, if we know

  1. Initial condition (IC)

    • u(0,r)u \left( 0, \mathbf{r} \right) for all r∈S\mathbf{r} \in \mathcal S.

    • ut(0,r)u_t \left( 0, \mathbf{r} \right) for all r∈S\mathbf{r} \in \mathcal S (This term is required if uttu_{tt} appears in FF. Otherwise, it is not needed.).

  2. Boundary condition (BC)

    • u(t,r)u \left( t, \mathbf{r} \right) for all t∈[0,T]t \in \left[ 0 , T \right] and r∈Boundary(S)\mathbf{r} \in \text{Boundary} \left( \mathcal S \right).

Then the value of u(t,r)u \left( t , \mathbf{r} \right) for any t∈[0,T]t \in \left[ 0 , T \right] and r∈S\mathbf{r} \in \mathcal S is uniquely determined.

However, many such systems do not admit closed-form solutions. The canonical approach of discretizing a PDE to find numeric solutions has many limitations.

To avoid those challenges, in this problem, you are asked to use the deep neural network approach to solve a physics-informed PDE, hereafter called as Physics-Informed Neural Network (PINN).

In this problem, let us consider the following specific 1-dim thermal system:

  • A 1-dim rod with unit length.

  • The thermal diffusivity is α>0\alpha > 0.

  • Two endpoints of the rod are connected to two heat reservoirs whose temperatures are constant and normalized as 0.

  • At time t=0t = 0, the temperature distribution on the rod follows a sinusoidal pattern.

Denote by u(t,x)u \left( t, x \right) the temperature at time tt on position xx in the rod.

Thus, u(t,x)u \left( t, x \right) satisfies:

  1. PDE

    ut−α uxx=0, x∈[0,1], t∈[0,1],u_t - \alpha \ u_{xx} = 0 , \ x \in \left[ 0, 1 \right] , \ t \in \left[ 0, 1 \right] ,

    where

    • utu_t: ∂u∂t\frac{\partial u}{\partial t}.

    • uxu_x: ∂u∂x\frac{\partial u}{\partial x}.

    • uxxu_{xx}: ∂2u∂x2\frac{\partial^2 u}{\partial x^2}.

  2. IC

    u(0,x)=sin⁡(πx), ∀ x∈[0,1].u \left( 0, x \right) = \sin \left( \pi x \right) , \ \forall \ x \in \left[ 0, 1 \right] .
  3. BC

    u(t,0)=u(t,1)=0, ∀ t∈[0,1].u \left( t, 0 \right) = u \left( t, 1 \right) = 0 , \ \forall \ t \in \left[ 0, 1 \right] .

Before starting this problem, make sure to run the following code first without any change:

import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
import torch.optim as optim
import torch.autograd as autograd
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm

WARNING !!!\color{red}{\text{WARNING !!!}}

  • Beyond importing libraries/modules/classes/functions in the preceeding cell, you are NOT allowed to import anything else for the following purposes:

    • As a part of your final solution. For instance, if a problem asks you to build a model without using sklearn but you use it, then you will not earn points.

    • Temporarily import something to assist you to get a solution. For instance, if a problem asks you to manually compute eigenvalues but you temporarily use np.linalg.eig to get an answer and then delete your code, then you violate the rule.

    Rule of thumb: Each part has its particular purpose to intentionally test you something. Do not attempt to find a shortcut to circumvent the rule.

Part 1

10 ptsNon-codingForum thread

Prove that the solution to the above PDE, IC, and BC takes the following form:

u(t,x)=e−απ2tsin⁡(πx).u \left( t, x \right) = e^{- \alpha \pi^2 t} \sin \left( \pi x \right) .
  • Reasoning is required.

  • This part is used for the purpose of verifying the correctness of our subsequent PINN solution.

Show official solution

Official solution

First, we have

ut(t,x)=−απ2u(t,x)\begin{align*} u_t \left( t, x \right) & = - \alpha \pi^2 u \left( t, x \right) \end{align*}

and

uxx(t,x)=−π2u(t,x).\begin{align*} u_{xx} \left( t, x \right) & = - \pi^2 u \left( t, x \right) . \end{align*}

Hence, u(t,x)u \left( t, x \right) satisfies the PDE.

Second,

u(0,x)=sin⁡(πx).\begin{align*} u \left( 0, x \right) & = \sin \left( \pi x \right) . \end{align*}

Hence, u(t,x)u \left( t, x \right) satisfies the IC.

Third,

u(t,0)=u(t,1)=0.\begin{align*} u \left( t, 0 \right) & = u \left( t, 1\right) = 0 . \end{align*}

Hence, u(t,x)u \left( t, x \right) satisfies the BC.

The high level idea of PINN is as follows:

  1. (Neural network) We design a neural network (functional mapping) U(⋅,⋅∣θ):[0,1]2→RU \left( \cdot, \cdot \mid \mathbf{\theta} \right): \left[ 0 , 1 \right]^2 \rightarrow \Bbb R, such that

    • θ\mathbf{\theta}: learnable parameters in UU.

    • Inputs are time tt and position xx.

    • Output is the predicted temperature.

  2. (Training data) To train UU (equivalently, to learn θ\mathbf{\theta}), we use the following three groups of temporal-spacial data (t,x)\left( t, x \right):

    • (Training data for PDE) (t,x)\left( t, x \right) are randomly sampled from [0,1]2\left[ 0 , 1 \right]^2.

      Denote by DPDE\mathcal D_{PDE} the set of these data points.

    • (Training data for IC) (0,x)\left( 0, x \right) with xx that are evenly distributed on [0,1]\left[ 0 , 1 \right].

      Denote by DIC\mathcal D_{IC} the set of these data points.

    • (Training data for BC) (t,0)\left( t, 0 \right) and (t,1)\left( t, 1 \right) with tt that are evenly distributed on [0,1]\left[ 0 , 1 \right].

      Denote by DBC\mathcal D_{BC} the set of these data points.

  3. (Loss function in training)

    Ltotal=LPDE+LIC+LBC,L_{total} = L_{PDE} + L_{IC} + L_{BC} ,

    where

    • Residual loss in PDE:
    LPDE=1∣DPDE∣∑(t,x)∈DPDE(∂U(t,x∣θ)∂t−α∂2U(t,x∣θ)∂x2)2.L_{PDE} = \frac{1}{| \mathcal D_{PDE} |} \sum_{\left( t, x \right) \in \mathcal D_{PDE}} \left( \frac{\partial U \left( t, x \mid \mathbf{\theta} \right)}{\partial t} - \alpha \frac{\partial^2 U \left( t, x \mid \mathbf{\theta} \right)}{\partial x^2} \right)^2 .
    • IC loss:
    LIC=1∣DIC∣∑(t,x)∈DIC(U(t,x∣θ)−u(t,x))2.L_{IC} = \frac{1}{| \mathcal D_{IC} |} \sum_{\left( t, x \right) \in \mathcal D_{IC}} \left( U \left( t, x \mid \mathbf{\theta} \right) - u \left( t, x \right) \right)^2 .
    • BC loss:
    LBC=1∣DBC∣∑(t,x)∈DBC(U(t,x∣θ)−u(t,x))2.L_{BC} = \frac{1}{| \mathcal D_{BC} |} \sum_{\left( t, x \right) \in \mathcal D_{BC}} \left( U \left( t, x \mid \mathbf{\theta} \right) - u \left( t, x \right) \right)^2 .

In this part, you are asked to build a deep neural network that is used to output PDE solutions.

  1. The class name is HeatPINN.

    It subclasses nn.Module.

  2. The model consists of the following layers that are sequentially conntected:

    (1) Fully connected layer with out_features = 64 (you need to determine in_features taken from the input).

    (2) Activation layer with tanh function.

    (3) Fully connected layer with in_features = 64 and out_features = 64.

    (4) Activation layer with tanh function.

    (5) Fully connected layer with in_features = 64 (you need to determine out_features as the output of the entire model).

  3. Construct a model who is an object of this class and is called as model.

Show official solution

Official solution


class HeatPINN(nn.Module):
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(2, 64),
            nn.Tanh(),
            nn.Linear(64, 64),
            nn.Tanh(),
            nn.Linear(64, 1)
        )

    def forward(self, x):
        return self.net(x)

model = HeatPINN()

Do the following tasks:

Let x be a tensor with shape (N,2).

  1. What is the number of dimensions of model(x)?

  2. What is the shape of model(x)?

  3. Explain the reasoning of your answers.

Show official solution

Official solution

  1. The dimension of model(x) is 2.

  2. The shape of model(x) is (N,1).

  3. For each sample, the output is a 1-dim tensor with shape (1,). Therefore, by having N samples, we get the answers above.

In this part, you are asked to create the dataset DPDE\mathcal D_{PDE}.

  1. The dataset object is called dataset_train_PDE. It is in a class called Dataset_PDE that you need to build.

  2. Class Dataset_PDE subclasses Dataset.

  3. Each (t,x)∈DPDE\left( t, x \right) \in \mathcal D_{PDE} is randomly sampled from [0,1]2\left[ 0 , 1 \right]^2.

  4. Set ∣DPDE∣=500| \mathcal D_{PDE} | = 500.

Show official solution

Official solution


num_samples = 500

class Dataset_PDE(Dataset):
    def __init__(self, num_samples):
        self.data = torch.rand(num_samples, 2, requires_grad=True)

    def __len__(self):
        return self.data.shape[0]

    def __getitem__(self, idx):
        return self.data[idx]

dataset_train_PDE = Dataset_PDE(num_samples)

In this part, you are asked to define a Dataloader object called dataloader_PDE:

  1. dataset = dataset_train_PDE

  2. batch_size = 32

  3. shuffle = True

Show official solution

Official solution


batch_size_PDE = 32

dataloader_PDE = DataLoader(dataset_train_PDE, batch_size=batch_size_PDE, shuffle=True)

In this part, you are asked to create the dataset DIC\mathcal D_{IC}.

  1. Define dataset DIC\mathcal D_{IC} in the way that for each (t,x)∈DIC\left( t, x \right) \in \mathcal D_{IC}, tt is fixed at 0 and xx is evenly sampled from {0,0.01,0.02,⋯ ,0.98,0.99,1}\left\{ 0, 0.01, 0.02, \cdots , 0.98, 0.99, 1 \right\}. Therefore, ∣DIC∣=101| \mathcal D_{IC} | = 101.

  2. The dataset shall be a tensor with name dataset_train_IC and shape (101,2).

  3. Set dataset_train_IC.requires_grad = True.

  4. Print dataset_train_IC.requires_grad and dataset_train_IC.shape.

  5. Define tensor u_IC to be the groud-truth functional values of all data in DIC\mathcal D_{IC} (You can find the formula from Part 1).

  6. Set u_IC.requires_grad = True and u_IC.shape = (101,1).

  7. Print u_IC.requires_grad and u_IC.shape.

Show official solution

Official solution


num_samples = 101

dataset_train_IC = torch.stack([torch.zeros(num_samples), torch.linspace(0, 1, num_samples)], dim=1)

print(dataset_train_IC.requires_grad)
print(dataset_train_IC.shape)

u_IC = torch.sin(torch.pi * dataset_train_IC[:,1].view(-1,1))
u_IC.requires_grad_(True)

print(u_IC.requires_grad)
print(u_IC.shape)

In this part, you are asked to create the dataset DBC\mathcal D_{BC}.

  1. Define dataset DBC\mathcal D_{BC} in the way that for each (t,x)∈DBC\left( t, x \right) \in \mathcal D_{BC}, xx is either 0 or 1, and tt is evenly sampled from {0,0.01,0.02,⋯ ,0.98,0.99,1}\left\{ 0, 0.01, 0.02, \cdots , 0.98, 0.99, 1 \right\}. Therefore, ∣DBC∣=2⋅101=202| \mathcal D_{BC} | = 2 \cdot 101 = 202.

  2. The dataset shall be a tensor with name dataset_train_BC and shape (202,2).

  3. Set dataset_train_BC.requires_grad = True.

  4. Print dataset_train_BC.requires_grad and dataset_train_IC.shape.

Show official solution

Official solution


num_samples = 202

data_0 = torch.stack([torch.linspace(0, 1, num_samples//2), torch.zeros(num_samples//2)], dim=1)
data_1 = torch.stack([torch.linspace(0, 1, num_samples//2), torch.ones(num_samples//2)], dim=1)
dataset_train_BC = torch.cat([data_0, data_1], dim=0)
dataset_train_BC.requires_grad_(True)

print(dataset_train_BC.requires_grad)
print(dataset_train_BC.shape)

In this part, you are asked to configure your optimizer.

  1. Define an optimizer object called optimizer.

  2. Configure the optimization method as Adam.

  3. Set the learning rate as 1e-3.

Show official solution

Official solution


lr = 1e-3
optimizer = optim.Adam(model.parameters(), lr=lr)

The purpose of this part is to guide you to learn using torch.autograd.grad.

For each given input (t,x)\left( t, x \right), we not only compute U(t,x∣θ)U \left( t, x \mid \mathbf{\theta} \right) (output from the model), but also its 1st and 2nd order partial derivatives.

In PyTorch, these can be done by using torch.autograd.grad.

Part 9.1

Consider the following function

f(p,q)=p2+q3+pq2.f \left( p, q \right) = p^2 + q^3 + p q^2 .

Do the following tasks at (p,q)=(1,2)\left( p, q \right) = \left( 1, 2 \right):

  1. Define tensors p and q that have values 1.0 and 2.0 (float data type), respectively, an identical shape () (that is, 0-dim), and requires_grad = True.

  2. Compute tensor f according to the formula above.

  3. Compute ∂f(p,q)∂p\frac{\partial f \left( p, q \right)}{\partial p} by using

    f_p = autograd.grad(f, p, create_graph=True)[0]
    

    Print f_p.

  4. Compute ∂f(p,q)∂q\frac{\partial f \left( p, q \right)}{\partial q} by using

    f_q = autograd.grad(f, q, create_graph=True)[0]
    

    Print f_q.

  5. Compute ∂2f(p,q)∂p2\frac{\partial^2 f \left( p, q \right)}{\partial p^2} by using

    f_pp = autograd.grad(f_p, p, create_graph=True)[0]
    

    Print f_pp.

  6. Compute ∂2f(p,q)∂q2\frac{\partial^2 f \left( p, q \right)}{\partial q^2} by using

    f_qq = autograd.grad(f_q, q, create_graph=True)[0]
    

    Print out f_qq.

  7. Compute ∂2f(p,q)∂p∂q\frac{\partial^2 f \left( p, q \right)}{\partial p \partial q} by using

    f_pq = autograd.grad(f_p, q, create_graph=True)[0]
    

    Print f_pq.

  8. Compute ∂3f(p,q)∂q3\frac{\partial^3 f \left( p, q \right)}{\partial q^3} by using

    f_qqq = autograd.grad(f_qq, q, create_graph=True)[0]
    

    Print f_qqq.

Part 9.2

Consider the following function

g(x)=x2.g \left( x \right) = x^2 .

Let xx be a vector with values 0,0.1,⋯ ,0.9,10, 0.1, \cdots , 0.9, 1.

Do the following tasks.

  1. Generate x as a 1-dim tensor and set x.requires_grad = True.

  2. Generate g = x**2. Thus, g has the same shape as x.

  3. Define g_x to be an element-wise 1st-order derivative of function gg with respect to xx. Thus, g_x has the same shape as x.

    Write code to compute g_x. Print g_x and g_x.shape.

    Hint: by using autograd.grad(f, x, create_graph=True)[0], tensor x can be with any dimension, but tensor f must be with dimension 0. In this problem, tensor g is not with dimension 0. So you need to think about how to address this issue.

  4. Define g_xx to be an element-wise 2st-order derivative of function gg with respect to xx. Thus, g_xx has the same shape as x. Write code to compute g_xx. Print it out g_xx and g_xx.shape.

Show official solution

Official solution


# Part 9.1
p = torch.tensor(1.0, requires_grad=True)
q = torch.tensor(2.0, requires_grad=True)

f = p**2 + q**3 + p*q**2

f_p = autograd.grad(f, p, create_graph=True)[0]
print(f_p)

f_q = autograd.grad(f, q, create_graph=True)[0]
print(f_q)

f_pp = autograd.grad(f_p, p, create_graph=True)[0]
print(f_pp)

f_qq = autograd.grad(f_q, q, create_graph=True)[0]
print(f_qq)

f_pq = autograd.grad(f_p, q, create_graph=True)[0]
print(f_pq)

f_qqq = autograd.grad(f_qq, q, create_graph=True)[0]
print(f_qqq)

# Part 9.2

x = torch.linspace(0, 1, 10)
x.requires_grad_(True)

g = x**2
g_x = autograd.grad(torch.sum(g), x, create_graph=True)[0]
print(g_x)
print(g_x.shape)

g_xx = autograd.grad(torch.sum(g_x), x, create_graph=True)[0]
print(g_xx)
print(g_xx.shape)

This part asks you to do a mini-batch training of the model.

  1. Set the parameter in the PDE alpha = 0.1. (This is not for learning. In PINN, we know the exact form of a PDE. We just need neural networks to help us solve it.)

  2. Set the number of epochs as 1000.

  3. Define

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

  4. While iterating over epochs, use tqdm to track the progress:

    for epoch in tqdm(range(num_epochs)):

  5. In each epoch,

    (1) Configure the model to the training mode.

    (2) Iterate over all mini-batches of dataset_train_PDE.

    (3) For each of the above mini-batch of the PDE dataset, while computing the total loss function, you also need to use all data in dataset_train_IC and dataset_train_BC.

    (4) Do all these tasks on GPU.

  6. In each epoch, after training over all mini-batches, if the epoch index is divisible by 100, do the following tasks:

    (1) Configure the model to the evaluation mode.

    (2) Compute the total loss over the entire three datasets: dataset_train_PDE, dataset_train_IC, dataset_train_BC.

    (3) Print the epoch index, the residual loss from PDE, the IC loss, the BC loss, and the total loss.

    (4) Do all these tasks on CPU.

Show official solution

Official solution


alpha = 0.1
num_epochs = 1000
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

for epoch in tqdm(range(num_epochs)):
    model.train()
    model.to(device)
    for batch_PDE in dataloader_PDE:
        batch_PDE = batch_PDE.to(device)
        optimizer.zero_grad()
        U_PDE = model(batch_PDE)
        U_t_and_x_PDE = autograd.grad(torch.sum(U_PDE), batch_PDE, create_graph=True)[0]
        U_t_PDE = U_t_and_x_PDE[:,0]
        U_x_PDE = U_t_and_x_PDE[:,1]
        U_xx_PDE = autograd.grad(torch.sum(U_x_PDE), batch_PDE, create_graph=True)[0][:,1]
        loss_PDE = torch.mean((U_t_PDE - alpha * U_xx_PDE)**2)

        U_IC = model(dataset_train_IC.to(device))
        loss_IC = torch.mean((U_IC - u_IC.to(device))**2)

        U_BC = model(dataset_train_BC.to(device))
        loss_BC = torch.mean(U_BC**2)

        loss = loss_PDE + loss_IC + loss_BC
        loss.backward()
        optimizer.step()

    if epoch % 100 == 0:
        model.eval()
        model.to('cpu')
        batch_PDE = next(iter(dataloader_PDE))
        batch_PDE.requires_grad_(True)
        U_PDE = model(batch_PDE)
        U_t_and_x_PDE = autograd.grad(torch.sum(U_PDE), batch_PDE, create_graph=True)[0]
        U_xx_PDE = autograd.grad(torch.sum(U_t_and_x_PDE[:,1]), batch_PDE, create_graph=True)[0][:,1]
        loss_PDE = torch.mean((U_t_and_x_PDE[:,0] - alpha * U_xx_PDE)**2)

        with torch.no_grad():
            U_IC = model(dataset_train_IC)
            loss_IC = torch.mean((U_IC - u_IC)**2)
            U_BC = model(dataset_train_BC)
            loss_BC = torch.mean(model(dataset_train_BC)**2)
            loss = loss_PDE + loss_IC + loss_BC

        print(f"{loss_PDE.item():.4e}, {loss_IC.item():.4e}, {loss_BC.item():.4e}")
        print(f"Epoch {epoch}, Loss: {loss.item():.4e}")

Part 11

5 ptsNon-codingForum thread

Answer the following free-response question.

  • In each epoch, while iterating over each mini-batch of dataset_PDE, why do we consider the entire data points in dataset_IC and dataset_BC, rather than also a mini-batch in these two datasets?

To be specific, recall that the mini-batch size of dataset_PDE is 32. The sizes of dataset_IC and dataset_BC are 101 and 202, respectively.

Then in each iteration, the number of data points that we use to compute the total loss value is 32+101+202=33532 + 101 + 202 = 335.

Suppose we also do mini-batch on the IC and BC datasets with the same mini-batch size, say, 32. Then in each iteration, the number of data points that we use is 32+32+32=9632 + 32 + 32 = 96.

We adopt the former approach, not the latter approach. You need to explain why.

Show official solution

Official solution

In training, we always need to ensure that all IC and BC constraints are satisfied. Therefore, we enforce these constraints all the time.

In this part, you are asked to do the following tasks to test the effectiveness of our PINN model.

  1. Generate a dataset {(t,x)∈{0,0.01,⋯ ,1}2}\left\{ \left( t , x \right) \in \left\{ 0, 0.01, \cdots, 1 \right\}^2 \right\}. Save the dataset as a tensor with name tx_test and shape (101,2).

  2. For each data point, compute u(t,x)u \left( t , x \right) whose formula is given in Part 1. Save the result as a tensor with name u_test and shape (101,2).

  3. For each data point, use our trained PINN model to compute the predicted value U(t,x∣θ)U \left( t, x \mid \mathbf{\theta} \right). Save the result as a tensor with name U_test and shape (101,2).

  4. Print the mean squared error between u_test and U_test.

  5. Generate two 2-dim scatter plots for (t,x)\left( t, x \right) by using the above data points.

    • In Figure 1, the value on each position is the ground-truth temperature u(t,x)u \left( t , x \right).

    • In Figure 2, the value on each position is the predicted temperature U(t,x∣θ)U \left( t, x \mid \mathbf{\theta} \right).

    • In each plot,

      • Set c as the values on those scattered positions

      • Set cmap='viridis'

      • Add plt.colorbar(label='Value').

Show official solution

Official solution


model.to('cpu')
data_1dim = torch.linspace(0, 1, 101)
data_grid = torch.meshgrid(data_1dim, data_1dim)
tx_test = torch.stack([data_grid[0].reshape(-1), data_grid[1].reshape(-1)], dim=1)
u_test = torch.exp(- alpha * torch.pi**2 * tx_test[:,0]) * torch.sin(torch.pi * tx_test[:,1])
U_test = model(tx_test).reshape(-1).detach()

mse = torch.mean((u_test - U_test)**2).item()
print(mse)

plt.figure(1)
plt.scatter(tx_test[:,0], tx_test[:,1], c=u_test, cmap='viridis')
plt.xlabel('t')
plt.ylabel('x')
plt.colorbar(label='Value')
plt.title('Ground-truth')

plt.show()

plt.figure(2)
plt.scatter(tx_test[:,0], tx_test[:,1], c=U_test, cmap='viridis')
plt.xlabel('t')
plt.ylabel('x')
plt.colorbar(label='Value')
plt.title('Predicted')

plt.show()

Problem 2Multi-head attention and its variants

100 pts

SummaryWork through the shapes and formulas of multi-head attention, implement MHA and grouped-query attention, relate GQA to DeepSeek's multi-head latent attention, and compare KV-cache sizes across the three.

    TransformersGQAMLAKV cache

Multi-head attention (MHA) is a big breakthrough in AI. Based on its original form, there are many variants that improved it.

In this problem, you are asked to study multi-head attention and its variants.

We use the following notation in this problem.

  • BB: batch size. bb: index of a sample.

  • L1L_1: length of an attending sequence. l1l_1: index of a position in this sequence.

  • L2L_2: length of a being attended sequence. l2l_2: index of a position in this sequence.

  • D1D_1: dimension of a hidden state/token in an attending sequence.

  • D2D_2: dimension of a hidden state/token in a being attended sequence.

  • HH: number of heads. hh: index of a head.

  • DvD_v: dimension of a value vector.

  • DqkD_{qk}: dimension of a query/key vector.

# Run code in this cell

"""
DO NOT MAKE ANY CHANGE IN THIS CELL.
"""

import torch
import torch.nn as nn
import numpy as np

WARNING !!!\color{red}{\text{WARNING !!!}}

  • Beyond importing libraries/modules/classes/functions in the preceeding cell, you are NOT allowed to import anything else for the following purposes:

    • As a part of your final solution. For instance, if a problem asks you to build a model without using sklearn but you use it, then you will not earn points.

    • Temporarily import something to assist you to get a solution. For instance, if a problem asks you to manually compute eigenvalues but you temporarily use np.linalg.eig to get an answer and then delete your code, then you violate the rule.

    Rule of thumb: Each part has its particular purpose to intentionally test you something. Do not attempt to find a shortcut to circumvent the rule.

Part 1

5 ptsNon-codingForum thread

Do the following tasks (Reasoning is not required).

  1. For each hidden state at position l1l_1 in an attending sequence, xl1∈RD1\mathbf{x}_{l_1} \in \Bbb R^{D_1}, we project it into a query vector for head hh according to

    ql1,h=WhQxl1.\mathbf{q}_{l_1,h} = \mathbf{W}^{\mathbf{Q}}_h \mathbf{x}_{l_1} .

    What is the shape of WhQ\mathbf{W}^{\mathbf{Q}}_h?

  2. For each hidden state at position l2l_2 in a being attended sequence yl2∈RD2\mathbf{y}_{l_2} \in \Bbb R^{D_2}, we project it into a key vector for head hh according to

    kl2,h=WhKyl2.\mathbf{k}_{l_2,h} = \mathbf{W}^{\mathbf{K}}_h \mathbf{y}_{l_2} .

    What is the shape of WhK\mathbf{W}^{\mathbf{K}}_h?

  3. For each hidden state at position l2l_2 in a being attended sequence yl2∈RD2\mathbf{y}_{l_2} \in \Bbb R^{D_2}, we project it into a value vector for head hh according to

    vl2,h=WhVyl2.\mathbf{v}_{l_2,h} = \mathbf{W}^{\mathbf{V}}_h \mathbf{y}_{l_2} .

    What is the shape of WhV\mathbf{W}^{\mathbf{V}}_h?

Show official solution

Official solution

  1. The shape of WhQ\mathbf{W}^{\mathbf{Q}}_h is (Dqk,D1)\left( D_{qk}, D_1 \right).

  2. The shape of WhK\mathbf{W}^{\mathbf{K}}_h is (Dqk,D2)\left( D_{qk}, D_2 \right).

  3. The shape of WhV\mathbf{W}^{\mathbf{V}}_h is (Dv,D2)\left( D_v, D_2 \right).

Part 2

5 ptsNon-codingForum thread

For M∈{Q,K,V}\mathbf{M} \in \left\{ \mathbf{Q}, \mathbf{K}, \mathbf{V} \right\}, We concatenate M\mathbf{M}-projection matrices {WhM:h∈{0,1,⋯ ,H−1}}\left\{ \mathbf{W}^{\mathbf{M}}_h : h \in \left\{ 0, 1, \cdots , H-1 \right\} \right\} along axis 0 as

WM=[W0MW1M⋮WH−1M].\mathbf{W}^{\mathbf{M}} = \begin{bmatrix} \mathbf{W}^{\mathbf{M}}_0 \\ \mathbf{W}^{\mathbf{M}}_1 \\ \vdots \\ \mathbf{W}^{\mathbf{M}}_{H-1} \end{bmatrix} .

At each position l1l_1 in an attending sequence, we concatenate queries {ql1,h:h∈{0,1,⋯ ,H−1}}\left\{ \mathbf{q}_{l_1,h} : h \in \left\{ 0, 1, \cdots , H-1 \right\} \right\} along axis 0 to get

ql1=[ql1,0ql1,1⋮ql1,H−1].\mathbf{q}_{l_1} = \begin{bmatrix} \mathbf{q}_{l_1,0} \\ \mathbf{q}_{l_1,1} \\ \vdots \\ \mathbf{q}_{l_1,H-1} \end{bmatrix} .

At each position l2l_2 in a being attended sequence, we concatenate keys/values m∈{k,v}{ml2,h:h∈{0,1,⋯ ,H−1}}\mathbf{m} \in \left\{ \mathbf{k}, \mathbf{v} \right\}\left\{ \mathbf{m}_{l_2,h} : h \in \left\{ 0, 1, \cdots , H-1 \right\} \right\} along axis 0 to get

ml2=[ml2,0ml2,1⋮ml2,H−1].\mathbf{m}_{l_2} = \begin{bmatrix} \mathbf{m}_{l_2,0} \\ \mathbf{m}_{l_2,1} \\ \vdots \\ \mathbf{m}_{l_2,H-1} \end{bmatrix} .

Do the following tasks (Reasoning is not required).

  1. What is the shape of WM\mathbf{W}^{\mathbf{M}} for M∈{Q,K,V}\mathbf{M} \in \left\{ \mathbf{Q}, \mathbf{K}, \mathbf{V} \right\}?

  2. What is the shape of ql1\mathbf{q}_{l_1}?

  3. What is the relationship between ql1\mathbf{q}_{l_1} and WQ\mathbf{W}^{\mathbf{Q}}?

  4. For m∈{k,v}\mathbf{m} \in \left\{ \mathbf{k}, \mathbf{v} \right\} , what is the shape of ml2\mathbf{m}_{l_2}?

  5. What is the relationship between ml2\mathbf{m}_{l_2} and WM\mathbf{W}^{\mathbf{M}}?

Show official solution

Official solution

  1. The shape of WQ\mathbf{W}^{\mathbf{Q}} is (H⋅Dqk,D1)\left( H \cdot D_{qk}, D_1 \right).

    The shape of WK\mathbf{W}^{\mathbf{K}} is (H⋅Dqk,D2)\left( H \cdot D_{qk}, D_2 \right).

    The shape of WhV\mathbf{W}^{\mathbf{V}}_h is (H⋅Dv,D2)\left( H \cdot D_v, D_2 \right).

  2. The shape of ql1\mathbf{q}_{l_1} is (H⋅Dqk,)\left( H \cdot D_{qk}, \right).

ql1=WQxl1.\mathbf{q}_{l_1} = \mathbf{W}^{\mathbf{Q}} \mathbf{x}_{l_1} .
  1. The shape of kl2\mathbf{k}_{l_2} is (H⋅Dqk,)\left( H \cdot D_{qk}, \right).

    The shape of vl2\mathbf{v}_{l_2} is (H⋅Dv,)\left( H \cdot D_v, \right).

kl2=WKyl2.\mathbf{k}_{l_2} = \mathbf{W}^{\mathbf{K}} \mathbf{y}_{l_2} . vl2=WVyl2.\mathbf{v}_{l_2} = \mathbf{W}^{\mathbf{V}} \mathbf{y}_{l_2} .

Part 3

10 ptsNon-codingForum thread

Define function Softmax:Rd→Rd\text{Softmax}: \Bbb R^d \rightarrow \Bbb R^d, with the iith output value as

Softmaxi(z)=exp⁡(zi)∑j=0d−1exp⁡(zj).\text{Softmax}_i \left( \mathbf{z} \right) = \frac{\exp \left( z_i \right)}{\sum_{j=0}^{d-1} \exp \left( z_j \right)} .

At position l1l_1 in the attending sequence, its attention score to position l2l_2 in the being attended sequence for head hh is denoted as αh,l1l2\alpha_{h, l_1 l_2}.

We can write αh,l1l2\alpha_{h, l_1 l_2} in the following form:

αh,l1l2=Softmaxl2(???),\alpha_{h, l_1 l_2} = \text{Softmax}_{l_2} \left( \color{red}{\boxed{???}} \right) ,

What is the formula in the above red box (reasoning is not required)?

Show official solution

Official solution

αh,l1l2=Softmaxl2(qh,l1⊤Kh⊤Dqk),\alpha_{h, l_1 l_2} = \text{Softmax}_{l_2} \left( \frac{\mathbf{q}_{h, l_1}^\top \mathbf{K}_h^\top}{\sqrt{D_{qk}}} \right) ,

where

Kh=[kh,0⊤kh,1⊤⋮kh,L2−1⊤]∈RL2×Dqk.\mathbf{K}_h = \begin{bmatrix} \mathbf{k}_{h, 0}^\top \\ \mathbf{k}_{h, 1}^\top \\ \vdots \\ \mathbf{k}_{h, L_2-1}^\top \end{bmatrix} \in \Bbb R^{L_2 \times D_{qk}} .

Part 4

5 ptsNon-codingForum thread

At position l1l_1 in an attending sequence, for head hh, the information extracted from attending to a being attended sequence is given by

oh,l1=∑l2=0L2−1αh,l1l2vl2,h.\mathbf{o}_{h,l_1} = \sum_{l_2 = 0}^{L_2 - 1} \alpha_{h, l_1 l_2} \mathbf{v}_{l_2,h} .

We hereafter call oh,l1\mathbf{o}_{h,l_1} a pre-out-projection output vector.

Do the following tasks.

  1. What is the shape of vector oh,l1\mathbf{o}_{h,l_1}?

  2. We concatenate {oh,l1:h∈{0,1,⋯ ,H−1}}\left\{\mathbf{o}_{h,l_1} : h \in \left\{ 0, 1 , \cdots , H-1 \right\} \right\} along axis 0:

    ol1=[o0,l1o1,l1⋮oH−1,l1]\mathbf{o}_{l_1} = \begin{bmatrix} \mathbf{o}_{0,l_1} \\ \mathbf{o}_{1,l_1} \\ \vdots \\ \mathbf{o}_{H-1,l_1} \end{bmatrix}

    What is the shape of ol1\mathbf{o}_{l_1}?

  3. We project ol1\mathbf{o}_{l_1} to a post-out-projection output vector via an out-projection matrix:

    xl1out=WOol1∈RD1,\mathbf{x}_{l_1}^{out} = \mathbf{W}^O \mathbf{o}_{l_1} \in \Bbb R^{D_1} ,

    where

    WO=[W0OW1O⋯WH−1O]\mathbf{W}^O = \begin{bmatrix} \mathbf{W}^O_0 & \mathbf{W}^O_1 & \cdots & \mathbf{W}^O_{H-1} \end{bmatrix}

    What is the shape of WhO\mathbf{W}^O_h for each h∈{0,1,⋯ ,H−1}h \in \left\{ 0 , 1 , \cdots , H-1 \right\} and WO\mathbf{W}^O?

Show official solution

Official solution

  1. The shape of oh,l1\mathbf{o}_{h,l_1} is (Dv,)\left( D_v, \right).

  2. The shape of ol1\mathbf{o}_{l_1} is (H⋅Dv,)\left( H \cdot D_v, \right).

  3. For each head hh, the shape of WhO\mathbf{W}^O_h is (D1,Dv)\left( D_1, D_v \right).

    The shape of WO\mathbf{W}^O is (D1,H⋅Dv)\left( D_1, H \cdot D_v \right).

In this part, you are asked to build your own multi-head attention module that subclasses nn.Module.

  • For simplicity, we ignore any masking. That is, each position in an attending sequence attends to all positions in a being attended sequence.

  • In your code, you do not need to worry about whether your code is efficient in an autoprogressive token generation process when your module is used in inference in a GPT-like task.

    That is, if we use your code in a GPT-like task to autoprogressively generate tokens, it is totally fine if you repeatly generate the same key and value at a given position rather than more efficiently storing their values in cache.

  • The class name is MyMHA.

  • Attributes:

    • D_1: Dimension of a hidden state/token in an attending sequence.

    • D_2: Dimension of a hidden state/token in a being attended sequence.

    • D_v: Dimension of a value vector.

    • D_qk: Dimension of a query/key vector.

    • H: Number of heads.

    • W_Q: A linear module whose weights is a query-projection matrix. The shape should be consistant with your answer in Part 2. No bias.

    • W_K: A linear module whose weights is key-projection matrix. The shape should be consistant with your answer in Part 2. No bias.

    • W_V: A linear module whose weights is value-projection matrix. The shape should be consistant with your answer in Part 2. No bias.

    • W_O: A linear module whose weights is an out-projection matrix. The shape should be consistant with your answer in Part 4. No bias.

  • Method __init__:

    • Inputs

      • D_1

      • D_2

      • D_qk

      • D_v

      • H

    • Outputs

      • None
    • What to do inside this method

      • Initialize attribute values
  • Method forward:

    • Inputs:

      • An attending sequence (tensor) with shape (B,L_1,D_1)

      • A being addended sequence (tensor) with shape (B,L_2,D_2)

    • Outputs

      • Post-out-projection outputs with shape (B,L_1,D_1)
    • What to do inside this method

      • Compute the outputs

      • After each operation, add a comment on the tensor shape

      • Do not use any loop

Show official solution

Official solution


class MyMHA(nn.Module):
    def __init__(self, D_1, D_2, D_qk, D_v, H):
        super().__init__()
        self.D_1 = D_1
        self.D_2 = D_2
        self.D_qk = D_qk
        self.D_v = D_v
        self.H = H

        self.W_Q = nn.Linear(in_features=D_1, out_features=H*D_qk, bias=False)
        self.W_K = nn.Linear(in_features=D_2, out_features=H*D_qk, bias=False)
        self.W_V = nn.Linear(in_features=D_2, out_features=H*D_v, bias=False)
        self.W_O = nn.Linear(in_features=H*D_v, out_features=D_1, bias=False)

    def forward(self, x, y):
        B = x.shape[0] # batch size
        L_1 = x.shape[1] # the length of sequence x
        L_2 = y.shape[1] # the length of sequence y

        Q = self.W_Q(x) # shape: (B,L_1,H*D_qk)
        K = self.W_K(y) # shape: (B,L_2,H*D_qk)
        V = self.W_V(y) # shape: (B,L_2,H*D_v)

        Q = Q.reshape(B,L_1,self.H,self.D_qk) # shape: (B,L_1,H,D_qk)
        K = K.reshape(B,L_2,self.H,self.D_qk) # shape: (B,L_2,H,D_qk)
        V = V.reshape(B,L_2,self.H,self.D_v) # shape: (B,L_2,H,D_v)

        Q = Q.permute(0,2,1,3) # shape: (B,H,L_1,D_qk)
        K = K.permute(0,2,1,3) # shape: (B,H,L_2,D_qk)
        V = V.permute(0,2,1,3) # shape: (B,H,L_2,D_v)

        logits = Q @ K.transpose(-2,-1) / (self.D_qk**0.5) # shape: (B,H,L_1,L_2)
        alpha = torch.softmax(logits, dim=-1) # shape: (B,H,L_1,L_2)

        O = alpha @ V # shape: (B,H,L_1,D_v)

        O = O.permute(0,2,1,3) # shape: (B,L_1,H,D_v)
        O = O.reshape(B,L_1,self.H*self.D_v) # shape: (B,L_1,H*D_v)
        return self.W_O(O) # shape: (B,L_1,D_1)

Part 6

5 ptsNon-codingForum thread

Next, let us study a variant of MHA: Group Query Attention (GQA).

Recall that in MHA, the number of heads in queries, keys and values are the same, HH. Thus, query ql1,h\mathbf{q}_{l_1, h} attends to key kl2,h\mathbf{k}_{l_2, h} with the same head index hh.

In GQA, we relax this constraint by allowing keys and values to have GG heads (G≤HG \leq H), where GG is factor of HH. For instance, if H=12H = 12, then G∈{1,2,3,4,6,12}G \in \left\{ 1, 2, 3, 4, 6, 12 \right\}.

In GQA, a query ql1,h\mathbf{q}_{l_1, \color{red}{h}} with head h\color{red}{h} is permitted to attend to a key kl2,g\mathbf{k}_{l_2, \color{blue}{g}} and use value vl2,g\mathbf{v}_{l_2, \color{blue}{g}} in computing its output with head g\color{blue}{g} if

h≡g(modG).\color{red}{h} \equiv \color{blue}{g} \pmod{G} .

Thus, each head in keys and values is mapped to HG≥1\frac{H}{G} \geq 1 heads in queries.

As an example, suppose H=12H = 12 and G=3G = 3. Then

  • Head g=0\color{blue}{g} = 0 in keys and values is associated with heads h=0,3,6,9\color{red}{h} = 0, 3, 6, 9 in queries.

  • Head g=1\color{blue}{g} = 1 in keys and values is associated with heads h=1,4,7,10\color{red}{h} = 1, 4, 7, 10 in queries.

  • Head g=2\color{blue}{g} = 2 in keys and values is associated with heads h=2,5,8,11\color{red}{h} = 2, 5, 8, 11 in queries.

Show official solution

Official solution

For M∈{K,V}\mathbf{M} \in \left\{ \mathbf{K}, \mathbf{V} \right\}, Denote the M\mathbf{M}-projection matrix as

WM,GQA=[W0M,GQA⋮WG−1M,GQA]\mathbf{W}^{\mathbf{M}, GQA} = \begin{bmatrix} \mathbf{W}^{\mathbf{M}, GQA}_0 \\ \vdots \\ \mathbf{W}^{\mathbf{M}, GQA}_{G-1} \end{bmatrix}

Now, we concatenate HG\frac{H}{G} copies of the above matrix along axis 0:

W~M,GQA=[WM,GQAWM,GQA⋮WM,GQA]\mathbf{\tilde W}^{\mathbf{M}, GQA} = \begin{bmatrix} \mathbf{W}^{\mathbf{M}, GQA} \\ \mathbf{W}^{\mathbf{M}, GQA} \\ \vdots \\ \mathbf{W}^{\mathbf{M}, GQA} \end{bmatrix}

What is the relationship between rank(W~M,GQA)\text{rank} \left( \mathbf{\tilde W}^{\mathbf{M}, GQA} \right) and rank(WM,GQA)\text{rank} \left( \mathbf{W}^{\mathbf{M}, GQA} \right)?

  • Reasoning is required.

In this part, please build your own GQA module called MyGQA.

  • The requirement is pretty much the same as Part 5.

  • Do NOT create H/GH/G copies of key-projection and value-projection matrices. Otherwise, you will use too much unnecessary memory.

  • No loop is allowed.

Show official solution

Official solution


class MyGQA(nn.Module):
    def __init__(self, D_1, D_2, D_qk, D_v, H, G):
        super().__init__()
        self.D_1 = D_1
        self.D_2 = D_2
        self.D_qk = D_qk
        self.D_v = D_v
        self.H = H
        self.G = G

        self.W_Q = nn.Linear(in_features=D_1, out_features=H*D_qk, bias=False)
        self.W_K = nn.Linear(in_features=D_2, out_features=G*D_qk, bias=False)
        self.W_V = nn.Linear(in_features=D_2, out_features=G*D_v, bias=False)
        self.W_O = nn.Linear(in_features=H*D_v, out_features=D_1, bias=False)

    def forward(self, x, y):
        B = x.shape[0] # batch size
        L_1 = x.shape[1] # the length of sequence x
        L_2 = y.shape[1] # the length of sequence y
        num_copies = self.H // self.G

        Q = self.W_Q(x) # shape: (B,L_1,H*D_qk)
        K = self.W_K(y) # shape: (B,L_2,G*D_qk)
        V = self.W_V(y) # shape: (B,L_2,G*D_v)

        Q = Q.reshape(B,L_1,num_copies,self.G,self.D_qk) # shape: (B,L_1,num_copies,G,D_qk)
        K = K.reshape(B,L_2,1,self.G,self.D_qk) # shape: (B,L_2,1,G,D_qk)
        V = V.reshape(B,L_2,1,self.G,self.D_v) # shape: (B,L_2,1,G,D_v)

        Q = Q.permute(0,2,3,1,4) # shape: (B,num_copies,G,L_1,D_qk)
        K = K.permute(0,2,3,1,4) # shape: (B,1,G,L_2,D_qk)
        V = V.permute(0,2,3,1,4) # shape: (B,1,G,L_2,D_v)

        logits = Q @ K.transpose(-2,-1) / (self.D_qk**0.5) # shape: (B,num_copies,G,L_1,L_2)
        alpha = torch.softmax(logits, dim=-1) # shape: (B,num_copies,G,L_1,L_2)

        O = alpha @ V # shape: (B,num_copies,G,L_1,D_v)

        O = O.permute(0,3,1,2,4) # shape: (B,L_1,num_copies,G,D_v)
        O = O.reshape(B,L_1,-1) # shape: (B,L_1,H*D_v)
        return self.W_O(O) # shape: (B,L_1,D_1)

Part 8

5 ptsNon-codingForum thread

MHA is a special case of GQA. Explain why.

Show official solution

Official solution

When G=HG = H, GQA becomes MHA.

Part 9

10 ptsNon-codingForum thread

Now, let us study another variant of MHA: Multi-head Latent Attention (MLA). MLA was introduced by DeepSeek. It is a core component of DeepSeek's large language model (LLM).

The key intuition of MLA is as follows. In MHA, the key and value projection matrices

WK,MHA∈RH⋅Dqk×D2,WV,MHA∈RH⋅Dv×D2\mathbf{W}^{\mathbf{K}, MHA} \in \Bbb R^{H \cdot D_{qk} \times D_2} , \quad \mathbf{W}^{\mathbf{V}, MHA} \in \Bbb R^{H \cdot D_v \times D_2}

may be high dimensional.

For instance, suppose H⋅Dqk=H⋅Dv=D2=4096H \cdot D_{qk} = H \cdot D_v = D_2 = 4096.

However, it is not necessarily the case that these matrices are with high ranks (such as 4096). Their actual ranks (or top few ranks that make their truncated singular value decomposition (SVD) to be close to the actual matrices) may be much lower than that.

To capture the low-rank feature, MLA proposed the following model:

WK,MHA=WUK,MLAWDKV,MLAWV,MHA=WUV,MLAWDKV,MLA\begin{align*} \mathbf{W}^{\mathbf{K}, MHA} & = \color{blue}{\mathbf{W}^{\mathbf{UK}, MLA}} \color{red}{\mathbf{W}^{\mathbf{DKV}, MLA}} \\ \mathbf{W}^{\mathbf{V}, MHA} & = \color{green}{\mathbf{W}^{\mathbf{UV}, MLA}} \color{red}{\mathbf{W}^{\mathbf{DKV}, MLA}} \end{align*}

where

  • WDKV,MLA∈Rr×D2\color{red}{\mathbf{W}^{\mathbf{DKV}, MLA}} \in \Bbb R^{r \times D_2}: down-projection matrix for computing keys and values.

  • WUK,MLA∈RH⋅Dqk×r\color{blue}{\mathbf{W}^{\mathbf{UK}, MLA}} \in \Bbb R^{H \cdot D_{qk} \times r}: up-projection matrix for computing keys.

  • WUV,MLA∈RH⋅Dv×r\color{green}{\mathbf{W}^{\mathbf{UV}, MLA}} \in \Bbb R^{H \cdot D_v \times r}: up-projection matrix for computing values.

In practice, rank rr is typically much smaller than min⁡{H⋅Dqk,H⋅Dv,D2}\min \left\{ H \cdot D_{qk} , H \cdot D_v , D_2 \right\}.

In all remaining parts of this problem, to simplify your analysis and highlight the relationships of MHA, GQA and MLA, we make the following assumptions:

  • D1=D2=DD_1 = D_2 = \color{red}{D}.

  • Dqk=Dv=dD_{qk} = D_v = \color{red}{d}.

  • dd is a factor of DD.

Under these assumptions, the number heads HH satisfies

H=Dd.\color{red}{H} = \frac{D}{d} .

In this part, you are asked to prove that GQA can be equivalently represented by MLA.

In your solution, it is sufficient for you to prove that for M∈{K,V}\mathbf{M} \in \left\{ \mathbf{K}, \mathbf{V} \right\}, for matrix

W~M,GQA=[WM,GQAWM,GQA⋮WM,GQA]∈RD×D\mathbf{\tilde W}^{\mathbf{M}, GQA} = \begin{bmatrix} \color{orange}{\mathbf{W}^{\mathbf{M}, GQA}} \\ \color{orange}{\mathbf{W}^{\mathbf{M}, GQA}} \\ \vdots \\ \color{orange}{\mathbf{W}^{\mathbf{M}, GQA}} \end{bmatrix} \in \Bbb R^{D \times D}

(defined in Part 6) who is the concatenation of HG\frac{H}{G} copies of

WM,GQA=[W0M,GQA⋮WG−1M,GQA]∈RG⋅d×D{\color{orange}{\mathbf{W}^{\mathbf{M}, GQA}}} = \begin{bmatrix} \mathbf{W}^{\mathbf{M}, GQA}_0 \\ \vdots \\ \mathbf{W}^{\mathbf{M}, GQA}_{G-1} \end{bmatrix} \in \Bbb R^{G \cdot d \times D}

matrix W~M,GQA\mathbf{\tilde W}^{\mathbf{M}, GQA} can be decomposed as

W~M,GQA=WUM,MLAWDKV,MLA\mathbf{\tilde W}^{\mathbf{M}, GQA} = \color{blue}{\mathbf{W}^{\mathbf{UM}, MLA}} \color{red}{\mathbf{W}^{\mathbf{DKV}, MLA}}

where

  • WDKV,MLA∈Rr×D\color{red}{\mathbf{W}^{\mathbf{DKV}, MLA}} \in \Bbb R^{r \times D}: down-projection matrix for computing keys and values.

  • WUM,MLA∈RD×r\color{blue}{\mathbf{W}^{\mathbf{UM}, MLA}} \in \Bbb R^{D \times r}: up-projection matrix for computing M\mathbf{M} (keys or values).

  • r=G⋅dr = G \cdot d.

Show official solution

Official solution

We have

rank(W~M,GQA)=rank(WM,GQA)≤min⁡{G⋅d,D}=min⁡{r,D}=r,\begin{align*} \text{rank} \left( \mathbf{\tilde W}^{\mathbf{M}, GQA} \right) & = \text{rank} \left( \mathbf{W}^{\mathbf{M}, GQA} \right) \\ & \leq \min \left\{ G \cdot d, D \right\} \\ & = \min \left\{ r, D \right\} \\ & = r , \end{align*}

where the first equality follows from Part 6.

Therefore, SVD implies

W~M,GQA=∑i=0r−1σiuivi⊤=[u0u1⋯ur−1]⏟WUM,MLA[σ0v0⊤σ1v1⊤⋮σr−1vr−1⊤]⏟WDKV,MLA.\begin{align*} \mathbf{\tilde W}^{\mathbf{M}, GQA} & = \sum_{i=0}^{r-1} \sigma_i \mathbf{u}_i \mathbf{v}_i^\top \\ & = \underbrace{\begin{bmatrix} \mathbf{u}_0 & \mathbf{u}_1 & \cdots & \mathbf{u}_{r-1} \end{bmatrix}}_{\color{blue}{\mathbf{W}^{\mathbf{UM}, MLA}}} \underbrace{\begin{bmatrix} \sigma_0 \mathbf{v}_0^\top \\ \sigma_1 \mathbf{v}_1^\top \\ \vdots \\ \sigma_{r-1} \mathbf{v}_{r-1}^\top \end{bmatrix}}_{\color{red}{\mathbf{W}^{\mathbf{DKV}, MLA}}} . \end{align*}

This question follows Part 9.

You are asked to define a function called GQA_2_MLA that performs the following tasks:

  • Input:

    • W_M_GQA: A numpy array with shape (r,D), where r is guaranteed to be a factor of D (not something you need to worry about).
  • Outputs:

    • W_DKV_MLA: A numpy array with shape (r,D).

    • W_UM_MLA: A numpy array with shape (D,r).

  • Things to do inside this function:

    • Compute W_M_GQA_tilde that concatenates D/r copies of W_M_GQA along axis 0.

    • Print the shapes of W_UM_MLA and W_DKV_MLA.

    • Print the mean-squared error between W_M_GQA_tilde and W_UM_MLA @ W_DKV_MLA.

Hints:

  • You may use np.linalg.

  • PyTorch is not allowed.

  • No loop in your code.

After defining this function, test it with the input np.random.randn(4,24).

Show official solution

Official solution


def GQA_2_MLA(W_M_GQA):
    r = W_M_GQA.shape[0]
    D = W_M_GQA.shape[1]
    num_copies = D // r

    W_K_GQA_tilde = np.concatenate([W_M_GQA] * num_copies, axis=0)
    U, S, V = np.linalg.svd(W_K_GQA_tilde)
    W_UM_MLA = U[:, :r]
    W_DKV_MLA = S.reshape(-1,1)[:r, :] * V[:r, :]
    print(f"Shape of W_UK_MLA: {W_UM_MLA.shape}")
    print(f"Shape of W_DKV_MLA: {W_DKV_MLA.shape}")

    MSE = np.mean((W_K_GQA_tilde - W_UM_MLA @ W_DKV_MLA)**2)
    print(f"Mean-squared error: {MSE}")

    return W_DKV_MLA, W_UM_MLA

GQA_2_MLA(np.random.randn(4,24))

Part 11

10 ptsNon-codingForum thread

So far, we have proved that GQA can always be represented by MLA.

In this part, you are asked to prove that GQA is not equivalent to MLA. What you need to do is to find one example that MLA cannot be represented as GQA.

To be specific, please do the following things:

  1. Construct WDKV,MLA∈R1×2\color{red}{\mathbf{W}^{\mathbf{DKV}, MLA}} \in \Bbb R^{1 \times 2}.

  2. Construct WUM,MLA∈R2×1\color{blue}{\mathbf{W}^{\mathbf{UM}, MLA}} \in \Bbb R^{2 \times 1}.

  3. Do matrix multiplication WUM,MLAWDKV,MLA\color{blue}{\mathbf{W}^{\mathbf{UM}, MLA}} \color{red}{\mathbf{W}^{\mathbf{DKV}, MLA}}.

  4. Show that this product matrix is not the concatenation of two copies of 1-by-2 matrices along axis 0.

Show official solution

Official solution

Define

WDKV,MLA=[12]\color{red}{\mathbf{W}^{\mathbf{DKV}, MLA}} = \begin{bmatrix} 1 & 2 \end{bmatrix}

and

WUM,MLA=[34]\color{blue}{\mathbf{W}^{\mathbf{UM}, MLA}} = \begin{bmatrix} 3 \\ 4 \end{bmatrix}

Hence,

WUM,MLAWDKV,MLA=[3648].\begin{align*} \color{blue}{\mathbf{W}^{\mathbf{UM}, MLA}} \color{red}{\mathbf{W}^{\mathbf{DKV}, MLA}} & = \begin{bmatrix} 3 & 6 \\ 4 & 8 \end{bmatrix} . \end{align*}

Two rows of this product matrix are not identical.

Therefore, this is an example that MLA cannot always be represented by GQA.

Part 12

10 ptsNon-codingForum thread

MLA does not only enjoy its advantage of being more general than MHA and GQA, it is also computationally more efficient.

An intuitive approach of computing MLA.

  1. Compute the key-projection matrix WUK,MLAWDKV,MLA∈RD×D\mathbf{W}^{\mathbf{UK}, MLA} \mathbf{W}^{\mathbf{DKV}, MLA} \in \Bbb R^{D \times D} and the value-projection matrix WUV,MLAWDKV,MLA∈RD×D\mathbf{W}^{\mathbf{UV}, MLA} \mathbf{W}^{\mathbf{DKV}, MLA} \in \Bbb R^{D \times D}.

  2. Follow the standard steps in MHA.

This approach is hereafter called a vanilla approach\color{red}{\textbf{vanilla approach}}. This approach fails to enjoy the low-rank feature of WDKV,MLA\mathbf{W}^{\mathbf{DKV}, MLA}, WUK,MLA\mathbf{W}^{\mathbf{UK}, MLA}, and WUV,MLA\mathbf{W}^{\mathbf{UV}, MLA}.

In this part, you are asked to study an alternative approach to compute MLA.

  1. Find a head-independent reduced key-projection matrix W^K,MLA∈Rr×D\color{blue}{\hat {\mathbf W}^{\mathbf{K}, MLA}} \in \Bbb R^{r \times D} and a reduced query-projection matrix W^Q,MLA∈RH⋅r×D\color{blue}{\hat {\mathbf W}^{\mathbf{Q}, MLA}} \in \Bbb R^{H \cdot r \times D}, such that

    • The reduced key at position l2l_2 for head hh in a being attended sequence is head-independent and is given by:
    k^l2=W^K,MLAyl2∈Rr\mathbf{\hat k}_{l_2} = \color{blue}{\hat {\mathbf W}^{\mathbf{K}, MLA}} \mathbf{y}_{l_2} \in \Bbb R^r
    • The reduced query at position l1l_1 for head hh in an attending sequence is given by:
    q^l1,h=W^hQ,MLAxl1∈Rr\mathbf{\hat q}_{l_1, h} = \color{blue}{\hat {\mathbf W}^{\mathbf{Q}, MLA}_h} \mathbf{x}_{l_1} \in \Bbb R^r

    \quad \quad where

    W^Q,MLA=[W^0Q,MLAW^1Q,MLA⋮W^H−1Q,MLA]\color{blue}{\hat {\mathbf W}^{\mathbf{Q}, MLA}} = \begin{bmatrix} \color{blue}{\hat {\mathbf W}^{\mathbf{Q}, MLA}_0} \\ \color{blue}{\hat {\mathbf W}^{\mathbf{Q}, MLA}_1 }\\ \vdots \\ \color{blue}{\hat {\mathbf W}^{\mathbf{Q}, MLA}_{H-1}} \end{bmatrix}
    • The attention score (query-key similarity) is invariant in both the original and the reduced forms. That is
    ql1,h⊤vl2,hD/H=q^l1,h⊤v^l2r.(1)\frac{\mathbf{q}_{l_1,h}^\top \mathbf{v}_{l_2,h}}{\sqrt{D/H}} = \frac{\mathbf{\hat q}_{l_1,h}^\top \mathbf{\hat v}_{l_2}}{\sqrt{r}} . \quad (1)
  2. Find a head-independent reduced value-projection matrix W^V,MLA∈Rr×D\color{blue}{\hat {\mathbf W}^{\mathbf{V}, MLA}} \in \Bbb R^{r \times D} and a reduced out-projection matrix W^O,MLA∈RD×H⋅r\color{blue}{\hat {\mathbf W}^{O, MLA}} \in \Bbb R^{D \times H \cdot r}, such that

    • The reduced value with head hh on position l2l_2 in a being attended sequence is head-independent and is given by:
    v^l2=W^V,MLAyl2∈Rr\mathbf{\hat v}_{l_2} = {\color{blue}{\hat {\mathbf W}^{\mathbf{V}, MLA}}} \mathbf{y}_{l_2} \in \Bbb R^r
    • Post-out-projection is invariant in both the original and the reduced forms.

      Let

    W^O,MLA=[W^0O,MLAW^1O,MLA⋯W^H−1O,MLA]\color{blue}{\hat {\mathbf W}^{O, MLA}} = \begin{bmatrix} \color{blue}{\hat {\mathbf W}^{O, MLA}_0} & \color{blue}{\hat {\mathbf W}^{O, MLA}_1} & \cdots & \color{blue}{\hat {\mathbf W}^{O, MLA}_{H-1}} \end{bmatrix}

    \quad \quad Then we must have

    ∑h=0H−1WhO∑l2=0L2−1αh,l1l2vl2,h=∑h=0H−1W^hO,MLA∑l2=0L2−1αh,l1l2v^l2,h.(2)\sum_{h=0}^{H-1} \mathbf W^O_h \sum_{l_2 = 0}^{L_2 - 1} \alpha_{h, l_1 l_2} \mathbf{v}_{l_2,h} = \sum_{h=0}^{H-1} {\color{blue}{\hat {\mathbf W}^{O, MLA}_h}} \sum_{l_2 = 0}^{L_2 - 1} \alpha_{h, l_1 l_2} \mathbf{\hat v}_{l_2,h} . \quad (2)
  3. You answer of W^K,MLA\color{blue}{\hat {\mathbf W}^{\mathbf{K}, MLA}}, W^V,MLA\color{blue}{\hat {\mathbf W}^{\mathbf{V}, MLA}}, W^Q,MLA\color{blue}{\hat {\mathbf W}^{\mathbf{Q}, MLA}}, and W^O,MLA\color{blue}{\hat {\mathbf W}^{O, MLA}} should be written in terms of WDKV\mathbf{W}^{\mathbf{DKV}}, WUK\mathbf{W}^{\mathbf{UK}}, WUV\mathbf{W}^{\mathbf{UV}}, WQ\mathbf{W}^{\mathbf{Q}}, and WO\mathbf{W}^O.

Show official solution

Official solution

First, we study Equation (1).

For the LHS in (1), we have

ql1,h⊤vl2,hD/H=1D/H(WhQxl1)⊤(WhUKWDKVyl2)=1D/Hxl1⊤WhQ,⊤WhUKWDKVyl2(1.1)\begin{align*} \frac{\mathbf{q}_{l_1,h}^\top \mathbf{v}_{l_2,h}}{\sqrt{D/H}} & = \frac{1}{\sqrt{D/H}} \left( {\mathbf W}^{\mathbf{Q}}_h \mathbf{x}_{l_1} \right)^\top \left( {\mathbf W}^{\mathbf{UK}}_h {\mathbf W}^{\mathbf{DKV}} \mathbf{y}_{l_2} \right) \\ & = \frac{1}{\sqrt{D/H}} \mathbf{x}_{l_1}^\top {\mathbf W}^{\mathbf{Q}, \top}_h {\mathbf W}^{\mathbf{UK}}_h {\mathbf W}^{\mathbf{DKV}} \mathbf{y}_{l_2} \quad (1.1) \end{align*}

For the RHS in (1), we have

q^l1,h⊤v^l2r=1r(W^hQ,MLAxl1)⊤(W^K,MLAyl2)=1rxl1⊤W^hQ,MLA,⊤W^K,MLAyl2(1.2)\begin{align*} \frac{\mathbf{\hat q}_{l_1,h}^\top \mathbf{\hat v}_{l_2}}{\sqrt{r}} & = \frac{1}{\sqrt{r}} \left( {\color{blue}{\hat {\mathbf W}^{\mathbf{Q}, MLA}_h} }\mathbf{x}_{l_1} \right)^\top \left( {\color{blue}{\hat {\mathbf W}^{\mathbf{K}, MLA}}} \mathbf{y}_{l_2} \right) \\ & = \frac{1}{\sqrt{r}} \mathbf{x}_{l_1}^\top {\color{blue}{\hat {\mathbf W}^{\mathbf{Q}, MLA, \top}_h} \color{blue}{\hat {\mathbf W}^{\mathbf{K}, MLA}}} \mathbf{y}_{l_2} \quad (1.2) \end{align*}

By equating (1.1) and (1.2), we can set

W^K,MLA=WDKV{\color{blue}{\hat {\mathbf W}^{\mathbf{K}, MLA}}} = \boxed{\mathbf{W}^{\mathbf{DKV}} }

and

W^hQ,MLA=rD/HWhUK,⊤WhQ{\color{blue}{\hat {\mathbf W}^{\mathbf{Q}, MLA}_h}} = \frac{\sqrt{r}}{\sqrt{D/H}} \mathbf{W}^{\mathbf{UK}, \top}_h \mathbf{W}^{\mathbf{Q}}_h

Therefore,

W^Q,MLA=[W^0Q,MLAW^1Q,MLA⋮W^H−1Q,MLA]=rD/H[W0UK,⊤W0QW1UK,⊤W1Q⋮WH−1UK,⊤WH−1Q]\begin{align*} \color{blue}{\hat {\mathbf W}^{\mathbf{Q}, MLA}} & = \begin{bmatrix} \color{blue}{\hat {\mathbf W}^{\mathbf{Q}, MLA}_0} \\ \color{blue}{\hat {\mathbf W}^{\mathbf{Q}, MLA}_1} \\ \vdots \\ \color{blue}{\hat {\mathbf W}^{\mathbf{Q}, MLA}_{H-1}} \end{bmatrix} \\ & = \boxed{\frac{\sqrt{r}}{\sqrt{D/H}} \begin{bmatrix} \mathbf{W}^{\mathbf{UK}, \top}_0 \mathbf{W}^{\mathbf{Q}}_0 \\ \mathbf{W}^{\mathbf{UK}, \top}_1 \mathbf{W}^{\mathbf{Q}}_1 \\ \vdots \\ \mathbf{W}^{\mathbf{UK}, \top}_{H-1} \mathbf{W}^{\mathbf{Q}}_{H-1} \end{bmatrix}} \end{align*}

Second, we study Equation (2).

For the LHS in (2), we have

∑h=0H−1WhO,MLA∑l2=0L2−1αh,l1l2vl2,h=∑h=0H−1∑l2=0L2−1αh,l1l2WhOWhUVWDKVyl2\begin{align*} \sum_{h=0}^{H-1} \mathbf W^{O, MLA}_h \sum_{l_2 = 0}^{L_2 - 1} \alpha_{h, l_1 l_2} \mathbf{v}_{l_2,h} & = \sum_{h=0}^{H-1} \sum_{l_2 = 0}^{L_2 - 1} \alpha_{h, l_1 l_2} \mathbf W^O_h {\mathbf W}^{\mathbf{UV}}_h {\mathbf W}^{\mathbf{DKV}} \mathbf{y}_{l_2} \end{align*}

For the RHS in (2), we have

∑h=0H−1W^hO,MLA∑l2=0L2−1αh,l1l2v^l2,h=∑h=0H−1∑l2=0L2−1αh,l1l2W^hO,MLAW^V,MLAyl2\begin{align*} \sum_{h=0}^{H-1} {\color{blue}{\hat {\mathbf W}^{O, MLA}_h}} \sum_{l_2 = 0}^{L_2 - 1} \alpha_{h, l_1 l_2} \mathbf{\hat v}_{l_2,h} & = \sum_{h=0}^{H-1} \sum_{l_2 = 0}^{L_2 - 1} \alpha_{h, l_1 l_2} {\color{blue}{\hat {\mathbf W}^{O, MLA}_h} \color{blue}{\hat {\mathbf W}^{\mathbf{V}, MLA}}} \mathbf{y}_{l_2} \end{align*}

By equating (2.1) and (2.2), we can set

W^V,MLA=WDKV{\color{blue}{\hat {\mathbf W}^{\mathbf{V}, MLA}}} = \boxed{\mathbf{W}^{\mathbf{DKV}} }

and

W^hO,MLA=WhOWhUV{\color{blue}{\hat {\mathbf W}^{O, MLA}_h}} = \mathbf{W}^O_h \mathbf{W}^{\mathbf{UV}}_h

Therefore

W^O,MLA=[W^0O,MLAW^1O,MLA⋯W^H−1O,MLA]=[W0OW0UVW1OW1UV⋯WH−1OWH−1UV]\begin{align*} \color{blue}{\hat {\mathbf W}^{O, MLA}} & = \begin{bmatrix} \color{blue}{\hat {\mathbf W}^{O, MLA}_0} & \color{blue}{\hat {\mathbf W}^{O, MLA}_1} & \cdots & \color{blue}{\hat {\mathbf W}^{O, MLA}_{H-1}} \end{bmatrix} \\ & = \boxed{\begin{bmatrix} \mathbf{W}^O_0 \mathbf{W}^{\mathbf{UV}}_0 & \mathbf{W}^O_1 \mathbf{W}^{\mathbf{UV}}_1 & \cdots & \mathbf{W}^O_{H-1} \mathbf{W}^{\mathbf{UV}}_{H-1} \end{bmatrix}} \end{align*}

Do the following tasks:

  1. Define a function called reduced_matrices.

    • Input arguments

      • W_DKV, W_UK, W_UV, W_Q, W_O, H
    • Outputs

      • W_K_MLA_hat, W_V_MLA_hat, W_Q_MLA_hat, W_O_MLA_hat
    • Requirment of your code

      • The code of computing each output must be in one line

      • Loop is not allowed

  2. Set your device as gpu:

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")


3. Construct the following synthetic data:

D = 1024 H = 32 D_qkv = D // H r = 50

W_DKV = torch.randn(r, D) W_UK = torch.randn(D, r) W_UV = torch.randn(D, r) W_Q = torch.randn(D, D) W_O = torch.randn(D, D)

B = 32 L_1 = 100 L_2 = 300

x = torch.randn(B, L_1, D).to(device) y = torch.randn(B, L_2, D).to(device)


4. Study a vanilla attention model

 * Initialize the model

   ```
model_MHA_vanilla = MyMHA(D, D, D_qkv, D_qkv, H)
   ```

 * Update model paramteres

     * `model_MHA_vanilla.W_K.weight, model_MHA_vanilla.W_V.weight, model_MHA_vanilla.W_Q.weight, model_MHA_vanilla.W_O.weight`

     * Compute the output

        ```
        output_vanilla = model_MHA_vanilla(x, y)
        ```

5. Study a reduced attention model

 * Initialize the model

   ```
model_MHA_reduced = MyMHA(D, D, r, r, H)
   ```

 * Update model paramteres

     * `model_MHA_reduced.W_K.weight, model_MHA_reduced.W_V.weight, model_MHA_reduced.W_Q.weight, model_MHA_reduced.W_O.weight`

     * Compute the output

        ```
        output_reduced = model_MHA_reduced(x, y)
        ```

6. Check the correctness of the reduced model by computing and printing a relative error:

relative_error = mse_output**.5 / torch.mean(output_vanilla2).5

Show official solution

Official solution


# Function

def reduced_matrices(W_DKV, W_UK, W_UV, W_Q, W_O, H):
    r = W_DKV.shape[0]
    D = W_DKV.shape[1]

    W_K_MLA_hat = W_DKV
    W_V_MLA_hat = W_DKV
    W_Q_MLA_hat = (W_UK.reshape(H, -1, r).transpose(-2, -1) @ W_Q.reshape(H, -1, D)).reshape(-1, D)  * (r/(D/H))**.5
    W_O_MLA_hat = (W_O.reshape(D, H, -1).transpose(0, 1) @ W_UV.reshape(H, -1, r)).transpose(0, 1).reshape(D, -1)

    return W_K_MLA_hat, W_V_MLA_hat, W_Q_MLA_hat, W_O_MLA_hat

# Device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Data
D = 1024
H = 32
D_qkv = D // H
r = 50

W_DKV = torch.randn(r, D)
W_UK = torch.randn(D, r)
W_UV = torch.randn(D, r)
W_Q = torch.randn(D, D)
W_O = torch.randn(D, D)

B = 32
L_1 = 100
L_2 = 300

x = torch.randn(B, L_1, D).to(device)
y = torch.randn(B, L_2, D).to(device)

# Vanilla model
model_MHA_vanilla = MyMHA(D, D, D_qkv, D_qkv, H)
model_MHA_vanilla.W_K.weight = nn.Parameter(W_UK @ W_DKV)
model_MHA_vanilla.W_V.weight = nn.Parameter(W_UV @ W_DKV)
model_MHA_vanilla.W_Q.weight = nn.Parameter(W_Q)
model_MHA_vanilla.W_O.weight = nn.Parameter(W_O)

model_MHA_vanilla.to(device)
output_vanilla = model_MHA_vanilla(x, y)

# Reduced model
model_MHA_reduced = MyMHA(D, D, r, r, H)
W_K_MLA_hat, W_V_MLA_hat, W_Q_MLA_hat, W_O_MLA_hat = reduced_matrices(W_DKV, W_UK, W_UV, W_Q, W_O, H)
model_MHA_reduced.W_K.weight = nn.Parameter(torch.concatenate([W_K_MLA_hat] * H, dim = 0))
model_MHA_reduced.W_V.weight = nn.Parameter(torch.concatenate([W_V_MLA_hat] * H, dim = 0))
model_MHA_reduced.W_Q.weight = nn.Parameter(W_Q_MLA_hat)
model_MHA_reduced.W_O.weight = nn.Parameter(W_O_MLA_hat)

model_MHA_reduced.to(device)
output_reduced = model_MHA_reduced(x, y)

# Check the correctness of the reduced model
mse_output = torch.mean((output_vanilla - output_reduced)**2)
relative_error = mse_output**.5 / torch.mean(output_vanilla**2)**.5

print(f"Relative error: {relative_error.item()}")

Part 14

5 ptsNon-codingForum thread

In generative AI, such as GPT, we autoprogressively generate tokens. For a given position ll, the keys and values on this position kl\mathbf{k}_l and vl\mathbf{v}_l are repeatly used in generating tokens for positions l′>ll' > l.

Therefore, the values of kl\mathbf{k}_l and vl\mathbf{v}_l are typically stored in cache (no need to revise your code in earlier parts if your code does not support this). We call such storage as kvkv-cache.

Do the following tasks to compute kvkv-cache in different models while doing autoregressive inference: (reasoning is required)

  1. In MHA, the kvkv-cache at each position is 2D2 D. Explain why.

  2. In MLA, what is the kvkv-cache at each position?

Show official solution

Official solution

  1. In MHA, kl,vl∈RD\mathbf{k}_l, \mathbf{v}_l \in \Bbb R^D. Therefore, the kvkv-cache at each position is 2D\boxed{2D}.

  2. In MLA, because WDKV∈Rr×D\mathbf{W}^{\mathbf{DKV}} \in \Bbb R^{r \times D}, we have k^l,v^l∈Rr\mathbf{\hat k}_l, \mathbf{\hat v}_l \in \Bbb R^r.

    In addition, because k^l=v^l\mathbf{\hat k}_l = \mathbf{\hat v}_l, the kvkv-cache at each position is r\boxed{r}.

Problem 3CLIP: contrastive language-image pre-training

100 pts

SummaryPreprocess paired images and captions, build and train a small CLIP model with a learnable temperature and contrastive loss, and prove that random high-dimensional vectors are nearly orthogonal to justify cosine similarity.

    Multimodal AIContrastive learningHigh-dimensional geometry

In this problem, you are asked to study Contrastive Language-Image Pre-Training (CLIP), a powerful tool in multimodal AI.

# Run code in this cell

"""
DO NOT MAKE ANY CHANGE IN THIS CELL.

HINT: If something is not corrected installed, simply run this cell for few more times.
"""

!pip install datasets transformers

WARNING !!!\color{red}{\text{WARNING !!!}}

  • Beyond importing libraries/modules/classes/functions in the following cell, you are NOT allowed to import anything else for the following purposes:

    • As a part of your final solution. For instance, if a problem asks you to build a model without using sklearn but you use it, then you will not earn points.

    • Temporarily import something to assist you to get a solution. For instance, if a problem asks you to manually compute eigenvalues but you temporarily use np.linalg.eig to get an answer and then delete your code, then you violate the rule.

    Rule of thumb: Each part has its particular purpose to intentionally test you something. Do not attempt to find a shortcut to circumvent the rule.

# Run code in this cell

"""
DO NOT MAKE ANY CHANGE IN THIS CELL.
"""

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset

from transformers import BertTokenizer, BertModel, ViTModel

We will use flickr30k dataset to do image-language matching.

# Run code in this cell

"""

DO NOT MAKE ANY CHANGE IN THIS CELL.

"""

from datasets import load_dataset

dataset_train = load_dataset("USAAIO/2025-Round2-Problem3", split='train')

Do the following tasks to explore the properties of dataset_train:

  1. dataset_train is a list-like object. Print the number of elements in it.

  2. Consider index idx = 2025. Print the type of dataset_train[idx].

  3. Print all keys in dataset_train[idx].

  4. Name the value associated with the key image as image_PIL. Print it.

  5. Convert image_PIL to a NumPy array object, called image_np. Print image_np and its shape.

  6. Display this image by using plt.imshow.

  7. Print the value associated with the key alt_text. Print its type.

Show official solution

Official solution


print(len(dataset_train))

idx = 2025
print(type(dataset_train[idx]))
print(dataset_train[idx].keys())

image_PIL = dataset_train[idx]['image']
print(image_PIL)

image_np = np.array(image_PIL)
print(image_np)
print(image_np.shape)

plt.imshow(image_np)
plt.show()

print(dataset_train[idx]['alt_text'])
print(type(dataset_train[idx]['alt_text']))

This dataset is too big. In our contest, we only use a small portion with 1000 samples.

To avoid introducing any bias, we will randomly select 1000 distinct samples.

Use NumPy to randomly select 1000 sample indices.

  • Use the random seed number 2025 to generated randomized indices. After the generation is completed, reset the seed number back to None.

  • The name of the output is called indices. It must be a list that contains 1000 integer type (not numpy array integers) objects.

Show official solution

Official solution


np.random.seed(2025)
indices = np.random.permutation(len(dataset_train))[:1000]
np.random.seed()
indices = [int(idx) for idx in indices]

In this part, we create our image and text datasets.

  • All sample indices are selected from indices generated in Part 2.

  • All images (resp. texts) are extracted from the key image (resp. alt_text).

  • The image (resp. text) dataset is called image_list (resp. text_list). The data type of both datasets are list`.

  • In image_list, each element is an PIL object.

  • In text_list, each element is a string object.

Show official solution

Official solution


image_list = [dataset_train[idx]['image'] for idx in indices]
text_list = [dataset_train[idx]['alt_text'][0] for idx in indices]

In this part, we preprocess image data.

  1. Your job is to create a tensor images_pt from image_list that has shape (1000,3,224,224) and datatype float64.

    • The data range is from -1 to 1.

    • Hint: If a is a PIL object, then you can use a.resize to resize it.

  2. Print images_pt.shape.

  3. Print images_pt.dtype.

  4. Print images_pt[5].

Show official solution

Official solution


images_pt_list = []

for image in image_list:
    image = image.resize((224,224)) # Resize the image
    image_np = np.array(image) # Convert to numpy array
    image_pt = torch.from_numpy(image_np) # Convert to pytorch tensor
    image_pt = image_pt.permute(2,0,1) # Permute the dimension
    image_pt = image_pt / 255 # Normalize value between 0 and 1
    image_pt = image_pt * 2 - 1 # Normalize value between -1 and 1
    images_pt_list.append(image_pt)

images_pt = torch.stack(images_pt_list)

print(images_pt.shape)
print(images_pt.dtype)
print(images_pt[5])

Part 5

5 ptsNon-codingForum thread

Note that our final goal is to build a CLIP neural network. For the image data, we will use Vision Transformers (ViT) to extract image embeddings.

With the above high level information, please explain the reasons behind the following things that you did in Part 4.

  1. Why the channel dimension is ahead of the height and width dimensions?

  2. Why the sizes of all images are normalized to (224,224)?

  3. Why each pixel value is normalized between -1 and 1?

Show official solution

Official solution

  1. The input of ViT requires the channel dimension to go ahead of the height and width dimensions.

  2. ViT model requires this dimension.

  3. ViT model requires data to fall into this range.

In this part, we preprocess text data text_list.

  1. Do tokenization with

    tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
    
  2. Call

    token_id_list = tokenizer(text_list)['input_ids']
    
  3. Print token_id_list.

  4. Print the type of token_id_list.

  5. Print the length of token_id_list.

  6. Print token_id_list[5].

  7. Print the type of token_id_list[5].

  8. Print the type of token_id_list[5][0].

  9. For each idx, convert token_id_list[idx] from the above type to a 1-dim tensor. That is, after this step, token_id_list is a list that consists of all 1-dim tensors.

  10. Print token_id_list[5:7].

  11. Print the data type of token_id_list[5][0].

Show official solution

Official solution


tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')

token_id_list = tokenizer(text_list)['input_ids']

print(token_id_list)
print(type(token_id_list))
print(len(token_id_list))

print(token_id_list[5])
print(type(token_id_list[5]))
print(type(token_id_list[5][0]))

token_id_list = [torch.tensor(token_id_list[idx]) for idx in range(len(token_id_list))]
print(token_id_list[5:7])
print(token_id_list[5][0].dtype)

Part 7

5 ptsNon-codingForum thread

This part follows Part 6.

Do the following tasks.

  1. Explain why token lists of all samples begin with token ID 101.

  2. Explain why token lists of all samples end with token ID 102.

Show official solution

Official solution

  1. In BERT, token ID 101 refers to a special token [CLS] that denotes the start of a sentence.

  2. In BERT, token ID 102 refers to a special token [SEP] that denotes the end of a sentence.

In this part, we prepare our CLIP dataset.

  1. Define class MyDataset that subclasses Dataset.

    • __init__

      • Inputs: images_pt, token_id_list.

      • Attributes: Same as inputs.

    • __len__

      • Output: total number of samples.
    • __getitem__

      • Input: sample index idx

      • Outputs: images_pt[idx], token_id_list[idx]

  2. Define dataset CLIP_dataset that is an object of MyDataset.

Show official solution

Official solution


class MyDataset(Dataset):
    def __init__(self, images_pt, token_id_list):
        self.images_pt = images_pt
        self.token_id_list = token_id_list

    def __len__(self):
        return len(self.token_id_list)

    def __getitem__(self, idx):
        return self.images_pt[idx], self.token_id_list[idx]

CLIP_dateset = MyDataset(images_pt, token_id_list)

Part 9.1

Define your own collate function.

  • The function name is my_collate_fn.

  • Padding

    • For text data, let the longest sample be with K tokens.

    • Consider another text sample with L tokens satisfying L < K. Then, in addition to those L tokens, this sample is padded with K-L padding tokens whose values are 0.

  • Outputs

    • token_id_batch. If the batch size is B and the longest sample in the text data has K tokens, then token_id_batch is a tensor with shape (B,K).

    • attention_mask_batch. This is a tensor that has shape (B,K). If a position is occupied by a non-padding token, its value is 1. Otherwise, if it is occupied by a padding token, its value is 0. Data types are int64.

    • image_batch. This is a tensor that has shape (B,3,224,224).

Part 9.2

Define a DataLoader object called CLIP_dataloader.

  • Set batch_size = 16.

  • Set shuffle = True.

  • Use the collate function defined in Part 10.

Show official solution

Official solution


# Part 9.1

def my_collate_fn(batch):
    image_batch_input, token_id_batch_input = zip(*batch)

    image_batch = torch.stack(image_batch_input)

    max_len_token_id = max([len(token_id) for token_id in token_id_batch_input])
    token_id_batch = []
    attention_mask_batch = []

    for token_id in token_id_batch_input:
        token_id_batch.append(torch.concatenate([token_id, torch.zeros(max_len_token_id - len(token_id), dtype = torch.int64)]))
        attention_mask_batch.append(torch.concatenate([torch.ones(len(token_id), dtype = torch.int64), \
                                                       torch.zeros(max_len_token_id - len(token_id), dtype = torch.int64)]))

    token_id_batch = torch.stack(token_id_batch)
    attention_mask_batch = torch.stack(attention_mask_batch)

    return image_batch, token_id_batch, attention_mask_batch

# Part 9.2

batch_size = 16

CLIP_dataloader = DataLoader(CLIP_dateset, batch_size = batch_size, shuffle = True, collate_fn = my_collate_fn)

Part 10

5 ptsNon-codingForum thread

In this part, you are asked to answer some questions about a CLIP model that you shall build in the next part.

  • Write your answers in the text cell below.

  • To get answers, you may need to run experimental code to better learn the ViT and Bert models.

  • We only grade your answers in the text cell.

  1. Image encoder

    • Define model_image = ViTModel.from_pretrained('google/vit-base-patch16-224'). We use all blocks except the last pooler layer. That is, this ViT model has two outputs: with their key names as last_hidden_state and pooler_output. You should take the value associated with the key last_hidden_state.

    • From the last hidden state, we project from position 0 to a latent space with dimension embedding_size (e.g., 512). The output is called image embedding.

  2. Text encoder

    • Define model_text = BertModel.from_pretrained('bert-base-uncased'). We use all blocks except the last pooler layer. That is, this Bert model has two outputs: with their key names as last_hidden_state and pooler_output. You should take the value associated with the key last_hidden_state.

    • From the last hidden state, we project from position 0 to a latent space with dimension embedding_size (e.g., 512). The output is called text embedding.

Answer the following questions. (Reasoning is required only for Question 3)

  1. Let image_batch be with shape (B,3,224,224). What is the shape of model_image(image_batch)[last_hidden_state]?

  2. Let token_id_batch and attention_mask_batch be with shape (B,L). What is the shape of model_text(input_ids = token_id_batch, attention_mask = attention_mask_batch)['last_hidden_state']?

  3. For both the image encoder and the text encoder, we project the last hidden state from position 0 to a latent space with the same dimension embedding_size.

    3.1. Why do we add this additional out-projection layer?

    3.2. Why this layer is added on position 0 only?

    3.3. Why the output dimensions from these two encoders are the same?

Show official solution

Official solution

### DO YOU EXPERIMENTAL STUDY HERE ###

image_batch, token_id_batch, attention_mask_batch = next(iter(CLIP_dataloader))

model_image = ViTModel.from_pretrained('google/vit-base-patch16-224')

print(model_image(image_batch).keys())

print(model_image(image_batch)['last_hidden_state'].shape)

model_text = BertModel.from_pretrained('bert-base-uncased')

print(model_text(input_ids = token_id_batch, attention_mask = attention_mask_batch).keys())

print(model_text(input_ids = token_id_batch, attention_mask = attention_mask_batch)['last_hidden_state'].shape)

  1. (B,197,768).

  2. (B,L,768).

3.1. Ensure that the embedding of an image and the embedding of a text are similar to each other when the image and the text refer to the same thing.

3.2. In both ViT and BERT, position 0 in the last hidden state stores information of the whole image and text, respectively.

3.3. We need to compute their similarity, such as the cosine similarity. So this requires their dimensions to be same.

In this part, you are asked to build your CLIP model.

  • The class name is MyCLIP. It subclasses nn.Module.

  • __init__:

    • It takes one input argument - the size of the final embedding of text and image data. Set its default value as 512.

    • Attribute log_tau is the log of temperature. It is a learnable parameter. Its initial value follows the standard normal distribution.

  • __forward__:

    • It returns two objects: image embedding, text embedding.
Show official solution

Official solution


class MyCLIP(nn.Module):
    def __init__(self, embedding_size = 512):
        super().__init__()
        self.model_image = ViTModel.from_pretrained('google/vit-base-patch16-224')
        self.model_text = BertModel.from_pretrained('bert-base-uncased')
        self.embedding_size = embedding_size
        self.last_layer_image = nn.Linear(768, self.embedding_size)
        self.last_layer_text = nn.Linear(768, self.embedding_size)
        self.log_tau = nn.Parameter(torch.randn(1))

    def encoder_image(self, image_batch):
        image_embedding = self.model_image(image_batch)['last_hidden_state'][:,0]
        image_embedding = self.last_layer_image(image_embedding)
        return image_embedding

    def encoder_text(self, token_id_batch, attention_mask_batch):
        text_embedding = self.model_text(input_ids = token_id_batch, attention_mask = attention_mask_batch)['last_hidden_state'][:,0]
        text_embedding = self.last_layer_text(text_embedding)
        return text_embedding

    def forward(self, image_batch, token_id_batch, attention_mask_batch):
        return self.encoder_image(image_batch), self.encoder_text(token_id_batch, attention_mask_batch)

Part 12

5 ptsNon-codingForum thread

Explain why we use log⁡τ\log \tau as an attribute, not τ\tau.

Show official solution

Official solution

log⁡τ\log \tau can take all real values. So we do not have to worry about its range.

However, τ\tau must be positive. Hence, if we use τ\tau, we always need to take care of its domain.

Do the following tasks:

  1. Define your model by calling model_CLIP = MyCLIP().

  2. Fix all parameter values in the ViT and Bert blocks in your model. That is, you are only allowed to train

    • Out-projection matrices in the image and text encoders.

    • Temperature.

Show official solution

Official solution


model_CLIP = MyCLIP()

for param in model_CLIP.model_text.parameters():
    param.requires_grad = False

for param in model_CLIP.model_image.parameters():
    param.requires_grad = False

Do the following tasks:

  1. Set the learning rate as 1e-3.

  2. Choose your optimization algorithm as Adam.

  3. Define an optimizer.

Show official solution

Official solution


lr = 1e-3
optimizer = optim.Adam(model_CLIP.parameters(), lr = lr)

In this part, you are asked to define a loss function.

Let IiI_i and TjT_j be image ii's embedding and text jj's embedding, respectively. Let BB be the batch size. Let τ\tau be the temperature.

Then the loss function is defined as

L=12(−1B∑i=0B−1log⁡exp⁡(SIM(Ii,Ti)/τ)∑j=0B−1exp⁡(SIM(Ii,Tj)/τ)−1B∑i=0B−1log⁡exp⁡(SIM(Ii,Ti)/τ)∑j=0B−1exp⁡(SIM(Ij,Ti)/τ)),L = \frac{1}{2} \left(- \frac{1}{B} \sum_{i = 0}^{B-1} \log \frac{\exp \left( \text{SIM} \left( I_i, T_i \right) / \tau \right) } {\sum_{j = 0}^{B-1} \exp \left( \text{SIM} \left( I_i, T_j \right) / \tau \right)} - \frac{1}{B} \sum_{i = 0}^{B-1} \log \frac{\exp \left( \text{SIM} \left( I_i, T_i \right) / \tau \right)} {\sum_{j = 0}^{B-1} \exp \left( \text{SIM} \left( I_j, T_i \right) / \tau \right)} \right) ,

where

SIM(Ii,Tj)=Ii⊤Tj∣∣Ii∣∣2∣∣Tj∣∣2.\text{SIM} \left( I_i, T_j \right) = \frac{I_i^\top T_j}{|| I_i ||_2 || T_j ||_2} .
Show official solution

Official solution


def CLIP_loss_fn(image_embedding, text_embedding):
    image_embedding = image_embedding / torch.norm(image_embedding, dim = -1, keepdim = True)
    text_embedding = text_embedding / torch.norm(text_embedding, dim = -1, keepdim = True)
    sim = torch.sum(image_embedding.unsqueeze(1) * text_embedding.unsqueeze(0), dim = -1)
    loss = .5 * (-torch.mean(torch.diagonal(torch.log_softmax(sim / torch.exp(model_CLIP.log_tau), dim = 0))) \
                 -torch.mean(torch.diagonal(torch.log_softmax(sim / torch.exp(model_CLIP.log_tau), dim = 1))))
    return loss

In this part, you are asked to train your model.

  1. Set the number of epochs as 100.

  2. Do training on GPU.

  3. For every epoch, print the average loss per sample in this epoch.

  4. You may use tqdm to track your progress and help you manage your time.

Show official solution

Official solution


num_epochs = 100
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model_CLIP.to(device)

for epoch in tqdm(range(num_epochs)):
    model_CLIP.train()
    optimizer.zero_grad()
    loss_cum = 0
    for image_batch, token_id_batch, attention_mask_batch in CLIP_dataloader:
        image_batch = image_batch.to(device)
        token_id_batch = token_id_batch.to(device)
        attention_mask_batch = attention_mask_batch.to(device)

        image_embedding, text_embedding = model_CLIP(image_batch, token_id_batch, attention_mask_batch)
        loss = CLIP_loss_fn(image_embedding, text_embedding)
        loss.backward()
        optimizer.step()

        loss_cum += loss.item() * image_batch.shape[0]

    loss = loss_cum / len(CLIP_dateset)
    print(f'Epoch {epoch}, Loss: {loss}')

Part 17

5 ptsNon-codingForum thread

So far, we use the cosine function to measure the similarity between two vectors. Next, you are asked to do theoretical study of its reasonableness.

Your task is to prove the following theorem.

Theorem:

  • Let x,y∈Rd\mathbf{x}, \mathbf{y} \in \Bbb R^d be two independent dd-dim vectors that follow the same multi-variate standard normal distribution N(0d,Id×d)N \left( \mathbf{0}_d , \mathbf{I}_{d \times d} \right).

Then for any ϵ>0\epsilon > 0, when dd is large,

P(x⊤y∣∣x∣∣2∣∣y∣∣2>ϵ)≤1ϵ2d.\Bbb P \left( \frac{\mathbf{x}^\top \mathbf{y}}{|| \mathbf{x} ||_2 || \mathbf{y}||_2 } > \epsilon \right) \leq \frac{1}{\epsilon^2 d} .

We prove this in multiple steps.

First, you are asked to prove the following lemma.

Lemma 1:

  • If x∼N(0d,Id×d)\mathbf{x} \sim N \left( \mathbf{0}_d , \mathbf{I}_{d \times d} \right), then for any unit vector e^∈Rd\mathbf{\hat e} \in \Bbb R^d,
e^⊤x∼N(0,1).\mathbf{\hat e}^\top \mathbf{x} \sim N \left( 0 , 1 \right) .

That is, the projection of x\mathbf{x} onto e^\mathbf{\hat e} is a standard normal random variable.

Hint: You can directly use the result that e^⊤x\mathbf{\hat e}^\top \mathbf{x} is normal. Therefore, you only need to prove that e^⊤x\mathbf{\hat e}^\top \mathbf{x} has mean 0 and variance 1.

Show official solution

Official solution

First, we have

E[e^⊤x]=e^⊤E[x]=e^⊤0d=0.\begin{align*} \text{E} \left[ \mathbf{\hat e}^\top \mathbf{x} \right] & = \mathbf{\hat e}^\top \text{E} \left[ \mathbf{x} \right] \\ & = \mathbf{\hat e}^\top \mathbf{0}_d \\ & = 0 . \end{align*}

Second, we have

Var[e^⊤x]=E[(e^⊤x)2]−(E[e^⊤x])2=E[(e^⊤x)2]=E[e^⊤xx⊤e^]=e^⊤E[xx⊤]e^=e^⊤Id×de^=e^⊤e^=1.\begin{align*} \text{Var} \left[ \mathbf{\hat e}^\top \mathbf{x} \right] & = \text{E} \left[ \left( \mathbf{\hat e}^\top \mathbf{x} \right)^2 \right] - \left( \text{E} \left[ \mathbf{\hat e}^\top \mathbf{x} \right] \right)^2 \\ & = \text{E} \left[ \left( \mathbf{\hat e}^\top \mathbf{x} \right)^2 \right] \\ & = \text{E} \left[ \mathbf{\hat e}^\top \mathbf{x} \mathbf{x}^\top \mathbf{\hat e} \right] \\ & = \mathbf{\hat e}^\top \text{E} \left[ \mathbf{x} \mathbf{x}^\top \right] \mathbf{\hat e} \\ & = \mathbf{\hat e}^\top \mathbf{I}_{d \times d} \mathbf{\hat e} \\ & = \mathbf{\hat e}^\top \mathbf{\hat e} \\ & = 1 . \end{align*}

Therefore, e^⊤x\mathbf{\hat e}^\top \mathbf{x} is a standard normal random variable.

Part 18

5 ptsNon-codingForum thread

Lemma 1 implies that the projection of x\mathbf{x} onto any direction is a standard normal. Therefore, all directions are homogeneous.

Therefore,

P(x⊤y∣∣x∣∣2∣∣y∣∣2>ϵ)=P(x⊤y∣∣x∣∣2∣∣y∣∣2>ϵ∣x=x^), ∀ x^∈Rd.\Bbb P \left( \frac{\mathbf{x}^\top \mathbf{y}}{|| \mathbf{x} ||_2 || \mathbf{y}||_2 } > \epsilon \right) = \Bbb P \left( \frac{\mathbf{x}^\top \mathbf{y}}{|| \mathbf{x} ||_2 || \mathbf{y}||_2 } > \epsilon \mid \mathbf{x} = \mathbf{\hat x} \right), \ \forall \ \mathbf{\hat x} \in \Bbb R^d .

For simplicity, we consider

x^=[10⋮0]∈Rd.\mathbf{\hat x} = \begin{bmatrix} 1 \\ 0 \\ \vdots \\ 0 \end{bmatrix} \in \Bbb R^d .

Therefore, we only need to bound

P(y0∣∣y∣∣2>ϵ)\Bbb P \left( \frac{y_0}{|| \mathbf{y}||_2 } > \epsilon \right)

By symmetry, it is easy to see that

E[y0∣∣y∣∣2]=0.\text{E} \left[ \frac{y_0}{|| \mathbf{y}||_2} \right] = 0 .

Hence, we get

P(y0∣∣y∣∣2>ϵ)≤Var[y0∣∣y∣∣2]ϵ2=E[y02∣∣y∣∣22]ϵ2=1ϵ2d E[y021d∑i=0d−1yi2]\begin{align*} \Bbb P \left( \frac{y_0}{|| \mathbf{y}||_2 } > \epsilon \right) & \leq \frac{\text{Var} \left[ \frac{y_0}{|| \mathbf{y}||_2} \right]}{\epsilon^2} \\ & = \frac{\text{E} \left[ \frac{y_0^2}{|| \mathbf{y}||_2^2} \right]}{\epsilon^2} \\ & = \frac{1}{\epsilon^2 d} \ \text{E} \left[ \frac{y_0^2}{\frac{1}{d}\sum_{i=0}^{d-1} y_i^2} \right] \end{align*}

where the first inequality follows from the Chebyshev's inequality.

To prove the theorem, it is equivalent to prove the following lemma.

Lemma 2:

  • Let y0,⋯ ,yd−1y_0, \cdots , y_{d-1} be identically and independent variables that are all standard normals. Then for large dd,
E[y021d∑i=0d−1yi2]≈1.\text{E} \left[ \frac{y_0^2}{\frac{1}{d}\sum_{i=0}^{d-1} y_i^2} \right] \approx 1 .

In this part, your task is to prove this lemma.

Hint: It is hard to prove this statement in an exact way. You can make any reasonable approximation.

Show official solution

Official solution

Since yiy_i is a standard normal, E[yi2]=1\text{E} \left[ y_i^2 \right] = 1 and Var[yi2]=2\text{Var} \left[ y_i^2 \right] = 2.

For large dd, the central limit theorem implies

1d∑i=0d−1yi2∼N(1,2d).\frac{1}{d}\sum_{i=0}^{d-1} y_i^2 \sim N \left( 1, \frac{2}{d} \right) .

Hence, for large dd, 1d∑i=0d−1yi2\frac{1}{d}\sum_{i=0}^{d-1} y_i^2 can be approximated as its mean value, 1.

Therefore, for large dd,

E[y021d∑i=0d−1yi2]≈E[y02]=1.\begin{align*} \text{E} \left[ \frac{y_0^2}{\frac{1}{d}\sum_{i=0}^{d-1} y_i^2} \right] & \approx \text{E} \left[ y_0^2 \right] \\ & = 1 . \end{align*}

Part 19

5 ptsNon-codingForum thread

Lemmas 1 and 2 jointly imply the theorem above. Please use the result in this theorem to explain why it is reasonable to use the cosine function to measure similarity of two embedding vectors and why the latent space needs to be high dimensional (such as 512, 768, 1024).

Show official solution

Official solution

The theorem states that in a high dimensional space, almost all pairs of vectors are orthogonal (independent), except very few that are in the same direction.

This is exactly what we want in matching images and texts. For instance, suppose there are 30k pairs of iamges and texts. For each image embedding vector, we want it to be aligned with only one text embedding vector, but orthogonal to other 30k-1 text embedding vectors. This is guaranteed by the above theorem.

Recall that a key condition of the above theorem is that the dimension must be high. Therefore, in image and text embeddings, the embedded vectors must be high dimensional.

Part 20

5 ptsNon-codingForum thread

In the loss function, we introduced a crutial learnable parameter τ\tau, called temperature.

Let us explore some properties of τ\tau.

Let z0>z1>⋯>zN−1z_0 > z_1 > \cdots > z_{N-1}.

Define

fi=exp⁡(zi/τ)∑j=0N−1exp⁡(zj/τ).f_i = \frac{\exp \left( z_i / \tau \right)} {\sum_{j = 0}^{N-1} \exp \left( z_j / \tau \right)} .

Do the following analysis. Reasoning is required.

  1. Compute
lim⁡τ→0+fi.\lim_{\tau \rightarrow 0^+} f_i .
  1. Compute
lim⁡τ→∞fi.\lim_{\tau \rightarrow \infty} f_i .
Show official solution

Official solution

  1. We have
lim⁡τ→0+fi=lim⁡τ→0+exp⁡(zi/τ)∑j=0N−1exp⁡(zj/τ)=lim⁡τ→0+exp⁡((zi−z0)/τ)∑j=0N−1exp⁡((zj−z0)/τ)={1\mboxifi=00\mboxifi≠0.\begin{align*} \lim_{\tau \rightarrow 0^+} f_i & = \lim_{\tau \rightarrow 0^+} \frac{\exp \left( z_i / \tau \right)} {\sum_{j = 0}^{N-1} \exp \left( z_j / \tau \right)} \\ & = \lim_{\tau \rightarrow 0^+} \frac{\exp \left( \left( z_i - z_0 \right) / \tau \right)} {\sum_{j = 0}^{N-1} \exp \left( \left( z_j - z_0 \right) / \tau \right)} \\ & = \boxed{\begin{cases} 1 & \mbox{if } i = 0 \\ 0 & \mbox{if } i \neq 0 \end{cases}} . \end{align*}
  1. Compute
lim⁡τ→∞fi=lim⁡τ→∞exp⁡(zi/τ)∑j=0N−1exp⁡(zj/τ)=1∑j=0N−11=1N.\begin{align*} \lim_{\tau \rightarrow \infty} f_i & = \lim_{\tau \rightarrow \infty} \frac{\exp \left( z_i / \tau \right)} {\sum_{j = 0}^{N-1} \exp \left( z_j / \tau \right)} \\ & = \frac{1}{\sum_{j = 0}^{N-1} 1} \\ & = \boxed{\frac{1}{N}} . \end{align*}

Problems and solutions © USA-NA-AIO (USAAIO). Shown for educational purposes with attribution; summaries and topic tags are written by ResAI. Source: usaaio.org