Week 11 · Vision transformers and image-text embeddings

Follow a patch tensor and compare image-text scores with supervised scores.

← Week 10 · Subject contents · Week 12 →

Follow a patch tensor and compare image-text scores with supervised scores.

Work through the problem

A vision transformer flattens image patches and projects each to a token. A 4×4 grayscale image with 2×2 non-overlapping patches yields four tokens, each containing four raw values before projection. Positional information lets attention distinguish where each patch occurred.

A zero-shot classifier can compare normalized image vectors with vectors for text descriptions using cosine similarity. It depends on alignment learned beforehand. This toy lab uses hand-aligned representations and deliberately swaps the text descriptors to show how alignment errors affect the result. A learned linear head provides a supervised comparison on the same image features.

Run the Python lab

import numpy as np
def patch_tokens(img):
    return img.reshape(2,2,2,2).transpose(0,2,1,3).reshape(4,4)
def features(img):
    return patch_tokens(img).mean(1)[[0,3]]
top = np.zeros((4,4))
top[:2,:2] = 1
bottom = np.rot90(top,2)
examples = np.stack([features(a) for a in [top,.8*top,bottom,.8*bottom]])
labels = np.eye(2)[[0,0,1,1]]
head = np.linalg.lstsq(examples,labels,rcond=None)[0]
test = np.stack([features(.65*top),features(.9*bottom)])
def normalized(x):
    return x/np.linalg.norm(x,axis=1,keepdims=True)
for name, scores in [("Supervised",test@head),("Aligned text",normalized(test)@np.eye(2)),("Swapped text",normalized(test)@np.eye(2)[::-1])]:
    print(name,scores.argmax(1).tolist())
assert patch_tokens(top).shape==(4,4)

Output from the lab

Supervised [0, 1]
Aligned text [0, 1]
Swapped text [1, 0]

Practice

  1. Is this a test of a pretrained vision-language model?

Check your reasoning

  1. No. It isolates token shapes and the similarity rule. A real model requires a separate test on labelled images and varied prompts.

← Week 10 · Subject contents · Week 12 →

Further reading · Szeliski · Computer Vision: Algorithms and Applications