Skip to main content
The final exam covers the whole syllabus: learning and neural networks, detection and segmentation, camera calibration, transformers, vision-language models and generative models. The questions below are the kind you can expect. Each has a worked solution. Try each question before you read its solution.

Question 1, Multinomial Log-Likelihood (15 points)

A multiclass classifier with KK classes outputs the probability of class kk given input x\mathbf{x} via the softmax: P(y=k∣x)=exp⁡(x⊤wk)∑j=1Kexp⁡(x⊤wj)P(y = k \mid \mathbf{x}) = \frac{\exp(\mathbf{x}^\top \mathbf{w}_k)}{\sum_{j=1}^{K} \exp(\mathbf{x}^\top \mathbf{w}_j)} Write down the log-likelihood expression for a single training example (x,y)(\mathbf{x}, y) under this multinomial model. Your derivation should follow the same steps used in the course for the binary cross-entropy loss.

Solution

For a single example with true class yy, the probability assigned by the model is P(y∣x)P(y \mid \mathbf{x}). In indicator notation, the log-likelihood is: log⁡p(y∣x)=∑k=1K1[y=k] log⁡P(y=k∣x)\log p(y \mid \mathbf{x}) = \sum_{k=1}^{K} \mathbf{1}[y = k]\, \log P(y = k \mid \mathbf{x}) Substituting the softmax expression: =∑k=1K1[y=k][x⊤wk−ln⁡∑j=1Kexp⁡(x⊤wj)]= \sum_{k=1}^{K} \mathbf{1}[y = k] \left[ \mathbf{x}^\top \mathbf{w}_k - \ln\sum_{j=1}^{K} \exp(\mathbf{x}^\top \mathbf{w}_j) \right] Since exactly one indicator is 1 (the true class cc), this simplifies to: =x⊤wc−ln⁡∑j=1Kexp⁡(x⊤wj)= \mathbf{x}^\top \mathbf{w}_c - \ln\sum_{j=1}^{K}\exp(\mathbf{x}^\top \mathbf{w}_j) The negative of this expression (averaged over mm training examples) is the categorical cross-entropy loss minimized during training. Providing the expression for the full dataset (summed over mm examples) is also acceptable.

Question 2, Softmax Temperature (10 points)

Consider the following enhanced softmax function for a vector z\mathbf{z} of length KK: softmax(z)i=eβzi∑j=1Keβzjfor i=1,…,K\text{softmax}(\mathbf{z})_i = \frac{e^{\beta z_i}}{\sum_{j=1}^K e^{\beta z_j}} \quad \text{for } i = 1, \dotsc , K Using your calculator or a local Python interpreter, calculate the softmax of the vector z=[1,8,3,10,5]\mathbf{z} = [1, 8, 3, 10, 5] for β=1\beta = 1 and β=10\beta = 10. Explain the difference between the two results and the impact of β≠1\beta \ne 1 in the classifier.

Solution

With β=1/T\beta = 1/T, increasing TT above 1 (decreasing β\beta) spreads the probability more evenly across the classes, and decreasing TT toward 0 (increasing β\beta) concentrates it on the highest-scoring class. In the limit T→∞T \to \infty every class has the same probability (uniform). In the limit T→0T \to 0 only the argmax class receives all the probability (hard argmax). For β=10\beta = 10, the high-scoring entry (z4=10z_4 = 10) receives almost all of the probability mass, so the classifier is very confident. For β=1\beta = 1 the distribution is softer and multiple classes receive non-negligible probability. A temperature T>1T > 1 corrects an over-confident network by bringing logits closer together; T<1T < 1 drives logits further apart.

Question 3, SGD and Feature Scaling (10 points)

Part A (5 points)

Scaling or normalizing the features makes SGD converge faster. Explain why.

Part B (5 points)

A colleague suggests that the scaling should also include the target variable yy. Do you agree or disagree? Explain.

Solution

Part A. If features have very different scales, the loss surface in parameter space becomes highly anisotropic (elongated along the direction of the large-scale feature). The gradient ∇wL\nabla_{\mathbf{w}} L will then point mostly in the direction of the dominant feature, forcing SGD to take tiny zig-zag steps in the other directions to avoid overshooting. After standardizing the features (zero mean, unit variance) the loss surface becomes more isotropic, so SGD can take larger, more direct steps toward the minimum and converges faster. Part B. Agree, but for a numerical reason. Standardizing yy keeps the loss and its gradients on a scale of order 1, so the same learning rate and initialization work well and SGD converges faster. Standardizing does not make the target more Gaussian, because subtracting a mean and dividing by a standard deviation does not change the shape of a distribution. The Gaussian noise assumption behind the MSE loss is about the residuals y−f(x)y - f(\mathbf{x}) given the inputs, not about the distribution of yy on its own. A log transform is a separate modeling choice. Use it when the size of the residuals grows with yy (prices, counts), so that the errors on the log scale have roughly constant variance.

Question 4, SGD Jitter, Momentum, and Convergence (15 points)

The figure in your notes shows a contour plot of a loss function in weight space together with the SGD trajectory as it searches for the minimum. The trajectory exhibits substantial jitter. (A) (5 points) Is this the best trajectory you can think of? (B) (5 points) Why is there so much jitter? (C) (5 points) A colleague suggests that adding a fraction of the previous update vector to the current update improves convergence. Do you agree? If so, why? Recall the weight update: wk+1=wk−η∇wL(wk)\mathbf{w}_{k+1} = \mathbf{w}_k - \eta \nabla_{\mathbf{w}} L(\mathbf{w}_k)

Solution

(A) No. The jittery trajectory converges very slowly; a smoother, more direct path would be preferable. (B) The axes of the contour plot represent the model parameters w\mathbf{w}. The jitter arises because the two parameter dimensions have very different dynamic ranges (the loss surface is elongated). A single learning rate η\eta is simultaneously too large for the steep direction and too small for the flat direction, causing oscillation in the steep direction. (C) Yes. Adding a fraction β\beta of the previous update implements a momentum (exponential moving average) update: Vk+1=βVk+(1−β) ∇wL(wk),wk+1=wk−η Vk+1V_{k+1} = \beta V_k + (1-\beta)\, \nabla_{\mathbf{w}} L(\mathbf{w}_k), \qquad \mathbf{w}_{k+1} = \mathbf{w}_k - \eta\, V_{k+1} The averaging filters out high-frequency noise in the gradient, so the trajectory is smoother and more direct and converges faster, as the right-hand plot in the notes shows.

Question 5, L1 vs L2 Regularization (15 points)

Part A (5 points)

Explain what early stopping does in terms of controlling model capacity, and what its main risk is.

Part B (10 points)

It has been argued that early stopping has an effect similar to L2 regularization. A colleague claims the same equivalence holds for L1 regularization. Do you agree or disagree? Justify your answer and sketch the constrained loss contours for L1 regularization.

Solution

Part A. Early stopping limits the number of SGD update steps, which caps the model’s capacity: the fewer the steps, the less the model can overfit the training data. The main risk is tuning this hyperparameter badly: stopping too early leads to underfitting; stopping too late leads to overfitting. Finding the right stopping point requires periodic evaluation on a held-out validation set, which adds cost. Part B. Disagree. Early stopping produces a regularization effect analogous to L2 (weight-decay) because it shrinks all weights toward zero at a similar rate. L1 regularization has a different geometry: the L1 constraint ball (a “diamond” in 2-D) has corners aligned with the coordinate axes, which encourages the optimal solution to lie at a corner where some weights are exactly zero. The solution is sparse, with many weights identically zero, and early stopping does not produce sparse solutions. L1 regularization, with its diamond-shaped constraint, is therefore not equivalent to early stopping.

Question 6, Correlated Dataset and SGD Mini-Batch Size (15 points)

You are given a dataset with KK classes for multi-class neural-network classification. Initial exploration reveals that the dataset contains heavily correlated examples within each class.

Part A (5 points)

Explain why a strongly correlated dataset may not be a good one for training.

Part B (10 points)

Given that you must work with this dataset, what is the best choice of SGD mini-batch size and why? How are the gradients affected by correlation within a mini-batch?

Solution

Part A. Correlated examples within a class contain redundant information. The classifier cannot learn the full diversity of intra-class variation, so even a small distributional shift at test time (e.g. a slightly different viewpoint or lighting condition) will cause large performance drops. The model memorizes the dominant template of each class and does not learn the true decision boundary. Part B. Correlated examples yield correlated gradient estimates within each mini-batch. Normally, you want each gradient update to be driven by a representative sample of all classes, which motivates a batch size of order M×KM \times K (a multiple MM of the number of classes KK, limited by GPU memory). With correlated data, however, increasing MM beyond 1 gives almost no additional information per batch: the gradient estimates stay highly correlated whatever the batch size. The best strategy is therefore a small mini-batch size (even M=1M=1, i.e. stochastic gradient descent), accepting higher gradient variance in exchange for more frequent and more diverse updates.

Question 7, CNN Parameter Count and Output Size (15 points)

Consider a CNN trained to classify 64×64 RGB images (3 channels) into 3 vehicle classes (cars, trucks, motorcycles). The architecture is:
  • Conv1: 32 filters, kernel 3×33 \times 3, stride 1, ReLU
  • MaxPool1: 2×22 \times 2, stride 2
  • Conv2: 64 filters, kernel 3×33 \times 3, stride 1, ReLU
  • MaxPool2: 2×22 \times 2, stride 2
  • Conv3: 128 filters, kernel 3×33 \times 3, stride 1, ReLU
  • MaxPool3: 2×22 \times 2, stride 2
  • FC1: 512 neurons, ReLU
  • Output: 3 neurons, softmax

PS3.A (5 points)

How many trainable parameters does Conv1 have?

PS3.B (5 points)

What is the output spatial size of Conv1 (assuming no padding)?

PS3.C (5 points)

What is the effect of increasing the number of filters in a convolutional layer on the parameter count and on the model’s performance?

Solution

PS3.A, Parameters in Conv1. Each of the 32 filters has size 3×3×33 \times 3 \times 3 (spatial × input channels). Including one bias per filter: params=32×(3×3×3+1)=32×28=896\text{params} = 32 \times (3 \times 3 \times 3 + 1) = 32 \times 28 = \mathbf{896} (Without biases: 32×27=86432 \times 27 = 864. Both values are acceptable.) PS3.B, Output size of Conv1 (no padding, stride 1): output=64−31+1=62⇒62×62×32\text{output} = \frac{64 - 3}{1} + 1 = 62 \quad \Rightarrow \quad \mathbf{62 \times 62 \times 32} PS3.C, Effect of more filters. Increasing the filter count proportionally increases the number of trainable parameters (more weights to store and update). With more filters the network can learn a richer set of feature detectors, which generally improves performance on complex tasks. The trade-offs are higher memory and compute cost, and a greater risk of overfitting on small datasets.

Question 8, IoU and Non-Maximum Suppression (15 points)

Boxes are given as (x1,y1,x2,y2)(x_1, y_1, x_2, y_2) in pixels, the top left and bottom right corners. A detector returns three person detections:
  1. (5 points) Compute the intersection over union (IoU) of D1 with D2, and of D1 with D3.
  2. (5 points) Apply non-maximum suppression (NMS) with an IoU threshold of 0.5. Which detections remain?
  3. (5 points) Suppose D1 and D2 are in fact two different people, one standing behind the other. What does NMS do to the recall in that case, and what can you change to reduce the damage?

Solution

1. IoU. Each box is 40×4040 \times 40, so each has area 1600. D1 and D2 overlap on (12,12,50,50)(12, 12, 50, 50), an area of 38×38=144438 \times 38 = 1444: IoU(D1,D2)=14441600+1600−1444=14441756≈0.82\text{IoU}(D1, D2) = \frac{1444}{1600 + 1600 - 1444} = \frac{1444}{1756} \approx 0.82 D1 and D3 overlap on (30,30,50,50)(30, 30, 50, 50), an area of 20×20=40020 \times 20 = 400: IoU(D1,D3)=4001600+1600−400=4002800≈0.14\text{IoU}(D1, D3) = \frac{400}{1600 + 1600 - 400} = \frac{400}{2800} \approx 0.14 2. NMS. Sort by score and keep D1, the highest. D2 overlaps D1 with IoU 0.82 > 0.5, so it is suppressed. D3 overlaps D1 with IoU 0.14 < 0.5, so it is kept. The output is D1 and D3. 3. Crowded scenes. NMS assumes that two boxes with a large overlap describe the same object. When two people really do overlap, the lower-scoring one is removed, and the detector misses it, so recall drops. A higher IoU threshold keeps more overlapping boxes but lets more duplicates through, which lowers precision. Soft-NMS reduces the score of an overlapping box in proportion to the overlap instead of deleting it, so a second object can survive if its score was high. Detectors that predict a set of boxes directly, such as DETR, do not need NMS at all.

Question 9, U-Net Skip Connections (15 points)

The code below is a small U-Net for semantic segmentation. A U-Net has two parts: a contracting path (the encoder), which captures context, and an expanding path (the decoder), which recovers precise locations.
DoubleConv(c_in, c_out) is two 3×33 \times 3 convolutions with padding 1, each followed by a ReLU, so it keeps the spatial size. Explain what the skip connections from the encoder to the decoder help the network achieve in semantic segmentation. The answer is not backpropagation or gradient flow.

Solution

Max pooling (or strided convolution) in the encoder reduces the resolution, from 224×224224 \times 224 down to 28×2828 \times 28 here, and discards fine, high-frequency detail such as edges and thin structures. An encoder-decoder without skip connections reconstructs from the bottleneck alone, so it recovers the coarse shape of objects but blurs their boundaries. The skip connections pass the high-resolution encoder features e1, e2 and e3 directly to the decoder stage of the same resolution, where they are concatenated with the upsampled features. The decoder then combines the context from the deep path (what the object is) with the precise location from the shallow path (where its boundary is), which is what a pixel-accurate mask needs.

Question 10, Pinhole Projection and Calibration (15 points)

A camera has the intrinsic matrix K=[80003200800240001].K = \begin{bmatrix} 800 & 0 & 320 \\ 0 & 800 & 240 \\ 0 & 0 & 1 \end{bmatrix}.
  1. (5 points) A point has camera-frame coordinates (X,Y,Z)=(0.5,−0.25,2.0)(X, Y, Z) = (0.5, -0.25, 2.0) m. Compute its pixel coordinates (u,v)(u, v).
  2. (5 points) Find a second point, at a depth of 4 m, that projects to the same pixel. What does this tell you about recovering depth from a single image?
  3. (5 points) In Zhang’s method you photograph a planar checkerboard from several poses. How many intrinsic parameters does KK have in general, how many constraints on them does each view give, and what is the minimum number of views?

Solution

1. Projection. u=fxX/Z+cxu = f_x X / Z + c_x and v=fyY/Z+cyv = f_y Y / Z + c_y: u=800⋅0.52.0+320=520,v=800⋅−0.252.0+240=140u = 800 \cdot \frac{0.5}{2.0} + 320 = 520, \qquad v = 800 \cdot \frac{-0.25}{2.0} + 240 = 140 2. Scale ambiguity. Every point on the ray through the camera center, λ(0.5,−0.25,2.0)\lambda (0.5, -0.25, 2.0), projects to the same pixel. With λ=2\lambda = 2 the point (1.0,−0.5,4.0)(1.0, -0.5, 4.0) also lands at (520,140)(520, 140). A single image fixes the ray, not the distance along it, so depth needs extra information: a second view, a known object size, or a learned prior. 3. Zhang’s method. The general KK has five parameters: fxf_x, fyf_y, cxc_x, cyc_y and the skew. The checkerboard and its image are related by a homography with 8 degrees of freedom. Six of them describe the pose of the board (three for rotation, three for translation), so each view leaves 2 constraints on the intrinsics. Five unknowns need at least three views. If you assume zero skew, four unknowns remain and two views are enough. In practice you use 10 to 20 views at varied angles to average out noise and to estimate lens distortion as well.

Question 11, Multi-Head Self-Attention and the Role of WOW^O (15 points)

Consider a transformer layer with three attention heads, each producing Z(h)∈RT×dhZ^{(h)} \in \mathbb{R}^{T\times d_h}. (a) Why are multiple heads used instead of a single larger head? (b) Write the concatenation and output-projection equations and explain the role of the projection matrix WOW^O. (c) What happens if WOW^O is fixed to the identity matrix? (d) Why is the position-wise feed-forward network (FFN) necessary after self-attention?

Solution

(a) Different heads can specialize in different relations, for example one head on syntactic (subject-verb) dependencies, another on semantics and a third on long-range coreference. These roles emerge during training. Together they let the layer relate tokens in more ways than one head of the same total width can. (b) Concatenation and projection: Z=Concat(Z(1),Z(2),Z(3))∈RT×d,Y=ZWO,WO∈Rd×d.Z = \mathrm{Concat}(Z^{(1)}, Z^{(2)}, Z^{(3)}) \in \mathbb{R}^{T\times d}, \qquad Y = Z W^O, \quad W^O \in \mathbb{R}^{d\times d}. WOW^O linearly mixes features across heads and projects back into the residual-stream dimension. Without it, heads cannot interact. (c) If WO=IW^O = I (which requires dmodel=∑hdhd_{\text{model}} = \sum_h d_h, as is the case here), the heads’ outputs are concatenated with no learned cross-head mixing inside the attention sub-layer, and each head’s contribution stays in its own slice of the residual stream. The FFN and later layers can still mix the heads, so only part of the cross-head interaction is lost. (d) Self-attention is already nonlinear, because the weights softmax(QK⊤/dk)\text{softmax}(QK^\top/\sqrt{d_k}) depend on the input. Each output is still a weighted average of the value vectors, though, so attention mixes information across tokens without transforming the features of any one token beyond the linear value projection. The FFN applies a two-layer network with a nonlinearity (for example GELU) to each token separately, which lets the model build higher-level features. It also holds most of the layer’s parameters. Roughly, attention chooses which tokens to read from, and the FFN computes new features from what it read.

Question 12, Vision Transformer: Patching, Attention and Classifier Head (15 points)

You wish to classify a 224×224×3224\times 224\times 3 image using a ViT encoder with P=28P = 28 patch size and a single attention head. (a) How many patches are produced and what is their dimensionality? How are they embedded and position-encoded? (b) Write down the query / key / value computation and the attention equation (assume H=1H=1). (c) Describe the classifier head on top of the encoder and dimension the final tensor for a KK-class problem.

Solution

(a) The image is split into N=HW/P2=224⋅224/282=64N = HW/P^2 = 224\cdot 224 / 28^2 = 64 flattened patches of dimension P2⋅C=282⋅3=2352P^2 \cdot C = 28^2 \cdot 3 = 2352. Each patch is mapped to a DD-dimensional embedding by a trainable linear projection. A learnable positional embedding encoding the 2-D location (h,w)(h,w) of each patch is added to the patch embeddings. (b) For z∈RN×Dz \in \mathbb{R}^{N\times D}, with joint projection Uqkv∈RD×3DU_{qkv} \in \mathbb{R}^{D\times 3D}: [q,k,v]=zUqkv,[q, k, v] = z U_{qkv}, A=softmax ⁣(qk⊤D)∈RN×N,A = \mathrm{softmax}\!\left(\frac{q k^\top}{\sqrt{D}}\right) \in \mathbb{R}^{N\times N}, SA(z)=Av.\mathrm{SA}(z) = A v. (c) A [CLS] token (or global-average-pool of patch tokens) feeds an MLP classification head ending in a softmax over KK classes; the final posterior is a vector in RK\mathbb{R}^{K} (or shape B×KB\times K for a batch of size BB). The full forward pass stacks: patch-embed → +positional → LayerNorm → self-attention → residual → LayerNorm → FFN → residual → pool → Linear(D→K)(D\rightarrow K) → softmax.

Question 13, Positional Encodings in Vision Transformers (20 points)

Transformers encode the position of each token with sinusoids: PE(pos, 2i)=sin⁡ ⁣(pos100002i/dmodel),PE(pos, 2i+1)=cos⁡ ⁣(pos100002i/dmodel),\text{PE}_{(pos,\,2i)} = \sin\!\Big(\frac{pos}{10000^{2i/d_{\text{model}}}}\Big), \qquad \text{PE}_{(pos,\,2i+1)} = \cos\!\Big(\frac{pos}{10000^{2i/d_{\text{model}}}}\Big), where pospos is the token’s position, ii indexes the embedding dimensions, and dmodeld_{\text{model}} is the embedding size.
  1. (5 points) Explain how these sinusoids give the transformer positional information. You can draw a figure.
  2. (5 points) Extend the encoding to the 2D position of a patch in an image processed by a Vision Transformer.
  3. (10 points) Explain the purpose of multiple attention heads in a Vision Transformer, specifically for images.

Solution

1. Sinusoids. Each pair of dimensions (2i,2i+1)(2i, 2i+1) is a sine and cosine of the position at its own frequency, from fast (small ii) to very slow (large ii). Reading down the dimensions is like reading a clock with many hands: the fast pairs tell nearby positions apart, and the slow pairs tell distant ones apart, so every position gets a distinct vector. Because sin⁡\sin and cos⁡\cos of pos+kpos + k are a fixed rotation of those of pospos, the encoding of a position shifted by kk is a linear function of the original. Attention can therefore learn to respond to relative offsets, and the dot product between two encodings depends mainly on the distance between the positions. The encoding is added to the token embedding, so attention sees content and position together. 2. 2D patches. A patch at row rr and column cc of the patch grid gets a 1D sinusoidal encoding of rr in half of the dimensions and of cc in the other half, and the two are concatenated: PE(r,c)=[PEd/2(r), PEd/2(c)]\text{PE}(r, c) = [\text{PE}_{d/2}(r),\ \text{PE}_{d/2}(c)]. For a 224×224224 \times 224 image cut into 16×1616 \times 16 patches, rr and cc run from 0 to 13. The original ViT instead learns one positional embedding per patch index, and those learned embeddings turn out to encode the row and column structure on their own. 3. Multiple heads. Each head has its own query, key and value projections, so each one computes its own pattern of which patches attend to which. In images, some heads attend locally, to neighboring patches, much like a convolution that picks up edges and textures. Others attend globally across the image, to relate an object’s parts or an object to its context. Heads can also specialize in different feature subspaces, such as color or shape. With one head, a single softmax would have to average all of these relations into one attention map. Multiple heads keep them separate, and the output projection combines them.

Question 14, CLIP Contrastive Image-Text Learning (10 points)

(a) Sketch the CLIP architecture at the block level (image encoder, text encoder, projection layers, similarity computation). (b) Explain the contrastive loss used to train it and what each component encourages.

Solution

(a) The image encoder is a CNN (e.g., ResNet) or a ViT that maps an image into a feature vector, followed by a linear projection into a shared embedding space. A parallel text encoder (usually a transformer) maps the caption into the same shared space via its own linear projection. Similarity between image and text embeddings is computed via a (scaled) dot product, producing an N×NN\times N similarity matrix for a batch of NN image-text pairs. (b) CLIP uses a single symmetric InfoNCE loss over the N×NN\times N similarity matrix Sij=⟨ui,vj⟩/τS_{ij} = \langle u_i, v_j\rangle / \tau, where uiu_i is the (normalized) image embedding, vjv_j the (normalized) text embedding, and τ\tau is a learned temperature. Define Li→t=−1N∑i=1Nlog⁡exp⁡(Sii)∑j=1Nexp⁡(Sij),Lt→i=−1N∑j=1Nlog⁡exp⁡(Sjj)∑i=1Nexp⁡(Sij),L_{i\to t} = -\frac{1}{N}\sum_{i=1}^{N}\log\frac{\exp(S_{ii})}{\sum_{j=1}^{N}\exp(S_{ij})}, \qquad L_{t\to i} = -\frac{1}{N}\sum_{j=1}^{N}\log\frac{\exp(S_{jj})}{\sum_{i=1}^{N}\exp(S_{ij})}, and the total loss L=12(Li→t+Lt→i)L = \tfrac{1}{2}(L_{i\to t} + L_{t\to i}). Each row’s softmax cross-entropy implicitly pulls the matched (diagonal) image-text pair together while pushing the N−1N-1 in-batch negatives apart through the denominator. The symmetric form trains the embedding for both directions (image→text retrieval and text→image retrieval).

Question 15, Siamese Networks and Contrastive Loss (10 points)

You are given a Siamese network with two identical CNN branches that share weights, used to decide whether two input images belong to the same class (e.g., both person) or different classes (e.g., person vs. animal). The contrastive loss for a pair (x1,x2)(x_1, x_2) with label y∈{0,1}y \in \{0, 1\} (0 = same class, 1 = different class) is L(x1,x2,y)=(1−y) 12 DW2+y 12 [max⁡(0, m−DW)]2\mathcal{L}(x_1, x_2, y) = (1-y)\,\tfrac{1}{2}\,D_W^2 + y\,\tfrac{1}{2}\,\big[\max(0,\, m - D_W)\big]^2 where DW=∥fW(x1)−fW(x2)∥2D_W = \lVert f_W(x_1) - f_W(x_2) \rVert_2 is the Euclidean distance between the two CNN embeddings and m>0m > 0 is a margin. (a) Sketch (or describe) the network architecture and explain why both branches must share weights. (b) Explain the role of each of the two terms in the loss and what the network learns to do for matched vs. unmatched pairs. (c) Why is the margin mm necessary in the second term?

Solution

(a) The Siamese network has two identical CNN towers that each map an input image into an embedding vector fW(x)f_W(x). The towers share weights so that the same input always produces the same embedding. Only then is the Euclidean distance DWD_W between two embeddings a meaningful, symmetric measure of similarity in a single learned feature space. Two independent CNNs would learn two unrelated spaces, and the distance would be meaningless. What the network learns is an embedding in which same-class pairs are close and different-class pairs are far apart. (b) For a matched pair (y=0y=0), only the first term is active: it minimizes the squared Euclidean distance DW2D_W^2, pulling the two embeddings together. For an unmatched pair (y=1y=1), only the second term is active: it minimizes [max⁡(0,m−DW)]2[\max(0, m - D_W)]^2, which pushes the embeddings apart until their distance reaches the margin mm. Together the terms shape an embedding space where intra-class distances shrink and inter-class distances grow. (c) Without a margin, the model could trivially reduce the second term by pushing unmatched pairs infinitely far apart, leading to unbounded gradients and degenerate solutions. The margin mm caps the penalty: once DW≥mD_W \ge m the pair is considered “far enough” and contributes zero loss. Training then concentrates on the hard negatives, the pairs still closer than the margin, and is more stable.

Question 16, Visual Tokens and Fine-Tuning a VLM (15 points)

A LLaVA-style VLM uses a CLIP ViT-L/14 vision encoder at 336×336336 \times 336 input resolution, with a patch size of 14 and an output width of 1024. A two-layer MLP projector maps each visual token to the language model’s width of 4096: Linear(1024 → 4096), GELU, Linear(4096 → 4096).
  1. (5 points) How many visual tokens does one image become? How many trainable parameters does the projector have?
  2. (5 points) Training runs in two stages. Which parts of the model are trained in each stage, and why is the vision encoder frozen?
  3. (5 points) You fine-tune the language model with LoRA of rank r=8r = 8 on a 4096×40964096 \times 4096 weight matrix. How many trainable parameters does LoRA add for this matrix, and what fraction of the full matrix is that?

Solution

1. Tokens and projector. The image is cut into (336/14)2=242=576(336 / 14)^2 = 24^2 = 576 patches, so it becomes 576 visual tokens in the language model’s input sequence. The projector has (1024⋅4096+4096)+(4096⋅4096+4096)=20,979,712≈21M(1024 \cdot 4096 + 4096) + (4096 \cdot 4096 + 4096) = 20{,}979{,}712 \approx 21\text{M} parameters. 2. Two stages. In the first stage (feature alignment) only the projector is trained, on image-caption pairs, so that visual tokens land where the frozen language model can read them. In the second stage (visual instruction tuning) the projector and the language model are trained on instruction-following conversations about images. The vision encoder stays frozen in both stages. It was already trained contrastively on hundreds of millions of image-text pairs, and updating it on a much smaller instruction dataset would cost memory and risk degrading its general features. 3. LoRA. LoRA freezes WW and learns the update ΔW=BA\Delta W = BA with B∈R4096×8B \in \mathbb R^{4096 \times 8} and A∈R8×4096A \in \mathbb R^{8 \times 4096}: r (d+k)=8⋅(4096+4096)=65,536r\,(d + k) = 8 \cdot (4096 + 4096) = 65{,}536 The full matrix has 40962=16,777,2164096^2 = 16{,}777{,}216 entries, so LoRA trains about 0.39% of them.

Question 17, Promptable Segmentation with SAM (10 points)

  1. (4 points) SAM has three parts: an image encoder, a prompt encoder and a mask decoder. Which part is expensive, how often does each one run when a user clicks several points on the same image, and why is the model split this way?
  2. (3 points) Given a single foreground point, SAM returns three masks with a predicted IoU score for each. Why three?
  3. (3 points) SAM does not take a text query such as “the red mug”. Describe how a VLM or an open-vocabulary detector can be combined with SAM to segment objects named in text.

Solution

1. Amortization. The image encoder, a large ViT pretrained as a masked autoencoder, is the expensive part. It runs once per image and produces an image embedding. The prompt encoder and the lightweight mask decoder run once per prompt and take tens of milliseconds. Splitting the model this way lets a user, or a planner, try many prompts on one image without paying for the encoder each time. 2. Ambiguity. One point does not say which object you mean. A point on a shirt could mean the shirt, the person, or a logo on the shirt. SAM predicts three nested masks, roughly part, object and whole, and ranks them by predicted IoU. Training back-propagates only the loss of the best of the three, so the model is not penalized for an ambiguity that the prompt itself contains. 3. Grounding. A text-to-box model such as Grounding DINO, or a VLM that outputs box coordinates, turns the text into one or more bounding boxes. Each box is passed to SAM as a box prompt, and SAM returns the mask. This is the Grounded SAM pipeline: the VLM or detector decides what to segment and roughly where, and SAM produces the pixel-accurate mask.

Found an error on this page? Report an issue.