The ViT-MLP-LLM pattern#
Bridge mechanisms#
- MLP projector
- Linear, GELU, Linear. Maps
(N_patches, d_vit) to (N_patches, d_llm). - Q-Former
- 32 learnable queries cross-attend to frozen ViT patches. Output is 32 visual tokens.
- Perceiver resampler
- K = 64 learnable latents. Any patch count exits as 64 tokens.
- Gated cross-attention
- y = \tanh(\alpha) \cdot \mathrm{cross} + x. Alpha starts at 0.
- Cross-attention
- Q comes from the text stream. K and V come from the image stream.
- Cosine alignment loss
- 1 - \cos(\mathrm{image}, \mathrm{text}). 0 is aligned, 2 is opposite.
- DeepStack
- stacks features from several ViT depths, not the last layer only.
- CMER
- share of outputs with high text confidence and low image-text similarity.
Three training stages#
Tasks in code#
| Task | Code |
|---|
| Build a projector | Projector(vit_dim=768, llm_dim=4096, hidden=4096) |
|---|
| Stack ViT depths | deepstack_features(per_layer_features) |
|---|
| Measure CMER | cross_modal_error_rate(image_emb, text_emb, text_confidence) |
|---|
| Resample patches to fixed latents | perceiver_resampler(patches, num_latents=8, num_blocks=2) |
|---|
| Gated step, closed gate | gated_cross_attention_step(text_hidden, visual, alpha=0.0) |
|---|
| One image per text token | interleaved_mask(seq) |
|---|
| LLaVA prompt with 576 tokens | build_llava_prompt(system, user, image_tokens=576) |
|---|
| Self-attention mask | causal_mask(length) |
|---|
Merge image tokens into the text#
vision_tokens = self.vit(image)(B, N_patches, d_vit)
vision_embeds = self.projector(vision_tokens)(B, N_patches, d_llm)
text_embeds = self.llm.get_input_embeddings()(input_ids)(B, M, d_llm)
out = text_embeds.clone()copy, then fill
for b in range(input_ids.size(0)):one sample at a time
positions = (input_ids[b] == self.image_token_id).nonzero(as_tuple=True)[0]
out[b, positions] = vision_embeds[b]<image> slots get vision
Train only the projection#
cfg = AlignConfig()768 -> 1024 -> 512, 200 steps
encoder = VisionEncoder(encoder_cfg).eval()
freeze(encoder)requires_grad_(False)
projector = MLPProjector(cfg.vision_hidden, cfg.projection_hidden, cfg.text_hidden)
with torch.no_grad():
_, cls = encoder(img)CLS pool, no encoder grads
text_emb = text(ids)frozen MockTextEmbedding
image_emb = projector(cls)
loss = cosine_alignment_loss(image_emb, text_emb)