SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2412.02237 · ICLR · 2025

Cross-Attention Head Position Patterns Can Align with Human Visual Concepts in Text-to-Image Generative Models

Wonjong Rhee, Jungwon Park, Jungmin Ko, Dongnam Byun, Jangwon Suh

arXiv · PDF · Open in the Atlas

Code that ran

3 of 4 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (1 of them constructed an object rather than computing a result; 1 honoured the contract we drafted, 0 violated it and 1 has no contract verdict; 1 failure of our instrument; 1 no recorded run), measured 2026-11-23; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2412.02237.json · badge: /api/ran/2412.02237.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
snu-drl/hrv canonical (classifier label)
classifier basis: classifier_2025
3 ran · 1 no recorded run
FunctionStatusWhere it lives
AttentionStore Ran
ran on a synthesized input · constructed an object; no result was computed
snu-drl/hrv/head_relevance_calculation.py
code served (permissive licence) · get_code("e76c358ecdf7b5cd")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, AttentionStore: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

torch.manual_seed(0)

class AttentionControl:
    def step_callback(self, x_t):
        return x_t

    def between_steps(self):
        return

    @property
    def num_uncond_att_layers(self):
        return 0

    def forward(self, attn, is_cross: bool, place_in_unet: str):
        raise NotImplementedError

    def __call__(self, attn, is_cross: bool, place_in_unet: str):
        if self.cur_att_layer >= self.num_uncond_att_layers:
            h = attn.shape[0]
            attn[h // 2:] = self.forward(attn[h // 2:], is_cross, place_in_unet)
        self.cur_att_layer += 1
        if self.cur_att_layer == self.num_att_layers + self.num_uncond_att_layers:
            self.cur_att_layer = 0
            self.cur_step += 1
            self.between_steps()
        return attn

    def reset(self):
        self.cur_step = 0
        self.cur_att_layer = 0

    def __init__(self):
        self.cur_step = 0
        self.num_att_layers = -1
        self.cur_att_layer = 0


class AttentionStore(AttentionControl):

    @staticmethod
    def get_empty_store():
        return {'down_cross': [], 'mid_cross': [], 'up_cross': [], 'down_self': [], 'mid_self': [], 'up_self': []}

    def forward(self, attn, is_cross: bool, place_in_unet: str):
        key = f"{place_in_unet}_{('cross' if is_cross else 'self')}"
        if attn.shape[1] <= 32 ** 2:
            self.step_store[key].append(attn)
        return attn

    def between_steps(self):
        if len(self.attention_store) == 0:
            self.attention_store = self.step_store
        else:
            for key in self.attention_store:
                for i in range(len(self.attention_store[key])):
                    self.attention_store[key][i] += self.step_store[key][i]
        self.step_store = self.get_empty_store()

    def get_average_attention(self):
        average_attention = {key: [item / self.cur_step for item in self.attention_store[key]] for key in self.attention_store}
        return average_attention

    def reset(self):
        super(AttentionStore, self).reset()
        self.step_store = self.get_empty_store()
        self.attention_store = {}

    def __init__(self):
        super(AttentionStore, self).__init__()
        self.step_store = self.get_empty_store()
        self.attention_store = {}


ARGS = {}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type AttentionStore — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a AttentionStore output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
aggregate_attention Ran
ran, honoured the contract we drafted
snu-drl/hrv/applications/attend_and_excite_hrv.py
code served (permissive licence) · get_code("ca57b6c2d536bc73")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned Tensor, ndim 3, dtype family float, shape (4, 4, 4) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import abc

torch.manual_seed(0)

LOW_RESOURCE = False

class AttentionControl(abc.ABC):

    def step_callback(self, x_t):
        return x_t

    def between_steps(self):
        return

    @property
    def num_uncond_att_layers(self):
        return self.num_att_layers if LOW_RESOURCE else 0

    @abc.abstractmethod
    def forward(self, attn, is_cross: bool, place_in_unet: str, layer, num_heads):
        raise NotImplementedError

    def __call__(self, attn, is_cross: bool, place_in_unet: str, layer, num_heads):
        if self.cur_att_layer >= self.num_uncond_att_layers:
            self.forward(attn, is_cross, place_in_unet, layer, num_heads)
        self.cur_att_layer += 1
        if self.cur_att_layer == self.num_att_layers + self.num_uncond_att_layers:
            self.cur_att_layer = 0
            self.cur_step += 1
            self.between_steps()
        return attn

    def reset(self):
        self.cur_step = 0
        self.cur_att_layer = 0

    def __init__(self):
        self.cur_step = 0
        self.num_att_layers = -1
        self.cur_att_layer = 0

class AttentionStore(AttentionControl):

    @staticmethod
    def get_empty_store():
        return {'down_cross': [], 'mid_cross': [], 'up_cross': [], 'down_self': [], 'mid_self': [], 'up_self': []}

    def forward(self, attn, is_cross: bool, place_in_unet: str, layer, num_heads):
        key = f"{place_in_unet}_{('cross' if is_cross else 'self')}"
        if attn.shape[1] <= 32 ** 2:
            self.step_store[key].append(attn)
        return attn

    def between_steps(self):
        self.attention_store = self.step_store
        self.step_store = self.get_empty_store()

    def get_average_attention(self):
        average_attention = self.attention_store
        return average_attention

    def reset(self):
        super(AttentionStore, self).reset()
        self.step_store = self.get_empty_store()
        self.attention_store = {}

    def __init__(self):
        super(AttentionStore, self).__init__()
        self.step_store = self.get_empty_store()
        self.attention_store = {}

def aggregate_attention(attention_store, res, from_where, is_cross, select, prompts=['']):
    """For selected locations (from_where: 'down', 'mid', 'up') and selected resolutions (res: ex. 16)
       returns the average attention map for the selected prompt (sel: ex. 0)."""
    out = []
    attention_maps = attention_store.get_average_attention()
    num_pixels = res ** 2
    for location in from_where:
        for item in attention_maps[f"{location}_{('cross' if is_cross else 'self')}"]:
            if item.shape[1] == num_pixels:
                cross_maps = item.reshape(len(prompts), -1, res, res, item.shape[-1])[select]
                out.append(cross_maps)
    out = torch.cat(out, dim=0)
    out = out.sum(0) / out.shape[0]
    return out

# Create an AttentionStore instance
attention_store = AttentionStore()

# Populate it with some attention maps
# For res=4, num_pixels = 16
# We need attention tensors with shape[1] == 16
# Shape: (batch_size, num_pixels, num_prompts, feature_dim)
# Let's create: (2, 16, 2, 4) where batch=2, num_pixels=16, num_prompts=2, feature_dim=4
attn_tensor_1 = torch.randn(2, 16, 2, 4)
attn_tensor_2 = torch.randn(2, 16, 2, 4)

# Manually set up the attention_store with some data
attention_store.attention_store = {
    'down_cross': [attn_tensor_1],
    'mid_cross': [attn_tensor_2],
    'up_cross': [],
    'down_self': [],
    'mid_self': [],
    'up_self': []
}

ARGS = {
    'attention_store': attention_store,
    'res': 4,
    'from_where': ['down', 'mid'],
    'is_cross': True,
    'select': 0,
    'prompts': ['prompt1', 'prompt2']
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 3, dtype family float, shape (4, 4, 4) — shape (4, 4, 4) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
latent2image Ran
ran; our contract draft was wrong, not the code
snu-drl/hrv/applications/attend_and_excite_hrv.py
code served (permissive licence) · get_code("e3c3bb87bbe9b4a7")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned ndarray, ndim 4, dtype family int, shape (2, 32, 32, 3) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
import numpy as np

torch.manual_seed(0)

class MockVAE(nn.Module):
    def __init__(self):
        super().__init__()
        self.decoder_layer = nn.Linear(4, 768)
    
    def decode(self, latents):
        # latents shape: (batch, channels, height, width)
        # We need to return a dict with 'sample' key containing decoded image
        batch_size = latents.shape[0]
        # Return a tensor of shape (batch, 3, 32, 32) for RGB image
        sample = torch.randn(batch_size, 3, 32, 32)
        return {'sample': sample}

vae = MockVAE()
latents = torch.randn(2, 4, 8, 8)

ARGS = {
    'vae': vae,
    'latents': latents
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type ndarray, ndim 4, dtype family int, shape (2, 32, 32, 3) — shape (2, 32, 32, 3) as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
AttentionControl Not yet run
unverified (harvested, no recorded run)
snu-drl/hrv/head_relevance_calculation.py
code served (permissive licence) · get_code("fe61a29c1374cc61")
How it ran

no invocation recorded.

Also present in other papers' code

Of 4 samples lifted from this paper's linked repositories, 4 carry a function identity and 0 do not. Of the 4 distinct functions with an identity, 2 are also present in other papers whose code we hold (2 with at least one paper dated earlier, 0 the same month, 0 later) and 2 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

FunctionAlso present inEarliest-datedOthers named
latent2image 13 other papers
12 dated earlier, 1 same year, order not determinable
2305.15581 (2023-05)
Unsupervised Semantic Correspondence Using Stable Diffusion
2305.19164 (2023-05)
LANCE: Stress-testing Visual Models by Generating Language-guided Counterfactual Images
2308.06160 (2023-08)
DatasetDM: Synthesizing Data with Perception Annotations Using Diffusion Models
and 10 more not named here
AttentionStore
brick of this paper's assembly: entry
1 other paper
1 dated earlier
2408.05159 (2024-08)
EasyInv: Toward Fast and Better DDIM Inversion

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-23.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Recent text-to-image diffusion models leverage cross-attention layers, which have been effectively utilized to enhance a range of visual generative tasks. However, our understanding of cross-attention layers remains somewhat limited. In this study, we introduce a mechanistic interpretability approach for diffusion models by constructing Head Relevance Vectors (HRVs) that align with human-specified visual concepts. An HRV for a given visual concept has a length equal to the total number of cross-attention heads, with each element representing the importance of the corresponding head for the given visual concept. To validate HRVs as interpretable features, we develop an ordered weakening analysis that demonstrates their effectiveness. Furthermore, we propose concept strengthening and concept adjusting methods and apply them to enhance three visual generative tasks. Our results show that HRVs can reduce misinterpretations of polysemous words in image generation, successfully modify five challenging attributes in image editing, and mitigate catastrophic neglect in multi-concept generation. Overall, our work provides an advancement in understanding cross-attention layers and introduces new approaches for fine-controlling these layers at the head level 1 .

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2412.02237")
get_code_for_paper("2412.02237")
have("2412.02237")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2412.02237.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2412.02237.svg)](https://syntology.ai/paper/2412.02237)

Connect an agent — have() is free.