Module contents
Lesson 24 of 33Core 105 min

Multimodal fusion: cross-modal attention, FiLM and Perceiver

Compare early, intermediate and late multimodal fusion; implement cross-attention, FiLM, Perceiver bottlenecks and gated attention, and assess modality imbalance and missing inputs.

After this lesson you can

  • Classify multimodal architectures by fusion point and mechanism and anticipate cost.
  • Implement cross-modal attention, FiLM and a Perceiver block and compare token costs.
  • Explain zero-initialized Flamingo gates and preservation of a pretrained language model.
  • Detect modality imbalance through ablation and mitigate it with modality dropout or auxiliary losses.
  • Design camera, proprioception and language fusion for a robotic policy.

Before you start

Where do modalities meet?

A policy following “reach the red block” must relate image, instruction, and actuator position. The fusion taxonomy distinguishes where they mix: early fusion combines inputs or tokens before much processing; intermediate fusion exchanges features between networks; late fusion combines already computed predictions or representations. These categories are not exclusive: a system can fuse at several stages.

Late fusion allows branches to be replaced or run at different frequencies, but can lose fine interactions if each branch summarizes its input too early. Early fusion permits rich interactions and can be expensive for long sequences. A 30 Hz camera and 1 kHz force sensor also require timestamp synchronization and modeling observation age; concatenating the latest sample from each sensor without stating it does not resolve the offset.

InteractiveBuild your fusion architecture

Early attention counts (n+t+p)² scores; cross counts n·t; Perceiver counts L(n+t+p)+L². FiLM counts multiplication and addition per channel. We use d=128, 16 language tokens and one proprioceptive token; projections, MLP and other costs are excluded. Matrix total is not measured peak memory.

Success was evaluated on 200 held-out simulated scenes for CNN concatenation, FiLM or cross-attention policies trained on other scenes. Perceiver was not trained. Only full input and camera-off cases were measured; changing order or theoretical token count does not change those results.

Mechanism
256
Attention entries74.529
Approximate operations38.16 M
Float32 matrix total0.28 MiB
Measured success99.0 %
Ideal one-layer counts and measured success in small MuJoCo policies. Theoretical cost is not the measured cost of those CNNs; Perceiver and untested combinations are marked as unmeasured.

Querying and modulating

Cross-modal attention uses queries from one source and keys and values from another. With queries Q∈Rnq×dQ\in\mathbb R^{n_q\times d}, keys K∈Rnk×dK\in\mathbb R^{n_k\times d} and values V∈Rnk×dvV\in\mathbb R^{n_k\times d_v},

Attn⁡(Q,K,V)=softmax⁡filas ⁣(QK⊤d)V.\operatorname{Attn}(Q,K,V)=\operatorname{softmax}_{\mathrm{filas}}\!\left(\frac{QK^\top}{\sqrt d}\right)V.

The output has nqn_q rows; reversing queries and keys changes which elements receive context. Co-attention can update both modalities with two operations. Masks must prevent attention to missing or future tokens when required. The score matrix has nqnkn_qn_k entries per head; projections, MLPs, and activations also cost memory and operations.

FiLM transforms activations per channel: yh,w,c=γc(z)xh,w,c+βc(z)y_{h,w,c}=\gamma_c(z)x_{h,w,c}+\beta_c(z), with parameters generated from condition zz. It can amplify, attenuate, invert, or shift channels; it needs no attention matrix between every pixel and word. Applied after layer normalization, it is a per-channel affine transformation of normalized activation. AdaLN uses the same idea of conditioned scale and shift on a normalized representation; placement and gating details depend on architecture.

InteractiveFiLM in action

MuJoCo scene

Two rendered blocks and cursor

Before FiLM

After FiLM

Maps and parameters from the actually trained FiLM policy on held-out scene 800. Six channels were chosen by activation variance; colors are comparable. ‘Left’ did not appear in the two training instructions: its response is extrapolation without a semantic guarantee.

CLIP instruction
7
Applied γ1.089
Applied β−0.024
Actual channel7
Activations, γ and β extracted from a FiLM policy trained on MuJoCo blocks; held-out scene and six channels selected by variance. The left instruction did not appear in training.

Latents and gates

The Perceiver latent bottleneck uses LL latent queries to read NN inputs with LNLN scores, followed by latent self-attention with L2L^2. Perceiver IO adds output queries to produce variable-size structures. This reduces the attention matrix relative to direct N2N^2 self-attention when L≪NL\ll N, but projections, multiple layers, inputs, and output queries are not free. A bottleneck that is too small can discard useful information.

With 4096 image and 512 text tokens, concatenating them in a self-attention layer produces 46082=21 233 6644608^2=21\,233\,664 scores per head. A 64-latent read over the image alone produces 64⋅4096=262 14464\cdot4096=262\,144, 81 times fewer scores; latent self-attention adds 642=409664^2=4096. This ratio compares two specific operations and does not guarantee end-to-end speedup.

Gated cross-attention adds a visual residual to a base model: y=x+tanh⁡(α)f(x,m)y=x+\tanh(\alpha)f(x,m). Initializing α=0\alpha=0 gives exactly y=xy=x if other components stay unchanged; ∂y/∂α=f(x,m)\partial y/\partial\alpha=f(x,m) at zero can allow the gate to learn. Internal parameters of ff receive gradient multiplied by the gate and, with it exactly zero, their initial gradient from that residual is zero. Flamingo uses gated cross blocks to connect vision and a language model; our block is a simplification illustrating initial identity.

Dominant or missing modalities

Modality imbalance occurs when an easy branch solves the training loss and another receives little useful signal, or their generalization rates differ. High joint accuracy does not show both branches are used. Ablation removes a modality, swapping breaks correspondence between modality and label, and single-branch tests show different dependencies. Replacement may be out of distribution: specify how it was done and avoid interpreting one test as definitive causality.

InteractiveThe lazy modality
5075100060

Green: both; blue: audio only; orange: video only. Each branch receives eight synthetic features. Audio is easier while video is noisier; ablations remove the other branch’s contribution. These are accuracies on 1024 held-out examples from the same distribution.

Training
60
Both99.1 %
Audio only97.8 %
Video only50.1 %
Three actual training runs on synthetic features from two branches. Audio is deliberately easier than video; curves evaluate 1024 held-out synthetic examples from the same distribution.

Modality dropout trains with some branches absent; auxiliary losses force each branch to predict. Both change the objective and may reduce joint performance or induce another bias. Wang and colleagues analyze differences in overfitting and generalization across modalities; do not attribute all failures to one cause.

In the figure’s simulation, after 60 epochs video-only accuracy was 50.1% without correction, 74.1% with dropout and 73.1% with auxiliary losses; with both branches it was about 99% in all three cases. Inputs are vectors constructed with different signal-to-noise ratios, not recordings. This branch’s improvement is measured on the same synthetic distribution and does not guarantee robustness to domain shift.

Robustness to missing modalities requires defining absence: a black image, disconnected sensor, explicit mask, and delayed data are different conditions. Train and evaluate those that matter, retain timestamps, and distinguish uncertainty from a valid zero measurement. A physical policy needs motion limits and whole-system validation as well as simulation accuracy.

Lab: mechanisms in NumPy

The cell implements cross-attention with stable softmax, FiLM, latent reading and self-attention, and a residual gate. It checks weight sums, exact identity for a zero gate, and its derivative by central differences. These are simplified blocks without learned projections, normalization, or masks; they are not complete Perceiver or Flamingo implementations.

[ ]Attention, FiLM and latentsBrowser
import numpy as np

def cross_attention(query,key,value):
 if query.shape[-1]!=key.shape[-1] or len(key)!=len(value):raise ValueError('dimensiones incompatibles')
 scores=query@key.T/np.sqrt(query.shape[-1]);scores-=scores.max(axis=1,keepdims=True);weights=np.exp(scores);weights/=weights.sum(axis=1,keepdims=True)
 return weights@value,weights
def film(x,gamma,beta):return x*np.asarray(gamma)+np.asarray(beta)
def perceiver(latents,inputs):
 read,_=cross_attention(latents,inputs,inputs);latents=latents+read
 self_out,_=cross_attention(latents,latents,latents);return latents+self_out
def gated_block(x,media,alpha):return x+np.tanh(alpha)*cross_attention(x,media,media)[0]
rng=np.random.default_rng(24);text=rng.normal(size=(5,8));vision=rng.normal(size=(48,8));latents=rng.normal(size=(4,8))
out,w=cross_attention(text,vision,vision);print('formas salida/pesos:',out.shape,w.shape,'error suma de filas:',np.max(np.abs(w.sum(1)-1)))
gain=np.linspace(.5,1.5,8);shift=np.linspace(-.2,.2,8);print('FiLM forma:',film(vision,gain,shift).shape,'Perceiver:',perceiver(latents,vision).shape)
base=gated_block(text,vision,0.);h=1e-6;grad=(gated_block(text,vision,h)-gated_block(text,vision,-h))/(2*h);expected=cross_attention(text,vision,vision)[0]
print('puerta cero igual:',np.array_equal(base,text),'error derivada:',np.max(np.abs(grad-expected)),'norma derivada:',np.linalg.norm(grad))
nimg=4096;ntext=512;L=64;early=(nimg+ntext)**2;read=L*nimg
print('puntuaciones temprana/lectura Perceiver:',early,read,'razón:',early/read,'latentes internas:',L*L)

Local lab: reaching blocks

A cursor with two prismatic joints and position actuators moves in a MuJoCo plane toward one of two fixed blocks. Each overhead camera image, current position, and English instruction encoded by OpenCLIP feeds a policy emitting a target position; the servo applies it for 100 steps. Contact is disabled: success means ending within 0.08 m of the center and does not represent grasping, forces, or physical hardware. We generated 1000 scenes: 800 training and 200 held out, with two instructions per scene.

In one RTX 3060 run, success over 200 scenes for the red instruction, instruction swapped to blue, and black camera was 99%/100%/1% for concatenation, 100%/100%/1% for FiLM, and 100%/100%/0% for cross-attention. The swap test also changes the expected target; mean action changed about 0.62 m between instructions. A black camera was not used in training. These are two easy tasks and a simulated camera: they establish neither general robustness nor broad language understanding.

The architectures have different capacity and computation. Cross-attention uses the instruction as query and spatial features with coordinates as keys and values; FiLM modulates channels; concatenation combines visual representation, text, and position. To reproduce, install NumPy, mujoco==4.0.1, compatible PyTorch and torchvision, open_clip_torch==4.2.2 and huggingface_hub. The revision-pinned OpenCLIP checkpoint is downloaded if FUSION_CLIP_WEIGHTS is not set; rendering requires OpenGL. Results and times vary: repeating the cell in CUDA, concatenation achieved 99.5%/99.5%/0.5%, FiLM 99.5%/100%/1%, and cross-attention 1.5%/93%/1% for red/blue/black camera. This last run failed on red; one seed and two runs cannot establish which architecture is more robust.

[ ]MuJoCo block-reaching policiesLocal GPU
import numpy as np
import mujoco

XML='''<mujoco model="reach"><option timestep="0.01" gravity="0 0 -9.81"/><visual><global offwidth="64" offheight="64"/></visual>
<worldbody><light pos="0 0 2" dir="0 0 -1" diffuse=".8 .8 .8" ambient=".5 .5 .5"/><camera name="top" pos="0 0 2" fovy="48"/>
<geom type="plane" size="1 1 .05" rgba=".35 .35 .35 1" contype="0" conaffinity="0"/>
<geom name="red" type="box" pos="-.3 .2 .05" size=".07 .07 .05" rgba=".9 .05 .05 1" contype="0" conaffinity="0"/>
<geom name="blue" type="box" pos=".3 -.2 .05" size=".07 .07 .05" rgba=".05 .1 .9 1" contype="0" conaffinity="0"/>
<body name="cursor" pos="0 0 .11"><joint name="x" type="slide" axis="1 0 0" damping="3"/><joint name="y" type="slide" axis="0 1 0" damping="3"/><geom type="sphere" size=".035" mass=".2" rgba="1 1 1 1" contype="0" conaffinity="0"/></body></worldbody>
<actuator><position joint="x" kp="35"/><position joint="y" kp="35"/></actuator></mujoco>'''
def scene_data(n=1000,seed=24):
 rng=np.random.default_rng(seed);model=mujoco.MjModel.from_xml_string(XML);data=mujoco.MjData(model);renderer=mujoco.Renderer(model,64,64)
 redid=mujoco.mj_name2id(model,mujoco.mjtObj.mjOBJ_GEOM,'red');blueid=mujoco.mj_name2id(model,mujoco.mjtObj.mjOBJ_GEOM,'blue')
 images=[];targets=[];positions=[]
 for _ in range(n):
  while True:
   pts=rng.uniform(-.55,.55,(3,2))
   if min(np.linalg.norm(pts[0]-pts[1]),np.linalg.norm(pts[0]-pts[2]),np.linalg.norm(pts[1]-pts[2]))>.22:break
  model.geom_pos[redid,:2]=pts[0];model.geom_pos[blueid,:2]=pts[1];mujoco.mj_resetData(model,data);data.qpos[:2]=pts[2];data.ctrl[:]=pts[2];mujoco.mj_forward(model,data)
  renderer.update_scene(data,camera='top');images.append(renderer.render().copy());targets.append(pts[:2]);positions.append(pts[2])
 renderer.close();return np.asarray(images),np.asarray(targets),np.asarray(positions)

import os,time
from huggingface_hub import hf_hub_download
import numpy as np
import torch
import torch.nn.functional as F
import open_clip
import mujoco

torch.set_num_threads(2);torch.manual_seed(24);np.random.seed(24);device='cuda' if torch.cuda.is_available() else 'cpu'
images,targets,positions=scene_data()
clip_weights=os.environ.get('FUSION_CLIP_WEIGHTS') or hf_hub_download('laion/CLIP-ViT-B-32-laion2B-s34B-b79K',filename='open_clip_model.safetensors',revision='1a25a446712ba5ee05982a381eed697ef9b435cf')
clip,_,_=open_clip.create_model_and_transforms('ViT-B-32',pretrained=clip_weights,device=device);clip.eval();tok=open_clip.get_tokenizer('ViT-B-32')
phrases=['reach the red block','reach the blue block']
with torch.no_grad():texts=clip.encode_text(tok(phrases).to(device),normalize=True).detach()
del clip
I=torch.tensor(images.transpose(0,3,1,2)/255,dtype=torch.float32,device=device);P=torch.tensor(positions,dtype=torch.float32,device=device);Y=torch.tensor(targets,dtype=torch.float32,device=device)
class Policy(torch.nn.Module):
 def __init__(self,mode):
  super().__init__();self.mode=mode
  self.cnn=torch.nn.Sequential(torch.nn.Conv2d(3,16,5,2,2),torch.nn.ReLU(),torch.nn.Conv2d(16,32,3,2,1),torch.nn.ReLU(),torch.nn.Conv2d(32,32,3,1,1),torch.nn.ReLU())
  if mode=='concat':self.t=torch.nn.Linear(512,32);size=32*16*16+32+2
  elif mode=='film':self.mod=torch.nn.Linear(512,64);size=32*16*16+2
  elif mode=='cross':
   self.query=torch.nn.Linear(512,32);self.key=torch.nn.Linear(34,32);self.value=torch.nn.Linear(34,32);size=32+2
  self.head=torch.nn.Sequential(torch.nn.Linear(size,128),torch.nn.ReLU(),torch.nn.Linear(128,2))
 def forward(self,im,proprio,language):
  feat=self.cnn(im)
  if self.mode=='concat':h=torch.cat([feat.flatten(1),self.t(language),proprio],dim=1)
  elif self.mode=='film':
   gamma,beta=self.mod(language).chunk(2,dim=1);h=torch.cat([(feat*(1+gamma[:,:,None,None])+beta[:,:,None,None]).flatten(1),proprio],dim=1)
  else:
   H,W=feat.shape[-2:];yy,xx=torch.meshgrid(torch.linspace(-1,1,H,device=im.device),torch.linspace(-1,1,W,device=im.device),indexing='ij');coords=torch.stack([xx,yy],-1).reshape(1,H*W,2).expand(len(im),-1,-1)
   tokens=torch.cat([feat.flatten(2).transpose(1,2),coords],-1);q=self.query(language)[:,None,:];a=torch.softmax((q@self.key(tokens).transpose(1,2))/np.sqrt(32),dim=-1);v=(a@self.value(tokens)).squeeze(1);h=torch.cat([v,proprio],1)
  return self.head(h)
def run_eval(pred,goal,start,scene_targets):
 m=mujoco.MjModel.from_xml_string(XML);d=mujoco.MjData(m);success=[];final=[]
 red_id=mujoco.mj_name2id(m,mujoco.mjtObj.mjOBJ_GEOM,'red');blue_id=mujoco.mj_name2id(m,mujoco.mjtObj.mjOBJ_GEOM,'blue')
 for action,target,p,blocks in zip(pred,goal,start,scene_targets):
  m.geom_pos[red_id,:2]=blocks[0];m.geom_pos[blue_id,:2]=blocks[1]
  mujoco.mj_resetData(m,d);d.qpos[:2]=p;d.ctrl[:]=np.clip(action,-.7,.7);mujoco.mj_forward(m,d)
  for _ in range(100):mujoco.mj_step(m,d)
  err=np.linalg.norm(d.qpos[:2]-target);success.append(err<.08);final.append(err)
 return float(np.mean(success)),float(np.mean(final))
results={};start=time.perf_counter()
for mode in ('concat','film','cross'):
 torch.manual_seed(24);net=Policy(mode).to(device);opt=torch.optim.Adam(net.parameters(),lr=.001)
 for epoch in range(100):
  order=torch.randperm(1600,device=device)
  for batch in order.split(64):
   scene=batch//2;color=batch%2;pred=net(I[scene],P[scene],texts[color]);loss=((pred-Y[scene,color])**2).mean();opt.zero_grad();loss.backward();opt.step()
  if epoch in (0,24,49,99):print(mode,'época',epoch+1,'loss',round(float(loss.detach()),5),flush=True)
 with torch.no_grad():
  im=I[800:];pos=P[800:];n=len(pos);red=net(im,pos,texts[0].expand(n,-1)).cpu().numpy();blue=net(im,pos,texts[1].expand(n,-1)).cpu().numpy();blank=net(torch.zeros_like(im),pos,texts[0].expand(n,-1)).cpu().numpy()
 red_success,red_err=run_eval(red,targets[800:,0],positions[800:],targets[800:]);blue_success,blue_err=run_eval(blue,targets[800:,1],positions[800:],targets[800:]);blank_success,blank_err=run_eval(blank,targets[800:,0],positions[800:],targets[800:]);delta=np.linalg.norm(red-blue,axis=1)
 results[mode]={'normal':red_success,'swapped':blue_success,'blank':blank_success,'normal_error':red_err,'swapped_error':blue_err,'blank_error':blank_err,'mean_action_change':float(delta.mean())}
 print(mode,results[mode],flush=True)
print('total s:',round(time.perf_counter()-start,2),'device:',device)
import json
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofA per-channel transformation
Prove: Prove what transformations FiLM expresses after layer normalization.
0
Let h be the already normalized activation and a and b arbitrary per-channel scale and shift vectors.

Step 1 of 3. Which FiLM parameters produce a ⊙ h + b?

CodeGated residual
Implement gated_xattn_block(x, media, alpha): x has shape (N,D), media (M,D), M>0. Use direct attention softmax(x·mediaᵀ/√D)·media and return x + tanh(alpha)·attention. Calculate softmax stably by row.
import numpy as np
def gated_xattn_block(x, media, alpha):
  pass
Shift+Enter to run
Numeric
With 4096 image tokens and 512 text tokens, how many times more scores does concatenated self-attention compute than a 64-latent read over the image?
Quiz
What test helps detect whether a policy uses the instruction?
Quiz
What initial design facilitates combining a 30 Hz camera and 1 kHz force sensor?
Key idea
Fusion must specify what information crosses, what it costs, and how the policy behaves when a modality changes or is missing.

Sources: FiLM, Perceiver, Perceiver IO, Flamingo, multimodal imbalance and attention bottlenecks.