Buckets:
hf-doc-build/doc / diffusers /v0.16.0 /en /_app /pages /tutorials /basic_training.mdx-hf-doc-builder.js
| import{S as Yo,i as Wo,s as Vo,e as n,k as m,w as f,t as o,M as Jo,c as l,d as e,m as h,x as g,a as r,h as i,b as c,N as Tl,G as a,g as p,y as d,q as _,o as j,B as b,v as Ko}from"../../chunks/vendor-hf-doc-builder.js";import{T as Nl}from"../../chunks/Tip-hf-doc-builder.js";import{I as ie}from"../../chunks/IconCopyLink-hf-doc-builder.js";import{C as v}from"../../chunks/CodeBlock-hf-doc-builder.js";import{D as Qo}from"../../chunks/DocNotebookDropdown-hf-doc-builder.js";function Xo(V){let u,D,w,$,E;return{c(){u=n("p"),D=o("\u{1F4A1} This training tutorial is based on the "),w=n("a"),$=o("Training with \u{1F9E8} Diffusers"),E=o(" notebook. For additional details and context about diffusion models like how they work, check out the notebook!"),this.h()},l(y){u=l(y,"P",{});var k=r(u);D=i(k,"\u{1F4A1} This training tutorial is based on the "),w=l(k,"A",{href:!0,rel:!0});var z=r(w);$=i(z,"Training with \u{1F9E8} Diffusers"),z.forEach(e),E=i(k," notebook. For additional details and context about diffusion models like how they work, check out the notebook!"),k.forEach(e),this.h()},h(){c(w,"href","https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/training_example.ipynb"),c(w,"rel","nofollow")},m(y,k){p(y,u,k),a(u,D),a(u,w),a(w,$),a(u,E)},d(y){y&&e(u)}}}function Zo(V){let u,D,w,$,E,y,k,z,_s,A,js,J,P,bs,B;return{c(){u=n("p"),D=o("\u{1F4A1} You can find additional datasets from the "),w=n("a"),$=o("HugGan Community Event"),E=o(" or you can use your own dataset by creating a local "),y=n("a"),k=n("code"),z=o("ImageFolder"),_s=o(". Set "),A=n("code"),js=o("config.dataset_name"),J=o(" to the repository id of the dataset if it is from the HugGan Community Event, or "),P=n("code"),bs=o("imagefolder"),B=o(" if you\u2019re using your own images."),this.h()},l(H){u=l(H,"P",{});var q=r(u);D=i(q,"\u{1F4A1} You can find additional datasets from the "),w=l(q,"A",{href:!0,rel:!0});var ws=r(w);$=i(ws,"HugGan Community Event"),ws.forEach(e),E=i(q," or you can use your own dataset by creating a local "),y=l(q,"A",{href:!0,rel:!0});var x=r(y);k=l(x,"CODE",{});var re=r(k);z=i(re,"ImageFolder"),re.forEach(e),x.forEach(e),_s=i(q,". Set "),A=l(q,"CODE",{});var L=r(A);js=i(L,"config.dataset_name"),L.forEach(e),J=i(q," to the repository id of the dataset if it is from the HugGan Community Event, or "),P=l(q,"CODE",{});var pe=r(P);bs=i(pe,"imagefolder"),pe.forEach(e),B=i(q," if you\u2019re using your own images."),q.forEach(e),this.h()},h(){c(w,"href","https://huggingface.co/huggan"),c(w,"rel","nofollow"),c(y,"href","https://huggingface.co/docs/datasets/image_dataset#imagefolder"),c(y,"rel","nofollow")},m(H,q){p(H,u,q),a(u,D),a(u,w),a(w,$),a(u,E),a(u,y),a(y,k),a(k,z),a(u,_s),a(u,A),a(A,js),a(u,J),a(u,P),a(P,bs),a(u,B)},d(H){H&&e(u)}}}function si(V){let u,D;return{c(){u=n("p"),D=o("\u{1F4A1} The training loop below may look intimidating and long, but it\u2019ll be worth it later when you launch your training in just one line of code! If you can\u2019t wait and want to start generating images, feel free to copy and run the code below. You can always come back and examine the training loop more closely later, like when you\u2019re waiting for your model to finish training. \u{1F917}")},l(w){u=l(w,"P",{});var $=r(u);D=i($,"\u{1F4A1} The training loop below may look intimidating and long, but it\u2019ll be worth it later when you launch your training in just one line of code! If you can\u2019t wait and want to start generating images, feel free to copy and run the code below. You can always come back and examine the training loop more closely later, like when you\u2019re waiting for your model to finish training. \u{1F917}"),$.forEach(e)},m(w,$){p(w,u,$),a(u,D)},d(w){w&&e(u)}}}function ei(V){let u,D,w,$,E,y,k,z,_s,A,js,J,P,bs,B,H,q,ws,x,re,L,pe,At,ys,Bt,It,fa,K,ga,I,St,vs,Ft,Ut,ks,Mt,Ht,da,$s,_a,Q,Lt,Es,Ct,Rt,ja,Ds,ba,ce,Gt,wa,qs,ya,X,Ot,zs,Yt,Wt,va,Ps,ka,C,Z,Me,xs,Vt,He,Jt,$a,ss,Kt,Le,Qt,Xt,Ea,Ts,Da,R,es,Ce,Ns,Zt,Re,sn,qa,as,en,As,an,tn,za,Bs,Pa,ts,xa,S,nn,Is,ln,on,Ss,Ge,rn,pn,Ta,Fs,Na,Us,Oe,Al,Aa,me,cn,Ba,F,ns,Ye,mn,hn,We,un,fn,gn,he,Ve,dn,_n,jn,ue,Je,bn,wn,Ia,Ms,Sa,U,yn,Hs,vn,kn,Ke,$n,En,Fa,Ls,Ua,ls,Dn,Cs,qn,zn,Ma,Rs,Ha,G,os,Qe,Gs,Pn,Xe,xn,La,is,Tn,fe,Nn,An,Ca,Os,Ra,ge,Bn,Ga,Ys,Oa,de,In,Ya,O,rs,Ze,Ws,Sn,sa,Fn,Wa,M,Un,ea,Mn,Hn,aa,Ln,Cn,Va,T,Rn,_e,Gn,On,ta,Yn,Wn,na,Vn,Jn,Ja,Vs,Ka,Js,la,Bl,Qa,je,Kn,Xa,Ks,Za,Y,ps,oa,Qs,Qn,ia,Xn,st,be,Zn,et,we,sl,at,Xs,tt,cs,el,ye,al,tl,nt,Zs,lt,ve,nl,ot,ms,it,se,rt,hs,ll,ee,ol,il,pt,ae,ct,ke,rl,mt,te,ht,ne,ra,Il,ut,W,us,pa,le,pl,ca,cl,ft,fs,ml,$e,hl,ul,gt,N,Ee,De,fl,gl,dl,qe,ze,_l,jl,bl,Pe,xe,wl,yl,vl,Te,Ne,kl,$l,dt;return w=new Qo({props:{classNames:"absolute z-10 right-0 top-0",options:[{label:"Mixed",value:"https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers_doc/en/basic_training.ipynb"},{label:"PyTorch",value:"https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers_doc/en/pytorch/basic_training.ipynb"},{label:"TensorFlow",value:"https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers_doc/en/tensorflow/basic_training.ipynb"},{label:"Mixed",value:"https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/diffusers_doc/en/basic_training.ipynb"},{label:"PyTorch",value:"https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/diffusers_doc/en/pytorch/basic_training.ipynb"},{label:"TensorFlow",value:"https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/diffusers_doc/en/tensorflow/basic_training.ipynb"}]}}),z=new ie({}),K=new Nl({props:{$$slots:{default:[Xo]},$$scope:{ctx:V}}}),$s=new v({props:{code:"!pip install diffusers[training]",highlighted:"!pip install diffusers[training]"}}),Ds=new v({props:{code:`from huggingface_hub import notebook_login | |
| notebook_login()`,highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> huggingface_hub <span class="hljs-keyword">import</span> notebook_login | |
| <span class="hljs-meta">>>> </span>notebook_login()`}}),qs=new v({props:{code:"huggingface-cli login",highlighted:"huggingface-cli login"}}),Ps=new v({props:{code:`!sudo apt -qq install git-lfs | |
| !git config --global credential.helper store`,highlighted:`!sudo apt -qq install git-lfs | |
| !git config --global credential.helper store`}}),xs=new ie({}),Ts=new v({props:{code:`from dataclasses import dataclass | |
| @dataclass | |
| class TrainingConfig: | |
| image_size = 128 # the generated image resolution | |
| train_batch_size = 16 | |
| eval_batch_size = 16 # how many images to sample during evaluation | |
| num_epochs = 50 | |
| gradient_accumulation_steps = 1 | |
| learning_rate = 1e-4 | |
| lr_warmup_steps = 500 | |
| save_image_epochs = 10 | |
| save_model_epochs = 30 | |
| mixed_precision = "fp16" # \`no\` for float32, \`fp16\` for automatic mixed precision | |
| output_dir = "ddpm-butterflies-128" # the model name locally and on the HF Hub | |
| push_to_hub = True # whether to upload the saved model to the HF Hub | |
| hub_private_repo = False | |
| overwrite_output_dir = True # overwrite the old model when re-running the notebook | |
| seed = 0 | |
| config = TrainingConfig()`,highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> dataclass | |
| <span class="hljs-meta">>>> </span>@dataclass | |
| <span class="hljs-meta">... </span><span class="hljs-keyword">class</span> <span class="hljs-title class_">TrainingConfig</span>: | |
| <span class="hljs-meta">... </span> image_size = <span class="hljs-number">128</span> <span class="hljs-comment"># the generated image resolution</span> | |
| <span class="hljs-meta">... </span> train_batch_size = <span class="hljs-number">16</span> | |
| <span class="hljs-meta">... </span> eval_batch_size = <span class="hljs-number">16</span> <span class="hljs-comment"># how many images to sample during evaluation</span> | |
| <span class="hljs-meta">... </span> num_epochs = <span class="hljs-number">50</span> | |
| <span class="hljs-meta">... </span> gradient_accumulation_steps = <span class="hljs-number">1</span> | |
| <span class="hljs-meta">... </span> learning_rate = <span class="hljs-number">1e-4</span> | |
| <span class="hljs-meta">... </span> lr_warmup_steps = <span class="hljs-number">500</span> | |
| <span class="hljs-meta">... </span> save_image_epochs = <span class="hljs-number">10</span> | |
| <span class="hljs-meta">... </span> save_model_epochs = <span class="hljs-number">30</span> | |
| <span class="hljs-meta">... </span> mixed_precision = <span class="hljs-string">"fp16"</span> <span class="hljs-comment"># \`no\` for float32, \`fp16\` for automatic mixed precision</span> | |
| <span class="hljs-meta">... </span> output_dir = <span class="hljs-string">"ddpm-butterflies-128"</span> <span class="hljs-comment"># the model name locally and on the HF Hub</span> | |
| <span class="hljs-meta">... </span> push_to_hub = <span class="hljs-literal">True</span> <span class="hljs-comment"># whether to upload the saved model to the HF Hub</span> | |
| <span class="hljs-meta">... </span> hub_private_repo = <span class="hljs-literal">False</span> | |
| <span class="hljs-meta">... </span> overwrite_output_dir = <span class="hljs-literal">True</span> <span class="hljs-comment"># overwrite the old model when re-running the notebook</span> | |
| <span class="hljs-meta">... </span> seed = <span class="hljs-number">0</span> | |
| <span class="hljs-meta">>>> </span>config = TrainingConfig()`}}),Ns=new ie({}),Bs=new v({props:{code:`from datasets import load_dataset | |
| config.dataset_name = "huggan/smithsonian_butterflies_subset" | |
| dataset = load_dataset(config.dataset_name, split="train")`,highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> datasets <span class="hljs-keyword">import</span> load_dataset | |
| <span class="hljs-meta">>>> </span>config.dataset_name = <span class="hljs-string">"huggan/smithsonian_butterflies_subset"</span> | |
| <span class="hljs-meta">>>> </span>dataset = load_dataset(config.dataset_name, split=<span class="hljs-string">"train"</span>)`}}),ts=new Nl({props:{$$slots:{default:[Zo]},$$scope:{ctx:V}}}),Fs=new v({props:{code:`import matplotlib.pyplot as plt | |
| fig, axs = plt.subplots(1, 4, figsize=(16, 4)) | |
| for i, image in enumerate(dataset[:4]["image"]): | |
| axs[i].imshow(image) | |
| axs[i].set_axis_off() | |
| fig.show()`,highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt | |
| <span class="hljs-meta">>>> </span>fig, axs = plt.subplots(<span class="hljs-number">1</span>, <span class="hljs-number">4</span>, figsize=(<span class="hljs-number">16</span>, <span class="hljs-number">4</span>)) | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">for</span> i, image <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(dataset[:<span class="hljs-number">4</span>][<span class="hljs-string">"image"</span>]): | |
| <span class="hljs-meta">... </span> axs[i].imshow(image) | |
| <span class="hljs-meta">... </span> axs[i].set_axis_off() | |
| <span class="hljs-meta">>>> </span>fig.show()`}}),Ms=new v({props:{code:`from torchvision import transforms | |
| preprocess = transforms.Compose( | |
| [ | |
| transforms.Resize((config.image_size, config.image_size)), | |
| transforms.RandomHorizontalFlip(), | |
| transforms.ToTensor(), | |
| transforms.Normalize([0.5], [0.5]), | |
| ] | |
| )`,highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> torchvision <span class="hljs-keyword">import</span> transforms | |
| <span class="hljs-meta">>>> </span>preprocess = transforms.Compose( | |
| <span class="hljs-meta">... </span> [ | |
| <span class="hljs-meta">... </span> transforms.Resize((config.image_size, config.image_size)), | |
| <span class="hljs-meta">... </span> transforms.RandomHorizontalFlip(), | |
| <span class="hljs-meta">... </span> transforms.ToTensor(), | |
| <span class="hljs-meta">... </span> transforms.Normalize([<span class="hljs-number">0.5</span>], [<span class="hljs-number">0.5</span>]), | |
| <span class="hljs-meta">... </span> ] | |
| <span class="hljs-meta">... </span>)`}}),Ls=new v({props:{code:`def transform(examples): | |
| images = [preprocess(image.convert("RGB")) for image in examples["image"]] | |
| return {"images": images} | |
| dataset.set_transform(transform)`,highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">transform</span>(<span class="hljs-params">examples</span>): | |
| <span class="hljs-meta">... </span> images = [preprocess(image.convert(<span class="hljs-string">"RGB"</span>)) <span class="hljs-keyword">for</span> image <span class="hljs-keyword">in</span> examples[<span class="hljs-string">"image"</span>]] | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">return</span> {<span class="hljs-string">"images"</span>: images} | |
| <span class="hljs-meta">>>> </span>dataset.set_transform(transform)`}}),Rs=new v({props:{code:`import torch | |
| train_dataloader = torch.utils.data.DataLoader(dataset, batch_size=config.train_batch_size, shuffle=True)`,highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-meta">>>> </span>train_dataloader = torch.utils.data.DataLoader(dataset, batch_size=config.train_batch_size, shuffle=<span class="hljs-literal">True</span>)`}}),Gs=new ie({}),Os=new v({props:{code:`from diffusers import UNet2DModel | |
| model = UNet2DModel( | |
| sample_size=config.image_size, # the target image resolution | |
| in_channels=3, # the number of input channels, 3 for RGB images | |
| out_channels=3, # the number of output channels | |
| layers_per_block=2, # how many ResNet layers to use per UNet block | |
| block_out_channels=(128, 128, 256, 256, 512, 512), # the number of output channels for each UNet block | |
| down_block_types=( | |
| "DownBlock2D", # a regular ResNet downsampling block | |
| "DownBlock2D", | |
| "DownBlock2D", | |
| "DownBlock2D", | |
| "AttnDownBlock2D", # a ResNet downsampling block with spatial self-attention | |
| "DownBlock2D", | |
| ), | |
| up_block_types=( | |
| "UpBlock2D", # a regular ResNet upsampling block | |
| "AttnUpBlock2D", # a ResNet upsampling block with spatial self-attention | |
| "UpBlock2D", | |
| "UpBlock2D", | |
| "UpBlock2D", | |
| "UpBlock2D", | |
| ), | |
| )`,highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> UNet2DModel | |
| <span class="hljs-meta">>>> </span>model = UNet2DModel( | |
| <span class="hljs-meta">... </span> sample_size=config.image_size, <span class="hljs-comment"># the target image resolution</span> | |
| <span class="hljs-meta">... </span> in_channels=<span class="hljs-number">3</span>, <span class="hljs-comment"># the number of input channels, 3 for RGB images</span> | |
| <span class="hljs-meta">... </span> out_channels=<span class="hljs-number">3</span>, <span class="hljs-comment"># the number of output channels</span> | |
| <span class="hljs-meta">... </span> layers_per_block=<span class="hljs-number">2</span>, <span class="hljs-comment"># how many ResNet layers to use per UNet block</span> | |
| <span class="hljs-meta">... </span> block_out_channels=(<span class="hljs-number">128</span>, <span class="hljs-number">128</span>, <span class="hljs-number">256</span>, <span class="hljs-number">256</span>, <span class="hljs-number">512</span>, <span class="hljs-number">512</span>), <span class="hljs-comment"># the number of output channels for each UNet block</span> | |
| <span class="hljs-meta">... </span> down_block_types=( | |
| <span class="hljs-meta">... </span> <span class="hljs-string">"DownBlock2D"</span>, <span class="hljs-comment"># a regular ResNet downsampling block</span> | |
| <span class="hljs-meta">... </span> <span class="hljs-string">"DownBlock2D"</span>, | |
| <span class="hljs-meta">... </span> <span class="hljs-string">"DownBlock2D"</span>, | |
| <span class="hljs-meta">... </span> <span class="hljs-string">"DownBlock2D"</span>, | |
| <span class="hljs-meta">... </span> <span class="hljs-string">"AttnDownBlock2D"</span>, <span class="hljs-comment"># a ResNet downsampling block with spatial self-attention</span> | |
| <span class="hljs-meta">... </span> <span class="hljs-string">"DownBlock2D"</span>, | |
| <span class="hljs-meta">... </span> ), | |
| <span class="hljs-meta">... </span> up_block_types=( | |
| <span class="hljs-meta">... </span> <span class="hljs-string">"UpBlock2D"</span>, <span class="hljs-comment"># a regular ResNet upsampling block</span> | |
| <span class="hljs-meta">... </span> <span class="hljs-string">"AttnUpBlock2D"</span>, <span class="hljs-comment"># a ResNet upsampling block with spatial self-attention</span> | |
| <span class="hljs-meta">... </span> <span class="hljs-string">"UpBlock2D"</span>, | |
| <span class="hljs-meta">... </span> <span class="hljs-string">"UpBlock2D"</span>, | |
| <span class="hljs-meta">... </span> <span class="hljs-string">"UpBlock2D"</span>, | |
| <span class="hljs-meta">... </span> <span class="hljs-string">"UpBlock2D"</span>, | |
| <span class="hljs-meta">... </span> ), | |
| <span class="hljs-meta">... </span>)`}}),Ys=new v({props:{code:`sample_image = dataset[0]["images"].unsqueeze(0) | |
| print("Input shape:", sample_image.shape) | |
| print("Output shape:", model(sample_image, timestep=0).sample.shape)`,highlighted:`<span class="hljs-meta">>>> </span>sample_image = dataset[<span class="hljs-number">0</span>][<span class="hljs-string">"images"</span>].unsqueeze(<span class="hljs-number">0</span>) | |
| <span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(<span class="hljs-string">"Input shape:"</span>, sample_image.shape) | |
| Input shape: torch.Size([<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">128</span>, <span class="hljs-number">128</span>]) | |
| <span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(<span class="hljs-string">"Output shape:"</span>, model(sample_image, timestep=<span class="hljs-number">0</span>).sample.shape) | |
| Output shape: torch.Size([<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">128</span>, <span class="hljs-number">128</span>])`}}),Ws=new ie({}),Vs=new v({props:{code:`import torch | |
| from PIL import Image | |
| from diffusers import DDPMScheduler | |
| noise_scheduler = DDPMScheduler(num_train_timesteps=1000) | |
| noise = torch.randn(sample_image.shape) | |
| timesteps = torch.LongTensor([50]) | |
| noisy_image = noise_scheduler.add_noise(sample_image, noise, timesteps) | |
| Image.fromarray(((noisy_image.permute(0, 2, 3, 1) + 1.0) * 127.5).type(torch.uint8).numpy()[0])`,highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> DDPMScheduler | |
| <span class="hljs-meta">>>> </span>noise_scheduler = DDPMScheduler(num_train_timesteps=<span class="hljs-number">1000</span>) | |
| <span class="hljs-meta">>>> </span>noise = torch.randn(sample_image.shape) | |
| <span class="hljs-meta">>>> </span>timesteps = torch.LongTensor([<span class="hljs-number">50</span>]) | |
| <span class="hljs-meta">>>> </span>noisy_image = noise_scheduler.add_noise(sample_image, noise, timesteps) | |
| <span class="hljs-meta">>>> </span>Image.fromarray(((noisy_image.permute(<span class="hljs-number">0</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>) + <span class="hljs-number">1.0</span>) * <span class="hljs-number">127.5</span>).<span class="hljs-built_in">type</span>(torch.uint8).numpy()[<span class="hljs-number">0</span>])`}}),Ks=new v({props:{code:`import torch.nn.functional as F | |
| noise_pred = model(noisy_image, timesteps).sample | |
| loss = F.mse_loss(noise_pred, noise)`,highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> torch.nn.functional <span class="hljs-keyword">as</span> F | |
| <span class="hljs-meta">>>> </span>noise_pred = model(noisy_image, timesteps).sample | |
| <span class="hljs-meta">>>> </span>loss = F.mse_loss(noise_pred, noise)`}}),Qs=new ie({}),Xs=new v({props:{code:`from diffusers.optimization import get_cosine_schedule_with_warmup | |
| optimizer = torch.optim.AdamW(model.parameters(), lr=config.learning_rate) | |
| lr_scheduler = get_cosine_schedule_with_warmup( | |
| optimizer=optimizer, | |
| num_warmup_steps=config.lr_warmup_steps, | |
| num_training_steps=(len(train_dataloader) * config.num_epochs), | |
| )`,highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> diffusers.optimization <span class="hljs-keyword">import</span> get_cosine_schedule_with_warmup | |
| <span class="hljs-meta">>>> </span>optimizer = torch.optim.AdamW(model.parameters(), lr=config.learning_rate) | |
| <span class="hljs-meta">>>> </span>lr_scheduler = get_cosine_schedule_with_warmup( | |
| <span class="hljs-meta">... </span> optimizer=optimizer, | |
| <span class="hljs-meta">... </span> num_warmup_steps=config.lr_warmup_steps, | |
| <span class="hljs-meta">... </span> num_training_steps=(<span class="hljs-built_in">len</span>(train_dataloader) * config.num_epochs), | |
| <span class="hljs-meta">... </span>)`}}),Zs=new v({props:{code:`from diffusers import DDPMPipeline | |
| import math | |
| import os | |
| def make_grid(images, rows, cols): | |
| w, h = images[0].size | |
| grid = Image.new("RGB", size=(cols * w, rows * h)) | |
| for i, image in enumerate(images): | |
| grid.paste(image, box=(i % cols * w, i // cols * h)) | |
| return grid | |
| def evaluate(config, epoch, pipeline): | |
| # Sample some images from random noise (this is the backward diffusion process). | |
| # The default pipeline output type is \`List[PIL.Image]\` | |
| images = pipeline( | |
| batch_size=config.eval_batch_size, | |
| generator=torch.manual_seed(config.seed), | |
| ).images | |
| # Make a grid out of the images | |
| image_grid = make_grid(images, rows=4, cols=4) | |
| # Save the images | |
| test_dir = os.path.join(config.output_dir, "samples") | |
| os.makedirs(test_dir, exist_ok=True) | |
| image_grid.save(f"{test_dir}/{epoch:04d}.png")`,highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> DDPMPipeline | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> math | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> os | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">make_grid</span>(<span class="hljs-params">images, rows, cols</span>): | |
| <span class="hljs-meta">... </span> w, h = images[<span class="hljs-number">0</span>].size | |
| <span class="hljs-meta">... </span> grid = Image.new(<span class="hljs-string">"RGB"</span>, size=(cols * w, rows * h)) | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">for</span> i, image <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(images): | |
| <span class="hljs-meta">... </span> grid.paste(image, box=(i % cols * w, i // cols * h)) | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">return</span> grid | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">evaluate</span>(<span class="hljs-params">config, epoch, pipeline</span>): | |
| <span class="hljs-meta">... </span> <span class="hljs-comment"># Sample some images from random noise (this is the backward diffusion process).</span> | |
| <span class="hljs-meta">... </span> <span class="hljs-comment"># The default pipeline output type is \`List[PIL.Image]\`</span> | |
| <span class="hljs-meta">... </span> images = pipeline( | |
| <span class="hljs-meta">... </span> batch_size=config.eval_batch_size, | |
| <span class="hljs-meta">... </span> generator=torch.manual_seed(config.seed), | |
| <span class="hljs-meta">... </span> ).images | |
| <span class="hljs-meta">... </span> <span class="hljs-comment"># Make a grid out of the images</span> | |
| <span class="hljs-meta">... </span> image_grid = make_grid(images, rows=<span class="hljs-number">4</span>, cols=<span class="hljs-number">4</span>) | |
| <span class="hljs-meta">... </span> <span class="hljs-comment"># Save the images</span> | |
| <span class="hljs-meta">... </span> test_dir = os.path.join(config.output_dir, <span class="hljs-string">"samples"</span>) | |
| <span class="hljs-meta">... </span> os.makedirs(test_dir, exist_ok=<span class="hljs-literal">True</span>) | |
| <span class="hljs-meta">... </span> image_grid.save(<span class="hljs-string">f"<span class="hljs-subst">{test_dir}</span>/<span class="hljs-subst">{epoch:04d}</span>.png"</span>)`}}),ms=new Nl({props:{$$slots:{default:[si]},$$scope:{ctx:V}}}),se=new v({props:{code:`from accelerate import Accelerator | |
| from huggingface_hub import HfFolder, Repository, whoami | |
| from tqdm.auto import tqdm | |
| from pathlib import Path | |
| import os | |
| def get_full_repo_name(model_id: str, organization: str = None, token: str = None): | |
| if token is None: | |
| token = HfFolder.get_token() | |
| if organization is None: | |
| username = whoami(token)["name"] | |
| return f"{username}/{model_id}" | |
| else: | |
| return f"{organization}/{model_id}" | |
| def train_loop(config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler): | |
| # Initialize accelerator and tensorboard logging | |
| accelerator = Accelerator( | |
| mixed_precision=config.mixed_precision, | |
| gradient_accumulation_steps=config.gradient_accumulation_steps, | |
| log_with="tensorboard", | |
| logging_dir=os.path.join(config.output_dir, "logs"), | |
| ) | |
| if accelerator.is_main_process: | |
| if config.push_to_hub: | |
| repo_name = get_full_repo_name(Path(config.output_dir).name) | |
| repo = Repository(config.output_dir, clone_from=repo_name) | |
| elif config.output_dir is not None: | |
| os.makedirs(config.output_dir, exist_ok=True) | |
| accelerator.init_trackers("train_example") | |
| # Prepare everything | |
| # There is no specific order to remember, you just need to unpack the | |
| # objects in the same order you gave them to the prepare method. | |
| model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare( | |
| model, optimizer, train_dataloader, lr_scheduler | |
| ) | |
| global_step = 0 | |
| # Now you train the model | |
| for epoch in range(config.num_epochs): | |
| progress_bar = tqdm(total=len(train_dataloader), disable=not accelerator.is_local_main_process) | |
| progress_bar.set_description(f"Epoch {epoch}") | |
| for step, batch in enumerate(train_dataloader): | |
| clean_images = batch["images"] | |
| # Sample noise to add to the images | |
| noise = torch.randn(clean_images.shape).to(clean_images.device) | |
| bs = clean_images.shape[0] | |
| # Sample a random timestep for each image | |
| timesteps = torch.randint( | |
| 0, noise_scheduler.config.num_train_timesteps, (bs,), device=clean_images.device | |
| ).long() | |
| # Add noise to the clean images according to the noise magnitude at each timestep | |
| # (this is the forward diffusion process) | |
| noisy_images = noise_scheduler.add_noise(clean_images, noise, timesteps) | |
| with accelerator.accumulate(model): | |
| # Predict the noise residual | |
| noise_pred = model(noisy_images, timesteps, return_dict=False)[0] | |
| loss = F.mse_loss(noise_pred, noise) | |
| accelerator.backward(loss) | |
| accelerator.clip_grad_norm_(model.parameters(), 1.0) | |
| optimizer.step() | |
| lr_scheduler.step() | |
| optimizer.zero_grad() | |
| progress_bar.update(1) | |
| logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0], "step": global_step} | |
| progress_bar.set_postfix(**logs) | |
| accelerator.log(logs, step=global_step) | |
| global_step += 1 | |
| # After each epoch you optionally sample some demo images with evaluate() and save the model | |
| if accelerator.is_main_process: | |
| pipeline = DDPMPipeline(unet=accelerator.unwrap_model(model), scheduler=noise_scheduler) | |
| if (epoch + 1) % config.save_image_epochs == 0 or epoch == config.num_epochs - 1: | |
| evaluate(config, epoch, pipeline) | |
| if (epoch + 1) % config.save_model_epochs == 0 or epoch == config.num_epochs - 1: | |
| if config.push_to_hub: | |
| repo.push_to_hub(commit_message=f"Epoch {epoch}", blocking=True) | |
| else: | |
| pipeline.save_pretrained(config.output_dir)`,highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> accelerate <span class="hljs-keyword">import</span> Accelerator | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> huggingface_hub <span class="hljs-keyword">import</span> HfFolder, Repository, whoami | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> tqdm.auto <span class="hljs-keyword">import</span> tqdm | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> pathlib <span class="hljs-keyword">import</span> Path | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> os | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">get_full_repo_name</span>(<span class="hljs-params">model_id: <span class="hljs-built_in">str</span>, organization: <span class="hljs-built_in">str</span> = <span class="hljs-literal">None</span>, token: <span class="hljs-built_in">str</span> = <span class="hljs-literal">None</span></span>): | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">if</span> token <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>: | |
| <span class="hljs-meta">... </span> token = HfFolder.get_token() | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">if</span> organization <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>: | |
| <span class="hljs-meta">... </span> username = whoami(token)[<span class="hljs-string">"name"</span>] | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">return</span> <span class="hljs-string">f"<span class="hljs-subst">{username}</span>/<span class="hljs-subst">{model_id}</span>"</span> | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">else</span>: | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">return</span> <span class="hljs-string">f"<span class="hljs-subst">{organization}</span>/<span class="hljs-subst">{model_id}</span>"</span> | |
| <span class="hljs-meta">>>> </span><span class="hljs-keyword">def</span> <span class="hljs-title function_">train_loop</span>(<span class="hljs-params">config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler</span>): | |
| <span class="hljs-meta">... </span> <span class="hljs-comment"># Initialize accelerator and tensorboard logging</span> | |
| <span class="hljs-meta">... </span> accelerator = Accelerator( | |
| <span class="hljs-meta">... </span> mixed_precision=config.mixed_precision, | |
| <span class="hljs-meta">... </span> gradient_accumulation_steps=config.gradient_accumulation_steps, | |
| <span class="hljs-meta">... </span> log_with=<span class="hljs-string">"tensorboard"</span>, | |
| <span class="hljs-meta">... </span> logging_dir=os.path.join(config.output_dir, <span class="hljs-string">"logs"</span>), | |
| <span class="hljs-meta">... </span> ) | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">if</span> accelerator.is_main_process: | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">if</span> config.push_to_hub: | |
| <span class="hljs-meta">... </span> repo_name = get_full_repo_name(Path(config.output_dir).name) | |
| <span class="hljs-meta">... </span> repo = Repository(config.output_dir, clone_from=repo_name) | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">elif</span> config.output_dir <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>: | |
| <span class="hljs-meta">... </span> os.makedirs(config.output_dir, exist_ok=<span class="hljs-literal">True</span>) | |
| <span class="hljs-meta">... </span> accelerator.init_trackers(<span class="hljs-string">"train_example"</span>) | |
| <span class="hljs-meta">... </span> <span class="hljs-comment"># Prepare everything</span> | |
| <span class="hljs-meta">... </span> <span class="hljs-comment"># There is no specific order to remember, you just need to unpack the</span> | |
| <span class="hljs-meta">... </span> <span class="hljs-comment"># objects in the same order you gave them to the prepare method.</span> | |
| <span class="hljs-meta">... </span> model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare( | |
| <span class="hljs-meta">... </span> model, optimizer, train_dataloader, lr_scheduler | |
| <span class="hljs-meta">... </span> ) | |
| <span class="hljs-meta">... </span> global_step = <span class="hljs-number">0</span> | |
| <span class="hljs-meta">... </span> <span class="hljs-comment"># Now you train the model</span> | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">for</span> epoch <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(config.num_epochs): | |
| <span class="hljs-meta">... </span> progress_bar = tqdm(total=<span class="hljs-built_in">len</span>(train_dataloader), disable=<span class="hljs-keyword">not</span> accelerator.is_local_main_process) | |
| <span class="hljs-meta">... </span> progress_bar.set_description(<span class="hljs-string">f"Epoch <span class="hljs-subst">{epoch}</span>"</span>) | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">for</span> step, batch <span class="hljs-keyword">in</span> <span class="hljs-built_in">enumerate</span>(train_dataloader): | |
| <span class="hljs-meta">... </span> clean_images = batch[<span class="hljs-string">"images"</span>] | |
| <span class="hljs-meta">... </span> <span class="hljs-comment"># Sample noise to add to the images</span> | |
| <span class="hljs-meta">... </span> noise = torch.randn(clean_images.shape).to(clean_images.device) | |
| <span class="hljs-meta">... </span> bs = clean_images.shape[<span class="hljs-number">0</span>] | |
| <span class="hljs-meta">... </span> <span class="hljs-comment"># Sample a random timestep for each image</span> | |
| <span class="hljs-meta">... </span> timesteps = torch.randint( | |
| <span class="hljs-meta">... </span> <span class="hljs-number">0</span>, noise_scheduler.config.num_train_timesteps, (bs,), device=clean_images.device | |
| <span class="hljs-meta">... </span> ).long() | |
| <span class="hljs-meta">... </span> <span class="hljs-comment"># Add noise to the clean images according to the noise magnitude at each timestep</span> | |
| <span class="hljs-meta">... </span> <span class="hljs-comment"># (this is the forward diffusion process)</span> | |
| <span class="hljs-meta">... </span> noisy_images = noise_scheduler.add_noise(clean_images, noise, timesteps) | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">with</span> accelerator.accumulate(model): | |
| <span class="hljs-meta">... </span> <span class="hljs-comment"># Predict the noise residual</span> | |
| <span class="hljs-meta">... </span> noise_pred = model(noisy_images, timesteps, return_dict=<span class="hljs-literal">False</span>)[<span class="hljs-number">0</span>] | |
| <span class="hljs-meta">... </span> loss = F.mse_loss(noise_pred, noise) | |
| <span class="hljs-meta">... </span> accelerator.backward(loss) | |
| <span class="hljs-meta">... </span> accelerator.clip_grad_norm_(model.parameters(), <span class="hljs-number">1.0</span>) | |
| <span class="hljs-meta">... </span> optimizer.step() | |
| <span class="hljs-meta">... </span> lr_scheduler.step() | |
| <span class="hljs-meta">... </span> optimizer.zero_grad() | |
| <span class="hljs-meta">... </span> progress_bar.update(<span class="hljs-number">1</span>) | |
| <span class="hljs-meta">... </span> logs = {<span class="hljs-string">"loss"</span>: loss.detach().item(), <span class="hljs-string">"lr"</span>: lr_scheduler.get_last_lr()[<span class="hljs-number">0</span>], <span class="hljs-string">"step"</span>: global_step} | |
| <span class="hljs-meta">... </span> progress_bar.set_postfix(**logs) | |
| <span class="hljs-meta">... </span> accelerator.log(logs, step=global_step) | |
| <span class="hljs-meta">... </span> global_step += <span class="hljs-number">1</span> | |
| <span class="hljs-meta">... </span> <span class="hljs-comment"># After each epoch you optionally sample some demo images with evaluate() and save the model</span> | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">if</span> accelerator.is_main_process: | |
| <span class="hljs-meta">... </span> pipeline = DDPMPipeline(unet=accelerator.unwrap_model(model), scheduler=noise_scheduler) | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">if</span> (epoch + <span class="hljs-number">1</span>) % config.save_image_epochs == <span class="hljs-number">0</span> <span class="hljs-keyword">or</span> epoch == config.num_epochs - <span class="hljs-number">1</span>: | |
| <span class="hljs-meta">... </span> evaluate(config, epoch, pipeline) | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">if</span> (epoch + <span class="hljs-number">1</span>) % config.save_model_epochs == <span class="hljs-number">0</span> <span class="hljs-keyword">or</span> epoch == config.num_epochs - <span class="hljs-number">1</span>: | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">if</span> config.push_to_hub: | |
| <span class="hljs-meta">... </span> repo.push_to_hub(commit_message=<span class="hljs-string">f"Epoch <span class="hljs-subst">{epoch}</span>"</span>, blocking=<span class="hljs-literal">True</span>) | |
| <span class="hljs-meta">... </span> <span class="hljs-keyword">else</span>: | |
| <span class="hljs-meta">... </span> pipeline.save_pretrained(config.output_dir)`}}),ae=new v({props:{code:`from accelerate import notebook_launcher | |
| args = (config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler) | |
| notebook_launcher(train_loop, args, num_processes=1)`,highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> accelerate <span class="hljs-keyword">import</span> notebook_launcher | |
| <span class="hljs-meta">>>> </span>args = (config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler) | |
| <span class="hljs-meta">>>> </span>notebook_launcher(train_loop, args, num_processes=<span class="hljs-number">1</span>)`}}),te=new v({props:{code:`import glob | |
| sample_images = sorted(glob.glob(f"{config.output_dir}/samples/*.png")) | |
| Image.open(sample_images[-1])`,highlighted:`<span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> glob | |
| <span class="hljs-meta">>>> </span>sample_images = <span class="hljs-built_in">sorted</span>(glob.glob(<span class="hljs-string">f"<span class="hljs-subst">{config.output_dir}</span>/samples/*.png"</span>)) | |
| <span class="hljs-meta">>>> </span>Image.<span class="hljs-built_in">open</span>(sample_images[-<span class="hljs-number">1</span>])`}}),le=new ie({}),{c(){u=n("meta"),D=m(),f(w.$$.fragment),$=m(),E=n("h1"),y=n("a"),k=n("span"),f(z.$$.fragment),_s=m(),A=n("span"),js=o("Train a diffusion model"),J=m(),P=n("p"),bs=o("Unconditional image generation is a popular application of diffusion models that generates images that look like those in the dataset used for training. Typically, the best results are obtained from finetuning a pretrained model on a specific dataset. You can find many of these checkpoints on the "),B=n("a"),H=o("Hub"),q=o(", but if you can\u2019t find one you like, you can always train your own!"),ws=m(),x=n("p"),re=o("This tutorial will teach you how to train a "),L=n("a"),pe=o("UNet2DModel"),At=o(" from scratch on a subset of the "),ys=n("a"),Bt=o("Smithsonian Butterflies"),It=o(" dataset to generate your own \u{1F98B} butterflies \u{1F98B}."),fa=m(),f(K.$$.fragment),ga=m(),I=n("p"),St=o("Before you begin, make sure you have \u{1F917} Datasets installed to load and preprocess image datasets, and \u{1F917} Accelerate, to simplify training on any number of GPUs. The following command will also install "),vs=n("a"),Ft=o("TensorBoard"),Ut=o(" to visualize training metrics (you can also use "),ks=n("a"),Mt=o("Weights & Biases"),Ht=o(" to track your training)."),da=m(),f($s.$$.fragment),_a=m(),Q=n("p"),Lt=o("We encourage you to share your model with the community, and in order to do that, you\u2019ll need to login to your Hugging Face account (create one "),Es=n("a"),Ct=o("here"),Rt=o(" if you don\u2019t already have one!). You can login from a notebook and enter your token when prompted:"),ja=m(),f(Ds.$$.fragment),ba=m(),ce=n("p"),Gt=o("Or login in from the terminal:"),wa=m(),f(qs.$$.fragment),ya=m(),X=n("p"),Ot=o("Since the model checkpoints are quite large, install "),zs=n("a"),Yt=o("Git-LFS"),Wt=o(" to version these large files:"),va=m(),f(Ps.$$.fragment),ka=m(),C=n("h2"),Z=n("a"),Me=n("span"),f(xs.$$.fragment),Vt=m(),He=n("span"),Jt=o("Training configuration"),$a=m(),ss=n("p"),Kt=o("For convenience, create a "),Le=n("code"),Qt=o("TrainingConfig"),Xt=o(" class containing the training hyperparameters (feel free to adjust them):"),Ea=m(),f(Ts.$$.fragment),Da=m(),R=n("h2"),es=n("a"),Ce=n("span"),f(Ns.$$.fragment),Zt=m(),Re=n("span"),sn=o("Load the dataset"),qa=m(),as=n("p"),en=o("You can easily load the "),As=n("a"),an=o("Smithsonian Butterflies"),tn=o(" dataset with the \u{1F917} Datasets library:"),za=m(),f(Bs.$$.fragment),Pa=m(),f(ts.$$.fragment),xa=m(),S=n("p"),nn=o("\u{1F917} Datasets uses the "),Is=n("a"),ln=o("Image"),on=o(" feature to automatically decode the image data and load it as a "),Ss=n("a"),Ge=n("code"),rn=o("PIL.Image"),pn=o(" which we can visualize:"),Ta=m(),f(Fs.$$.fragment),Na=m(),Us=n("div"),Oe=n("img"),Aa=m(),me=n("p"),cn=o("The images are all different sizes though, so you\u2019ll need to preprocess them first:"),Ba=m(),F=n("ul"),ns=n("li"),Ye=n("code"),mn=o("Resize"),hn=o(" changes the image size to the one defined in "),We=n("code"),un=o("config.image_size"),fn=o("."),gn=m(),he=n("li"),Ve=n("code"),dn=o("RandomHorizontalFlip"),_n=o(" augments the dataset by randomly mirroring the images."),jn=m(),ue=n("li"),Je=n("code"),bn=o("Normalize"),wn=o(" is important to rescale the pixel values into a [-1, 1] range, which is what the model expects."),Ia=m(),f(Ms.$$.fragment),Sa=m(),U=n("p"),yn=o("Use \u{1F917} Datasets\u2019 "),Hs=n("a"),vn=o("set_transform"),kn=o(" method to apply the "),Ke=n("code"),$n=o("preprocess"),En=o(" function on the fly during training:"),Fa=m(),f(Ls.$$.fragment),Ua=m(),ls=n("p"),Dn=o("Feel free to visualize the images again to confirm that they\u2019ve been resized. Now you\u2019re ready to wrap the dataset in a "),Cs=n("a"),qn=o("DataLoader"),zn=o(" for training!"),Ma=m(),f(Rs.$$.fragment),Ha=m(),G=n("h2"),os=n("a"),Qe=n("span"),f(Gs.$$.fragment),Pn=m(),Xe=n("span"),xn=o("Create a UNet2DModel"),La=m(),is=n("p"),Tn=o("Pretrained models in \u{1F9E8} Diffusers are easily created from their model class with the parameters you want. For example, to create a "),fe=n("a"),Nn=o("UNet2DModel"),An=o(":"),Ca=m(),f(Os.$$.fragment),Ra=m(),ge=n("p"),Bn=o("It is often a good idea to quickly check the sample image shape matches the model output shape:"),Ga=m(),f(Ys.$$.fragment),Oa=m(),de=n("p"),In=o("Great! Next, you\u2019ll need a scheduler to add some noise to the image."),Ya=m(),O=n("h2"),rs=n("a"),Ze=n("span"),f(Ws.$$.fragment),Sn=m(),sa=n("span"),Fn=o("Create a scheduler"),Wa=m(),M=n("p"),Un=o("The scheduler behaves differently depending on whether you\u2019re using the model for training or inference. During inference, the scheduler generates image from the noise. During training, the scheduler takes a model output - or a sample - from a specific point in the diffusion process and applies noise to the image according to a "),ea=n("em"),Mn=o("noise schedule"),Hn=o(" and an "),aa=n("em"),Ln=o("update rule"),Cn=o("."),Va=m(),T=n("p"),Rn=o("Let\u2019s take a look at the "),_e=n("a"),Gn=o("DDPMScheduler"),On=o(" and use the "),ta=n("code"),Yn=o("add_noise"),Wn=o(" method to add some random noise to the "),na=n("code"),Vn=o("sample_image"),Jn=o(" from before:"),Ja=m(),f(Vs.$$.fragment),Ka=m(),Js=n("div"),la=n("img"),Qa=m(),je=n("p"),Kn=o("The training objective of the model is to predict the noise added to the image. The loss at this step can be calculated by:"),Xa=m(),f(Ks.$$.fragment),Za=m(),Y=n("h2"),ps=n("a"),oa=n("span"),f(Qs.$$.fragment),Qn=m(),ia=n("span"),Xn=o("Train the model"),st=m(),be=n("p"),Zn=o("By now, you have most of the pieces to start training the model and all that\u2019s left is putting everything together."),et=m(),we=n("p"),sl=o("First, you\u2019ll need an optimizer and a learning rate scheduler:"),at=m(),f(Xs.$$.fragment),tt=m(),cs=n("p"),el=o("Then, you\u2019ll need a way to evaluate the model. For evaluation, you can use the "),ye=n("a"),al=o("DDPMPipeline"),tl=o(" to generate a batch of sample images and save it as a grid:"),nt=m(),f(Zs.$$.fragment),lt=m(),ve=n("p"),nl=o("Now you can wrap all these components together in a training loop with \u{1F917} Accelerate for easy TensorBoard logging, gradient accumulation, and mixed precision training. To upload the model to the Hub, write a function to get your repository name and information and then push it to the Hub."),ot=m(),f(ms.$$.fragment),it=m(),f(se.$$.fragment),rt=m(),hs=n("p"),ll=o("Phew, that was quite a bit of code! But you\u2019re finally ready to launch the training with \u{1F917} Accelerate\u2019s "),ee=n("a"),ol=o("notebook_launcher"),il=o(" function. Pass the function the training loop, all the training arguments, and the number of processes (you can change this value to the number of GPUs available to you) to use for training:"),pt=m(),f(ae.$$.fragment),ct=m(),ke=n("p"),rl=o("Once training is complete, take a look at the final \u{1F98B} images \u{1F98B} generated by your diffusion model!"),mt=m(),f(te.$$.fragment),ht=m(),ne=n("div"),ra=n("img"),ut=m(),W=n("h2"),us=n("a"),pa=n("span"),f(le.$$.fragment),pl=m(),ca=n("span"),cl=o("Next steps"),ft=m(),fs=n("p"),ml=o("Unconditional image generation is one example of a task that can be trained. You can explore other tasks and training techniques by visiting the "),$e=n("a"),hl=o("\u{1F9E8} Diffusers Training Examples"),ul=o(" page. Here are some examples of what you can learn:"),gt=m(),N=n("ul"),Ee=n("li"),De=n("a"),fl=o("Textual Inversion"),gl=o(", an algorithm that teaches a model a specific visual concept and integrates it into the generated image."),dl=m(),qe=n("li"),ze=n("a"),_l=o("DreamBooth"),jl=o(", a technique for generating personalized images of a subject given several input images of the subject."),bl=m(),Pe=n("li"),xe=n("a"),wl=o("Guide"),yl=o(" to finetuning a Stable Diffusion model on your own dataset."),vl=m(),Te=n("li"),Ne=n("a"),kl=o("Guide"),$l=o(" to using LoRA, a memory-efficient technique for finetuning really large models faster."),this.h()},l(s){const t=Jo('[data-svelte="svelte-1phssyn"]',document.head);u=l(t,"META",{name:!0,content:!0}),t.forEach(e),D=h(s),g(w.$$.fragment,s),$=h(s),E=l(s,"H1",{class:!0});var oe=r(E);y=l(oe,"A",{id:!0,class:!0,href:!0});var ma=r(y);k=l(ma,"SPAN",{});var ha=r(k);g(z.$$.fragment,ha),ha.forEach(e),ma.forEach(e),_s=h(oe),A=l(oe,"SPAN",{});var Sl=r(A);js=i(Sl,"Train a diffusion model"),Sl.forEach(e),oe.forEach(e),J=h(s),P=l(s,"P",{});var _t=r(P);bs=i(_t,"Unconditional image generation is a popular application of diffusion models that generates images that look like those in the dataset used for training. Typically, the best results are obtained from finetuning a pretrained model on a specific dataset. You can find many of these checkpoints on the "),B=l(_t,"A",{href:!0,rel:!0});var Fl=r(B);H=i(Fl,"Hub"),Fl.forEach(e),q=i(_t,", but if you can\u2019t find one you like, you can always train your own!"),_t.forEach(e),ws=h(s),x=l(s,"P",{});var Ae=r(x);re=i(Ae,"This tutorial will teach you how to train a "),L=l(Ae,"A",{href:!0});var Ul=r(L);pe=i(Ul,"UNet2DModel"),Ul.forEach(e),At=i(Ae," from scratch on a subset of the "),ys=l(Ae,"A",{href:!0,rel:!0});var Ml=r(ys);Bt=i(Ml,"Smithsonian Butterflies"),Ml.forEach(e),It=i(Ae," dataset to generate your own \u{1F98B} butterflies \u{1F98B}."),Ae.forEach(e),fa=h(s),g(K.$$.fragment,s),ga=h(s),I=l(s,"P",{});var Be=r(I);St=i(Be,"Before you begin, make sure you have \u{1F917} Datasets installed to load and preprocess image datasets, and \u{1F917} Accelerate, to simplify training on any number of GPUs. The following command will also install "),vs=l(Be,"A",{href:!0,rel:!0});var Hl=r(vs);Ft=i(Hl,"TensorBoard"),Hl.forEach(e),Ut=i(Be," to visualize training metrics (you can also use "),ks=l(Be,"A",{href:!0,rel:!0});var Ll=r(ks);Mt=i(Ll,"Weights & Biases"),Ll.forEach(e),Ht=i(Be," to track your training)."),Be.forEach(e),da=h(s),g($s.$$.fragment,s),_a=h(s),Q=l(s,"P",{});var jt=r(Q);Lt=i(jt,"We encourage you to share your model with the community, and in order to do that, you\u2019ll need to login to your Hugging Face account (create one "),Es=l(jt,"A",{href:!0,rel:!0});var Cl=r(Es);Ct=i(Cl,"here"),Cl.forEach(e),Rt=i(jt," if you don\u2019t already have one!). You can login from a notebook and enter your token when prompted:"),jt.forEach(e),ja=h(s),g(Ds.$$.fragment,s),ba=h(s),ce=l(s,"P",{});var Rl=r(ce);Gt=i(Rl,"Or login in from the terminal:"),Rl.forEach(e),wa=h(s),g(qs.$$.fragment,s),ya=h(s),X=l(s,"P",{});var bt=r(X);Ot=i(bt,"Since the model checkpoints are quite large, install "),zs=l(bt,"A",{href:!0,rel:!0});var Gl=r(zs);Yt=i(Gl,"Git-LFS"),Gl.forEach(e),Wt=i(bt," to version these large files:"),bt.forEach(e),va=h(s),g(Ps.$$.fragment,s),ka=h(s),C=l(s,"H2",{class:!0});var wt=r(C);Z=l(wt,"A",{id:!0,class:!0,href:!0});var Ol=r(Z);Me=l(Ol,"SPAN",{});var Yl=r(Me);g(xs.$$.fragment,Yl),Yl.forEach(e),Ol.forEach(e),Vt=h(wt),He=l(wt,"SPAN",{});var Wl=r(He);Jt=i(Wl,"Training configuration"),Wl.forEach(e),wt.forEach(e),$a=h(s),ss=l(s,"P",{});var yt=r(ss);Kt=i(yt,"For convenience, create a "),Le=l(yt,"CODE",{});var Vl=r(Le);Qt=i(Vl,"TrainingConfig"),Vl.forEach(e),Xt=i(yt," class containing the training hyperparameters (feel free to adjust them):"),yt.forEach(e),Ea=h(s),g(Ts.$$.fragment,s),Da=h(s),R=l(s,"H2",{class:!0});var vt=r(R);es=l(vt,"A",{id:!0,class:!0,href:!0});var Jl=r(es);Ce=l(Jl,"SPAN",{});var Kl=r(Ce);g(Ns.$$.fragment,Kl),Kl.forEach(e),Jl.forEach(e),Zt=h(vt),Re=l(vt,"SPAN",{});var Ql=r(Re);sn=i(Ql,"Load the dataset"),Ql.forEach(e),vt.forEach(e),qa=h(s),as=l(s,"P",{});var kt=r(as);en=i(kt,"You can easily load the "),As=l(kt,"A",{href:!0,rel:!0});var Xl=r(As);an=i(Xl,"Smithsonian Butterflies"),Xl.forEach(e),tn=i(kt," dataset with the \u{1F917} Datasets library:"),kt.forEach(e),za=h(s),g(Bs.$$.fragment,s),Pa=h(s),g(ts.$$.fragment,s),xa=h(s),S=l(s,"P",{});var Ie=r(S);nn=i(Ie,"\u{1F917} Datasets uses the "),Is=l(Ie,"A",{href:!0,rel:!0});var Zl=r(Is);ln=i(Zl,"Image"),Zl.forEach(e),on=i(Ie," feature to automatically decode the image data and load it as a "),Ss=l(Ie,"A",{href:!0,rel:!0});var so=r(Ss);Ge=l(so,"CODE",{});var eo=r(Ge);rn=i(eo,"PIL.Image"),eo.forEach(e),so.forEach(e),pn=i(Ie," which we can visualize:"),Ie.forEach(e),Ta=h(s),g(Fs.$$.fragment,s),Na=h(s),Us=l(s,"DIV",{class:!0});var ao=r(Us);Oe=l(ao,"IMG",{src:!0}),ao.forEach(e),Aa=h(s),me=l(s,"P",{});var to=r(me);cn=i(to,"The images are all different sizes though, so you\u2019ll need to preprocess them first:"),to.forEach(e),Ba=h(s),F=l(s,"UL",{});var Se=r(F);ns=l(Se,"LI",{});var ua=r(ns);Ye=l(ua,"CODE",{});var no=r(Ye);mn=i(no,"Resize"),no.forEach(e),hn=i(ua," changes the image size to the one defined in "),We=l(ua,"CODE",{});var lo=r(We);un=i(lo,"config.image_size"),lo.forEach(e),fn=i(ua,"."),ua.forEach(e),gn=h(Se),he=l(Se,"LI",{});var El=r(he);Ve=l(El,"CODE",{});var oo=r(Ve);dn=i(oo,"RandomHorizontalFlip"),oo.forEach(e),_n=i(El," augments the dataset by randomly mirroring the images."),El.forEach(e),jn=h(Se),ue=l(Se,"LI",{});var Dl=r(ue);Je=l(Dl,"CODE",{});var io=r(Je);bn=i(io,"Normalize"),io.forEach(e),wn=i(Dl," is important to rescale the pixel values into a [-1, 1] range, which is what the model expects."),Dl.forEach(e),Se.forEach(e),Ia=h(s),g(Ms.$$.fragment,s),Sa=h(s),U=l(s,"P",{});var Fe=r(U);yn=i(Fe,"Use \u{1F917} Datasets\u2019 "),Hs=l(Fe,"A",{href:!0,rel:!0});var ro=r(Hs);vn=i(ro,"set_transform"),ro.forEach(e),kn=i(Fe," method to apply the "),Ke=l(Fe,"CODE",{});var po=r(Ke);$n=i(po,"preprocess"),po.forEach(e),En=i(Fe," function on the fly during training:"),Fe.forEach(e),Fa=h(s),g(Ls.$$.fragment,s),Ua=h(s),ls=l(s,"P",{});var $t=r(ls);Dn=i($t,"Feel free to visualize the images again to confirm that they\u2019ve been resized. Now you\u2019re ready to wrap the dataset in a "),Cs=l($t,"A",{href:!0,rel:!0});var co=r(Cs);qn=i(co,"DataLoader"),co.forEach(e),zn=i($t," for training!"),$t.forEach(e),Ma=h(s),g(Rs.$$.fragment,s),Ha=h(s),G=l(s,"H2",{class:!0});var Et=r(G);os=l(Et,"A",{id:!0,class:!0,href:!0});var mo=r(os);Qe=l(mo,"SPAN",{});var ho=r(Qe);g(Gs.$$.fragment,ho),ho.forEach(e),mo.forEach(e),Pn=h(Et),Xe=l(Et,"SPAN",{});var uo=r(Xe);xn=i(uo,"Create a UNet2DModel"),uo.forEach(e),Et.forEach(e),La=h(s),is=l(s,"P",{});var Dt=r(is);Tn=i(Dt,"Pretrained models in \u{1F9E8} Diffusers are easily created from their model class with the parameters you want. For example, to create a "),fe=l(Dt,"A",{href:!0});var fo=r(fe);Nn=i(fo,"UNet2DModel"),fo.forEach(e),An=i(Dt,":"),Dt.forEach(e),Ca=h(s),g(Os.$$.fragment,s),Ra=h(s),ge=l(s,"P",{});var go=r(ge);Bn=i(go,"It is often a good idea to quickly check the sample image shape matches the model output shape:"),go.forEach(e),Ga=h(s),g(Ys.$$.fragment,s),Oa=h(s),de=l(s,"P",{});var _o=r(de);In=i(_o,"Great! Next, you\u2019ll need a scheduler to add some noise to the image."),_o.forEach(e),Ya=h(s),O=l(s,"H2",{class:!0});var qt=r(O);rs=l(qt,"A",{id:!0,class:!0,href:!0});var jo=r(rs);Ze=l(jo,"SPAN",{});var bo=r(Ze);g(Ws.$$.fragment,bo),bo.forEach(e),jo.forEach(e),Sn=h(qt),sa=l(qt,"SPAN",{});var wo=r(sa);Fn=i(wo,"Create a scheduler"),wo.forEach(e),qt.forEach(e),Wa=h(s),M=l(s,"P",{});var Ue=r(M);Un=i(Ue,"The scheduler behaves differently depending on whether you\u2019re using the model for training or inference. During inference, the scheduler generates image from the noise. During training, the scheduler takes a model output - or a sample - from a specific point in the diffusion process and applies noise to the image according to a "),ea=l(Ue,"EM",{});var yo=r(ea);Mn=i(yo,"noise schedule"),yo.forEach(e),Hn=i(Ue," and an "),aa=l(Ue,"EM",{});var vo=r(aa);Ln=i(vo,"update rule"),vo.forEach(e),Cn=i(Ue,"."),Ue.forEach(e),Va=h(s),T=l(s,"P",{});var gs=r(T);Rn=i(gs,"Let\u2019s take a look at the "),_e=l(gs,"A",{href:!0});var ko=r(_e);Gn=i(ko,"DDPMScheduler"),ko.forEach(e),On=i(gs," and use the "),ta=l(gs,"CODE",{});var $o=r(ta);Yn=i($o,"add_noise"),$o.forEach(e),Wn=i(gs," method to add some random noise to the "),na=l(gs,"CODE",{});var Eo=r(na);Vn=i(Eo,"sample_image"),Eo.forEach(e),Jn=i(gs," from before:"),gs.forEach(e),Ja=h(s),g(Vs.$$.fragment,s),Ka=h(s),Js=l(s,"DIV",{class:!0});var Do=r(Js);la=l(Do,"IMG",{src:!0}),Do.forEach(e),Qa=h(s),je=l(s,"P",{});var qo=r(je);Kn=i(qo,"The training objective of the model is to predict the noise added to the image. The loss at this step can be calculated by:"),qo.forEach(e),Xa=h(s),g(Ks.$$.fragment,s),Za=h(s),Y=l(s,"H2",{class:!0});var zt=r(Y);ps=l(zt,"A",{id:!0,class:!0,href:!0});var zo=r(ps);oa=l(zo,"SPAN",{});var Po=r(oa);g(Qs.$$.fragment,Po),Po.forEach(e),zo.forEach(e),Qn=h(zt),ia=l(zt,"SPAN",{});var xo=r(ia);Xn=i(xo,"Train the model"),xo.forEach(e),zt.forEach(e),st=h(s),be=l(s,"P",{});var To=r(be);Zn=i(To,"By now, you have most of the pieces to start training the model and all that\u2019s left is putting everything together."),To.forEach(e),et=h(s),we=l(s,"P",{});var No=r(we);sl=i(No,"First, you\u2019ll need an optimizer and a learning rate scheduler:"),No.forEach(e),at=h(s),g(Xs.$$.fragment,s),tt=h(s),cs=l(s,"P",{});var Pt=r(cs);el=i(Pt,"Then, you\u2019ll need a way to evaluate the model. For evaluation, you can use the "),ye=l(Pt,"A",{href:!0});var Ao=r(ye);al=i(Ao,"DDPMPipeline"),Ao.forEach(e),tl=i(Pt," to generate a batch of sample images and save it as a grid:"),Pt.forEach(e),nt=h(s),g(Zs.$$.fragment,s),lt=h(s),ve=l(s,"P",{});var Bo=r(ve);nl=i(Bo,"Now you can wrap all these components together in a training loop with \u{1F917} Accelerate for easy TensorBoard logging, gradient accumulation, and mixed precision training. To upload the model to the Hub, write a function to get your repository name and information and then push it to the Hub."),Bo.forEach(e),ot=h(s),g(ms.$$.fragment,s),it=h(s),g(se.$$.fragment,s),rt=h(s),hs=l(s,"P",{});var xt=r(hs);ll=i(xt,"Phew, that was quite a bit of code! But you\u2019re finally ready to launch the training with \u{1F917} Accelerate\u2019s "),ee=l(xt,"A",{href:!0,rel:!0});var Io=r(ee);ol=i(Io,"notebook_launcher"),Io.forEach(e),il=i(xt," function. Pass the function the training loop, all the training arguments, and the number of processes (you can change this value to the number of GPUs available to you) to use for training:"),xt.forEach(e),pt=h(s),g(ae.$$.fragment,s),ct=h(s),ke=l(s,"P",{});var So=r(ke);rl=i(So,"Once training is complete, take a look at the final \u{1F98B} images \u{1F98B} generated by your diffusion model!"),So.forEach(e),mt=h(s),g(te.$$.fragment,s),ht=h(s),ne=l(s,"DIV",{class:!0});var Fo=r(ne);ra=l(Fo,"IMG",{src:!0}),Fo.forEach(e),ut=h(s),W=l(s,"H2",{class:!0});var Tt=r(W);us=l(Tt,"A",{id:!0,class:!0,href:!0});var Uo=r(us);pa=l(Uo,"SPAN",{});var Mo=r(pa);g(le.$$.fragment,Mo),Mo.forEach(e),Uo.forEach(e),pl=h(Tt),ca=l(Tt,"SPAN",{});var Ho=r(ca);cl=i(Ho,"Next steps"),Ho.forEach(e),Tt.forEach(e),ft=h(s),fs=l(s,"P",{});var Nt=r(fs);ml=i(Nt,"Unconditional image generation is one example of a task that can be trained. You can explore other tasks and training techniques by visiting the "),$e=l(Nt,"A",{href:!0});var Lo=r($e);hl=i(Lo,"\u{1F9E8} Diffusers Training Examples"),Lo.forEach(e),ul=i(Nt," page. Here are some examples of what you can learn:"),Nt.forEach(e),gt=h(s),N=l(s,"UL",{});var ds=r(N);Ee=l(ds,"LI",{});var ql=r(Ee);De=l(ql,"A",{href:!0});var Co=r(De);fl=i(Co,"Textual Inversion"),Co.forEach(e),gl=i(ql,", an algorithm that teaches a model a specific visual concept and integrates it into the generated image."),ql.forEach(e),dl=h(ds),qe=l(ds,"LI",{});var zl=r(qe);ze=l(zl,"A",{href:!0});var Ro=r(ze);_l=i(Ro,"DreamBooth"),Ro.forEach(e),jl=i(zl,", a technique for generating personalized images of a subject given several input images of the subject."),zl.forEach(e),bl=h(ds),Pe=l(ds,"LI",{});var Pl=r(Pe);xe=l(Pl,"A",{href:!0});var Go=r(xe);wl=i(Go,"Guide"),Go.forEach(e),yl=i(Pl," to finetuning a Stable Diffusion model on your own dataset."),Pl.forEach(e),vl=h(ds),Te=l(ds,"LI",{});var xl=r(Te);Ne=l(xl,"A",{href:!0});var Oo=r(Ne);kl=i(Oo,"Guide"),Oo.forEach(e),$l=i(xl," to using LoRA, a memory-efficient technique for finetuning really large models faster."),xl.forEach(e),ds.forEach(e),this.h()},h(){c(u,"name","hf:doc:metadata"),c(u,"content",JSON.stringify(ai)),c(y,"id","train-a-diffusion-model"),c(y,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),c(y,"href","#train-a-diffusion-model"),c(E,"class","relative group"),c(B,"href","https://huggingface.co/search/full-text?q=unconditional-image-generation&type=model"),c(B,"rel","nofollow"),c(L,"href","/docs/diffusers/v0.16.0/en/api/models#diffusers.UNet2DModel"),c(ys,"href","https://huggingface.co/datasets/huggan/smithsonian_butterflies_subset"),c(ys,"rel","nofollow"),c(vs,"href","https://www.tensorflow.org/tensorboard"),c(vs,"rel","nofollow"),c(ks,"href","https://docs.wandb.ai/"),c(ks,"rel","nofollow"),c(Es,"href","https://hf.co/join"),c(Es,"rel","nofollow"),c(zs,"href","https://git-lfs.com/"),c(zs,"rel","nofollow"),c(Z,"id","training-configuration"),c(Z,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),c(Z,"href","#training-configuration"),c(C,"class","relative group"),c(es,"id","load-the-dataset"),c(es,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),c(es,"href","#load-the-dataset"),c(R,"class","relative group"),c(As,"href","https://huggingface.co/datasets/huggan/smithsonian_butterflies_subset"),c(As,"rel","nofollow"),c(Is,"href","https://huggingface.co/docs/datasets/v2.11.0/en/package_reference/main_classes#datasets.Image"),c(Is,"rel","nofollow"),c(Ss,"href","https://pillow.readthedocs.io/en/stable/reference/Image.html"),c(Ss,"rel","nofollow"),Tl(Oe.src,Al="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/butterflies_ds.png")||c(Oe,"src",Al),c(Us,"class","flex justify-center"),c(Hs,"href","https://huggingface.co/docs/datasets/v2.11.0/en/package_reference/main_classes#datasets.Dataset.set_transform"),c(Hs,"rel","nofollow"),c(Cs,"href","https://pytorch.org/docs/stable/data#torch.utils.data.DataLoader"),c(Cs,"rel","nofollow"),c(os,"id","create-a-unet2dmodel"),c(os,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),c(os,"href","#create-a-unet2dmodel"),c(G,"class","relative group"),c(fe,"href","/docs/diffusers/v0.16.0/en/api/models#diffusers.UNet2DModel"),c(rs,"id","create-a-scheduler"),c(rs,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),c(rs,"href","#create-a-scheduler"),c(O,"class","relative group"),c(_e,"href","/docs/diffusers/v0.16.0/en/api/schedulers/ddpm#diffusers.DDPMScheduler"),Tl(la.src,Bl="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/noisy_butterfly.png")||c(la,"src",Bl),c(Js,"class","flex justify-center"),c(ps,"id","train-the-model"),c(ps,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),c(ps,"href","#train-the-model"),c(Y,"class","relative group"),c(ye,"href","/docs/diffusers/v0.16.0/en/api/pipelines/ddpm#diffusers.DDPMPipeline"),c(ee,"href","https://huggingface.co/docs/accelerate/v0.18.0/en/package_reference/launchers#accelerate.notebook_launcher"),c(ee,"rel","nofollow"),Tl(ra.src,Il="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/butterflies_final.png")||c(ra,"src",Il),c(ne,"class","flex justify-center"),c(us,"id","next-steps"),c(us,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),c(us,"href","#next-steps"),c(W,"class","relative group"),c($e,"href","./training/overview"),c(De,"href","./training/text_inversion"),c(ze,"href","./training/dreambooth"),c(xe,"href","./training/text2image"),c(Ne,"href","./training/lora")},m(s,t){a(document.head,u),p(s,D,t),d(w,s,t),p(s,$,t),p(s,E,t),a(E,y),a(y,k),d(z,k,null),a(E,_s),a(E,A),a(A,js),p(s,J,t),p(s,P,t),a(P,bs),a(P,B),a(B,H),a(P,q),p(s,ws,t),p(s,x,t),a(x,re),a(x,L),a(L,pe),a(x,At),a(x,ys),a(ys,Bt),a(x,It),p(s,fa,t),d(K,s,t),p(s,ga,t),p(s,I,t),a(I,St),a(I,vs),a(vs,Ft),a(I,Ut),a(I,ks),a(ks,Mt),a(I,Ht),p(s,da,t),d($s,s,t),p(s,_a,t),p(s,Q,t),a(Q,Lt),a(Q,Es),a(Es,Ct),a(Q,Rt),p(s,ja,t),d(Ds,s,t),p(s,ba,t),p(s,ce,t),a(ce,Gt),p(s,wa,t),d(qs,s,t),p(s,ya,t),p(s,X,t),a(X,Ot),a(X,zs),a(zs,Yt),a(X,Wt),p(s,va,t),d(Ps,s,t),p(s,ka,t),p(s,C,t),a(C,Z),a(Z,Me),d(xs,Me,null),a(C,Vt),a(C,He),a(He,Jt),p(s,$a,t),p(s,ss,t),a(ss,Kt),a(ss,Le),a(Le,Qt),a(ss,Xt),p(s,Ea,t),d(Ts,s,t),p(s,Da,t),p(s,R,t),a(R,es),a(es,Ce),d(Ns,Ce,null),a(R,Zt),a(R,Re),a(Re,sn),p(s,qa,t),p(s,as,t),a(as,en),a(as,As),a(As,an),a(as,tn),p(s,za,t),d(Bs,s,t),p(s,Pa,t),d(ts,s,t),p(s,xa,t),p(s,S,t),a(S,nn),a(S,Is),a(Is,ln),a(S,on),a(S,Ss),a(Ss,Ge),a(Ge,rn),a(S,pn),p(s,Ta,t),d(Fs,s,t),p(s,Na,t),p(s,Us,t),a(Us,Oe),p(s,Aa,t),p(s,me,t),a(me,cn),p(s,Ba,t),p(s,F,t),a(F,ns),a(ns,Ye),a(Ye,mn),a(ns,hn),a(ns,We),a(We,un),a(ns,fn),a(F,gn),a(F,he),a(he,Ve),a(Ve,dn),a(he,_n),a(F,jn),a(F,ue),a(ue,Je),a(Je,bn),a(ue,wn),p(s,Ia,t),d(Ms,s,t),p(s,Sa,t),p(s,U,t),a(U,yn),a(U,Hs),a(Hs,vn),a(U,kn),a(U,Ke),a(Ke,$n),a(U,En),p(s,Fa,t),d(Ls,s,t),p(s,Ua,t),p(s,ls,t),a(ls,Dn),a(ls,Cs),a(Cs,qn),a(ls,zn),p(s,Ma,t),d(Rs,s,t),p(s,Ha,t),p(s,G,t),a(G,os),a(os,Qe),d(Gs,Qe,null),a(G,Pn),a(G,Xe),a(Xe,xn),p(s,La,t),p(s,is,t),a(is,Tn),a(is,fe),a(fe,Nn),a(is,An),p(s,Ca,t),d(Os,s,t),p(s,Ra,t),p(s,ge,t),a(ge,Bn),p(s,Ga,t),d(Ys,s,t),p(s,Oa,t),p(s,de,t),a(de,In),p(s,Ya,t),p(s,O,t),a(O,rs),a(rs,Ze),d(Ws,Ze,null),a(O,Sn),a(O,sa),a(sa,Fn),p(s,Wa,t),p(s,M,t),a(M,Un),a(M,ea),a(ea,Mn),a(M,Hn),a(M,aa),a(aa,Ln),a(M,Cn),p(s,Va,t),p(s,T,t),a(T,Rn),a(T,_e),a(_e,Gn),a(T,On),a(T,ta),a(ta,Yn),a(T,Wn),a(T,na),a(na,Vn),a(T,Jn),p(s,Ja,t),d(Vs,s,t),p(s,Ka,t),p(s,Js,t),a(Js,la),p(s,Qa,t),p(s,je,t),a(je,Kn),p(s,Xa,t),d(Ks,s,t),p(s,Za,t),p(s,Y,t),a(Y,ps),a(ps,oa),d(Qs,oa,null),a(Y,Qn),a(Y,ia),a(ia,Xn),p(s,st,t),p(s,be,t),a(be,Zn),p(s,et,t),p(s,we,t),a(we,sl),p(s,at,t),d(Xs,s,t),p(s,tt,t),p(s,cs,t),a(cs,el),a(cs,ye),a(ye,al),a(cs,tl),p(s,nt,t),d(Zs,s,t),p(s,lt,t),p(s,ve,t),a(ve,nl),p(s,ot,t),d(ms,s,t),p(s,it,t),d(se,s,t),p(s,rt,t),p(s,hs,t),a(hs,ll),a(hs,ee),a(ee,ol),a(hs,il),p(s,pt,t),d(ae,s,t),p(s,ct,t),p(s,ke,t),a(ke,rl),p(s,mt,t),d(te,s,t),p(s,ht,t),p(s,ne,t),a(ne,ra),p(s,ut,t),p(s,W,t),a(W,us),a(us,pa),d(le,pa,null),a(W,pl),a(W,ca),a(ca,cl),p(s,ft,t),p(s,fs,t),a(fs,ml),a(fs,$e),a($e,hl),a(fs,ul),p(s,gt,t),p(s,N,t),a(N,Ee),a(Ee,De),a(De,fl),a(Ee,gl),a(N,dl),a(N,qe),a(qe,ze),a(ze,_l),a(qe,jl),a(N,bl),a(N,Pe),a(Pe,xe),a(xe,wl),a(Pe,yl),a(N,vl),a(N,Te),a(Te,Ne),a(Ne,kl),a(Te,$l),dt=!0},p(s,[t]){const oe={};t&2&&(oe.$$scope={dirty:t,ctx:s}),K.$set(oe);const ma={};t&2&&(ma.$$scope={dirty:t,ctx:s}),ts.$set(ma);const ha={};t&2&&(ha.$$scope={dirty:t,ctx:s}),ms.$set(ha)},i(s){dt||(_(w.$$.fragment,s),_(z.$$.fragment,s),_(K.$$.fragment,s),_($s.$$.fragment,s),_(Ds.$$.fragment,s),_(qs.$$.fragment,s),_(Ps.$$.fragment,s),_(xs.$$.fragment,s),_(Ts.$$.fragment,s),_(Ns.$$.fragment,s),_(Bs.$$.fragment,s),_(ts.$$.fragment,s),_(Fs.$$.fragment,s),_(Ms.$$.fragment,s),_(Ls.$$.fragment,s),_(Rs.$$.fragment,s),_(Gs.$$.fragment,s),_(Os.$$.fragment,s),_(Ys.$$.fragment,s),_(Ws.$$.fragment,s),_(Vs.$$.fragment,s),_(Ks.$$.fragment,s),_(Qs.$$.fragment,s),_(Xs.$$.fragment,s),_(Zs.$$.fragment,s),_(ms.$$.fragment,s),_(se.$$.fragment,s),_(ae.$$.fragment,s),_(te.$$.fragment,s),_(le.$$.fragment,s),dt=!0)},o(s){j(w.$$.fragment,s),j(z.$$.fragment,s),j(K.$$.fragment,s),j($s.$$.fragment,s),j(Ds.$$.fragment,s),j(qs.$$.fragment,s),j(Ps.$$.fragment,s),j(xs.$$.fragment,s),j(Ts.$$.fragment,s),j(Ns.$$.fragment,s),j(Bs.$$.fragment,s),j(ts.$$.fragment,s),j(Fs.$$.fragment,s),j(Ms.$$.fragment,s),j(Ls.$$.fragment,s),j(Rs.$$.fragment,s),j(Gs.$$.fragment,s),j(Os.$$.fragment,s),j(Ys.$$.fragment,s),j(Ws.$$.fragment,s),j(Vs.$$.fragment,s),j(Ks.$$.fragment,s),j(Qs.$$.fragment,s),j(Xs.$$.fragment,s),j(Zs.$$.fragment,s),j(ms.$$.fragment,s),j(se.$$.fragment,s),j(ae.$$.fragment,s),j(te.$$.fragment,s),j(le.$$.fragment,s),dt=!1},d(s){e(u),s&&e(D),b(w,s),s&&e($),s&&e(E),b(z),s&&e(J),s&&e(P),s&&e(ws),s&&e(x),s&&e(fa),b(K,s),s&&e(ga),s&&e(I),s&&e(da),b($s,s),s&&e(_a),s&&e(Q),s&&e(ja),b(Ds,s),s&&e(ba),s&&e(ce),s&&e(wa),b(qs,s),s&&e(ya),s&&e(X),s&&e(va),b(Ps,s),s&&e(ka),s&&e(C),b(xs),s&&e($a),s&&e(ss),s&&e(Ea),b(Ts,s),s&&e(Da),s&&e(R),b(Ns),s&&e(qa),s&&e(as),s&&e(za),b(Bs,s),s&&e(Pa),b(ts,s),s&&e(xa),s&&e(S),s&&e(Ta),b(Fs,s),s&&e(Na),s&&e(Us),s&&e(Aa),s&&e(me),s&&e(Ba),s&&e(F),s&&e(Ia),b(Ms,s),s&&e(Sa),s&&e(U),s&&e(Fa),b(Ls,s),s&&e(Ua),s&&e(ls),s&&e(Ma),b(Rs,s),s&&e(Ha),s&&e(G),b(Gs),s&&e(La),s&&e(is),s&&e(Ca),b(Os,s),s&&e(Ra),s&&e(ge),s&&e(Ga),b(Ys,s),s&&e(Oa),s&&e(de),s&&e(Ya),s&&e(O),b(Ws),s&&e(Wa),s&&e(M),s&&e(Va),s&&e(T),s&&e(Ja),b(Vs,s),s&&e(Ka),s&&e(Js),s&&e(Qa),s&&e(je),s&&e(Xa),b(Ks,s),s&&e(Za),s&&e(Y),b(Qs),s&&e(st),s&&e(be),s&&e(et),s&&e(we),s&&e(at),b(Xs,s),s&&e(tt),s&&e(cs),s&&e(nt),b(Zs,s),s&&e(lt),s&&e(ve),s&&e(ot),b(ms,s),s&&e(it),b(se,s),s&&e(rt),s&&e(hs),s&&e(pt),b(ae,s),s&&e(ct),s&&e(ke),s&&e(mt),b(te,s),s&&e(ht),s&&e(ne),s&&e(ut),s&&e(W),b(le),s&&e(ft),s&&e(fs),s&&e(gt),s&&e(N)}}}const ai={local:"train-a-diffusion-model",sections:[{local:"training-configuration",title:"Training configuration"},{local:"load-the-dataset",title:"Load the dataset"},{local:"create-a-unet2dmodel",title:"Create a UNet2DModel"},{local:"create-a-scheduler",title:"Create a scheduler"},{local:"train-the-model",title:"Train the model"},{local:"next-steps",title:"Next steps"}],title:"Train a diffusion model"};function ti(V){return Ko(()=>{new URLSearchParams(window.location.search).get("fw")}),[]}class pi extends Yo{constructor(u){super();Wo(this,u,ti,ei,Vo,{})}}export{pi as default,ai as metadata}; | |
Xet Storage Details
- Size:
- 71 kB
- Xet hash:
- 93d323da05ae83d0ecfa39268d9d9abd851f06f1140e62390e90e8df4def9f44
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.