attention-map-diffusers

wooyeolbaekMIT活跃维护

为 Hugging Face diffusers 提供注意力图提取与可视化工具,方便查看 Stable Diffusion 文生图时文本如何影响图像区域。

attention map tools for huggingface/diffusers

v1.0.0发布于 2026-08-07 10:56 UTC415star27fork同步于 2026-11-07 07:30 UTC

怎么上手

由 README 提炼,执行前请确认
pip install attention-map-diffusers==1.0.0
硬件要求按 README 说明

README 未说明具体显存要求;示例代码用 torch.bfloat16 并 .to("cuda") 运行,视频示例提供 offload="cpu" 与 max_capture_bytes 上限以缓解显存/内存压力。

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

抓取并可视化 Diffusers 图像/视频管线的注意力图,看清模型到底关注了哪里

为 Hugging Face diffusers 提供注意力图提取与可视化工具,方便查看 Stable Diffusion 文生图时文本如何影响图像区域。

核心能力

  • 支持 text→text、text→image、image→text、image→image 四类关系
  • 视频管线可抓取 video→text 与 video→video 时空自注意力
  • 用 AttentionCapture 上下文管理器挂载到现有 pipeline
  • 默认保留末时间步与 head 均值,可开关全时间步/全层
  • 输出 PNG/GIF 注意力图与叠加图,附 metadata.json 溯源

容易踩的坑

需 Python 3.10+ 且 diffusers>=0.39.0,版本不够会装不上或跑不通;模型权重需从 Hugging Face 另行下载,首次运行会拉取大文件;默认 8 GiB 累计抓取上限,抓全时间步/全层需调大或加 --save-layer-maps 前先评估内存。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

2 个版本v1.0.0
  1. v1.0.0最新正式版2026-08-07 · 2026-08-07 10:56 UTC
  2. v0.1.52026-01-19 · 2026-01-19 18:11 UTC
    查看更新说明

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    attention-map-diffusers

    Relation-aware attention capture and visualization for Hugging Face Diffusers image and video pipelines.

    PyPI CI DOI License: MIT Hugging Face Space

    Visualization

    Image · FLUX.2 Klein

    Prompt: Editorial wildlife photograph of a red fox wearing round glasses beside a glowing blue lantern in a snowy pine forest at dusk.

    text→texttext→image · lantern
    image→text · lanternimage→image · center patch

    Video · Wan 2.1 T2V 1.3B

    Prompt: A cinematic tracking shot of a red fox running across pristine snow in a pine forest, detailed fur, natural winter light, smooth motion, stable camera.

    video→text · fox

    video→video · center patch

    Wan exposes cross-attention (video→text) and spatial-temporal self-attention (video→video), so the table shows every relation in its denoiser.

    Spatial examples are attention overlays, so the generated source is not shown again. Video maps preserve the patch grid as (T,H,W); each GIF also has per-frame PNG output. Spatial labels are off by default.

    Compatible models

    Requires Python 3.10+ and diffusers>=0.39.0.

    KeyCheckpointRelations
    flux2-kleinblack-forest-labs/FLUX.2-klein-4Bimage/text all
    z-image-turboTongyi-MAI/Z-Image-Turboimage/text all
    prx-pixelPhotoroom/prxpixel-t2iimage→text, image→image
    flux-schnellblack-forest-labs/FLUX.1-schnellimage/text all
    flux-devblack-forest-labs/FLUX.1-devimage/text all
    sd3-5stabilityai/stable-diffusion-3.5-mediumimage/text all
    sd3stabilityai/stable-diffusion-3-medium-diffusersimage/text all
    sanaEfficient-Large-Model/Sana_1600M_1024px_diffusersimage→text, image→image
    sdxlstabilityai/stable-diffusion-xl-base-1.0image→text, image→image
    sdsd2-community/stable-diffusion-2-1image→text, image→image
    cogvideox-2bTHUDM/CogVideoX-2bvideo/text all
    wan2.1-t2v-1.3bWan-AI/Wan2.1-T2V-1.3B-Diffusersvideo→text, video→video
    hunyuan-video-1.5hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_t2vvideo/text all

    “image/text all” is text→text, text→image, image→text, and image→image. “video/text all” is text→text, text→video, video→text, and video→video.

    Install

    pip install attention-map-diffusers==1.0.0
    

    Image quick start

    import torch
    from diffusers import Flux2KleinPipeline
    from attention_map_diffusers import AttentionCapture, text_tokenizers
    
    prompt = "A red fox beside a glowing blue lantern in a snowy forest."
    pipe = Flux2KleinPipeline.from_pretrained(
        "black-forest-labs/FLUX.2-klein-4B", torch_dtype=torch.bfloat16
    ).to("cuda")
    
    with AttentionCapture(
        pipe,
        relations=["text->text", "text->image", "image->text", "image->image"],
        offload="cuda",
    ) as capture:
        images = pipe(prompt=[prompt], num_inference_steps=4).images
    
    capture.compute().save(
        "outputs/attention", tokenizer=text_tokenizers(pipe),
        prompts=[prompt], images=images,
    )
    

    Video quick start

    import torch
    from diffusers import WanPipeline
    from attention_map_diffusers import AttentionCapture, VisualizationConfig, text_tokenizers
    
    prompt = "A cinematic tracking shot of a red fox running across snow in a pine forest."
    steps = 50
    pipe = WanPipeline.from_pretrained(
        "Wan-AI/Wan2.1-T2V-1.3B-Diffusers", torch_dtype=torch.bfloat16
    ).to("cuda")
    pipe.scheduler.set_timesteps(steps, device="cuda")
    last_timestep = [float(pipe.scheduler.timesteps[-1])]
    
    with AttentionCapture(
        pipe,
        relations=["video->text", "video->video"],
        timesteps=last_timestep,
        relation_query_indices={"video->video": "center"},
        offload="cpu",
        max_capture_bytes=16 * 1024**3,
    ) as capture:
        videos = pipe(
            prompt=[prompt], num_inference_steps=steps,
            height=480, width=832, num_frames=81,
        ).frames
    
    for component in pipe.components.values():
        if isinstance(component, torch.nn.Module):
            component.to("cpu")
    torch.cuda.empty_cache()
    capture.compute(compute_device="cuda").save(
        "outputs/attention", tokenizer=text_tokenizers(pipe),
        prompts=[prompt], videos=videos,
        visualization_config=VisualizationConfig(max_items=16, video_fps=16),
    )
    

    The shared runner contains native model defaults and reproducible metadata:

    python demo/run_attention_demo.py --model flux2-klein --relations all
    python demo/run_attention_demo.py --model wan2.1-t2v-1.3b --relations all
    

    Output and controls

    attention/
      metadata.json                         # provenance + capture settings
      raw/<relation>/*.pt                   # only with --save-raw
      raw-components/<relation>/<encoder>/ # token-concatenated encoders
      visuals/<relation>/aggregate/batch-000/
        maps/*.png                          # image attention
        maps/*.gif                          # video attention
        maps/<encoder>/*                    # token-concatenated encoders
        maps/<item>/frames/*.png
        overlays/                           # generated-media overlays, separate
    
    • The final timestep and head mean are retained by default.
    • Use --capture-timesteps all and --save-layer-maps for every timestep and layer. The default 8 GiB cumulative capture guard prevents silent RAM/VRAM exhaustion.
    • Every image→image query patch is rendered by default. Video→video defaults to the center query patch because a full (query T×H×W)² tensor is impractical; use --large-relation-query-indices sample:9 or all explicitly.
    • Raw .pt tensors are optional and are never required for visualization.
    • CFG stored as separate denoiser calls (HunyuanVideo 1.5) is tagged per call; visualizations use the conditional call by default while raw capture keeps both.
    • Token-axis concatenation is preserved. SD3 saves fused-CLIP and T5 maps separately (including all four text→text component pairs); HunyuanVideo 1.5 separates ByT5 and MLLM after its mask-based token reordering and records its two MLLM token-refiner layers as MLLM→MLLM maps. Feature-axis fusion such as SDXL CLIP-L+G remains one mathematically inseparable map.
    • Capture fails with a layer/processor report if any denoiser attention module is unsupported, preventing silently incomplete results.
    • Use --show-spatial-labels only when token/patch titles are wanted.

    Validation

    python -m pytest -q
    python demo/run_attention_demo.py --model all --relations all --dry-run
    python demo/audit_attention_coverage.py --model all
    python demo/validate_generation_parity.py --model cogvideox-2b --num-frames 9
    

    Citation

    @software{baek_attention_map_diffusers_2026,
      author = {Baek, Wooyeol and Baek, Seungyeol},
      title = {attention-map-diffusers},
      version = {1.0.0},
      year = {2026},
      publisher = {Zenodo},
      doi = {10.5281/zenodo.18304023},
      url = {https://doi.org/10.5281/zenodo.18304023}
    }
    

    MIT License · CITATION.cff