[{"data":1,"prerenderedAt":330},["ShallowReactive",2],{"content-query-uXlTx32Siq":3},{"_path":4,"_dir":5,"_draft":6,"_partial":6,"_locale":7,"title":8,"description":9,"date":10,"cover":11,"type":12,"category":13,"body":14,"_type":324,"_id":325,"_source":326,"_file":327,"_stem":328,"_extension":329},"/technology-blogs/zh/3750","zh",false,"","扩散模型系列——Palette","Palette   论文地址：Palette: Image-to-Image Diffusion Models    代码地址：https://github.com/Janspiry/Palette-Image-to-Image-Diffusion-Models","2025-05-15","https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/06/06/4530c7557a00491a8d1d0ed3ca5220c2.png","technology-blogs","开发者说",{"type":15,"children":16,"toc":308},"root",[17,25,32,47,58,65,70,75,95,101,108,113,131,137,142,160,166,171,184,190,195,252,258,263,292,298],{"type":18,"tag":19,"props":20,"children":22},"element","h1",{"id":21},"扩散模型系列palette",[23],{"type":24,"value":8},"text",{"type":18,"tag":26,"props":27,"children":29},"h2",{"id":28},"palette",[30],{"type":24,"value":31},"Palette",{"type":18,"tag":33,"props":34,"children":35},"p",{},[36,38],{"type":24,"value":37},"论文地址：",{"type":18,"tag":39,"props":40,"children":44},"a",{"href":41,"rel":42},"https://arxiv.org/pdf/2111.05826",[43],"nofollow",[45],{"type":24,"value":46},"Palette: Image-to-Image Diffusion Models",{"type":18,"tag":33,"props":48,"children":49},{},[50,52],{"type":24,"value":51},"代码地址：",{"type":18,"tag":39,"props":53,"children":56},{"href":54,"rel":55},"https://github.com/Janspiry/Palette-Image-to-Image-Diffusion-Models",[43],[57],{"type":24,"value":54},{"type":18,"tag":59,"props":60,"children":62},"h3",{"id":61},"一概述",[63],{"type":24,"value":64},"一、概述",{"type":18,"tag":33,"props":66,"children":67},{},[68],{"type":24,"value":69},"Palette 是一种基于扩散模型的通用图像转换模型，可用于图像着色，图像修复，图像补全和 JPEG 图像恢复等多种转换任务，它通过输入的条件x来构建分布p(y|x)，并通过图像级联的方式引入条件图像。",{"type":18,"tag":33,"props":71,"children":72},{},[73],{"type":24,"value":74},"Palette 的主要特点包括：",{"type":18,"tag":76,"props":77,"children":78},"ul",{},[79,85,90],{"type":18,"tag":80,"props":81,"children":82},"li",{},[83],{"type":24,"value":84},"统一框架：Palette 模型采用了统一的框架，通过条件扩散模型解决多个图像到图像翻译任务，而无需针对每个任务进行特定的超参数调整、架构定制或辅助损失函数的设计。",{"type":18,"tag":80,"props":86,"children":87},{},[88],{"type":24,"value":89},"样本多样性：通过采用 L2 损失函数，Palette 模型在多个任务上均展现出了较高的样本多样性。这对于需要生成多种可能结果的图像到图像翻译任务尤为重要。",{"type":18,"tag":80,"props":91,"children":92},{},[93],{"type":24,"value":94},"条件 UNet 主干：采用 256×256 分辨率的条件 UNet，通过跳跃连接融合多尺度特征，增强跨层信息传递。",{"type":18,"tag":59,"props":96,"children":98},{"id":97},"二主要步骤",[99],{"type":24,"value":100},"二、主要步骤",{"type":18,"tag":102,"props":103,"children":105},"h4",{"id":104},"_1-预训练基础扩散模型",[106],{"type":24,"value":107},"1. 预训练基础扩散模型",{"type":18,"tag":33,"props":109,"children":110},{},[111],{"type":24,"value":112},"Palette 的预训练阶段建立在扩散模型的核心框架上，通过学习图像的噪声分布来捕获数据的潜在结构。",{"type":18,"tag":76,"props":114,"children":115},{},[116,121,126],{"type":18,"tag":80,"props":117,"children":118},{},[119],{"type":24,"value":120},"扩散过程：逐步向图像添加高斯噪声，将原始图像 x转换为噪声样本 x_T。",{"type":18,"tag":80,"props":122,"children":123},{},[124],{"type":24,"value":125},"去噪过程：训练 UNet 模型学习反向过程，从噪声中恢复原始图像。",{"type":18,"tag":80,"props":127,"children":128},{},[129],{"type":24,"value":130},"关键技术：使用时间嵌入编码当前噪声强度，帮助模型理解去噪阶段。",{"type":18,"tag":102,"props":132,"children":134},{"id":133},"_2-任务条件化适配",[135],{"type":24,"value":136},"2. 任务条件化适配",{"type":18,"tag":33,"props":138,"children":139},{},[140],{"type":24,"value":141},"针对不同图像转换任务，Palette 通过以下方式进行条件化：",{"type":18,"tag":76,"props":143,"children":144},{},[145,150,155],{"type":18,"tag":80,"props":146,"children":147},{},[148],{"type":24,"value":149},"任务特定提示：为每个任务设计专用的输入提示（如掩码区域、低分辨率图像、灰度图等）。",{"type":18,"tag":80,"props":151,"children":152},{},[153],{"type":24,"value":154},"条件嵌入：将任务提示通过额外的网络层转换为条件嵌入，与 UNet 的中间特征融合。",{"type":18,"tag":80,"props":156,"children":157},{},[158],{"type":24,"value":159},"多任务学习：通过共享主干网络、任务特定分支的方式，使模型同时掌握多个任务。",{"type":18,"tag":102,"props":161,"children":163},{"id":162},"_3-自适应噪声调度",[164],{"type":24,"value":165},"3. 自适应噪声调度",{"type":18,"tag":33,"props":167,"children":168},{},[169],{"type":24,"value":170},"Palette 引入自适应噪声调度提升不同任务的性能：",{"type":18,"tag":76,"props":172,"children":173},{},[174,179],{"type":18,"tag":80,"props":175,"children":176},{},[177],{"type":24,"value":178},"任务感知噪声强度：根据任务难度动态调整噪声水平，例如修复任务使用更高噪声强度。",{"type":18,"tag":80,"props":180,"children":181},{},[182],{"type":24,"value":183},"渐进式细化：在去噪后期增加额外的细化步骤，提升细节质量。",{"type":18,"tag":102,"props":185,"children":187},{"id":186},"_4-后处理与质量优化",[188],{"type":24,"value":189},"4. 后处理与质量优化",{"type":18,"tag":33,"props":191,"children":192},{},[193],{"type":24,"value":194},"生成结果经过以下处理提升最终质量：",{"type":18,"tag":76,"props":196,"children":197},{},[198,216,234],{"type":18,"tag":80,"props":199,"children":200},{},[201,203],{"type":24,"value":202},"细化网络",{"type":18,"tag":76,"props":204,"children":205},{},[206,211],{"type":18,"tag":80,"props":207,"children":208},{},[209],{"type":24,"value":210},"局部增强：对生成的图像进行局部细化，例如增强边缘、平滑过渡区域。",{"type":18,"tag":80,"props":212,"children":213},{},[214],{"type":24,"value":215},"对抗训练：引入判别器网络，提升生成图像的真实性。",{"type":18,"tag":80,"props":217,"children":218},{},[219,221],{"type":24,"value":220},"一致性检查",{"type":18,"tag":76,"props":222,"children":223},{},[224,229],{"type":18,"tag":80,"props":225,"children":226},{},[227],{"type":24,"value":228},"区域匹配：确保生成区域与周围环境自然融合，避免人工痕迹。",{"type":18,"tag":80,"props":230,"children":231},{},[232],{"type":24,"value":233},"语义一致性：在多对象场景中，保持对象间的语义关系（如比例、遮挡）。",{"type":18,"tag":80,"props":235,"children":236},{},[237,239],{"type":24,"value":238},"质量控制",{"type":18,"tag":76,"props":240,"children":241},{},[242,247],{"type":18,"tag":80,"props":243,"children":244},{},[245],{"type":24,"value":246},"置信度估计：预测每个像素的生成置信度，对低置信度区域进行重采样。",{"type":18,"tag":80,"props":248,"children":249},{},[250],{"type":24,"value":251},"混合输出：结合多个采样结果，通过加权平均生成最终图像。",{"type":18,"tag":59,"props":253,"children":255},{"id":254},"三模型架构",[256],{"type":24,"value":257},"三、模型架构",{"type":18,"tag":33,"props":259,"children":260},{},[261],{"type":24,"value":262},"从论文中可以看出，Palette 模型的核心架构就是采用了条件扩散模型作为基础框架，并在此基础上做成了一些改进。",{"type":18,"tag":76,"props":264,"children":265},{},[266,271,276,281],{"type":18,"tag":80,"props":267,"children":268},{},[269],{"type":24,"value":270},"UNet 主干：使用的是 256×256 的条件 UNet，这是一种对称结构。它包含上下采样路径和瓶颈层。同时在上下采样路径中，都包含了每个残差块，它们使用了跳跃连接来整合不同尺度的特征信息，达到捕捉图像的多尺度细节的效果。",{"type":18,"tag":80,"props":272,"children":273},{},[274],{"type":24,"value":275},"条件嵌入：模型融合了多种条件信息来改变生成图像的结果，这其中包括了任务类型嵌入、时间步嵌入和条件图像特征。任务类型嵌入是用于区分图像的转换，例如着色、填充等；而时间步嵌入则是用于帮助模型理解生成过程中的时间信息；条件图像特征则是通过对输入的条件图像进行特征提取，将其作为额外的条件信息输入到模型中，使模型能够根据给定的条件图像生成相应的输出。",{"type":18,"tag":80,"props":277,"children":278},{},[279],{"type":24,"value":280},"多尺度特征融合：在模型生成图像过程中，有一个步骤为跳跃连接，它是将下采样过程中不同维度的图像特征与上采样过程中的对应维度图像特征进行融合，从而丰富图像在不同尺度上的表现。",{"type":18,"tag":80,"props":282,"children":283},{},[284,286,290],{"type":24,"value":285},"L2 损失函数：Palette 模型的损失函数是基于去噪目标的，即给定一个训练输出图像y，生成其噪声版本\\tilde{y}，并训练神经网络f_θ在条件x和噪声水平指标\\gamma下对\\tilde{y}进行去噪。而模型所使用的损失函数一般为 L2 范数，其数学公式为：",{"type":18,"tag":287,"props":288,"children":289},"br",{},[],{"type":24,"value":291},"E_{(x,y)}E_{\\epsilon\\sim N(0,I)}E_{\\gamma}||f_{\\theta}(x,\\sqrt{\\gamma}y+\\sqrt{1-\\gamma}\\epsilon,\\gamma)-\\epsilon||_2^2",{"type":18,"tag":59,"props":293,"children":295},{"id":294},"四代码实现",[296],{"type":24,"value":297},"四、代码实现",{"type":18,"tag":299,"props":300,"children":302},"pre",{"code":301},"import mindspore\nfrom mindspore import nn, ops\nfrom mindspore.common.initializer import Normal\n\nclass Swish(nn.Cell):\n    def construct(self, x):\n        return x * ops.sigmoid(x)\n\nclass TimeEmbedding(nn.Cell):\n    def __init__(self, dim):\n        super().__init__()\n        self.dim = dim\n        self.half_dim = dim // 2\n        self.emb = 9.210340371976184 / (self.half_dim - 1)\n        self.linear_1 = nn.Dense(dim, dim * 4)\n        self.linear_2 = nn.Dense(dim * 4, dim * 4)\n        self.swish = Swish()\n\n    def construct(self, time):\n        emb = time * ops.exp(ops.arange(self.half_dim, dtype=mindspore.float32) * -self.emb)\n        emb = ops.concat([ops.sin(emb), ops.cos(emb)], axis=1)\n        emb = self.linear_1(emb)\n        emb = self.swish(emb)\n        emb = self.linear_2(emb)\n        return emb\n\nclass ResidualBlock(nn.Cell):\n    def __init__(self, in_channels, out_channels, time_channels, dropout):\n        super().__init__()\n        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, pad_mode='pad')\n        self.norm1 = nn.GroupNorm(32, in_channels)\n        self.swish = Swish()\n        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, pad_mode='pad')\n        self.norm2 = nn.GroupNorm(32, out_channels)\n        self.time_emb_proj = nn.Dense(time_channels, out_channels)\n        self.dropout = nn.Dropout(1 - dropout)\n\n        if in_channels != out_channels:\n            self.shortcut = nn.Conv2d(in_channels, out_channels, kernel_size=1)\n        else:\n            self.shortcut = nn.Identity()\n\n    def construct(self, x, t):\n        h = self.swish(self.norm1(x))\n        h = self.conv1(h)\n\n        time_emb = self.swish(self.time_emb_proj(t))\n        time_emb = time_emb.expand_dims(-1).expand_dims(-1)\n        h = h + time_emb\n\n        h = self.swish(self.norm2(h))\n        h = self.dropout(h)\n        h = self.conv2(h)\n\n        return h + self.shortcut(x)\n\nclass AttentionBlock(nn.Cell):\n    def __init__(self, channels):\n        super().__init__()\n        self.channels = channels\n        self.norm = nn.GroupNorm(32, channels)\n        self.q = nn.Conv2d(channels, channels, kernel_size=1)\n        self.k = nn.Conv2d(channels, channels, kernel_size=1)\n        self.v = nn.Conv2d(channels, channels, kernel_size=1)\n        self.proj_out = nn.Conv2d(channels, channels, kernel_size=1)\n        self.scale = channels ** -0.5\n\n    def construct(self, x):\n        batch_size, channels, height, width = x.shape\n        h = self.norm(x)\n\n        q = self.q(h)\n        k = self.k(h)\n        v = self.v(h)\n\n        q = q.reshape(batch_size, channels, -1)\n        k = k.reshape(batch_size, channels, -1)\n        v = v.reshape(batch_size, channels, -1)\n\n        attn = ops.bmm(q.transpose(0, 2, 1), k) * self.scale\n        attn = ops.softmax(attn, axis=-1)\n\n        h = ops.bmm(v, attn.transpose(0, 2, 1))\n        h = h.reshape(batch_size, channels, height, width)\n        h = self.proj_out(h)\n\n        return x + h\n\nclass UNetDown(nn.Cell):\n    def __init__(self, in_channels, out_channels, time_channels, has_attn, dropout):\n        super().__init__()\n        self.res = ResidualBlock(in_channels, out_channels, time_channels, dropout)\n        self.attn = AttentionBlock(out_channels) if has_attn else nn.Identity()\n\n    def construct(self, x, t):\n        x = self.res(x, t)\n        x = self.attn(x)\n        return x\n\nclass UNetUp(nn.Cell):\n    def __init__(self, in_channels, out_channels, time_channels, has_attn, dropout):\n        super().__init__()\n        self.res = ResidualBlock(in_channels + out_channels, out_channels, time_channels, dropout)\n        self.attn = AttentionBlock(out_channels) if has_attn else nn.Identity()\n\n    def construct(self, x, skip, t):\n        x = ops.cat([x, skip], axis=1)\n        x = self.res(x, t)\n        x = self.attn(x)\n        return x\n\nclass MidBlock(nn.Cell):\n    def __init__(self, channels, time_channels, dropout):\n        super().__init__()\n        self.res1 = ResidualBlock(channels, channels, time_channels, dropout)\n        self.attn = AttentionBlock(channels)\n        self.res2 = ResidualBlock(channels, channels, time_channels, dropout)\n\n    def construct(self, x, t):\n        x = self.res1(x, t)\n        x = self.attn(x)\n        x = self.res2(x, t)\n        return x\n\nclass Upsample(nn.Cell):\n    def __init__(self, channels):\n        super().__init__()\n        self.conv = nn.Conv2d(channels, channels, kernel_size=3, padding=1, pad_mode='pad')\n\n    def construct(self, x):\n        x = ops.interpolate(x, scale_factor=2, mode='nearest')\n        x = self.conv(x)\n        return x\n\nclass Downsample(nn.Cell):\n    def __init__(self, channels):\n        super().__init__()\n        self.conv = nn.Conv2d(channels, channels, kernel_size=3, stride=2, padding=1, pad_mode='pad')\n\n    def construct(self, x):\n        return self.conv(x)\n\nclass Palette(nn.Cell):\n    def __init__(self, img_channels=3, base_channels=128, channel_mults=(1, 2, 4, 8),\n                 num_res_blocks=2, time_emb_dim=512, dropout=0.1, num_classes=None):\n        super().__init__()\n        self.img_channels = img_channels\n        self.base_channels = base_channels\n        self.num_classes = num_classes\n\n        # Time embedding\n        self.time_embed = TimeEmbedding(time_emb_dim)\n\n        # Class embedding (if applicable)\n        if num_classes is not None:\n            self.label_emb = nn.Embedding(num_classes, time_emb_dim)\n\n        # Initial convolution\n        self.init_conv = nn.Conv2d(img_channels, base_channels, kernel_size=3, padding=1, pad_mode='pad')\n\n        # Downsample path\n        down_channels = [base_channels]\n        curr_channels = base_channels\n        self.down = nn.CellList()\n\n        for i, mult in enumerate(channel_mults):\n            out_channels = base_channels * mult\n            for _ in range(num_res_blocks):\n                self.down.append(UNetDown(curr_channels, out_channels, time_emb_dim, i > 1, dropout))\n                curr_channels = out_channels\n                down_channels.append(curr_channels)\n\n            if i != len(channel_mults) - 1:\n                self.down.append(Downsample(curr_channels))\n                down_channels.append(curr_channels)\n\n        # Middle block\n        self.mid = MidBlock(curr_channels, time_emb_dim, dropout)\n\n        # Upsample path\n        self.up = nn.CellList()\n        up_channels = down_channels[::-1]\n\n        for i, mult in enumerate(reversed(channel_mults)):\n            out_channels = base_channels * mult\n            for _ in range(num_res_blocks + 1):\n                self.up.append(UNetUp(curr_channels, out_channels, time_emb_dim, i > 1, dropout))\n                curr_channels = out_channels\n\n            if i != len(channel_mults) - 1:\n                self.up.append(Upsample(curr_channels))\n\n        # Output block\n        self.norm_out = nn.GroupNorm(32, curr_channels)\n        self.swish_out = Swish()\n        self.final_conv = nn.Conv2d(curr_channels, img_channels, kernel_size=3, padding=1, pad_mode='pad')\n\n    def construct(self, x, time, y=None):\n        # Time embedding\n        t = self.time_embed(time)\n\n        # Class embedding (if applicable)\n        if y is not None:\n            t = t + self.label_emb(y)\n\n        # Initial convolution\n        x_orig = x\n        x = self.init_conv(x)\n        h = [x]\n\n        # Downsample path\n        for module in self.down:\n            if isinstance(module, UNetDown):\n                x = module(x, t)\n                h.append(x)\n            else:\n                x = module(x)\n                h.append(x)\n\n        # Middle block\n        x = self.mid(x, t)\n\n        # Upsample path\n        for module in self.up:\n            if isinstance(module, UNetUp):\n                skip = h.pop()\n                x = module(x, skip, t)\n            else:\n                x = module(x)\n\n        # Output block\n        x = self.swish_out(self.norm_out(x))\n        x = self.final_conv(x)\n\n        return x\n",[303],{"type":18,"tag":304,"props":305,"children":306},"code",{"__ignoreMap":7},[307],{"type":24,"value":301},{"title":7,"searchDepth":309,"depth":309,"links":310},4,[311],{"id":28,"depth":312,"text":31,"children":313},2,[314,316,322,323],{"id":61,"depth":315,"text":64},3,{"id":97,"depth":315,"text":100,"children":317},[318,319,320,321],{"id":104,"depth":309,"text":107},{"id":133,"depth":309,"text":136},{"id":162,"depth":309,"text":165},{"id":186,"depth":309,"text":189},{"id":254,"depth":315,"text":257},{"id":294,"depth":315,"text":297},"markdown","content:technology-blogs:zh:3750.md","content","technology-blogs/zh/3750.md","technology-blogs/zh/3750","md",1776506134452]