模块更新于 2026-11-21· 浏览 2· 下载 0
MV-Adapter 视图行注意力
保留原注意力通路,另设跨视图行注意力分支,联合建模不同视图中同一行的特征。还可通过独立的参考图像交叉注意力分支补充外观信息,各分支分别控制融合强度。
结构图

保留原注意力通路,另设跨视图行注意力分支,联合建模不同视图中同一行的特征。还可通过独立的参考图像交叉注意力分支补充外观信息,各分支分别控制融合强度。
论文信息
- 论文:MV-Adapter: Multi-View Consistent Image Generation Made Easy
- 出处:ICCV 2025
核心痛点
预训练文生图模型擅长生成单张图像,但不同视角独立生成时,物体外观和结构容易不一致,需要引入跨视图的信息交互。
模块亮点
- 保留原注意力通路,另设跨视图行注意力分支,联合建模不同视图中同一行的特征。还可通过独立的参考图像交叉注意力分支补充外观信息,各分支分别控制融合强度。
适用场景
适合预训练扩散模型中的多视图图像生成研究,可结合相机或几何条件进行实验。其他视觉任务需单独验证,单个注意力处理器不能替代完整生成流程。
插入位置建议
- 可在扩散网络对应注意力层中接入多视图处理器。检查Token能否还原为目标网格、批次排列是否与视图数一致,以及有条件和无条件分组是否正确;参考分支开启时还需提供匹配的缓存。
适用任务
- 预训练扩散模型中的多视图图像生成研究
- 可结合相机或几何条件进行实验。其他视觉任务需单独验证
- 单个注意力处理器不能替代完整生成流程
完整代码
mvadapter.py
"""40_MVAdapter_ICCV2025: 官方核心模块的单文件提取。
官方源码: https://github.com/huanngzh/MV-Adapter/blob/4277e0018232bac82bb2c103caf0893cedb711be/mvadapter/models/attention_processor.py
源码 SHA256: bd7fe7014e3c7d50bce9e124a963e5a3a3fb04a4c9ef1797f580b5e8e9a11500
提取核心: DecoupledMVRowSelfAttnProcessor2_0
整理说明: 保留官方行注意力、多视图分支和可选参考图像交叉注意力。main 使用两视图/CFG 布局;N必须是平方数,batch 与 num_views 布局需符合原实现。依赖 torch、einops、diffusers。
形状验证只说明接口可用,不代表已复现论文指标。初始化/辅助输入遵循原仓库;
需要语义特征、掩码、时间等条件的模块不能省略对应条件。
"""
from __future__ import annotations
# Upstream repository license: LICENSE
# Apache License
# Version 2.0, January 2004
# http://www.apache.org/licenses/
#
# TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
#
# 1. Definitions.
#
# "License" shall mean the terms and conditions for use, reproduction,
# and distribution as defined by Sections 1 through 9 of this document.
#
# "Licensor" shall mean the copyright owner or entity authorized by
# the copyright owner that is granting the License.
#
# "Legal Entity" shall mean the union of the acting entity and all
# other entities that control, are controlled by, or are under common
# control with that entity. For the purposes of this definition,
# "control" means (i) the power, direct or indirect, to cause the
# direction or management of such entity, whether by contract or
# otherwise, or (ii) ownership of fifty percent (50%) or more of the
# outstanding shares, or (iii) beneficial ownership of such entity.
#
# "You" (or "Your") shall mean an individual or Legal Entity
# exercising permissions granted by this License.
#
# "Source" form shall mean the preferred form for making modifications,
# including but not limited to software source code, documentation
# source, and configuration files.
#
# "Object" form shall mean any form resulting from mechanical
# transformation or translation of a Source form, including but
# not limited to compiled object code, generated documentation,
# and conversions to other media types.
#
# "Work" shall mean the work of authorship, whether in Source or
# Object form, made available under the License, as indicated by a
# copyright notice that is included in or attached to the work
# (an example is provided in the Appendix below).
#
# "Derivative Works" shall mean any work, whether in Source or Object
# form, that is based on (or derived from) the Work and for which the
# editorial revisions, annotations, elaborations, or other modifications
# represent, as a whole, an original work of authorship. For the purposes
# of this License, Derivative Works shall not include works that remain
# separable from, or merely link (or bind by name) to the interfaces of,
# the Work and Derivative Works thereof.
#
# "Contribution" shall mean any work of authorship, including
# the original version of the Work and any modifications or additions
# to that Work or Derivative Works thereof, that is intentionally
# submitted to Licensor for inclusion in the Work by the copyright owner
# or by an individual or Legal Entity authorized to submit on behalf of
# the copyright owner. For the purposes of this definition, "submitted"
# means any form of electronic, verbal, or written communication sent
# to the Licensor or its representatives, including but not limited to
# communication on electronic mailing lists, source code control systems,
# and issue tracking systems that are managed by, or on behalf of, the
# Licensor for the purpose of discussing and improving the Work, but
# excluding communication that is conspicuously marked or otherwise
# designated in writing by the copyright owner as "Not a Contribution."
#
# "Contributor" shall mean Licensor and any individual or Legal Entity
# on behalf of whom a Contribution has been received by Licensor and
# subsequently incorporated within the Work.
#
# 2. Grant of Copyright License. Subject to the terms and conditions of
# this License, each Contributor hereby grants to You a perpetual,
# worldwide, non-exclusive, no-charge, royalty-free, irrevocable
# copyright license to reproduce, prepare Derivative Works of,
# publicly display, publicly perform, sublicense, and distribute the
# Work and such Derivative Works in Source or Object form.
#
# 3. Grant of Patent License. Subject to the terms and conditions of
# this License, each Contributor hereby grants to You a perpetual,
# worldwide, non-exclusive, no-charge, royalty-free, irrevocable
# (except as stated in this section) patent license to make, have made,
# use, offer to sell, sell, import, and otherwise transfer the Work,
# where such license applies only to those patent claims licensable
# by such Contributor that are necessarily infringed by their
# Contribution(s) alone or by combination of their Contribution(s)
# with the Work to which such Contribution(s) was submitted. If You
# institute patent litigation against any entity (including a
# cross-claim or counterclaim in a lawsuit) alleging that the Work
# or a Contribution incorporated within the Work constitutes direct
# or contributory patent infringement, then any patent licenses
# granted to You under this License for that Work shall terminate
# as of the date such litigation is filed.
#
# 4. Redistribution. You may reproduce and distribute copies of the
# Work or Derivative Works thereof in any medium, with or without
# modifications, and in Source or Object form, provided that You
# meet the following conditions:
#
# (a) You must give any other recipients of the Work or
# Derivative Works a copy of this License; and
#
# (b) You must cause any modified files to carry prominent notices
# stating that You changed the files; and
#
# (c) You must retain, in the Source form of any Derivative Works
# that You distribute, all copyright, patent, trademark, and
# attribution notices from the Source form of the Work,
# excluding those notices that do not pertain to any part of
# the Derivative Works; and
#
# (d) If the Work includes a "NOTICE" text file as part of its
# distribution, then any Derivative Works that You distribute must
# include a readable copy of the attribution notices contained
# within such NOTICE file, excluding those notices that do not
# pertain to any part of the Derivative Works, in at least one
# of the following places: within a NOTICE text file distributed
# as part of the Derivative Works; within the Source form or
# documentation, if provided along with the Derivative Works; or,
# within a display generated by the Derivative Works, if and
# wherever such third-party notices normally appear. The contents
# of the NOTICE file are for informational purposes only and
# do not modify the License. You may add Your own attribution
# notices within Derivative Works that You distribute, alongside
# or as an addendum to the NOTICE text from the Work, provided
# that such additional attribution notices cannot be construed
# as modifying the License.
#
# You may add Your own copyright statement to Your modifications and
# may provide additional or different license terms and conditions
# for use, reproduction, or distribution of Your modifications, or
# for any such Derivative Works as a whole, provided Your use,
# reproduction, and distribution of the Work otherwise complies with
# the conditions stated in this License.
#
# 5. Submission of Contributions. Unless You explicitly state otherwise,
# any Contribution intentionally submitted for inclusion in the Work
# by You to the Licensor shall be under the terms and conditions of
# this License, without any additional terms or conditions.
# Notwithstanding the above, nothing herein shall supersede or modify
# the terms of any separate license agreement you may have executed
# with Licensor regarding such Contributions.
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor,
# except as required for reasonable and customary use in describing the
# origin of the Work and reproducing the content of the NOTICE file.
#
# 7. Disclaimer of Warranty. Unless required by applicable law or
# agreed to in writing, Licensor provides the Work (and each
# Contributor provides its Contributions) on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied, including, without limitation, any warranties or conditions
# of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
# PARTICULAR PURPOSE. You are solely responsible for determining the
# appropriateness of using or redistributing the Work and assume any
# risks associated with Your exercise of permissions under this License.
#
# 8. Limitation of Liability. In no event and under no legal theory,
# whether in tort (including negligence), contract, or otherwise,
# unless required by applicable law (such as deliberate and grossly
# negligent acts) or agreed to in writing, shall any Contributor be
# liable to You for damages, including any direct, indirect, special,
# incidental, or consequential damages of any character arising as a
# result of this License or out of the use or inability to use the
# Work (including but not limited to damages for loss of goodwill,
# work stoppage, computer failure or malfunction, or any and all
# other commercial damages or losses), even if such Contributor
# has been advised of the possibility of such damages.
#
# 9. Accepting Warranty or Additional Liability. While redistributing
# the Work or Derivative Works thereof, You may choose to offer,
# and charge a fee for, acceptance of support, warranty, indemnity,
# or other liability obligations and/or rights consistent with this
# License. However, in accepting such obligations, You may act only
# on Your own behalf and on Your sole responsibility, not on behalf
# of any other Contributor, and only if You agree to indemnify,
# defend, and hold each Contributor harmless for any liability
# incurred by, or claims asserted against, such Contributor by reason
# of your accepting any such warranty or additional liability.
#
# END OF TERMS AND CONDITIONS
#
# APPENDIX: How to apply the Apache License to your work.
#
# To apply the Apache License to your work, attach the following
# boilerplate notice, with the fields enclosed by brackets "[]"
# replaced with your own identifying information. (Don't include
# the brackets!) The text should be enclosed in the appropriate
# comment syntax for the file format. We also recommend that a
# file or class name and description of purpose be included on the
# same "printed page" as the copyright notice for easier
# identification within third-party archives.
#
# Copyright [yyyy] [name of copyright owner]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
from torch import nn
import torch.nn.functional as F
import math
from typing import Optional
from einops import rearrange
from diffusers.models.attention_processor import Attention
from diffusers.utils import deprecate
class DecoupledMVRowSelfAttnProcessor2_0(torch.nn.Module):
"""
Attention processor for Decoupled Row-wise Self-Attention and Image Cross-Attention for PyTorch 2.0.
"""
def __init__(self, query_dim: int, inner_dim: int, num_views: int=1, name: Optional[str]=None, use_mv: bool=True, use_ref: bool=False):
if not hasattr(F, 'scaled_dot_product_attention'):
raise ImportError('DecoupledMVRowSelfAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.')
super().__init__()
self.num_views = num_views
self.name = name
self.use_mv = use_mv
self.use_ref = use_ref
if self.use_mv:
self.to_q_mv = nn.Linear(in_features=query_dim, out_features=inner_dim, bias=False)
self.to_k_mv = nn.Linear(in_features=query_dim, out_features=inner_dim, bias=False)
self.to_v_mv = nn.Linear(in_features=query_dim, out_features=inner_dim, bias=False)
self.to_out_mv = nn.ModuleList([nn.Linear(in_features=inner_dim, out_features=query_dim, bias=True), nn.Dropout(0.0)])
if self.use_ref:
self.to_q_ref = nn.Linear(in_features=query_dim, out_features=inner_dim, bias=False)
self.to_k_ref = nn.Linear(in_features=query_dim, out_features=inner_dim, bias=False)
self.to_v_ref = nn.Linear(in_features=query_dim, out_features=inner_dim, bias=False)
self.to_out_ref = nn.ModuleList([nn.Linear(in_features=inner_dim, out_features=query_dim, bias=True), nn.Dropout(0.0)])
def __call__(self, attn: Attention, hidden_states: torch.FloatTensor, encoder_hidden_states: Optional[torch.FloatTensor]=None, attention_mask: Optional[torch.FloatTensor]=None, temb: Optional[torch.FloatTensor]=None, mv_scale: float=1.0, ref_hidden_states: Optional[torch.FloatTensor]=None, ref_scale: float=1.0, cache_hidden_states: Optional[List[torch.FloatTensor]]=None, use_mv: bool=True, use_ref: bool=True, num_views: Optional[int]=None, *args, **kwargs) -> torch.FloatTensor:
"""
New args:
mv_scale (float): scale for multi-view self-attention.
ref_hidden_states (torch.FloatTensor): reference encoder hidden states for image cross-attention.
ref_scale (float): scale for image cross-attention.
cache_hidden_states (List[torch.FloatTensor]): cache hidden states from reference unet.
"""
if len(args) > 0 or kwargs.get('scale', None) is not None:
deprecation_message = 'The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`.'
deprecate('scale', '1.0.0', deprecation_message)
if num_views is not None:
self.num_views = num_views
if cache_hidden_states is not None:
cache_hidden_states[self.name] = hidden_states.clone()
use_mv = self.use_mv and use_mv
use_ref = self.use_ref and use_ref
residual = hidden_states
if attn.spatial_norm is not None:
hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4:
batch_size, channel, height, width = hidden_states.shape
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
batch_size, sequence_length, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
if attention_mask is not None:
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
if attn.group_norm is not None:
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
query = attn.to_q(hidden_states)
if use_mv:
query_mv = self.to_q_mv(hidden_states)
if use_ref:
query_ref = self.to_q_ref(hidden_states)
if encoder_hidden_states is None:
encoder_hidden_states = hidden_states
elif attn.norm_cross:
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
key = attn.to_k(encoder_hidden_states)
value = attn.to_v(encoder_hidden_states)
inner_dim = key.shape[-1]
head_dim = inner_dim // attn.heads
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
hidden_states = F.scaled_dot_product_attention(query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False)
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
hidden_states = hidden_states.to(query.dtype)
if use_mv:
key_mv = self.to_k_mv(encoder_hidden_states)
value_mv = self.to_v_mv(encoder_hidden_states)
query_mv = query_mv.view(batch_size, -1, attn.heads, head_dim)
key_mv = key_mv.view(batch_size, -1, attn.heads, head_dim)
value_mv = value_mv.view(batch_size, -1, attn.heads, head_dim)
height = width = math.isqrt(sequence_length)
query_mv = rearrange(query_mv, '(b nv) (ih iw) h c -> (b nv ih) iw h c', nv=self.num_views, ih=height, iw=width).transpose(1, 2)
key_mv = rearrange(key_mv, '(b nv) (ih iw) h c -> b ih (nv iw) h c', nv=self.num_views, ih=height, iw=width)
key_mv = key_mv.repeat_interleave(self.num_views, dim=0).view(batch_size * height, -1, attn.heads, head_dim).transpose(1, 2)
value_mv = rearrange(value_mv, '(b nv) (ih iw) h c -> b ih (nv iw) h c', nv=self.num_views, ih=height, iw=width)
value_mv = value_mv.repeat_interleave(self.num_views, dim=0).view(batch_size * height, -1, attn.heads, head_dim).transpose(1, 2)
hidden_states_mv = F.scaled_dot_product_attention(query_mv, key_mv, value_mv, dropout_p=0.0, is_causal=False)
hidden_states_mv = rearrange(hidden_states_mv, '(b nv ih) h iw c -> (b nv) (ih iw) (h c)', nv=self.num_views, ih=height)
hidden_states_mv = hidden_states_mv.to(query.dtype)
hidden_states_mv = self.to_out_mv[0](hidden_states_mv)
hidden_states_mv = self.to_out_mv[1](hidden_states_mv)
if use_ref:
reference_hidden_states = ref_hidden_states[self.name]
key_ref = self.to_k_ref(reference_hidden_states)
value_ref = self.to_v_ref(reference_hidden_states)
query_ref = query_ref.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
key_ref = key_ref.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
value_ref = value_ref.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
hidden_states_ref = F.scaled_dot_product_attention(query_ref, key_ref, value_ref, dropout_p=0.0, is_causal=False)
hidden_states_ref = hidden_states_ref.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
hidden_states_ref = hidden_states_ref.to(query.dtype)
hidden_states_ref = self.to_out_ref[0](hidden_states_ref)
hidden_states_ref = self.to_out_ref[1](hidden_states_ref)
hidden_states = attn.to_out[0](hidden_states)
hidden_states = attn.to_out[1](hidden_states)
if use_mv:
hidden_states = hidden_states + hidden_states_mv * mv_scale
if use_ref:
hidden_states = hidden_states + hidden_states_ref * ref_scale
if input_ndim == 4:
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
if attn.residual_connection:
hidden_states = hidden_states + residual
hidden_states = hidden_states / attn.rescale_output_factor
return hidden_states
def set_num_views(self, num_views: int) -> None:
self.num_views = num_views
def main():
"""最小使用示例:创建模块,验证输入与输出形状。"""
torch.manual_seed(0)
module = Attention(query_dim=32, heads=4, dim_head=8)
module.set_processor(DecoupledMVRowSelfAttnProcessor2_0(query_dim=32, inner_dim=32, num_views=2, use_mv=True, use_ref=False))
input = torch.randn(4, 16, 32)
output = module(input, num_views=2)
assert input.shape == output.shape, (input.shape, output.shape)
assert torch.isfinite(output).all(), "output contains NaN/Inf"
print("input shape:", tuple(input.shape))
print("output shape:", tuple(output.shape))
return module, input, output
if __name__ == "__main__":
main()
环境与依赖
Python 3.9+
继续浏览
下一篇nnMamba 医学分割原理创新:融合CNN局部特征提取的归纳偏置和Mamba长序列高效建模能力,提出MICCSS基础块,同时实现通道、空间双维度的长距离依赖建模,适配小样本医影数据特性。相关资源
模块2026-11-21
CorrAdapter 对应区域聚合
在多视图行注意力旁并联一条局部对应分支,先用特征相似度挑选跨视图匹配,再用置信阈值过滤,只在匹配点附近的窗口内聚合信息,最后与原多视图响应混合;可选低秩分支进一步适配。
计算机视觉扩散模型多视图生成
计算机视觉MIT
模块2026-11-20
Agent Attention 代理注意力
代理聚合广播:在 (Q,K,V) 之外引入少量 Agent token,先代理 Query 从 K、V 聚合全局信息,再广播回每个 Query,兼得 Softmax 表达力与线性复杂度
计算机视觉注意力机制AgentAttention
计算机视觉MIT
模块2026-11-20
CBAM 卷积块注意力模块
双池化通道注意力:通道分支同时用平均池化和最大池化聚合空间信息,过共享 MLP 后逐元素相加,最大池化补平均池化的不足;
计算机视觉注意力机制CBAM
计算机视觉MIT