[{"data":1,"prerenderedAt":402},["ShallowReactive",2],{"content-query-87K7ANJ5MG":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":396,"_id":397,"_source":398,"_file":399,"_stem":400,"_extension":401},"/technology-blogs/zh/3748","zh",false,"","扩散模型系列——DDPM","DDPM   论文地址：Denoising Diffusion Probabilistic Models    代码地址：https://github.com/hojonathanho/diffusion","2025-05-07","https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/06/06/1a18a46ef03442ea8f8d83ba33b0a7af.png","technology-blogs","开发者说",{"type":15,"children":16,"toc":374},"root",[17,25,32,47,58,65,70,75,95,101,108,113,162,168,173,206,212,217,222,227,233,239,252,257,262,268,296,302,307,313,331,337,350,358,364],{"type":18,"tag":19,"props":20,"children":22},"element","h1",{"id":21},"扩散模型系列ddpm",[23],{"type":24,"value":8},"text",{"type":18,"tag":26,"props":27,"children":29},"h2",{"id":28},"ddpm",[30],{"type":24,"value":31},"DDPM",{"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/2006.11239",[43],"nofollow",[45],{"type":24,"value":46},"Denoising Diffusion Probabilistic 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/hojonathanho/diffusion",[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},"DDPM 是基于扩散过程的生成模型，通过逐步去除图像中的噪声来生成高质量的样本。其核心思想是将数据分布转换为更容易处理的简单高斯噪声分布，然后使用神经网络学习从该噪声分布中恢复原始数据的映射关系并通过优化变分下界简化训练，最终实现对复杂数据分布的建模。",{"type":18,"tag":33,"props":71,"children":72},{},[73],{"type":24,"value":74},"DDPM 的主要特点包括：",{"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},"双向马尔可夫链：正向过程固定（可解析求解），反向过程参数化（神经网络学习）；",{"type":18,"tag":80,"props":86,"children":87},{},[88],{"type":24,"value":89},"噪声预测机制：通过预测正向过程中添加的噪声间接恢复数据，避免显式估计复杂分布；",{"type":18,"tag":80,"props":91,"children":92},{},[93],{"type":24,"value":94},"U-Net 架构：利用多尺度特征和跳跃连接捕捉图像细节，结合时间嵌入感知扩散阶段。",{"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},"正向扩散是为了在每个时间步 t中，逐渐增加噪声的比例，将原始数据 x_0转变为带有噪声的数据 x_t = \\alpha_t x_0 + (1 - \\alpha_t) \\epsilon，其中 \\alpha_t是扩散系数，\\epsilon是标准正态分布的噪声。",{"type":18,"tag":76,"props":114,"children":115},{},[116,132],{"type":18,"tag":80,"props":117,"children":118},{},[119,121,125,127,130],{"type":24,"value":120},"单步扩散：每一步添加微小高斯噪声，状态转移分布为：",{"type":18,"tag":122,"props":123,"children":124},"br",{},[],{"type":24,"value":126},"q(x_t \\mid x_{t-1}) = \\mathcal{N}\\left(x_t; \\sqrt{1-\\beta_t}x_{t-1}, \\beta_t \\mathbf{I}\\right)",{"type":18,"tag":122,"props":128,"children":129},{},[],{"type":24,"value":131},"其中 \\beta_t \\in (0, 1)是预设的方差调度（通常随时间递增，如线性调度 \\beta_t = \\beta_{\\text{start}} + t*(\\beta_{\\text{end}} - \\beta_{\\text{start}})/T）。\\mathcal{N}(\\cdot; \\mu, \\sigma^2 I)表示均值为 \\mu，协方差矩阵为 \\sigma^2 I的多元高斯分布。",{"type":18,"tag":80,"props":133,"children":134},{},[135,137,140,142,145,147,150,152,155,157,160],{"type":24,"value":136},"边际分布：通过递归推导单步扩散公式，任意时刻 t的数据分布可直接由 x_0表示为：",{"type":18,"tag":122,"props":138,"children":139},{},[],{"type":24,"value":141},"q(x_t | x_0) = \\mathcal{N}(x_t; \\sqrt{\\bar{\\alpha}_t} x_0, (1 - \\bar{\\alpha}_t)I)",{"type":18,"tag":122,"props":143,"children":144},{},[],{"type":24,"value":146},"\\alpha_t = 1 - \\beta_t",{"type":18,"tag":122,"props":148,"children":149},{},[],{"type":24,"value":151},"\\bar{\\alpha}_t = \\prod_{s=1}^{t} \\alpha_s",{"type":18,"tag":122,"props":153,"children":154},{},[],{"type":24,"value":156},"该公式表明， x_t可直接由 x_0和随机噪声 \\epsilon \\sim \\mathcal{N}(0, \\mathbf{I})生成：",{"type":18,"tag":122,"props":158,"children":159},{},[],{"type":24,"value":161},"x_t = \\sqrt{\\bar{\\alpha}_t} x_0 + \\sqrt{1 - \\bar{\\alpha}_t} \\epsilon",{"type":18,"tag":102,"props":163,"children":165},{"id":164},"_2-反向去噪过程",[166],{"type":24,"value":167},"2. 反向去噪过程",{"type":18,"tag":33,"props":169,"children":170},{},[171],{"type":24,"value":172},"反向过程是将噪声分布转化为原始数据分布的过程，其目标是逆转扩散过程，从纯噪声 x_t出发，逐步去噪，最终生成与原始数据分布 p_{data}(x_0)相近的样本 x_0。",{"type":18,"tag":76,"props":174,"children":175},{},[176,201],{"type":18,"tag":80,"props":177,"children":178},{},[179,181,184,186,189,191,194,196,199],{"type":24,"value":180},"条件分布：反向过程的单步转移分布为参数化的高斯分布：",{"type":18,"tag":122,"props":182,"children":183},{},[],{"type":24,"value":185},"p_\\theta(x_{t-1} \\mid x_t) = \\mathcal{N}\\left(x_{t-1}; \\mu_\\theta(x_t, t), \\sigma_t^2 \\mathbf{I}\\right)",{"type":18,"tag":122,"props":187,"children":188},{},[],{"type":24,"value":190},"其中均值 \\mu_\\theta(x_t, t)由神经网络 \\epsilon_\\theta(x_t, t)预测噪声后推导得到：",{"type":18,"tag":122,"props":192,"children":193},{},[],{"type":24,"value":195},"\\mu_\\theta(x_t, t) = \\frac{1}{\\sqrt{\\alpha_t}} \\left( x_t - \\frac{1 - \\alpha_t}{\\sqrt{1 - \\bar{\\alpha}_t}} \\epsilon_\\theta(x_t, t) \\right)",{"type":18,"tag":122,"props":197,"children":198},{},[],{"type":24,"value":200},"方差 \\sigma_t^2可固定为预设值（如 \\sigma_t^2 = \\beta_t'，论文中采用可学习或固定的方差调度）。 同时，p(x_T) = \\mathcal{N}(x_T; 0, I)是预先定义的先验分布，通常为标准高斯分布。",{"type":18,"tag":80,"props":202,"children":203},{},[204],{"type":24,"value":205},"训练目标：通过最小化噪声预测的均方误差（MSE），使 \\epsilon_\\theta(x_t, t)逼近正向过程中添加的真实噪声 \\epsilon。",{"type":18,"tag":102,"props":207,"children":209},{"id":208},"_3-采样过程",[210],{"type":24,"value":211},"3. 采样过程",{"type":18,"tag":33,"props":213,"children":214},{},[215],{"type":24,"value":216},"从 x_T \\sim \\mathcal{N}(0, \\mathbf{I})开始，迭代应用反向过程：",{"type":18,"tag":33,"props":218,"children":219},{},[220],{"type":24,"value":221},"x_{t-1} = \\mu_\\theta(x_t, t) + \\sigma_t \\cdot z, \\quad z \\sim \\mathcal{N}(0, \\mathbf{I})",{"type":18,"tag":33,"props":223,"children":224},{},[225],{"type":24,"value":226},"直到生成 x_0，完成样本生成。",{"type":18,"tag":59,"props":228,"children":230},{"id":229},"三数学理论",[231],{"type":24,"value":232},"三、数学理论",{"type":18,"tag":102,"props":234,"children":236},{"id":235},"_1-变分推断框架",[237],{"type":24,"value":238},"1. 变分推断框架",{"type":18,"tag":33,"props":240,"children":241},{},[242,244,250],{"type":24,"value":243},"DDPM 的目标是最大化数据对数似然 \\log p_\\theta(x_0)，通过引入近似后验 q(x_{1:T} \\mid x_0)（即正向扩散过程），构建变分下界： $ \\log p_\\theta(x_0) \\geq \\mathbb{E}",{"type":18,"tag":245,"props":246,"children":247},"em",{},[248],{"type":24,"value":249},"{q(x",{"type":24,"value":251},"{1:T}|x_0)} \\left[ \\log \\frac{p_\\theta(x_{0:T})}{q(x_{1:T}|x_0)} \\right] =: L_{\\text{VLB}} $ 通过展开和简化（推导可见原论文），最终下界可分解为易于计算的噪声预测损失：",{"type":18,"tag":33,"props":253,"children":254},{},[255],{"type":24,"value":256},"L_{\\text{simple}} = \\mathbb{E}_{t \\sim \\mathcal{U}(1, T), x_0 \\sim q(x_0), \\epsilon \\sim \\mathcal{N}(0, \\mathbf{I})} \\left[ \\|\\epsilon - \\epsilon_\\theta\\left( x_t, t \\right)\\|^2 \\right]",{"type":18,"tag":33,"props":258,"children":259},{},[260],{"type":24,"value":261},"其中 x_t = \\sqrt{\\bar{\\alpha}_t}x_0 + \\sqrt{1-\\bar{\\alpha}_t}\\epsilon是正向过程生成的含噪数据。",{"type":18,"tag":102,"props":263,"children":265},{"id":264},"_2-关键公式推导",[266],{"type":24,"value":267},"2. 关键公式推导",{"type":18,"tag":76,"props":269,"children":270},{},[271,276,281],{"type":18,"tag":80,"props":272,"children":273},{},[274],{"type":24,"value":275},"正向过程的可加性：由于每一步添加的噪声独立，x_t可直接由 x_0和累积噪声权重生成，因此无需递归计算每一步 x_{t-1}。",{"type":18,"tag":80,"props":277,"children":278},{},[279],{"type":24,"value":280},"反向均值推导：利用贝叶斯公式和正向过程的高斯性质，将 \\mu_\\theta(x_t, t)表示为 x_t和预测噪声 \\epsilon_\\theta的线性组合，避免显式计算复杂的条件分布。",{"type":18,"tag":80,"props":282,"children":283},{},[284,286,289,291,294],{"type":24,"value":285},"变分下界分解：可分解为：",{"type":18,"tag":122,"props":287,"children":288},{},[],{"type":24,"value":290},"L = \\mathbb{E}_q \\left[ D_{KL}(q(x_T | x_0) \\parallel p(x_T)) + \\sum_{t=2}^{T} D_{KL}(q(x_{t-1} | x_t, x_0) \\parallel p_\\theta(x_{t-1} | x_t)) - \\log p_\\theta(x_0 | x_1) \\right]",{"type":18,"tag":122,"props":292,"children":293},{},[],{"type":24,"value":295},"其中 D_{KL}为两个高斯分布的 KL 散度。",{"type":18,"tag":59,"props":297,"children":299},{"id":298},"四模型结构",[300],{"type":24,"value":301},"四、模型结构",{"type":18,"tag":33,"props":303,"children":304},{},[305],{"type":24,"value":306},"DDPM 采用 U-Net 架构参数化反向过程的噪声预测函数 \\epsilon_\\theta(x_t, t)，核心设计包括：",{"type":18,"tag":102,"props":308,"children":310},{"id":309},"_1-网络架构",[311],{"type":24,"value":312},"1. 网络架构",{"type":18,"tag":76,"props":314,"children":315},{},[316,321,326],{"type":18,"tag":80,"props":317,"children":318},{},[319],{"type":24,"value":320},"编码器（下采样）：通过卷积和池化层提取多尺度特征，捕捉图像的全局结构。",{"type":18,"tag":80,"props":322,"children":323},{},[324],{"type":24,"value":325},"解码器（上采样）：通过转置卷积和跳跃连接恢复空间分辨率，融合编码器对应尺度的特征，保留细节信息。",{"type":18,"tag":80,"props":327,"children":328},{},[329],{"type":24,"value":330},"时间嵌入（Time Embedding）： 将时间步 t编码为高维向量（如正弦位置编码或可学习嵌入），通过线性层映射后与各层特征相加或拼接，使模型感知当前扩散阶段。",{"type":18,"tag":102,"props":332,"children":334},{"id":333},"_2-关键组件",[335],{"type":24,"value":336},"2. 关键组件",{"type":18,"tag":76,"props":338,"children":339},{},[340,345],{"type":18,"tag":80,"props":341,"children":342},{},[343],{"type":24,"value":344},"跳跃连接：直接传递编码器特征到解码器，避免下采样导致的信息丢失，增强细节恢复能力。",{"type":18,"tag":80,"props":346,"children":347},{},[348],{"type":24,"value":349},"自注意力机制：在中等分辨率层级（如 32×32 像素）引入自注意力层，建模长距离依赖关系，提升生成样本的全局一致性。",{"type":18,"tag":33,"props":351,"children":352},{},[353],{"type":18,"tag":354,"props":355,"children":357},"img",{"alt":7,"src":356},"https://obs-mindspore-file.obs.cn-north-4.myhuaweicloud.com/file/2025/06/06/9d76720bb0b946b48591b371f3d4d5fa.png",[],{"type":18,"tag":59,"props":359,"children":361},{"id":360},"五代码实现",[362],{"type":24,"value":363},"五、代码实现",{"type":18,"tag":365,"props":366,"children":368},"pre",{"code":367},"import 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\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",[369],{"type":18,"tag":370,"props":371,"children":372},"code",{"__ignoreMap":7},[373],{"type":24,"value":367},{"title":7,"searchDepth":375,"depth":375,"links":376},4,[377],{"id":28,"depth":378,"text":31,"children":379},2,[380,382,387,391,395],{"id":61,"depth":381,"text":64},3,{"id":97,"depth":381,"text":100,"children":383},[384,385,386],{"id":104,"depth":375,"text":107},{"id":164,"depth":375,"text":167},{"id":208,"depth":375,"text":211},{"id":229,"depth":381,"text":232,"children":388},[389,390],{"id":235,"depth":375,"text":238},{"id":264,"depth":375,"text":267},{"id":298,"depth":381,"text":301,"children":392},[393,394],{"id":309,"depth":375,"text":312},{"id":333,"depth":375,"text":336},{"id":360,"depth":381,"text":363},"markdown","content:technology-blogs:zh:3748.md","content","technology-blogs/zh/3748.md","technology-blogs/zh/3748","md",1776506134345]