CLIP's ResNet image encoder ends with a grid of feature vectors. Instead of averaging the grid, CLIP pools it with one layer of multi-head attention whose query comes from the global average. Its text encoder is a Transformer with causal attention; the text's feature is the top layer's vector at the end-of-sequence token, layer normalised and then projected. Implement both.
attention_pool(fmap, pos_emb, Wq, Wk, Wv, Wo, n_heads)
fmap: shape . Form tokens: first the mean of all grid vectors, then the grid vectors in row-major order (fmap.reshape(H * W, C)). Add pos_emb (shape ) to the tokens.Wq ; keys and values are all tokens times Wk and Wv . Split the query, keys and values into n_heads consecutive slices of width . In each head, the weights are the softmax over the tokens of , and the head output is the weighted sum of .Wo . No biases anywhere.(out, weights): out has shape , weights has shape .text_features(hidden, token_ids, eos_id, gain, bias, W_text, eps=1e-5)
hidden: top-layer activations, shape ; token_ids: shape .eos_id, apply layer normalisation (mean and population variance over its entries), then multiply by W_text .ValueError if a sequence has no eos_id.n_heads does not divide , raise ValueError.