Search

Search papers and lessons

Decoupled Cross-Attention

Level 4 · 13 min read

Decoupled cross-attention gives a frozen image model a second attention layer for image features, summed with the original text attention, so new inputs can be added without retraining the base.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Architectures
  • Discrete math
  • Linear algebra
  • Neural network basics
  • ReadReady to readNot yet

TL;DR

A large generative model is often trained on text, and you may later want it to also respond to an image. Decoupled cross-attention adds a second attention layer next to each existing text attention layer. The new layer reads only the image features and its output is added to the text output. The base model stays frozen, so only the small new weights are trained, using the same denoising loss as the base model. The method is the core of the IP-Adapter, which gives a text-to-image diffusion model an image prompt with about 22M trainable parameters.

Builds on: Attention Mechanism, Latent Diffusion Model · Leads to: IP-Adapter: Text Compatible Image Prompt Adapter for Diffusion Models

Where it's used

Image prompts for Stable Diffusion. The IP-Adapter was built on Stable Diffusion v1.5, a text-to-image Latent Diffusion Model with 16 cross-attention layers in its U-Net. The adapter adds one image cross-attention layer beside each of the 16. A user can then supply a reference picture and get new images in its style or with its content, while still writing a text prompt.

Reusing one adapter on related models. The paper reports that an adapter trained on the base model also works on other models fine-tuned from the same base, without retraining. This matters for communities that share many fine-tuned checkpoints of one architecture.

Combining image and text control. Because the text and image attention outputs are separate and simply summed, a weight can scale the image part at inference time. The paper uses this to balance the two prompts, and to combine the adapter with structure controls such as ControlNet.

How it works

Consider one attention layer in the image model. It has a set of query vectors (one per spatial position of the image being drawn) and a text prompt that has been turned into vectors. The original layer lets each query look up the text. The decoupled version runs a second lookup on image features and adds the two results.

  1. Start with the query vectors Z\mathbf{Z} coming from the image being generated. Each row is one spatial position. Check: the number of rows is the number of positions, not the number of words.
  2. Run the original text attention. The text tokens give keys and values. The layer computes how much each position should read from each text token, then returns a weighted mix of the text values. This is the text output.
  3. Take the image features (a small set of vectors made from a reference picture by a CLIP image encoder and a small projection network) and make a second pair of keys and values from them, using two new weight matrices Wk′\mathbf{W}'_k and Wv′\mathbf{W}'_v. The query matrix ZWq\mathbf{Z}\mathbf{W}_q is reused as it is. Check: the query is shared, so only two new matrices are needed per layer.
  4. Run the same attention rule with the image keys and values. This gives the image output, a weighted mix of image values.
  5. Add the image output to the text output. Check: if the image output is zero, the layer gives exactly the original text result.
  6. Pass the sum on as usual. Repeat for each of the cross-attention layers in the model.
  7. During training, freeze everything from the base model. Only Wk′\mathbf{W}'_k and Wv′\mathbf{W}'_v (and a small projection network that makes the image features) are updated.

The diagram shows the two parallel paths inside one layer.

flowchart LR
  Z["image query Z W_q"] --> A1["attention with text keys and values"]
  C["text tokens"] --> A1
  Z --> A2["attention with image keys and values"]
  I["image tokens"] --> A2
  A1 --> SUM["sum"]
  A2 -->|"times lambda"| SUM
  SUM --> OUT["next layer"]

The plot shows how the final output changes as the image weight λ\lambda goes from 0 to 1 in the worked examples below. It is a straight line, because the output is a text term plus λ\lambda times a fixed image term.

00.20.40.60.8101234image weight lambdalayer output (one number)
  • output as image weight grows
At lambda = 0 the layer is the original text-only layer. Raising lambda adds more of the image term.

The math

Definition

Definition: Decoupled cross-attention

Let Z\mathbf{Z} be the query matrix from the image, ct\mathbf{c}_t the text features and ci\mathbf{c}_i the image features. Define Q=ZWq\mathbf{Q} = \mathbf{Z}\mathbf{W}_q, K=ctWk\mathbf{K} = \mathbf{c}_t\mathbf{W}_k, V=ctWv\mathbf{V} = \mathbf{c}_t\mathbf{W}_v, K′=ciWk′\mathbf{K}' = \mathbf{c}_i\mathbf{W}'_k and V′=ciWv′\mathbf{V}' = \mathbf{c}_i\mathbf{W}'_v. The output of the layer is

Znew=Softmax⁡ ⁣(QK⊤d)V+λ Softmax⁡ ⁣(QK′⊤d)V′\mathbf{Z}^{\text{new}} = \operatorname{Softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^{\top}}{\sqrt{d}}\right)\mathbf{V} + \lambda \, \operatorname{Softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}'^{\top}}{\sqrt{d}}\right)\mathbf{V}'

where dd is the width of the key vectors and λ\lambda is a scalar weight. The paper sets λ=1.0\lambda = 1.0 when the image is the only prompt, and lets you lower it to balance image and text at inference.

In words: the first term is ordinary cross-attention on text, and the second term is the same operation on image features. The two use the same query, so the only new parameters are Wk′\mathbf{W}'_k and Wv′\mathbf{W}'_v. The Softmax turns each row of scores into weights that sum to one. The division by d\sqrt{d} keeps the scores from growing with the key width, as in standard attention.

Step 2 in symbols: the text term

A=Softmax⁡(QK⊤/d)\mathbf{A} = \operatorname{Softmax}(\mathbf{Q}\mathbf{K}^{\top}/\sqrt{d}) is a matrix with one row per query position and one column per text token. Each row sums to 1. The text output is AV\mathbf{A}\mathbf{V}.

Step 3 in symbols: the new projections

The paper initialises Wk′\mathbf{W}'_k and Wv′\mathbf{W}'_v from the original Wk\mathbf{W}_k and Wv\mathbf{W}_v. The paper says this speeds up convergence: the image path starts with the same weights the text path already has. Because the image features have the same width as the text features, the same matrix shapes apply.

Step 5 in symbols: the sum

If λ=0\lambda = 0, the second term vanishes and Znew\mathbf{Z}^{\text{new}} equals the original text-only output. This is the reason the adapter does not damage the base model at the start of training.

Step 7 in symbols: what is trained

Only Wk′\mathbf{W}'_k, Wv′\mathbf{W}'_v and the projection network that produces the image features are optimised. The training loss is the denoising loss of the base diffusion model, with the image features added as a condition:

L=E∥ϵ−ϵθ(xt,ct,ci,t)∥2\mathcal{L} = \mathbb{E}\left\|\boldsymbol{\epsilon} - \boldsymbol{\epsilon}_{\theta}(\mathbf{x}_t, \mathbf{c}_t, \mathbf{c}_i, t)\right\|^2

Here ϵ\boldsymbol{\epsilon} is the noise added to a training image, xt\mathbf{x}_t is the noisy image at step tt, and ϵθ\boldsymbol{\epsilon}_{\theta} is the network's guess at that noise. The gradient flows only through the image path; the text path and the frozen weights act as fixed functions.

Worked examples

Example
1. One query, one token each (tiny)

Use a single query, a single text token and a single image token. With one key each, the softmax has only one entry, so its weight is 1.

  1. Text value: v=2v = 2. The text attention output is 1⋅2=21 \cdot 2 = 2.
  2. Image value: v′=4v' = 4. The image attention output is 1⋅4=41 \cdot 4 = 4.
  3. Set λ=1\lambda = 1. The layer output is 2+1⋅4=62 + 1 \cdot 4 = 6.
  4. Set λ=0\lambda = 0. The layer output is 2+0⋅4=22 + 0 \cdot 4 = 2, which is the text-only result.

Interpretation: with one token each, the layer simply adds the two values, scaled by λ\lambda. The weight λ\lambda is a dial between "text only" and "text plus image".

Example
2. Two text tokens and two image tokens (standard)

Use one query with scalar key and value (so d=1d = 1 and d=1\sqrt{d} = 1). Text keys are K=[0, 1]K = [0,\ 1] with values V=[2, 0]V = [2,\ 0]. Image keys are K′=[1, 1]K' = [1,\ 1] with values V′=[4, 2]V' = [4,\ 2]. The query is q=1q = 1.

  1. Text scores: qK=[0, 1]q K = [0,\ 1].
  2. Text softmax: e0=1e^0 = 1 and e1=2.718e^1 = 2.718, total 3.7183.718. Weights [0.2689, 0.7311][0.2689,\ 0.7311].
  3. Text output: 0.2689⋅2+0.7311⋅0=0.53780.2689 \cdot 2 + 0.7311 \cdot 0 = 0.5378.
  4. Image scores: qK′=[1, 1]q K' = [1,\ 1]. Softmax gives [0.5, 0.5][0.5,\ 0.5].
  5. Image output: 0.5⋅4+0.5⋅2=3.00.5 \cdot 4 + 0.5 \cdot 2 = 3.0.
  6. With λ=1\lambda = 1: 0.5378+3.0=3.53780.5378 + 3.0 = 3.5378.
  7. With λ=0.5\lambda = 0.5: 0.5378+0.5⋅3.0=2.03780.5378 + 0.5 \cdot 3.0 = 2.0378.

Interpretation: the text term favours the second text token, which has the larger score, so its value 00 pulls the output down. The image term has equal scores, so it averages its two values. Raising λ\lambda moves the output toward the image average, which is the same effect the plot shows.

Example
3. Parameter count for one layer (realistic)

The IP-Adapter paper uses Stable Diffusion v1.5, which has 16 cross-attention layers, and reports about 22M trainable parameters for the whole adapter. Take one layer whose text features have width 768 and whose attention width is 320 (a layout chosen for this example, not read from the paper).

  1. The new key matrix Wk′\mathbf{W}'_k maps 768 inputs to 320 outputs, so it has 768×320=245,760768 \times 320 = 245{,}760 entries.
  2. The new value matrix Wv′\mathbf{W}'_v has the same shape, so it has another 245,760245{,}760 entries.
  3. One layer therefore adds 245,760+245,760=491,520245{,}760 + 245{,}760 = 491{,}520 trainable entries.
  4. Across 16 layers with this width: 16×491,520=7,864,32016 \times 491{,}520 = 7{,}864{,}320, about 7.9M.
  5. The paper's 22M also counts the projection network, a linear layer and a layer normalisation that turn the global image embedding into 4 image tokens.
  6. Our layout does not reach 22M. The paper gives no per-layer widths, and in SD v1.5 the attention width is larger in deeper blocks, so the real count is higher. Treat 7.9M as the cost of one narrow layout, not the paper's figure.

Interpretation: the adapter's trainable weights are dominated by the key and value matrices, which is why the method is cheap. Most of the base model's roughly 860M parameters never change.

Try it: the paper's table lists 22M trainable parameters for the IP-Adapter and about 860M for an SD-sized model that is fully fine-tuned for image prompts. What share of the model is trainable with the adapter? Answer: 22/860≈0.02622 / 860 \approx 0.026, about 2.6 percent. This is the sense in which the paper calls the adapter lightweight.

Common mistakes and tradeoffs

It is tempting to think that image features should be concatenated with the text tokens and fed to the same attention layer. That is the simple alternative the paper tested. In fact the paper found it insufficiently effective: its comparison (Figure 10) shows lower image quality and weaker consistency with the image prompt. The paper does not prove why; one plausible reason is that the image tokens must share the softmax with the text tokens. Separate layers keep each source's weights in its own path.

It is tempting to think that the sum of two attention outputs is an arbitrary choice. In fact the sum is what lets λ=0\lambda = 0 recover the base model exactly, and it is what makes the image weight adjustable after training. A concatenated design cannot be turned down this cleanly.

It is tempting to think that adding parameters always costs quality. The paper's point is the reverse: its 22M adapter scores CLIP-T 0.588 and CLIP-I 0.828 on COCO, against 0.587 and 0.830 for the 860M Versatile Diffusion, and 0.548 and 0.760 for the 860M SD Image Variations. The gain comes from keeping the pretrained text path intact and learning only the image path.

When to use it. Use decoupled cross-attention when a frozen model already has cross-attention layers over one kind of context, and you want to add a second kind of context with few trainable weights. It also helps when the adapter should be reusable across related checkpoints.

When not to use it. If the model has no cross-attention layers, there is no natural place for the second path. If the new input is very different from the training data, or must change the model's core behaviour rather than add a signal, a full fine-tune or a Low-Rank Adaptation (LoRA) of the base weights may be a better fit. The paper also notes a limit: the adapter reproduces the style and content of the reference image but cannot make images highly consistent with one specific subject the way DreamBooth, which fine-tunes the model on that subject, can.

Alternatives. Other adapters such as ControlNet and T2I-adapter add a separate network next to the model rather than a parallel attention path. The Adapter Tuning family includes these choices. The Multi-Head Attention idea of running several attention paths side by side is the closest relative, but there the paths share one input and the outputs are combined inside the same layer.

History

Cross-attention, where one sequence queries another, was part of the encoder-decoder attention that Vaswani and colleagues introduced in 2017. Latent diffusion models later used cross-attention layers in their U-Net to read a text encoder.

Earlier image-prompt systems either fine-tuned the text-to-image model on image embeddings (SD Image Variations, Stable unCLIP), which the paper notes is costly and loses the text ability, or used lightweight adapters such as ControlNet and T2I-adapter that the paper found less effective for image prompts. In 2023 the IP-Adapter paper by Ye and colleagues proposed the separate image attention path, which keeps the base weights frozen. It was posted as an arXiv preprint in August 2023.

Recap

  • A frozen image model's cross-attention layers read text features. Decoupled cross-attention adds a second cross-attention path that reads image features.
  • Both paths share the same query. Only the image path's key and value matrices are new.
  • The two outputs are summed, with a weight λ\lambda on the image term, so λ=0\lambda = 0 gives back the base model.
  • The method needs only about 22M trainable weights, so it trains cheaply and can be reused across related models.
  • The IP-Adapter is the main application: it gives Stable Diffusion an image prompt with about 22M trainable parameters.

Read next: IP-Adapter: Text Compatible Image Prompt Adapter for Diffusion Models for the full experiments, and Multi-Head Attention for the attention idea that the two paths extend.

Check yourself

QuestionRecall: in decoupled cross-attention, which matrices are trained, and which are left frozen?Show answer

Only the new image-path key and value matrices Wk′\mathbf{W}'_k and Wv′\mathbf{W}'_v (plus the small image projection network) are trained. The original text query, key and value matrices and all the base model's weights stay frozen.

QuestionComputation: one query with scalar key 0 and value 4 on the text path, and the same query with image key 0 and image value 2. The text path has only one token with weight 1. What is the output with λ=0.5\lambda = 0.5?Show answer

The text output is 1⋅4=41 \cdot 4 = 4. The image output is 1⋅2=21 \cdot 2 = 2. The layer output is 4+0.5⋅2=54 + 0.5 \cdot 2 = 5.

QuestionWhy: the paper initialises Wk′\mathbf{W}'_k and Wv′\mathbf{W}'_v from Wk\mathbf{W}_k and Wv\mathbf{W}_v rather than at random. What does this do for training?Show answer

It starts the image path with the same behaviour the text path already has, so the image output is a sensible attention result from the first step. This speeds up convergence, because the adapter does not have to learn basic attention behaviour from scratch while the base model is frozen.

QuestionApplied: a user loads the IP-Adapter on a fine-tuned checkpoint and the image prompt is too strong, so the output ignores the text. Using only the formula, what would you adjust, and what happens at the extremes?Show answer

Lower λ\lambda. The output is a text term plus λ\lambda times an image term, so a smaller λ\lambda weakens the image contribution and lets the text term dominate. At λ=0\lambda = 0 the layer is the original text-only layer, so the image prompt has no effect. At large λ\lambda the image term dominates.

Sources