<p>?</p><p/><h1>人工智能之核心技術(shù) 深度學(xué)習(xí)</h1><p/><p>第七章 擴(kuò)散模型(Diffusion Models)</p><p class="image-package"><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/30827302-5d2d84431912bea0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p>
<h1>前言:擴(kuò)散模型(Diffusion Models)—— 生成式 AI 的新王者</h1><p>如果說(shuō) GAN 是生成模型的“藝術(shù)家”,那么<strong>擴(kuò)散模型(Diffusion Models)</strong>?就是“科學(xué)家”——它通過(guò)模擬物理中的<strong>熱力學(xué)擴(kuò)散過(guò)程</strong>,以極其穩(wěn)定、高質(zhì)量的方式生成圖像、音頻、3D 等復(fù)雜數(shù)據(jù)。自 2020 年 DDPM 提出以來(lái),擴(kuò)散模型迅速超越 GAN,成為生成式 AI 的主流架構(gòu),并催生了?<strong>Stable Diffusion、DALL·E 2/3、Midjourney</strong>?等現(xiàn)象級(jí)應(yīng)用。</p>
<p><strong>一、擴(kuò)散模型核心原理</strong></p><p><strong>1.1 直觀類比:從“墨水滴入清水”說(shuō)起</strong></p><p>想象一滴墨水滴入清水中:</p><ul><li><p>??<strong>前向過(guò)程(Forward Process)</strong>:墨水逐漸擴(kuò)散,最終整杯水變均勻灰色(<strong>加噪</strong>)</p></li><li><p>??<strong>反向過(guò)程(Reverse Process)</strong>:如果知道擴(kuò)散規(guī)律,理論上可以逆向操作,讓墨水重新聚集成一滴(<strong>去噪</strong>)</p></li></ul><p>擴(kuò)散模型正是模擬這一過(guò)程:</p><ul><li><p>??<strong>訓(xùn)練階段</strong>:學(xué)習(xí)如何從噪聲中一步步還原原始數(shù)據(jù)</p></li><li><p>??<strong>生成階段</strong>:從純?cè)肼曢_(kāi)始,逐步“去噪”生成新樣本</p></li></ul>
<p><strong>1.2 前向擴(kuò)散過(guò)程(Fixed, Non-Learnable)</strong></p><p>給定真實(shí)圖像?,通過(guò)??步逐步添加高斯噪聲:</p><p/><p>其中:</p><ul><li><p>???是預(yù)設(shè)的小噪聲方差(如線性增長(zhǎng):0.0001 → 0.02)</p></li><li><p>??(通常?)</p></li><li><p>? 經(jīng)過(guò)足夠多步后,(純?cè)肼暎?lt;/p></li></ul><blockquote><p>??<strong>關(guān)鍵性質(zhì)</strong>:任意時(shí)刻??可直接由??計(jì)算(重參數(shù)化技巧):</p></blockquote><p/><p>其中?</p>
<p><strong>1.3 反向擴(kuò)散過(guò)程(Learnable)</strong></p><p>目標(biāo):學(xué)習(xí)一個(gè)神經(jīng)網(wǎng)絡(luò)?,預(yù)測(cè)每一步添加的噪聲?,從而逆向還原圖像。</p><p>反向過(guò)程定義為:</p><p/><p>在 DDPM 中,<strong>方差??固定為?</strong>,只需學(xué)習(xí)均值?。而更巧妙的是:<strong>直接預(yù)測(cè)噪聲?</strong>!</p>
<p><strong>1.4 馬爾可夫鏈建模</strong></p><p>整個(gè)擴(kuò)散過(guò)程構(gòu)成一個(gè)<strong>馬爾可夫鏈</strong>:</p><ul><li><p>? 每一步只依賴前一狀態(tài)</p></li><li><p>? 前向鏈固定,反向鏈由神經(jīng)網(wǎng)絡(luò)參數(shù)化</p></li><li><p class="image-package"><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/30827302-6c46df51ee2bf908.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p><p/></li></ul><blockquote><p>???<strong>優(yōu)勢(shì)</strong>:訓(xùn)練穩(wěn)定、不易模式崩潰、生成質(zhì)量高!</p></blockquote>
<p><strong>二、擴(kuò)散模型關(guān)鍵技術(shù)</strong></p><p><strong>2.1 噪聲預(yù)測(cè)網(wǎng)絡(luò):UNet 架構(gòu)</strong></p><p>擴(kuò)散模型的核心是一個(gè)<strong>時(shí)間條件 UNet</strong>:</p><p><strong>結(jié)構(gòu)特點(diǎn):</strong></p><ul><li><p>??<strong>編碼器-解碼器</strong>:下采樣提取特征,上采樣重建圖像</p></li><li><p>??<strong>殘差連接(Skip Connections)</strong>:保留細(xì)節(jié)信息</p></li><li><p>??<strong>時(shí)間嵌入(Time Embedding)</strong>:將時(shí)間步??編碼為向量,注入每一層(通過(guò) AdaGN 或 Attention)</p></li><li><p>??<strong>自注意力機(jī)制</strong>:增強(qiáng)全局建模能力(尤其在高分辨率)</p></li></ul><pre>UNetx_tConv?+?TimeEmbDownsample?+?TimeEmbAttention?+?ResBlockUpsample?+?Skip?+?TimeEmbConv?+?Skip?+?TimeEmbε?θ(x_t,?t)tTime?Embedding</pre>
<p><strong>2.2 損失函數(shù):簡(jiǎn)單而強(qiáng)大</strong></p><p>DDPM 使用<strong>簡(jiǎn)化版變分下界(ELBO)</strong>,最終等價(jià)于:</p><p/><ul><li><p>??<strong>輸入</strong>:帶噪圖像??+ 時(shí)間步?</p></li><li><p>??<strong>目標(biāo)</strong>:預(yù)測(cè)原始噪聲?</p></li><li><p>??<strong>損失</strong>:均方誤差(MSE)</p></li></ul><blockquote><p>??<strong>優(yōu)點(diǎn)</strong>:無(wú)需對(duì)抗訓(xùn)練,梯度穩(wěn)定,易于優(yōu)化!</p></blockquote>
<p><strong>2.3 采樣加速策略</strong></p><p>原始 DDPM 需 1000 步采樣 → 太慢!改進(jìn)方法:</p><p/><p/><blockquote><p>???<strong>Stable Diffusion 關(guān)鍵</strong>:
先用 VAE 將圖像壓縮到 latent space(如 64×64),再在此空間進(jìn)行擴(kuò)散 → 大幅降低計(jì)算成本!</p></blockquote>
<p><strong>三、經(jīng)典擴(kuò)散模型變體</strong></p><p><strong>3.1 DDPM(Denoising Diffusion Probabilistic Models, 2020)</strong></p><ul><li><p>??<strong>開(kāi)山之作</strong>,證明擴(kuò)散模型可生成高質(zhì)量圖像</p></li><li><p>? 使用 UNet + 時(shí)間嵌入</p></li><li><p>? 采樣慢(1000 步),但訓(xùn)練穩(wěn)定</p></li></ul>
<p><strong>3.2 Stable Diffusion(2022)</strong></p><ul><li><p>??<strong>文本到圖像生成的里程碑</strong></p></li><li><p>??<strong>三大組件</strong>:</p></li><ol><li><p>1.?<strong>VAE</strong>:圖像 ? 潛在表示</p></li><li><p>2.?<strong>UNet 擴(kuò)散模型</strong>:在 latent space 去噪</p></li><li><p>3.?<strong>CLIP Text Encoder</strong>:將文本編碼為條件向量</p></li></ol><li><p>??<strong>條件生成</strong>:UNet 輸入 = latent + text embedding + time</p></li></ul><pre>文本提示CLIP?Text?Encoder文本條件?c隨機(jī)噪聲?z_TUNet時(shí)間步?tz{t-1}...z_0VAE?Decoder生成圖像</pre><blockquote><p>??<strong>優(yōu)勢(shì)</strong>:開(kāi)源、高效、支持 fine-tuning(LoRA、Textual Inversion)</p></blockquote>
<p><strong>3.3 DALL·E 3(2023)</strong></p><ul><li><p>??<strong>結(jié)合 Transformer 與擴(kuò)散模型</strong></p></li><li><p>??<strong>兩階段生成</strong>:</p></li><ol><li><p>1.?<strong>Prompt 改寫(xiě)</strong>:用大語(yǔ)言模型(LLM)將用戶輸入改寫(xiě)為更詳細(xì)的描述</p></li><li><p>2.?<strong>擴(kuò)散生成</strong>:用改進(jìn)的 GLIDE 模型生成圖像</p></li></ol><li><p>??<strong>多模態(tài)對(duì)齊</strong>:確保圖像細(xì)節(jié)與文本嚴(yán)格一致</p></li></ul>
<p><strong>四、擴(kuò)散模型應(yīng)用場(chǎng)景</strong></p><p/><p/><blockquote><p>???<strong>趨勢(shì)</strong>:擴(kuò)散模型正成為<strong>多模態(tài)生成</strong>的統(tǒng)一框架!</p></blockquote>
<p><strong>五、配套代碼實(shí)現(xiàn)(簡(jiǎn)化 DDPM)</strong></p><pre>import?torchimport?torch.nn?as?nnimport?math#?1.?時(shí)間嵌入(Sinusoidal)def?timestep_embedding(timesteps,?dim,?max_period=10000):????half?=?dim?//?2????freqs?=?torch.exp(????????-math.log(max_period)??torch.arange(start=0,?end=half,?dtype=torch.float32)?/?half????).to(timesteps.device)????args?=?timesteps[:,?None].float()??freqs[None]????embedding?=?torch.cat([torch.cos(args),?torch.sin(args)],?dim=-1)????if?dim?%?2:????????embedding?=?torch.cat([embedding,?torch.zeros_like(embedding[:,?:1])],?dim=-1)????return?embedding#?2.?簡(jiǎn)化?UNet?塊class?UNetBlock(nn.Module):????def?init(self,?in_ch,?out_ch,?time_emb_dim):????????super().init()????????self.conv?=?nn.Conv2d(in_ch,?out_ch,?3,?padding=1)????????self.time_proj?=?nn.Linear(time_emb_dim,?out_ch)????????self.norm?=?nn.GroupNorm(8,?out_ch)????????self.act?=?nn.SiLU()????def?forward(self,?x,?time_emb):????????x?=?self.conv(x)????????time_bias?=?self.time_proj(time_emb)[:,?:,?None,?None]????????x?=?x?+?time_bias????????x?=?self.norm(x)????????return?self.act(x)#?3.?極簡(jiǎn)?UNet(僅示意)class?SimpleUNet(nn.Module):????def?init(self,?img_channels=3,?time_emb_dim=128):????????super().init()????????self.time_mlp?=?nn.Sequential(????????????nn.Linear(1,?time_emb_dim),????????????nn.SiLU(),????????????nn.Linear(time_emb_dim,?time_emb_dim)????????)????????self.enc1?=?UNetBlock(img_channels,?64,?time_emb_dim)????????self.enc2?=?UNetBlock(64,?128,?time_emb_dim)????????self.dec2?=?UNetBlock(128,?64,?time_emb_dim)????????self.final?=?nn.Conv2d(64,?img_channels,?1)????def?forward(self,?x,?t):????????#?t:?[batch_size]????????t?=?t.unsqueeze(-1).float()????????time_emb?=?self.time_mlp(t)??#?[B,?time_emb_dim]????????x1?=?self.enc1(x,?time_emb)????????x2?=?self.enc2(x1,?time_emb)????????x?=?self.dec2(x2,?time_emb)????????return?self.final(x)#?4.?訓(xùn)練步驟(核心)def?train_step(model,?x0,?t,?noise):????#?x0:?[B,?C,?H,?W],?t:?[B],?noise:?[B,?C,?H,?W]????alpha_bar?=?get_alpha_bar(t)??#?預(yù)計(jì)算?α?_t????xt?=?torch.sqrt(alpha_bar)??x0?+?torch.sqrt(1?-?alpha_bar)??noise????pred_noise?=?model(xt,?t)????loss?=?nn.functional.mse_loss(pred_noise,?noise)????return?loss#?使用示例model?=?SimpleUNet()x0?=?torch.randn(4,?3,?32,?32)t?=?torch.randint(0,?1000,?(4,))noise?=?torch.randn_like(x0)loss?=?train_step(model,?x0,?t,?noise)print("Loss:",?loss.item())</pre><blockquote><p>???<strong>說(shuō)明</strong>:此為教學(xué)簡(jiǎn)化版,實(shí)際 UNet 包含下采樣、上采樣、注意力等模塊。</p></blockquote>
<p><strong>六、擴(kuò)散模型 vs GAN</strong></p><p/><p/>
<p><strong>七、總結(jié)</strong></p><pre>DDPM?2020Improved?Sampling(DDIM,?etc.)Latent?Diffusion(Stable?Diffusion)ControlNet(可控生成)Text-to-3D(DreamFusion)Audio?Diffusion(DiffWave)多模態(tài)生成統(tǒng)一框架</pre><blockquote><p>??<strong>未來(lái)方向</strong>:</p><ul><li><p>??<strong>更快采樣</strong>(1 步生成?)</p></li><li><p>??<strong>更強(qiáng)語(yǔ)義控制</strong>(結(jié)合 LLM)</p></li><li><p>??<strong>3D/視頻/科學(xué)生成</strong></p></li></ul></blockquote>
<p>深度學(xué)習(xí)核心架構(gòu)的系統(tǒng)學(xué)習(xí):
<strong>CNN → RNN → Transformer → GAN → Diffusion</strong>
共同構(gòu)成了現(xiàn)代 AI 的技術(shù)基石。</p><h1>資料關(guān)注</h1><p>公眾號(hào):咚咚王
gitee:https://gitee.com/wy18585051844/ai_learning</p><p class="image-package"><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/30827302-9ae381ce562217ba.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p><p>《Python編程:從入門到實(shí)踐》
《利用Python進(jìn)行數(shù)據(jù)分析》
《算法導(dǎo)論中文第三版》
《概率論與數(shù)理統(tǒng)計(jì)(第四版) (盛驟) 》
《程序員的數(shù)學(xué)》
《線性代數(shù)應(yīng)該這樣學(xué)第3版》
《微積分和數(shù)學(xué)分析引論》
《(西瓜書(shū))周志華-機(jī)器學(xué)習(xí)》
《TensorFlow機(jī)器學(xué)習(xí)實(shí)戰(zhàn)指南》
《Sklearn與TensorFlow機(jī)器學(xué)習(xí)實(shí)用指南》
《模式識(shí)別(第四版)》
《深度學(xué)習(xí) deep learning》伊恩·古德費(fèi)洛著 花書(shū)
《Python深度學(xué)習(xí)第二版(中文版)【純文本】 (登封大數(shù)據(jù) (Francois Choliet)) (Z-Library)》
《深入淺出神經(jīng)網(wǎng)絡(luò)與深度學(xué)習(xí)+(邁克爾·尼爾森(Michael+Nielsen)》
《自然語(yǔ)言處理綜論 第2版》
《Natural-Language-Processing-with-PyTorch》
《計(jì)算機(jī)視覺(jué)-算法與應(yīng)用(中文版)》
《Learning OpenCV 4》
《AIGC:智能創(chuàng)作時(shí)代》杜雨+&+張孜銘
《AIGC原理與實(shí)踐:零基礎(chǔ)學(xué)大語(yǔ)言模型、擴(kuò)散模型和多模態(tài)模型》
《從零構(gòu)建大語(yǔ)言模型(中文版)》
《實(shí)戰(zhàn)AI大模型》
《AI 3.0》</p><p>?</p><p/><p/><p/><p/><p/>