[{"data":1,"prerenderedAt":378},["ShallowReactive",2],{"content-query-LeVLyeLRYa":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":372,"_id":373,"_source":374,"_file":375,"_stem":376,"_extension":377},"/technology-blogs/zh/3767","zh",false,"","开发者说 | 基于昇思MindSpore实现Palette扩散模型","作者：Adream   来源：昇思论坛","2025-06-19","https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/06/20/1b82d7e530b6452fbbb41739d16566ba.png","technology-blogs","开发者说",{"type":15,"children":16,"toc":367},"root",[17,25,31,36,41,50,58,63,68,88,96,104,114,119,137,147,152,170,178,183,196,204,209,267,275,283,288,311,319,327,335,345,354],{"type":18,"tag":19,"props":20,"children":22},"element","h1",{"id":21},"开发者说-基于昇思mindspore实现palette扩散模型",[23],{"type":24,"value":8},"text",{"type":18,"tag":26,"props":27,"children":28},"p",{},[29],{"type":24,"value":30},"作者：Adream",{"type":18,"tag":26,"props":32,"children":33},{},[34],{"type":24,"value":35},"来源：昇思论坛",{"type":18,"tag":26,"props":37,"children":38},{},[39],{"type":24,"value":40},"昇思MindSpore2024年技术帖分享大会圆满结束！全年收获80+高质量技术帖， 2025年全新升级，推出“2025年昇思干货小卖部，你投我就收！”，活动继续每月征集技术帖。本期技术文章由社区开发者Adrem输出并投稿。如果您对活动感兴趣，欢迎在昇思论坛投稿。",{"type":18,"tag":26,"props":42,"children":43},{},[44],{"type":18,"tag":45,"props":46,"children":47},"strong",{},[48],{"type":24,"value":49},"# 01",{"type":18,"tag":26,"props":51,"children":52},{},[53],{"type":18,"tag":45,"props":54,"children":55},{},[56],{"type":24,"value":57},"概述",{"type":18,"tag":26,"props":59,"children":60},{},[61],{"type":24,"value":62},"Palette 是一种基于扩散模型的通用图像转换模型，可用于图像着色，图像修复，图像补全和 JPEG 图像恢复等多种转换任务，它通过输入的条件x来构建分布p(y|x)，并通过图像级联的方式引入条件图像。",{"type":18,"tag":26,"props":64,"children":65},{},[66],{"type":24,"value":67},"Palette 的主要特点包括：",{"type":18,"tag":69,"props":70,"children":71},"ul",{},[72,78,83],{"type":18,"tag":73,"props":74,"children":75},"li",{},[76],{"type":24,"value":77},"**统一框架：**Palette 模型采用了统一的框架，通过条件扩散模型解决多个图像到图像翻译任务，而无需针对每个任务进行特定的超参数调整、架构定制或辅助损失函数的设计。",{"type":18,"tag":73,"props":79,"children":80},{},[81],{"type":24,"value":82},"**样本多样性：**通过采用 L2 损失函数，Palette 模型在多个任务上均展现出了较高的样本多样性。这对于需要生成多种可能结果的图像到图像翻译任务尤为重要。",{"type":18,"tag":73,"props":84,"children":85},{},[86],{"type":24,"value":87},"**条件 UNet 主干：**采用 256×256 分辨率的条件 UNet，通过跳跃连接融合多尺度特征，增强跨层信息传递。",{"type":18,"tag":26,"props":89,"children":90},{},[91],{"type":18,"tag":45,"props":92,"children":93},{},[94],{"type":24,"value":95},"# 02",{"type":18,"tag":26,"props":97,"children":98},{},[99],{"type":18,"tag":45,"props":100,"children":101},{},[102],{"type":24,"value":103},"主要步骤",{"type":18,"tag":26,"props":105,"children":106},{},[107,109],{"type":24,"value":108},"**1、**",{"type":18,"tag":45,"props":110,"children":111},{},[112],{"type":24,"value":113},"预训练基础扩散模型",{"type":18,"tag":26,"props":115,"children":116},{},[117],{"type":24,"value":118},"Palette 的预训练阶段建立在扩散模型的核心框架上，通过学习图像的噪声分布来捕获数据的潜在结构。",{"type":18,"tag":69,"props":120,"children":121},{},[122,127,132],{"type":18,"tag":73,"props":123,"children":124},{},[125],{"type":24,"value":126},"**扩散过程：**逐步向图像添加高斯噪声，将原始图像 x转换为噪声样本 x_T。",{"type":18,"tag":73,"props":128,"children":129},{},[130],{"type":24,"value":131},"**去噪过程：**训练 UNet 模型学习反向过程，从噪声中恢复原始图像。",{"type":18,"tag":73,"props":133,"children":134},{},[135],{"type":24,"value":136},"**关键技术：**使用时间嵌入编码当前噪声强度，帮助模型理解去噪阶段。",{"type":18,"tag":26,"props":138,"children":139},{},[140,142],{"type":24,"value":141},"**2、**",{"type":18,"tag":45,"props":143,"children":144},{},[145],{"type":24,"value":146},"任务条件化适配",{"type":18,"tag":26,"props":148,"children":149},{},[150],{"type":24,"value":151},"针对不同图像转换任务，Palette 通过以下方式进行条件化：",{"type":18,"tag":69,"props":153,"children":154},{},[155,160,165],{"type":18,"tag":73,"props":156,"children":157},{},[158],{"type":24,"value":159},"**任务特定提示：**为每个任务设计专用的输入提示（如掩码区域、低分辨率图像、灰度图等）。",{"type":18,"tag":73,"props":161,"children":162},{},[163],{"type":24,"value":164},"**条件嵌入：**将任务提示通过额外的网络层转换为条件嵌入，与 UNet 的中间特征融合。",{"type":18,"tag":73,"props":166,"children":167},{},[168],{"type":24,"value":169},"**多任务学习：**通过共享主干网络、任务特定分支的方式，使模型同时掌握多个任务。",{"type":18,"tag":26,"props":171,"children":172},{},[173],{"type":18,"tag":45,"props":174,"children":175},{},[176],{"type":24,"value":177},"3、自适应噪声调度",{"type":18,"tag":26,"props":179,"children":180},{},[181],{"type":24,"value":182},"Palette 引入自适应噪声调度提升不同任务的性能：",{"type":18,"tag":69,"props":184,"children":185},{},[186,191],{"type":18,"tag":73,"props":187,"children":188},{},[189],{"type":24,"value":190},"**任务感知噪声强度：**根据任务难度动态调整噪声水平，例如修复任务使用更高噪声强度。",{"type":18,"tag":73,"props":192,"children":193},{},[194],{"type":24,"value":195},"**渐进式细化：**在去噪后期增加额外的细化步骤，提升细节质量。",{"type":18,"tag":26,"props":197,"children":198},{},[199],{"type":18,"tag":45,"props":200,"children":201},{},[202],{"type":24,"value":203},"4、后处理与质量优化",{"type":18,"tag":26,"props":205,"children":206},{},[207],{"type":24,"value":208},"生成结果经过以下处理提升最终质量：",{"type":18,"tag":69,"props":210,"children":211},{},[212,231,249],{"type":18,"tag":73,"props":213,"children":214},{},[215,220,224,226,229],{"type":18,"tag":45,"props":216,"children":217},{},[218],{"type":24,"value":219},"细化网络",{"type":18,"tag":221,"props":222,"children":223},"br",{},[],{"type":24,"value":225},"**局部增强：**对生成的图像进行局部细化，例如增强边缘、平滑过渡区域。",{"type":18,"tag":221,"props":227,"children":228},{},[],{"type":24,"value":230},"**对抗训练：**引入判别器网络，提升生成图像的真实性。",{"type":18,"tag":73,"props":232,"children":233},{},[234,239,242,244,247],{"type":18,"tag":45,"props":235,"children":236},{},[237],{"type":24,"value":238},"一致性检查",{"type":18,"tag":221,"props":240,"children":241},{},[],{"type":24,"value":243},"**区域匹配：**确保生成区域与周围环境自然融合，避免人工痕迹。",{"type":18,"tag":221,"props":245,"children":246},{},[],{"type":24,"value":248},"**语义一致性：**在多对象场景中，保持对象间的语义关系（如比例、遮挡）。",{"type":18,"tag":73,"props":250,"children":251},{},[252,257,260,262,265],{"type":18,"tag":45,"props":253,"children":254},{},[255],{"type":24,"value":256},"质量控制",{"type":18,"tag":221,"props":258,"children":259},{},[],{"type":24,"value":261},"**置信度估计：**预测每个像素的生成置信度，对低置信度区域进行重采样。",{"type":18,"tag":221,"props":263,"children":264},{},[],{"type":24,"value":266},"**混合输出：**结合多个采样结果，通过加权平均生成最终图像。",{"type":18,"tag":26,"props":268,"children":269},{},[270],{"type":18,"tag":45,"props":271,"children":272},{},[273],{"type":24,"value":274},"# 03",{"type":18,"tag":26,"props":276,"children":277},{},[278],{"type":18,"tag":45,"props":279,"children":280},{},[281],{"type":24,"value":282},"模型结构",{"type":18,"tag":26,"props":284,"children":285},{},[286],{"type":24,"value":287},"从论文中可以看出，Palette 模型的核心架构就是采用了条件扩散模型作为基础框架，并在此基础上做成了一些改进。",{"type":18,"tag":69,"props":289,"children":290},{},[291,296,301,306],{"type":18,"tag":73,"props":292,"children":293},{},[294],{"type":24,"value":295},"**UNet 主干：**使用的是 256×256 的条件 UNet，这是一种对称结构。它包含上下采样路径和瓶颈层。同时在上下采样路径中，都包含了每个残差块，它们使用了跳跃连接来整合不同尺度的特征信息，达到捕捉图像的多尺度细节的效果。",{"type":18,"tag":73,"props":297,"children":298},{},[299],{"type":24,"value":300},"**条件嵌入：**模型融合了多种条件信息来改变生成图像的结果，这其中包括了任务类型嵌入、时间步嵌入和条件图像特征。任务类型嵌入是用于区分图像的转换，例如着色、填充等；而时间步嵌入则是用于帮助模型理解生成过程中的时间信息；条件图像特征则是通过对输入的条件图像进行特征提取，将其作为额外的条件信息输入到模型中，使模型能够根据给定的条件图像生成相应的输出。",{"type":18,"tag":73,"props":302,"children":303},{},[304],{"type":24,"value":305},"**多尺度特征融合：**在模型生成图像过程中，有一个步骤为跳跃连接，它是将下采样过程中不同维度的图像特征与上采样过程中的对应维度图像特征进行融合，从而丰富图像在不同尺度上的表现。",{"type":18,"tag":73,"props":307,"children":308},{},[309],{"type":24,"value":310},"L2 损失函数：Palette 模型的损失函数是基于去噪目标的，即给定一个训练输出图像y，生成其噪声版本\\tilde{y}，并训练神经网络f_θ在条件x和噪声水平指标\\gamma下对\\tilde{y}进行去噪。而模型所使用的损失函数一般为 L2 范数，其数学公式为：",{"type":18,"tag":26,"props":312,"children":313},{},[314],{"type":18,"tag":315,"props":316,"children":318},"img",{"alt":7,"src":317},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/06/20/31c7403bfb2741bd995fd69a3320fd74.png",[],{"type":18,"tag":26,"props":320,"children":321},{},[322],{"type":18,"tag":45,"props":323,"children":324},{},[325],{"type":24,"value":326},"# 04",{"type":18,"tag":26,"props":328,"children":329},{},[330],{"type":18,"tag":45,"props":331,"children":332},{},[333],{"type":24,"value":334},"MindSpo****re代码实现",{"type":18,"tag":336,"props":337,"children":339},"pre",{"code":338},"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        return x\n",[340],{"type":18,"tag":341,"props":342,"children":343},"code",{"__ignoreMap":7},[344],{"type":24,"value":338},{"type":18,"tag":346,"props":347,"children":349},"h3",{"id":348},"参考链接",[350],{"type":18,"tag":45,"props":351,"children":352},{},[353],{"type":24,"value":348},{"type":18,"tag":26,"props":355,"children":356},{},[357,359],{"type":24,"value":358},"[1] 论文地址：",{"type":18,"tag":360,"props":361,"children":365},"a",{"href":362,"rel":363},"https://arxiv.org/pdf/2111.05826",[364],"nofollow",[366],{"type":24,"value":362},{"title":7,"searchDepth":368,"depth":368,"links":369},4,[370],{"id":348,"depth":371,"text":348},3,"markdown","content:technology-blogs:zh:3767.md","content","technology-blogs/zh/3767.md","technology-blogs/zh/3767","md",1776506134798]