模块更新于 2026-11-21· 浏览 3· 下载 2
CorrAdapter 对应区域聚合
在多视图行注意力旁并联一条局部对应分支,先用特征相似度挑选跨视图匹配,再用置信阈值过滤,只在匹配点附近的窗口内聚合信息,最后与原多视图响应混合;可选低秩分支进一步适配。
结构图

在多视图行注意力旁并联一条局部对应分支,先用特征相似度挑选跨视图匹配,再用置信阈值过滤,只在匹配点附近的窗口内聚合信息,最后与原多视图响应混合;可选低秩分支进一步适配。
论文信息
- 论文:Align Images Before You Generate
- 出处:CVPR 2026
核心痛点
多视图扩散生成时,各视图之间缺少可靠的像素对应,无对应区域互相注意,容易把无关内容混进来,造成模糊和错位。
模块亮点
- 在多视图行注意力旁并联一条局部对应分支,先用特征相似度挑选跨视图匹配,再用置信阈值过滤,只在匹配点附近的窗口内聚合信息,最后与原多视图响应混合;可选低秩分支进一步适配。
适用场景
适合多视图、多图像扩散生成任务,用于提升视图间局部一致性。论文还讨论了动态视频场景,本地示例只覆盖静态多视图路径,其他任务需单独验证。
插入位置建议
- 放在扩散骨干的多视图注意力层,与行注意力并联,保持视图维排列一致;接入时核对视图数、局部窗口半径、温度与置信阈值,关闭该分支应能退回原基线。
适用任务
- 多视图
- 多图像扩散生成任务
- 提升视图间局部一致性。论文还讨论了动态视频场景
完整代码
corradapter.py
"""75_CorrAdapter_CVPR2026: 官方核心模块的单文件提取。
官方源码: https://github.com/SuhZhang/CorrAdapter/blob/a269d224f89aa7ae2bed1b4c61b2613352e8a1d2/image-conditioned/static/MVAdapter/mvadapter/models/attention_processor.py
源码 SHA256: 4e2029b7c8eaa36f7dceb3fa809812c0430dbaccd9b1d6f455789a8ad99f937e
提取核心: LoRAProjection, DecoupledMVRowSelfAttnProcessor2_0
整理说明: 提取官方增加局部对应关系分支的 MV 注意力处理器,保留匹配、置信度筛选、半径窗口聚合与混合。示例选中官方 up_blocks.1 局部层,不能通过关闭局部分支来冒充 CorrAdapter。
形状验证只说明接口可用,不代表已复现论文指标。初始化/辅助输入遵循原仓库;
需要语义特征、掩码、时间等条件的模块不能省略对应条件。
"""
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,List,Dict
from einops import rearrange,repeat
from diffusers.models.attention_processor import Attention
from diffusers.utils import deprecate
class LoRAProjection(nn.Module):
"""Low-rank adaptation branch used to augment linear projections."""
def __init__(self, in_features: int, out_features: int, rank: int=16, alpha: Optional[float]=None, dropout: float=0.0) -> None:
super().__init__()
if rank <= 0:
raise ValueError('LoRAProjection rank must be a positive integer.')
self.rank = rank
self.scaling = float(alpha if alpha is not None else rank) / float(rank)
self.dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
self.lora_down = nn.Linear(in_features, rank, bias=False)
self.lora_up = nn.Linear(rank, out_features, bias=False)
nn.init.kaiming_uniform_(self.lora_down.weight, a=math.sqrt(5))
nn.init.zeros_(self.lora_up.weight)
def forward(self, x: torch.Tensor) -> torch.Tensor:
orig_shape = x.shape
x_flat = x.reshape(-1, orig_shape[-1])
adapted = self.lora_up(self.dropout(self.lora_down(x_flat))) * self.scaling
return adapted.view(*orig_shape[:-1], -1)
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, local_lora_rank: int=16, local_lora_alpha: Optional[float]=None, local_lora_dropout: float=0.0):
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
self.local_radius: int = 3
self.local_tau: float = 1.0
self.local_conf_thresh: float = 0.05
self._local_memory_qks: List[List[torch.Tensor]] = []
self._local_memory_corrs: dict = {}
self._local_memory_maxlen: int = 1
self.local_lora_rank: int = max(1, int(local_lora_rank))
self.local_lora_alpha: float = float(local_lora_alpha) if local_lora_alpha is not None else float(self.local_lora_rank)
self.local_lora_dropout: float = float(local_lora_dropout)
self._lora_modules: List[nn.Module] = []
self._qdim = query_dim
self._inner_dim = inner_dim
self._is_self_attn = isinstance(self.name, str) and self.name.endswith('attn1.processor')
self._up_block_index = None
if isinstance(self.name, str) and self.name.startswith('up_blocks.'):
try:
self._up_block_index = int(self.name.split('up_blocks.')[1].split('.')[0])
except Exception:
self._up_block_index = None
self.enable_lora = bool(self._is_self_attn)
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)])
self._qdim = query_dim
self._inner_dim = inner_dim
self._is_self_attn = isinstance(self.name, str) and self.name.endswith('attn1.processor')
self._up_block_index = None
if isinstance(self.name, str) and self.name.startswith('up_blocks.'):
try:
self._up_block_index = int(self.name.split('up_blocks.')[1].split('.')[0])
except Exception:
self._up_block_index = None
default_local_up_block_index = 1
self.apply_mv_local_static = self._is_self_attn and self._up_block_index is not None and (self._up_block_index == default_local_up_block_index)
self.enable_lora = bool(self._is_self_attn) and (not bool(self.apply_mv_local_static))
if self.enable_lora:
self.q_m_lora = LoRAProjection(self._qdim, self._inner_dim, rank=self.local_lora_rank, alpha=self.local_lora_alpha, dropout=self.local_lora_dropout)
self.k_m_lora = LoRAProjection(self._qdim, self._inner_dim, rank=self.local_lora_rank, alpha=self.local_lora_alpha, dropout=self.local_lora_dropout)
self.v_m_lora = LoRAProjection(self._qdim, self._inner_dim, rank=self.local_lora_rank, alpha=self.local_lora_alpha, dropout=self.local_lora_dropout)
self.o_m_lora = LoRAProjection(self._inner_dim, self._qdim, rank=self.local_lora_rank, alpha=self.local_lora_alpha, dropout=self.local_lora_dropout)
self._lora_modules.extend([self.q_m_lora, self.k_m_lora, self.v_m_lora, self.o_m_lora])
if self.apply_mv_local_static:
self.to_q_loc = nn.Linear(self._qdim, self._inner_dim, bias=False)
self.to_k_loc = nn.Linear(self._qdim, self._inner_dim, bias=False)
self.to_v_loc = nn.Linear(self._qdim, self._inner_dim, bias=False)
with torch.no_grad():
self.to_q_loc.weight.copy_(self.to_q_mv.weight)
self.to_k_loc.weight.copy_(self.to_k_mv.weight)
self.to_v_loc.weight.copy_(self.to_v_mv.weight)
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 set_lora_train(self, mode: bool=True) -> None:
for module in self._lora_modules:
module.train(mode)
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, index: Optional[int]=None, local_radius: Optional[int]=None, local_tau: Optional[float]=None, local_conf_thresh: Optional[float]=None, local_up_block_index: Optional[int]=None, local_feature_maps: Optional[Dict[str, Dict[str, torch.Tensor]]]=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 local_radius is None:
local_radius = kwargs.get('local_radius', self.local_radius)
if local_tau is None:
local_tau = kwargs.get('local_tau', self.local_tau)
if local_conf_thresh is None:
local_conf_thresh = kwargs.get('local_conf_thresh', self.local_conf_thresh)
local_index = index if index is not None else kwargs.get('index', None)
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)
use_lora = bool(getattr(self, 'enable_lora', False))
if use_mv:
query_mv = self.to_q_mv(hidden_states)
if use_lora:
query_mv = query_mv + self.q_m_lora(hidden_states)
hidden_states_old = hidden_states.clone()
if use_ref:
query_ref = self.to_q_ref(hidden_states)
is_self_attention = encoder_hidden_states is None
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_per_head = F.scaled_dot_product_attention(query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False)
hidden_states = hidden_states_per_head.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)
if use_lora:
key_mv = key_mv + self.k_m_lora(encoder_hidden_states)
value_mv = value_mv + self.v_m_lora(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)
apply_mv_local = bool(self.apply_mv_local_static) and bool(is_self_attention) and (int(local_radius) > 0)
if apply_mv_local:
Bmv, Hh, Wq, Dd = query_mv.shape
nv_eff = max(1, int(self.num_views))
Wk = Wq
r = int(local_radius)
max_neg = -torch.finfo(query_mv.dtype).max
q_loc = self.to_q_loc(hidden_states_old)
k_loc = self.to_k_loc(encoder_hidden_states)
v_loc = self.to_v_loc(encoder_hidden_states)
q_loc = q_loc.view(batch_size, -1, attn.heads, head_dim)
k_loc = k_loc.view(batch_size, -1, attn.heads, head_dim)
v_loc = v_loc.view(batch_size, -1, attn.heads, head_dim)
q_loc = rearrange(q_loc, '(b nv) (ih iw) h c -> (b nv ih) iw h c', nv=self.num_views, ih=height, iw=width).transpose(1, 2)
k_loc = rearrange(k_loc, '(b nv) (ih iw) h c -> b ih (nv iw) h c', nv=self.num_views, ih=height, iw=width)
k_loc = k_loc.repeat_interleave(self.num_views, dim=0).view(batch_size * height, -1, attn.heads, head_dim).transpose(1, 2)
v_loc = rearrange(v_loc, '(b nv) (ih iw) h c -> b ih (nv iw) h c', nv=self.num_views, ih=height, iw=width)
v_loc = v_loc.repeat_interleave(self.num_views, dim=0).view(batch_size * height, -1, attn.heads, head_dim).transpose(1, 2)
qf = q_loc.reshape(Bmv * Hh, Wq, Dd)
kf = k_loc.reshape(Bmv * Hh, nv_eff * Wk, Dd)
vf = v_loc.reshape(Bmv * Hh, nv_eff * Wk, Dd)
q_coor = qf
k_coor = kf
q_bh = q_coor.view(Bmv, Hh, Wq, Dd)
k_bh = k_coor.view(Bmv, Hh, nv_eff, Wk, Dd)
v_bh = vf.view(Bmv, Hh, nv_eff, Wk, Dd)
view_ids = torch.arange(Bmv, device=q_bh.device) // height % nv_eff
sim_view = torch.einsum('bhqd,bhvkd->bhqvk', q_bh, k_bh) / math.sqrt(Dd)
same_mask = torch.arange(nv_eff, device=sim_view.device).view(1, 1, 1, nv_eff, 1) == view_ids.view(Bmv, 1, 1, 1, 1)
sim_view = sim_view.masked_fill(same_mask, max_neg)
sim_t = sim_view / float(local_tau)
conf = F.softmax(sim_t, dim=-1)
j_star = conf.argmax(dim=-1)
nn_mask = j_star == j_star
selected_conf = torch.gather(conf, dim=-1, index=j_star.unsqueeze(-1)).squeeze(-1)
keep_mask = nn_mask & (selected_conf > float(local_conf_thresh))
offsets = torch.arange(-r, r + 1, device=sim_view.device).view(1, 1, 1, 1, -1)
j_in_view = (j_star % Wk).unsqueeze(-1)
win_in_view = (j_in_view + offsets).clamp(0, Wk - 1)
k_exp = k_bh.unsqueeze(2).expand(-1, -1, Wq, -1, -1, -1)
v_exp = v_bh.unsqueeze(2).expand(-1, -1, Wq, -1, -1, -1)
idx_exp = win_in_view.unsqueeze(-1).expand(-1, -1, -1, -1, -1, Dd)
k_local = torch.gather(k_exp, dim=4, index=idx_exp)
v_local = torch.gather(v_exp, dim=4, index=idx_exp)
qi_exp = q_bh.unsqueeze(3).unsqueeze(4)
sim_local = (qi_exp * k_local).sum(-1) / math.sqrt(Dd)
attn_local = F.softmax(sim_local, dim=-1)
out_view = (attn_local.unsqueeze(-1) * v_local).sum(dim=-2)
acc = (out_view * keep_mask.unsqueeze(-1)).sum(dim=3)
cnt = keep_mask.sum(dim=3).clamp(min=1)
out_local = acc / cnt.clamp(min=1.0).unsqueeze(-1)
mask_weight = cnt.clamp(max=1.0).unsqueeze(-1)
ori_lambda = 0.1
hidden_states_mv = (1 - mask_weight) * hidden_states_mv + mask_weight * (ori_lambda * hidden_states_mv + (1 - ori_lambda) * out_local)
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)
if use_lora:
hidden_states_mv = self.to_out_mv[0](hidden_states_mv) + self.o_m_lora(hidden_states_mv)
else:
hidden_states_mv = self.to_out_mv[0](hidden_states_mv)
if apply_mv_local and local_feature_maps is not None:
feature_tensor = rearrange(hidden_states_old, '(b nv) (ih iw) c -> b nv ih iw c', nv=self.num_views, ih=height, iw=width)
local_feature_maps[self.name] = {'features': feature_tensor, 'height': height, 'width': width}
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)
processor = DecoupledMVRowSelfAttnProcessor2_0(32,32,num_views=2,name='up_blocks.1.attentions.0.transformer_blocks.0.attn1.processor',use_mv=True,use_ref=False)
module.set_processor(processor)
input = torch.randn(4,16,32)
output = module(input,num_views=2,local_radius=1,local_conf_thresh=0.05,index=1)
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+
继续浏览
下一篇COSA 锚点上下文压缩以重建坐标生成几何上下文,逐通道建模隐变量,再融合其嵌入给属性概率头使用。不同锚点可并行,依赖集中在单个锚点内部。相关资源
模块2026-11-21
MV-Adapter 视图行注意力
保留原注意力通路,另设跨视图行注意力分支,联合建模不同视图中同一行的特征。还可通过独立的参考图像交叉注意力分支补充外观信息,各分支分别控制融合强度。
计算机视觉注意力机制多视图生成
计算机视觉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