[{"data":1,"prerenderedAt":305},["ShallowReactive",2],{"content-query-safdbPKgA7":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":299,"_id":300,"_source":301,"_file":302,"_stem":303,"_extension":304},"/technology-blogs/zh/3789","zh",false,"","开发者说 | 基于昇思MindSpore实现DDPM扩散模型","作者：Adream   来源：昇思论坛","2025-07-07","https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/07/11/249de20705d44d6e93f5830b2f4fec62.png","technology-blogs","开发者说",{"type":15,"children":16,"toc":294},"root",[17,25,31,36,41,50,58,63,68,88,96,104,114,122,129,137,145,154,161,169,177,184,193,216,226,239,246,254,262,272,281],{"type":18,"tag":19,"props":20,"children":22},"element","h1",{"id":21},"开发者说-基于昇思mindspore实现ddpm扩散模型",[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},"DDPM 是基于扩散过程的生成模型，通过逐步去除图像中的噪声来生成高质量的样本。其核心思想是将数据分布转换为更容易处理的简单高斯噪声分布，然后使用神经网络学习从该噪声分布中恢复原始数据的映射关系并通过优化变分下界简化训练，最终实现对复杂数据分布的建模。",{"type":18,"tag":26,"props":64,"children":65},{},[66],{"type":24,"value":67},"DDPM 的主要特点包括：",{"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},"**双向马尔可夫链：**正向过程固定（可解析求解），反向过程参数化（神经网络学习）；",{"type":18,"tag":73,"props":79,"children":80},{},[81],{"type":24,"value":82},"**噪声预测机制：**通过预测正向过程中添加的噪声间接恢复数据，避免显式估计复杂分布；",{"type":18,"tag":73,"props":84,"children":85},{},[86],{"type":24,"value":87},"**U-Net 架构：**利用多尺度特征和跳跃连接捕捉图像细节，结合时间嵌入感知扩散阶段。",{"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":18,"tag":118,"props":119,"children":121},"img",{"alt":7,"src":120},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/07/11/d1204c2873f54e73b627d3a208b21a48.png",[],{"type":18,"tag":26,"props":123,"children":124},{},[125],{"type":18,"tag":118,"props":126,"children":128},{"alt":7,"src":127},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/07/11/f90eb636e74f43f088f83c230da94312.png",[],{"type":18,"tag":26,"props":130,"children":131},{},[132],{"type":18,"tag":45,"props":133,"children":134},{},[135],{"type":24,"value":136},"# 03",{"type":18,"tag":26,"props":138,"children":139},{},[140],{"type":18,"tag":45,"props":141,"children":142},{},[143],{"type":24,"value":144},"数学理论",{"type":18,"tag":26,"props":146,"children":147},{},[148,149],{"type":24,"value":108},{"type":18,"tag":45,"props":150,"children":151},{},[152],{"type":24,"value":153},"变分推断框架",{"type":18,"tag":26,"props":155,"children":156},{},[157],{"type":18,"tag":118,"props":158,"children":160},{"alt":7,"src":159},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/07/11/6cd4d654fd4d4c9a95a1fb8146a92829.png",[],{"type":18,"tag":26,"props":162,"children":163},{},[164],{"type":18,"tag":45,"props":165,"children":166},{},[167],{"type":24,"value":168},"# 04",{"type":18,"tag":26,"props":170,"children":171},{},[172],{"type":18,"tag":45,"props":173,"children":174},{},[175],{"type":24,"value":176},"模型结构",{"type":18,"tag":26,"props":178,"children":179},{},[180],{"type":18,"tag":118,"props":181,"children":183},{"alt":7,"src":182},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/07/11/699af066995443f1b6d87b341db519b0.png",[],{"type":18,"tag":26,"props":185,"children":186},{},[187,188],{"type":24,"value":108},{"type":18,"tag":45,"props":189,"children":190},{},[191],{"type":24,"value":192},"网络架构",{"type":18,"tag":69,"props":194,"children":195},{},[196,201,206],{"type":18,"tag":73,"props":197,"children":198},{},[199],{"type":24,"value":200},"**编码器（下采样）：**通过卷积和池化层提取多尺度特征，捕捉图像的全局结构。",{"type":18,"tag":73,"props":202,"children":203},{},[204],{"type":24,"value":205},"**解码器（上采样）：**通过转置卷积和跳跃连接恢复空间分辨率，融合编码器对应尺度的特征，保留细节信息。",{"type":18,"tag":73,"props":207,"children":208},{},[209,214],{"type":18,"tag":45,"props":210,"children":211},{},[212],{"type":24,"value":213},"时间嵌入（Time Embedding）：",{"type":24,"value":215}," 将时间步 t编码为高维向量（如正弦位置编码或可学习嵌入），通过线性层映射后与各层特征相加或拼接，使模型感知当前扩散阶段。",{"type":18,"tag":26,"props":217,"children":218},{},[219,221],{"type":24,"value":220},"**2、**",{"type":18,"tag":45,"props":222,"children":223},{},[224],{"type":24,"value":225},"关键组件",{"type":18,"tag":69,"props":227,"children":228},{},[229,234],{"type":18,"tag":73,"props":230,"children":231},{},[232],{"type":24,"value":233},"**跳跃连接：**直接传递编码器特征到解码器，避免下采样导致的信息丢失，增强细节恢复能力。",{"type":18,"tag":73,"props":235,"children":236},{},[237],{"type":24,"value":238},"**自注意力机制：**在中等分辨率层级（如 32×32 像素）引入自注意力层，建模长距离依赖关系，提升生成样本的全局一致性。",{"type":18,"tag":26,"props":240,"children":241},{},[242],{"type":18,"tag":118,"props":243,"children":245},{"alt":7,"src":244},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/07/11/338d37f5094b420a97a218051cac5b34.png",[],{"type":18,"tag":26,"props":247,"children":248},{},[249],{"type":18,"tag":45,"props":250,"children":251},{},[252],{"type":24,"value":253},"# 05",{"type":18,"tag":26,"props":255,"children":256},{},[257],{"type":18,"tag":45,"props":258,"children":259},{},[260],{"type":24,"value":261},"MindSpo****re代码实现",{"type":18,"tag":263,"props":264,"children":266},"pre",{"code":265},"\nimport mindspore\nfrom mindspore import nn, ops\nimport numpy as np\n\n# 时间嵌入模块\nclass TimestepEmbedding(nn.Cell):\n    \"\"\"将时间步t编码为高维向量\"\"\"\n    def __init__(self, embed_dim=128):\n        super(TimestepEmbedding, self).__init__()\n        self.embed_dim = embed_dim\n        # 使用可学习的Embedding（替代正弦编码，简化实现）\n        self.time_embed = nn.Embedding(1000, embed_dim)  # 假设最大时间步为1000\n   \n    def construct(self, t):\n        # 输入t为形状(batch_size,)的整数张量\n        return self.time_embed(t).view(-1, self.embed_dim, 1, 1)  # 扩展为(batch, dim, 1, 1)用于特征融合\n\n# U-Net 模型（含时间嵌入）\nclass UNet(nn.Cell):\n    \"\"\"带跳跃连接和时间嵌入的U-Net，用于预测噪声ε_θ(x_t, t)\"\"\"\n    def __init__(self, in_channels=1, out_channels=1, time_embed_dim=128):\n        super(UNet, self).__init__()\n        self.time_embedding = TimestepEmbedding(time_embed_dim)\n       \n        # 编码器（下采样路径）\n        self.enc_conv1 = nn.Conv2d(in_channels, 64, 3, padding=1, pad_mode='pad')\n        self.enc_conv2 = nn.Conv2d(64, 64, 3, padding=1, pad_mode='pad')\n        self.enc_pool = nn.MaxPool2d(2)\n        self.enc_conv3 = nn.Conv2d(64, 128, 3, padding=1, pad_mode='pad')\n        self.enc_conv4 = nn.Conv2d(128, 128, 3, padding=1, pad_mode='pad')\n        \n        # 解码器（上采样路径）\n        self.dec_transconv1 = nn.Conv2dTranspose(128, 64, 2, stride=2)  # 上采样到编码器第一层尺度\n        self.dec_conv1 = nn.SequentialCell(\n            nn.Conv2d(128, 64, 3, padding=1, pad_mode='pad'),  # 拼接后通道数64+64=128→64\n            nn.ReLU()\n        )\n       \n        self.dec_transconv2 = nn.Conv2dTranspose(64, 32, 2, stride=2)  # 上采样到输入尺度\n        self.dec_conv2 = nn.SequentialCell(\n            nn.Conv2d(33, 32, 3, padding=1, pad_mode='pad'),  # 输入通道数：32（上采样）+1（输入x）=33→32\n            nn.ReLU()\n        )\n        \n        self.final_conv = nn.Conv2d(32, out_channels, 3, padding=1, pad_mode='pad')  # 输出噪声预测\n        self.relu = nn.ReLU()\n   \n    def construct(self, x, t):\n        # 时间嵌入\n        t_emb = self.time_embedding(t)\n        \n        # 编码器前向传播\n        h1 = self.relu(self.enc_conv1(x))\n        h1 = self.relu(self.enc_conv2(h1))  # (batch, 64, H, W)\n        h1_pool = self.enc_pool(h1)  # (batch, 64, H/2, W/2)\n        \n        h2 = self.relu(self.enc_conv3(h1_pool))\n        h2 = self.relu(self.enc_conv4(h2))  # (batch, 128, H/4, W/4)\n       \n        # 解码器反向传播\n        h3 = self.dec_transconv1(h2)  # (batch, 64, H/2, W/2)\n        h3 = ops.concat((h3, h1), axis=1)  # 跳跃连接：拼接编码器同尺度特征（64+64=128通道）\n        h3 = self.dec_conv1(h3)  # (batch, 64, H/2, W/2)\n        \n        h4 = self.dec_transconv2(h3)  # (batch, 32, H, W)\n        h4 = ops.concat((h4, x), axis=1)  # 拼接原始输入x（示例简化，实际应匹配尺度，此处假设输入为单通道）\n        h4 = self.dec_conv2(h4)  # (batch, 32, H, W)\n        \n        out = self.final_conv(h4)  # 输出预测噪声，形状与输入x一致\n        return out\n\n# DDPM 模型主体\nclass DDPM(nn.Cell):\n    \"\"\"DDPM主类，管理扩散过程和损失计算\"\"\"\n    def __init__(self, unet, num_timesteps=1000, beta_start=0.0001, beta_end=0.02):\n        super(DDPM, self).__init__()\n        self.unet = unet\n        self.num_timesteps = num_timesteps\n       \n        # 计算扩散参数（使用MindSpore张量，支持自动微分）\n        self.betas = mindspore.Tensor(\n            np.linspace(beta_start, beta_end, num_timesteps, dtype=np.float32)\n        )\n        self.alphas = 1. - self.betas\n        self.alphas_cumprod = ops.cumprod(self.alphas, 0)  # 累积乘积，形状(num_timesteps,)\n        self.sqrt_alphas_cumprod = ops.sqrt(self.alphas_cumprod)\n        self.sqrt_one_minus_alphas_cumprod = ops.sqrt(1. - self.alphas_cumprod)\n    \n    def q_sample(self, x_start, t):\n        \"\"\"根据正向过程生成x_t = sqrt(α_t^bar)x0 + sqrt(1-α_t^bar)ε\"\"\"\n        sqrt_alpha_prod = ops.gather(self.sqrt_alphas_cumprod, t, 0)  # 提取批次对应的α累积根\n        sqrt_one_minus_alpha_prod = ops.gather(self.sqrt_one_minus_alphas_cumprod, t, 0)\n        noise = ops.randn_like(x_start)  # 生成随机噪声\n        return (sqrt_alpha_prod.view(-1, 1, 1, 1) * x_start +\n                sqrt_one_minus_alpha_prod.view(-1, 1, 1, 1) * noise)\n    \n    def p_losses(self, x_start, t):\n        \"\"\"计算噪声预测损失：MSE(ε_θ(x_t, t), ε)\"\"\"\n        noise = ops.randn_like(x_start)  # 真实噪声ε\n        x_noisy = self.q_sample(x_start, t)  # 生成含噪数据x_t\n        predicted_noise = self.unet(x_noisy, t)  # 模型预测噪声\n        return nn.MSELoss()(predicted_noise, noise)\n   \n    def construct(self, x):\n        \"\"\"训练时的前向传播：随机采样时间步t，计算损失\"\"\"\n        batch_size = x.shape[0]\n        t = ops.randint(0, self.num_timesteps, (batch_size,), dtype=mindspore.int32)\n        return self.p_losses(x, t)\n",[267],{"type":18,"tag":268,"props":269,"children":270},"code",{"__ignoreMap":7},[271],{"type":24,"value":265},{"type":18,"tag":273,"props":274,"children":276},"h2",{"id":275},"参考链接",[277],{"type":18,"tag":45,"props":278,"children":279},{},[280],{"type":24,"value":275},{"type":18,"tag":26,"props":282,"children":283},{},[284,286],{"type":24,"value":285},"[1] 论文地址：",{"type":18,"tag":287,"props":288,"children":292},"a",{"href":289,"rel":290},"https://arxiv.org/pdf/2006.11239",[291],"nofollow",[293],{"type":24,"value":289},{"title":7,"searchDepth":295,"depth":295,"links":296},4,[297],{"id":275,"depth":298,"text":275},2,"markdown","content:technology-blogs:zh:3789.md","content","technology-blogs/zh/3789.md","technology-blogs/zh/3789","md",1776506135231]