学术
模块更新于 2026-11-21· 浏览 1· 下载 0

AM-Adapter 外观匹配适配

把查询图像与示例图像之间的匹配关系表示成高维相关性张量,分别沿查询空间轴和示例空间轴做卷积,再组合更新;下采样、中间、上采样层级各用独立编码器,便于在不同分辨率上修正外观匹配。它不是对普通图像特征做通道注意力。

计算机视觉计算机视觉图像生成语义合成外观迁移扩散模型

结构图

AM-Adapter 外观匹配适配结构图
AM-Adapter 外观匹配适配结构图

把查询图像与示例图像之间的匹配关系表示成高维相关性张量,分别沿查询空间轴和示例空间轴做卷积,再组合更新;下采样、中间、上采样层级各用独立编码器,便于在不同分辨率上修正外观匹配。它不是对普通图像特征做通道注意力。

论文信息

  • 论文:AM-Adapter: Appearance Matching Adapter for Exemplar-based Semantic Image Synthesis in-the-Wild
  • 出处:ICCV 2025

核心痛点

示例引导的语义图像合成要把参考图里的物体外观搬到目标布局上,多对象场景里容易张冠李戴,把 A 物体的纹理贴到 B 区域,跨图像的对应关系很难只靠普通注意力建立。

模块亮点

  • 把查询图像与示例图像之间的匹配关系表示成高维相关性张量,分别沿查询空间轴和示例空间轴做卷积,再组合更新;下采样、中间、上采样层级各用独立编码器,便于在不同分辨率上修正外观匹配。它不是对普通图像特征做通道注意力。

适用场景

适合示例图像引导的语义图像合成,尤其是多对象场景中按语义区域转移局部外观;上游需要先给出跨图像的相关性与语义匹配信息。其他生成任务需单独验证,本模块不能单独生成图像。

插入位置建议

  • 接在扩散网络对应层、拿到相关性张量之后,输入为 B×L×Hq×Wq×Hs×Ws 六维张量,要与该层的编码器通道配置匹配。接入时注意示例把相关性通道设为 8,原默认 9 改 8 会改变通道,不能无条件当作同形状输出;同时留意相关性张量带来的显存开销。

适用任务

  • 示例图像引导的语义图像合成
  • 尤其是多对象场景中按语义区域转移局部外观
  • 上游需要先给出跨图像的相关性与语义匹配信息。其他生成任务需单独验证

完整代码

amadapter.py
"""54_AMAdapter_ICCV2025: 官方核心模块的单文件提取。

官方源码: https://github.com/cvlab-kaist/AM-Adapter/blob/5e44fd4b130126715bcf7645ed82d16a0034691f/src/models/matching_module.py
源码 SHA256: ef7e62399e192a5a712b8b15990f2664182dc867cb1678829026e862cd13a637
提取核心: OurModel
整理说明: 提取官方 attention matching 适配器和完整4D相关性卷积依赖,保留三个扩散层级的独立编码器。输入是 [B,L,Hq,Wq,Hs,Ws] 相关性张量,不能直接接普通 BCHW 特征。示例将可配置输入/输出相关性通道都设为8;原默认9->8会改变通道,使用默认配置时不承诺同形状。
形状验证只说明接口可用,不代表已复现论文指标。初始化/辅助输入遵循原仓库;
需要语义特征、掩码、时间等条件的模块不能省略对应条件。
"""
from __future__ import annotations

import torch
from torch import nn
import torch.nn.functional as F
from einops import rearrange


class MaxPool4d(nn.Module):

    def __init__(self, kernel_size, stride, padding, dim='support'):
        super().__init__()
        self.pool = nn.MaxPool2d(kernel_size, stride, padding, ceil_mode=True)
        self.dim = dim

    def forward(self, x):
        """
        x: Hyper correlation.
            shape: B L H_q W_q H_s W_s
        """
        B, L, H_q, W_q, H_s, W_s = x.size()
        if self.dim == 'support':
            x = rearrange(x, 'B L H_q W_q H_s W_s -> (B H_q W_q) L H_s W_s')
            x = self.pool(x)
            x = rearrange(x, '(B H_q W_q) L H_s W_s -> B L H_q W_q H_s W_s', H_q=H_q, W_q=W_q)
        elif self.dim == 'query':
            x = rearrange(x, 'B L H_q W_q H_s W_s -> (B H_s W_s) L H_q W_q')
            x = self.pool(x)
            x = rearrange(x, '(B H_s W_s) L H_q W_q -> B L H_q W_q H_s W_s', H_s=H_s, W_s=W_s)
        else:
            raise NotImplemented(f'Invalid dimension {self.dim}. dim should be "support" or "query"')
        return x


class Interpolate4d(nn.Module):

    def __init__(self, size, dim='support'):
        super().__init__()
        self.size = size
        self.dim = dim

    def forward(self, x):
        """
        x: Hyper correlation.
        """
        B, L, H_q, W_q, H_s, W_s = x.size()
        if self.dim == 'support':
            x = rearrange(x, 'B L H_q W_q H_s W_s -> (B H_q W_q) L H_s W_s')
            x = F.interpolate(x, size=self.size, mode='bilinear', align_corners=True)
            x = rearrange(x, '(B H_q W_q) L H_s W_s -> B L H_q W_q H_s W_s', H_q=H_q, W_q=W_q)
        elif self.dim == 'query':
            x = rearrange(x, 'B L H_q W_q H_s W_s -> (B H_s W_s) L H_q W_q')
            x = F.interpolate(x, size=self.size, mode='bilinear', align_corners=True)
            x = rearrange(x, '(B H_s W_s) L H_q W_q -> B L H_q W_q H_s W_s', H_s=H_s, W_s=W_s)
        else:
            raise NotImplemented(f'Invalid dimension {self.dim}. dim should be "support" or "query"')
        return x


class Conv4d(nn.Module):

    def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias=True, transposed_query=False, transposed_supp=False, target_size=None, output_padding=None):
        super().__init__()
        if transposed_query:
            assert output_padding is not None, 'output_padding cannot be None'
            self.query_conv = nn.ConvTranspose2d(in_channels, out_channels, kernel_size[:2], stride=stride[:2], bias=bias, padding=padding[:2], output_padding=output_padding[:2])
        else:
            self.query_conv = nn.Conv2d(in_channels, out_channels, kernel_size[:2], stride=stride[:2], bias=bias, padding=padding[:2])
        if transposed_supp:
            assert output_padding is not None, 'output_padding cannot be None'
            self.supp_conv = nn.ConvTranspose2d(in_channels, out_channels, kernel_size[2:], stride=stride[2:], bias=bias, padding=padding[2:], output_padding=output_padding[2:])
        else:
            self.supp_conv = nn.Conv2d(in_channels, out_channels, kernel_size[2:], stride=stride[2:], bias=bias, padding=padding[2:])
        self.change_supp = stride[-1] > 1 or (stride[0] == 1 and kernel_size[0] == 1)
        if self.change_supp:
            if transposed_supp:
                assert target_size is not None, 'Invalid size'
                self.pool_supp = Interpolate4d(target_size[-2:], dim='support')
            else:
                self.pool_supp = MaxPool4d(kernel_size=stride[-2:], stride=stride[-2:], padding=(0, 0), dim='support')
        self.change_query = stride[0] > 1 or (stride[0] == 1 and kernel_size[0] == 1)
        if self.change_query:
            if transposed_query:
                assert target_size is not None, 'Invalid size'
                self.pool_query = Interpolate4d(target_size[:2], dim='query')
            else:
                self.pool_query = MaxPool4d(kernel_size=stride[:2], stride=stride[:2], padding=(0, 0), dim='query')
        self.kernel_size = kernel_size
        self.stride = stride
        self.padding = padding

    def forward(self, x):
        """
        x: Hyper correlation map.
            shape: B L H_q W_q H_s W_s
        """
        B, L, H_q, W_q, H_s, W_s = x.size()
        if self.change_supp:
            x_query = self.pool_supp(x)
            H_s, W_s = x_query.shape[-2:]
        else:
            x_query = x.clone()
        if self.change_query:
            x_supp = self.pool_query(x)
            H_q, W_q = x_supp.shape[2:4]
        else:
            x_supp = x.clone()
        x_query = rearrange(x_query, 'B L H_q W_q H_s W_s -> (B H_s W_s) L H_q W_q')
        x_query = self.query_conv(x_query)
        x_query = rearrange(x_query, '(B H_s W_s) L H_q W_q -> B L H_q W_q H_s W_s', H_s=H_s, W_s=W_s)
        x_supp = rearrange(x_supp, 'B L H_q W_q H_s W_s -> (B H_q W_q) L H_s W_s')
        x_supp = self.supp_conv(x_supp)
        x_supp = rearrange(x_supp, '(B H_q W_q) L H_s W_s -> B L H_q W_q H_s W_s', H_q=H_q, W_q=W_q)
        return x_query + x_supp


class Encoder4D(nn.Module):

    def __init__(self, corr_levels, kernel_size, stride, padding, group=(4,), residual=True):
        super().__init__()
        self.conv4d = nn.ModuleList([])
        for i, (k, s, p) in enumerate(zip(kernel_size, stride, padding)):
            conv4d = nn.Sequential(Conv4d(corr_levels[i], corr_levels[i + 1], k, s, p), nn.GroupNorm(group[i], corr_levels[i + 1]), nn.ReLU())
            self.conv4d.append(conv4d)
        self.residual = residual

    def forward(self, x):
        """
        x: Hyper correlation. B L H_q W_q H_s W_s
        """
        residuals = []
        for conv in self.conv4d:
            if self.residual:
                residuals.append(x)
            x = conv(x)
        return (x, residuals)


class OurModel(nn.Module):

    def __init__(self, feat_dim=[9, 8], time_embed_dim=9):
        super().__init__()
        self.encoders = nn.ModuleList([])
        self.encoders.append(Encoder4D(corr_levels=(feat_dim[0], 16, 32, 16, feat_dim[1]), kernel_size=((1, 1, 3, 3), (1, 1, 3, 3), (1, 1, 3, 3), (1, 1, 3, 3)), stride=((1, 1, 1, 1), (1, 1, 1, 1), (1, 1, 1, 1), (1, 1, 1, 1)), padding=((0, 0, 1, 1), (0, 0, 1, 1), (0, 0, 1, 1), (0, 0, 1, 1)), group=(1, 1, 1, 1), residual=False))
        self.encoders.append(Encoder4D(corr_levels=(feat_dim[0], 16, 32, 16, feat_dim[1]), kernel_size=((1, 1, 3, 3), (1, 1, 3, 3), (1, 1, 3, 3), (1, 1, 3, 3)), stride=((1, 1, 1, 1), (1, 1, 1, 1), (1, 1, 1, 1), (1, 1, 1, 1)), padding=((0, 0, 1, 1), (0, 0, 1, 1), (0, 0, 1, 1), (0, 0, 1, 1)), group=(1, 1, 1, 1), residual=False))
        self.encoders.append(Encoder4D(corr_levels=(feat_dim[0], 16, 32, 16, feat_dim[1]), kernel_size=((1, 1, 3, 3), (1, 1, 3, 3), (1, 1, 3, 3), (1, 1, 3, 3)), stride=((1, 1, 1, 1), (1, 1, 1, 1), (1, 1, 1, 1), (1, 1, 1, 1)), padding=((0, 0, 1, 1), (0, 0, 1, 1), (0, 0, 1, 1), (0, 0, 1, 1)), group=(1, 1, 1, 1), residual=False))

    def forward(self, corr, t=None, block='down_blocks'):
        if block == 'down_blocks':
            corr = self.encoders[0](corr)[0]
        elif block == 'mid_block':
            corr = self.encoders[1](corr)[0]
        elif block == 'up_blocks':
            corr = self.encoders[2](corr)[0]
        return corr

    def to(self, *args, **kwargs):
        super().to(*args, **kwargs)
        self.dtype = next(self.parameters()).dtype
        return self


def main():
    """最小使用示例:创建模块,验证输入与输出形状。"""
    torch.manual_seed(0)
    module = OurModel(feat_dim=[8,8])
    input = torch.randn(2,8,4,4,4,4)
    output = module(input,block="down_blocks")
    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+

继续浏览

下一篇Att-Adapter CVAE 属性条件编码用 CVAE 编码连续多属性条件,经重参数化与条件解码注入扩散模型,实现细粒度、可解耦的属性控制。

相关资源