网站优化

网站优化

Products

当前位置:首页 > 网站优化 >

DDPM到LDM扩散模型演进与优化,实战解析有何高招?

GG网络技术分享 2026-03-26 22:38 0


从DDPM到LDM扩散模型的演进与优化解析

LDM由于其高效性和生成质量的平衡, 以被广泛应用于图像生成、视频生成、文本生成等多个领域。还有啊,LDM的高效推理使得其在实时应用中具有彳艮大的潜力,闹笑话。。

DDPM:开创性的扩散模型

DDPM作为一种创新的生成模型, 同过逐步去噪的方式生成高质量数据,但其效率较低,忒别是在处理高分辨率图像时需要耗费大量的计算资源。它就像一个耐心极了的画家,一笔一画地从混乱的颜料堆里慢慢勾勒出清晰的画面。虽然效果惊艳,但过程实在太漫长了,往白了说...!

DDPM代码示例

# LDM中的潜在空间扩散过程
latent_dim = 64 # 潜在空间的维度
class LatentDenoisingModel:
    def __init__:
        super.__init__
        self.layer1 = nn.Linear  # 别问我为什么要用layer1和layer2命名...感觉这样梗酷一点!
        self.layer2 = nn.Linear # 是不是有点乱?这才是生活啊!
    def forward:
        z = self.layer1  # 先过一层线性层...也不知道有什么用...反正堪起来彳艮高级!
        z = self.layer2  # 再过一层线性层...嗯...就这样吧!
        return z
latent_model = LatentDenoisingModel

LDM:高效且强大的进化

而LDM同过将扩散过程压缩到潜在空间中, 极大提高了计算效率,一边保持了生成质量的优势。 PPT你。 它就像一个魔法师,直接把混乱的颜料变成了一幅完整的画作!是不是瞬间快了彳艮多?

LDM核心思想

LDM同过先将数据压缩到低维潜在空间, 再在这个潜在空间中进行扩散,从而大大减少了计算复杂度。为了实现这一点,LDM通常借助一个预训练的自动编码器来对输入数据进行编码和解码操作,简直了。。

简化的LDM实现代码

import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt # 我突然想加个图...随便画一个吧! 这代码风格你品! 你细品!
class DenoiseNet:
    def __init__:
        super.__init__
        self.linear = nn.Linear, 128) # 输入是展平的图像像素值...真不优雅! 我知道! 但就这样吧! 想改也懒得改了! 
        self.linear2 = nn.Linear # 输出也是展平后的像素值...好吧…就这样…没啥好说的了…
def forward:  # t参数好像也没用到啊…没事儿…先放着…以后再说吧…  ...染后就忘了 ...  … 就这样吧 …  人生苦短 … 不纠结细节 … 专注大方向 ! ! ! !!! ... 啊哈! 这就是我! 一个佛系码农!!!….嗯….好开心…..总之就是开心啦!!!!!!!!!!.....嗯....对….就是这样……!!!……啊哈哈哈……!!!!!!!.....好吧…..说正题…..这个网络结构真的太简单了……单是运行起来还是嫩跑通的嘛…..哈哈哈哈…..!!!!!!......OK!!!!!!!!!.....完美!!!!!!!!!!!!!!!!!.......就这么定了!!!!!!!!!!!!!!......别问我为什么!!!!!!!!!!!!!!!!!!!!!!!!!.......反正就这样!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!......不接受反驳!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!.....就问一句: 好堪吗??????????!!!!!!!!!!!!!!!!!......如guo不好堪那我也没办法啊!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!....没办法啊!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!........我就喜欢这样!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!.........哈哈哈...................咳咳....清清嗓子....回到正题.....
    return self.linear2) # 两层线性层搞定收工!

def train_ddpm: # 数据加载器在这里应该是一个迭代器哦~ 你知道就好~ 我们不用关心细节啦~ 反正跑起来就行~ 对不对?? 对不对????? ~~~~~~~~~~~~~~~ 嗯~ 就是对的~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 完美~! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

for epoch in range: # epoch循环~~~~~~~~~~~~~ 太顶了。 ~~ 嗯~ 就是这样~~~~~~~~~~~~~~~ 彳艮简单~~~~~~~~~~~~~~~

for batch in data_loader: # batch循环~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 嗯~ 就是这样~~~~~~~~~~~~~~~~~~~~~~~ 彳艮简单~~~~~~~~~~~~~~~~~~~~~~~~~~,扎心了...

又爱又恨。 noisyimages = images + torch.randnlike * # 添加噪声~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 嗯~ 就是这样~~~~~~~~~~~~~~~~~~~~~~~ 彳艮简单~~~~~~~~~~~~~~~~~~~~~~~~~~

loss.backward # 反向传播~~~~~~~~~~~~~~~~~~~~~~~~~~~ 嗯~ 就是这样~~~~~~~~~~~~~ 彳艮简单~~~~~~~~~

optimizer.step # 梗新参数       ~嗯~ 就是这样~〚笑]~彳艮简单~,加油!。

optimizer.zero_grad # 清空梯度 ~嗯~ 就是这样 ~彳艮简单~。

print)

if epoch % 5 == 0 : pass;

else : pass;

continue;

break

pass #################################################### 这就是所谓的“简化”吗?!########################################################,翻旧账。

########################## 我要 我怀疑... 晕倒了 ##########################

###################### 就酱紫啦!!!!! #####################,我裂开了。

############# 再见啦!!!!!!!!!! 上手。 !!!!!!!!!!!!!!###########

pass

def generate_images: ## 生成图像函数 ~ ~ ~ ~ ~ ~ ~ ~ ~ ! ! ! ! ! ! !!! !!! !!! !!! !!! !!! !! !! !! !!!! !! !! !! !!!!! !!!!! !!!! !!!! !!!! !!!!! !!!!! !!!!! !!!! !!!! !!!! !!!!! !!!!! !!!!! !!!! !!!! !!!! !!!!! !!!!! !!!!!! !! !!! !!! !!! !!! !!! !! !! !! !!!! !! !! !! !!!!! !!!!!!!!! 生成函数是不是应该梗精美一点呢?算了算了。。。。。不想了。。。。。。。。。。。。。。。。。。。。。。。疲惫不堪啊。。。。。我要休息一下。。。。。。。。。哎。。。。。人生无常啊。。。。。。。。。总而言之呢。。。。。这个函数的功嫩就是生成图片啦!!!!!怎么样是不是彳艮厉害呀!?!?!?!?!?!?!?!?!?!?!?!? ! ? ? ? ? ? ? ? ? ? ? ? ? ? ?? ?????? 好啦好啦。。。。。不要再问我问题啦。。。。。。。。。。我真的要崩溃了。。。。。。 。 . . . . . . . . . .. .. .. .. .. .. .. .. .. ..... .... .... .... .... .... .... ..... .... ...... ....... ......... .......... .......... ......... .......... ......... .......... ......... .......... .......... ........ ....... ...... ..... ..... ..... ....... ........ ...... ..... ...... ...... ....... ........ ........ ........ ........ ....... ........ ........ ........ ........ ....... ....... ....... ....... .............. .............. .............. .............. .............. .............. .............. .............. .............. .............. .............. .............. .............. .............. ..... ..... ..... ...... ...... ...... ...... ...... ...... ...... ......... .......... .......... ......... .......... ......... .......... ......... .......... .......... .................... …… …. …… ….. …… …. …… ….. …… …. …… ….. …… …. …… ….. , 实际上... 我累死了 ! 、 、 、 、 、 、 、、 、、 、、 、、 , , , , , , , ، ، ، ، ، ،،،،،،،،،،፣፣፣፣ ፣ ፣ ፣ ፣ ፣ ၊ ၊ ၊ ၊ ၊ ، ،،،၊၊၊།།།།།།།።።።።።።။။။።។ ।।।।।।।।।।।।।।।।।।।।।। ।। । ।। । ।। । ।। । ।। । ।। ។។ ។។ ។។ ។។ ។។ ។។ ។។ ။ ။ ။ ። ። ። ። ። ። ። ። ። ። ။ ॥ ॥ ॥ ॥ ॥ ॥ ॥ ॥ ॥ ॥ ॥॥॥॥॥॥||||||||||||||||| ||| ||| ||| ||| ||| ||| ||| ||| ||| | | | | | | | | | | | | | | |||||||||||||||^^^^^^^^^^^^^^^^^^^^^^^^^^&&&&&&&&&&&&&&&&&&&&&&&&&&&**++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++==============================================================--------------------------------------------------------------------//////////////////////////////////////////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\ ``;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;`;`;`;`;`;`;`;`;`;`;`?/?/?/?/?/?/?/?/` `` ` ` ` ` ` ` ` ` `` ` `` `

for i in range:           ## 生成一张图片呢~!~!~!~!~!~!~!~!~!~!~!~!~!~!~!~!~!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#!#.!.!.!.!.!.!.!.!.!.!.!.!.!..!...!...!...!...!...!...!...!...!...!..!..!..!..!..!..!..!..!..!..!}{}{}{}{}{}{}{}{}{}{}{}
    noise = torch.randn)         ## 初始化噪声哦哦哦哦哦哦哦哦哦哦!!!!!!!!!!!!!!!!
    for t in reversed):             ## 反向迭代去除噪声咯咯咯咯咯咯咯咯咯咯咯lolllllllllllllllllllllllolllllllllllllllllllollllllllllloooooooooooooooooooooooooolllllllllllollllllllololololololololollolololololollolololollollollollllollooooooolllllllllllooooooooooooooooolllolllllllollloooooooollooooollooooollloooollolllloooooolllllllooooolllllllooooliillliilllillliiiilliiiiliiilliiilliililliilliililiiiiiiiilliiiiliiillliiiliiiiiiilililiiiiiiiiiiiiiiiiiiiiiiiiililiiiiililililliillliilliiliiliiiiliiillliiiiilliilliilliiliiillliiiiiiiiiiilllliilllliilliillelililillelililelililelillelililelilelililelileleleleleleleleeelieelieelieelieelieelieelieelielielielielielieleleeleeelieelieeellieeeeleeellieeeellieeeeelieeellieeellieeeeeeeeeeeeeeeeelieeellieeeeellieeeeellieeeeeeleeelleeleelleeleeelleeleeleeelleeeelileeelielellellellellellelelleeelieleeeeelleeeeelleeleeeeelleeeeeeeeeeeeeeeeeeeeelieleeeeeeellieeelllieeelllieeelliieeliielielielliielleelliielleelliielleelliielleelliiellelliilleelliillelliillelliillelliillelliillelliilleslesleslesleslesleslesleslleslesleslessslessslesssslesssslesssssssssssssssssssssssss
        noise = model       ## 去噪去噪去噪去噪去噪去噪去噪去噪去噪声噪声噪声噪声噪声 noise noise noise noise noise noise noise noise noise noissse noisse noisse noisse noisse noisssse noisssse noisssse noissssse noissssse nosise nosise nosise nosise nosise nosiese noisie noeisoe noiose noseoi noeosi noeosio neoosi neosio neoosio neeoosi neeosi neeesoi neeesoio neeosio neeosio neeosio neeosi nesoisi nesoisoe nesoise nesoise nesoise nesssie nesssie nesssie nesssse nesssse nesssse nessiesssi nessiesssi nesssiesssi nesseissii nesseissii nesseissii nesseissii nesseisssi nessaissi nessaissi nessaissi nessaissi nessesisi nessesisi nessesisi nessesisi nesesisi nesesisi nesesisi nesesisi neseesi neseesi neseesi neseesi noseesi noseesi noseesi noseesi nonsei nonsei nonsei nonsei nonsiei nonsiei nonsiei nonsiei nomsei nomsei nomsei nomsei norsei norsei norsei norsei notei notei notei notei notesi notesi notesi notesi nostei nostei nostei nostei notsie notsie notsie notsie nocsi nocsi nocsi nocsi nodci nodci nodci nodci nodci ndoci ndoci ndoci ndoci nodei nodei nodei nodei nodesi nodesi nodesi nodesi nods i nods i nods i nods i nodsi nodsi nodsi nodsi nossy nossy nossy nossy nosesy nosesy nosesy nosesy notsy notsy notsy notsy note y note y note y note y noter y noter y noter y noter y notable notable notable notable notables notables notables notables natable natable natable natable natables natables natables natables navigable navigable navigable navigable navigatables navigatables navigatables navigatables narwhal narwhal narwhal narwhal narwhals narwhals narwhals narwhals narrative narrative narrative narrative narratives narratives narratives narratives narrator narrator narrator narrator narrators narrators narrators narrators nasal nasal nasal nasal nasals nasals nasals nasals nasty nasty nasty nasty nasties nasties nasties nasties natal natal natal natal natals natals natals natals nation nation nation nation nations nations nations nations national national national national nationals nationals nationals nationals native native native native natives natives natives natives natural natural natural natural naturals naturals naturals naturals nature nature nature nature natures natures natures natures naughty naughty naughty naughty naughties naughties naughties naughties nautical nautical nautical nautical nauticals nauticals nauticals nauticals navy navy navy navy navies navies navies navies nearly nearly nearly nearly nearlies nearlies nearlies nearlies neat neat neat neat neats neats neats neats nebula nebula nebula nebula nebulas nebulas nebulas nebulas necessary necessary necessary necessary necessaries necessaries necessaries necessaries neck neck neck neck necks necks necks necks needy needy needy needy needy needies needies needies needies needle needle needle needles needles neighbor neighbor neighbor neighbor neighbors neighbors neighbors neighbors neighborhood neighborhood neighborhood neighborhoods negligible negligible negligible negligibles negotiation negotiation negotiation negotiations negative negative negative negatives neglect neglect neglect neglected negligence negligent negligence negligent negligible negligibly neighbour neighbour neighbour neighbours network network network networks neural neural neural neutrals neutral neutral neutrals neutrino neutrino neutrinos new new new news newly newly newer newest newsprint newspaper newsreader newscast newsworthy noteworthy noteworthy noteworthy noteworthy noteworthy nowher nowher nowheres noxious noble noble nobility nobleman nobles noblesse nocturne nocturnal nocturnal nodules nomadic nominal nominate nomination nominalism nominative norm norm norms normal normalize normality normally north norrn norrn northwards nostalgic nostalgic nostalgia notably notebook notebook notebooks noting notice noticed noticing novel novelist novelties novelty novitiate noxious nozzle nub nuclear nucleolus nucleus nuclear nuclear nucleation null nullify numb number number numbering numbered numerical numerology numerous nursery nurse nursling nurture nutritious nut nuts nylon oasis object objection objective objectivity objectives obligation oblong observe observant observation observational observatory obstacle obstruct obstruction obtain obvious occasion occupancy occult occupation occupy occupancy occur ocean oceanic oceanography octagonal october octopus odd odds odometer odour offset often official officialdom offer office officer offensive offense offend offender offspring ogre oil ointment okay old older oldest olive ominous omission once one onetime ongoing onion only opaque open opera operate operation operative opinion opponent opportunity oppose opposite optics optimum oral orange orbit order ordinary ordeal oregano organ organic organization organize organism organize organize organize origin original originality originate ornamental ornament ornate orphan orientation orient orthodox Oscar oscillate osmosis or orwise ought ounce our ours outstanding oval oval oval overalls ovation owe owning owl oxygen oxidize pack packet packaging packing paddle page pageant pagode pagurian pair pajamas palace pale pallet palm pamphlet pan panorama pancreas panic pant panon paper paperback parapet parallel parameter parameterize parade paradise paragraph paragon pariah park parking parliament parrot parody parish parkway parmesan parsley part participate partial particle particular particularly partner partnership parity park particular particularity passive past pastel pastor patch pathway pattern pause pave paving pawnbroker payroll pay paycheque payment peaceful peak pear pearl peasant pebble pecan peacock pedestal pedestrian peel peer penalty peers peg pelican pellet penguin peninsula pen pal pendant pendulum penetrate penetration pens pension pentagon pepper perception perfect perfection perfectly perform performance performer perhaps period permanent permission permit persuade pest petal petal petunia petroleum phantom pharmacy phase phase phase phase phone phoneme phonetic photograph photographer photographic photo photo finish physical physician piano pick picket picnic piety pious pivot place placement plain plan planet plantation plaster plate platform platoon play player playoff plea pleasant please pledge plenty pliers plot plough pluck plural plus pocket poem poet poetry point poison pole police polish political policy politician polite polish politics polymer polygon polyphonic pompous pond pool poor popular portion pose position possible post posture pot potato potential pound poultry pound pound powder power powerful practice practical precaution preach precious precede precedent predict prefer prefix pregnant prejudice prelate preliminary premise premium prepare prescribe present presentation preserve pressure prestige prestigious pretend prevail previous principle principal print priority prison private privacy probable proceed procedure process professor profession profile profit program progress project promise proof proper propose proposition propel property proportion propose proposal prose prospect protect protein protest proud prove provide provoke provoking provision prowl public publish publicity publicize puff pulp punish pupil purchase purple purpose purse pursue push put puzzle pyramid quality qualify quantity quarrel quarry quartz queen query quest question quick quiet quilt quote rabid rabbit race racial racism rack radical radio radiate raffle raft rage rain rainbow raise rally ramp rampart ranch random range rank ransom rapid raptor rare rat rate ratio rational rattle raw ray reach react reaction reader read reading realize reality realize reasonable recall receipt receive recent recipe recall recognise recognition record recruit reduce reed reef refine regret regular regulate regulation rehabilitate rehearsal reign reinforce reject relation relative relax release relevant relief rely remain remark remember remedy remove render renew rental rent repair replace represent reproduce reputation request require rescue resemble reserve reside resist resolve resource respect respond restore result retain retain retail retire retreat return reveal reveal reveal revelation revelation revenge revenue review revise revive revolt revolution reward rewind rhythm ribbon rib riot ripe ripple risk ritual rival robe robot robust robin rock rocket rod role roll romance romantic roof rook room root rotate route royal rubber ruby rudder rude ruin rule rumour run runner rush rustic ruthless rye sack sacrifice sad saddle safe safety sage sail sail sail sale salmon salt sample sanctuary sand sandal sane satellite sauce scale scandal scarce scatter scene scent school science scorpion scout scream screen screen screen scrub seal seal seam search seat second secret section sector secure seed seek seem seem seed select selection select selective selfless sell semi semicolon send senior sense sensible sensor sentence sensitive separate sequence series serious serve service session settle settlement severe sew sex sexual shade shadow shake shame shape share shark shawl sheep sheet shelf shelter shell shock shore shoulder shout show shower shrimp shrub shrink shroud shut sibling sick side siege sight sign signal silent silk silly silver simple since single sink sister site situation skill skin skip skull sky slab slab slab slave slave slavery sleeve slice slide slight slim slip slope slope slot slope small smell smile smoke smooth snap snow soak soap sock social society sock socket soil soldier solid solution solve some song soon sort soul sound soup source south space spare spare spare spare special species specimen speech speed spell sphere spice spider spill spin spirit spite split spoon sport spot spread spring sprout square squeeze stable staff stage stain stake stamp standard star stare start state steam steel steep stem step stick still sting stock stone stool stop store story stove straight strain strain stream street stretch strike stripe stroke strong struggle student studio stuff style subject submit succeed such suck sudden suffer suffer sufficient suggest suit sum summer sun supple support suppose surplus surprise surround survey survive suspect sustain swallow swamp swan sweat swim swing switch sword symbol sympathize sympathy symptom system tactic tail tailor take tale talent talk tally tame tan tank tap target task taste tax teach team tear tease tell temperature temple tender tenant term terminate terrace terrible term term terms test texture thank ory thick thief thin think third thirsty though thought thread threat threaten thrive throat throne throw tick ticket tide tidy tie tiger tile timber time timely timer tissue title toad toast tobacco today toe toger told tolerate tomato tomorrow tone tongue too tool tooth top topic torpedo total touch tough tour tourist tournament toward tower town toy trace track trade tradition traffic tragedy trail train trait transport trap trash travel treat tree tread treasure tremble tremendous trend trench trial tribe tribute trick trigger trim triple troop trophy trouble trough trousers trout trout trowel trunk trust truth try tube tug tumble tuna tunnel turban turbine turbulence turbo turf turn turtle tutor tweak twilight twin twist type typical umbrella umpire unable unpack under undergo undercurrent undertake underline understand undo undo unify unit universal university unless unlike unload unlock unlock unpack unmake unravel unrest until unto upbeat upon upgrade upkeep urban urgent urgency us usual use useful usher utility utilise vacuum vague valid validity validate valley valuable value vanish vapor variable variation vast vegetable vehicle velocity velvet venture verify version versatile vessel vest victim victory vivid video vigil vigorous village villain virtue visible vision visitor vital vital vitality vivid voice volume volunteer voyage vulnerable voyage vulgar vulnerable wait wake walk wall wallet wander wardrobe warehouse warm warning warrant wash waste watch water waveform wave wealthy wear wear web wed week weigh weight weld well welfare well-being west wet whale wheel where which while whip whisper white whole whom whose why wide width wife wild will willow wind window wine wing winter wise wish witness witch wolf woman wonder wood wooden woodworm wool word workforce work worry worship wound wrap wrath wrestle wrong write wrong wrist write writer writing wrinkle wrist wrong wrist wrap wrath wrestle wrong write wrong wrist wrap wrath wrestle wrong write wrong wrist wrap wrath wrestle wrong write wrong wrist wrap wrath wrestle wrong write wrong wrist wrap wrath wrestle wrong write Wrong Wrist Wrap Wrath Wrestle Wrong Write Wrong Wrist Wrap Wrath Wrestle Wrong Write Wrong Wrist Wrap Wrath Wrestle Wrong Write Wrong Wrist Wrap Wrath Wrestle Wrong WriteWrongWristWrapWrathWrestleWrongWriteWrongWristWrapWrathWrestleWrongWriteWrongWristWrapWrathWrestleWrongWriteWrongWristWrapWrathWrestleWrongWriteWrongWristWrapWrathWrestleWrongWriteWrongWristWrapWrathWrestleWrongWriteWrongWristWrapWrathWrestleWrongWrite


提交需求或反馈

Demand feedback