import{S as bm,i as gm,s as wm,e as a,k as f,w as u,t as i,M as $m,c as o,d as s,m,a as n,x as _,h as r,b as h,G as t,g as p,y as v,q as y,o as b,B as g,v as Em}from"../../chunks/vendor-hf-doc-builder.js";import{T as $n}from"../../chunks/Tip-hf-doc-builder.js";import{I as S}from"../../chunks/IconCopyLink-hf-doc-builder.js";import{C as D}from"../../chunks/CodeBlock-hf-doc-builder.js";function jm(x){let c;return{c(){c=i("It is strongly discouraged to make use of [`torch.autocast`](https://pytorch.org/docs/stable/amp.html#torch.autocast) in any of the pipelines as it can lead to black images and is always slower than using pure \n  float16 precision.")},l(d){c=r(d,"It is strongly discouraged to make use of [`torch.autocast`](https://pytorch.org/docs/stable/amp.html#torch.autocast) in any of the pipelines as it can lead to black images and is always slower than using pure \n  float16 precision.")},m(d,w){p(d,c,w)},d(d){d&&s(c)}}}function km(x){let c;return{c(){c=i(`Attention slicing is useful even if a batch size of just 1 is used - as long
  as the model uses more than one attention head. If there is more than one
  attention head the *QK^T* attention matrix can be computed sequentially for
  each head which can save a significant amount of memory.`)},l(d){c=r(d,`Attention slicing is useful even if a batch size of just 1 is used - as long
  as the model uses more than one attention head. If there is more than one
  attention head the *QK^T* attention matrix can be computed sequentially for
  each head which can save a significant amount of memory.`)},m(d,w){p(d,c,w)},d(d){d&&s(c)}}}function Tm(x){let c,d,w,T;return{c(){c=i("Consider using "),d=a("a"),w=i("model offloading"),T=i(" as another point in the optimization space: it will be much faster, but memory savings won't be as large."),this.h()},l($){c=r($,"Consider using "),d=o($,"A",{href:!0});var j=n(d);w=r(j,"model offloading"),j.forEach(s),T=r($," as another point in the optimization space: it will be much faster, but memory savings won't be as large."),this.h()},h(){h(d,"href","#model_offloading")},m($,j){p($,c,j),p($,d,j),t(d,w),p($,T,j)},d($){$&&s(c),$&&s(d),$&&s(T)}}}function Pm(x){let c;return{c(){c=i("This feature requires `accelerate` version 0.17.0 or larger.")},l(d){c=r(d,"This feature requires `accelerate` version 0.17.0 or larger.")},m(d,w){p(d,c,w)},d(d){d&&s(c)}}}function Am(x){let c,d,w,T,$,j,En,ms,jn,Va,q,kn,hs,Tn,Pn,Fe,An,Dn,dt,qn,Sn,Ma,ct,xn,Ra,me,ds,R,Ga,Un,cs,Nn,Cn,us,In,Fn,P,G,_s,Vn,Mn,vs,Rn,Gn,ys,zn,Hn,z,bs,Bn,On,gs,Ln,Xn,ws,Yn,Wn,H,$s,Kn,Qn,Es,Jn,Zn,js,ei,ti,B,ks,si,ai,Ts,oi,ni,Ps,ii,ri,O,As,li,pi,Ds,fi,mi,qs,hi,za,ut,di,Ha,L,he,Ss,Ve,ci,xs,ui,Ba,de,_i,Me,vi,yi,Oa,Re,La,X,ce,Us,Ge,bi,Ns,gi,Xa,U,wi,Cs,$i,Ei,Is,ji,ki,Ya,ze,Wa,ue,Ka,Y,_e,Fs,He,Ti,Vs,Pi,Qa,_t,Ai,Ja,ve,Za,ye,Di,vt,qi,Si,eo,Be,to,yt,xi,so,W,be,Ms,Oe,Ui,Rs,Ni,ao,bt,Ci,oo,N,Ii,gt,Fi,Vi,wt,Mi,Ri,no,ge,Gi,$t,zi,Hi,io,Le,ro,Et,Bi,lo,K,we,Gs,Xe,Oi,zs,Li,po,jt,Xi,fo,C,Yi,kt,Wi,Ki,Tt,Qi,Ji,mo,$e,Zi,Pt,er,tr,ho,Ye,co,At,sr,uo,Dt,_o,Q,Ee,Hs,We,ar,Bs,or,vo,qt,nr,yo,je,ir,St,rr,lr,bo,Ke,go,xt,pr,wo,ke,fr,Os,mr,hr,$o,Te,Eo,Ut,dr,jo,Qe,ko,A,Ls,cr,ur,Xs,_r,vr,Ys,yr,br,Je,gr,wr,To,Nt,Po,J,Pe,Ws,Ze,$r,Ks,Er,Ao,et,Ct,jr,kr,Do,I,Tr,Qs,Pr,Ar,Js,Dr,qr,qo,It,Sr,So,Ae,xr,Zs,Ur,Nr,xo,tt,Uo,Ft,Cr,No,st,Co,De,Io,Z,qe,ea,at,Ir,ta,Fr,Fo,Vt,Vr,Vo,Mt,Mr,Mo,ot,Ro,ee,Se,sa,nt,Rr,aa,Gr,Go,xe,zr,oa,Hr,Br,zo,Rt,Or,Ho,it,Bo,Ue,Lr,na,Xr,Yr,Oo,rt,Lo,te,Ne,ia,lt,Wr,ra,Kr,Xo,F,Qr,pt,Jr,Zr,ft,el,tl,Yo,Gt,sl,Wo,Ce,la,se,pa,al,ol,fa,nl,il,ma,rl,ll,E,ae,ha,pl,fl,da,ml,hl,ca,dl,cl,oe,ua,ul,_l,_a,vl,yl,va,bl,gl,ne,ya,wl,$l,ba,El,jl,ga,kl,Tl,ie,wa,Pl,Al,$a,Dl,ql,Ea,Sl,xl,re,ja,Ul,Nl,ka,Cl,Il,Ta,Fl,Vl,le,Pa,Ml,Rl,Aa,Gl,zl,Da,Hl,Bl,pe,qa,Ol,Ll,Sa,Xl,Yl,xa,Wl,Ko,zt,Kl,Qo,V,Ua,Ql,Jl,Na,Zl,ep,Ht,Bt,tp,sp,Jo,mt,Zo;return j=new S({}),Ve=new S({}),Re=new D({props:{code:`import torch

torch.backends.cuda.matmul.allow_tf32 = True`,highlighted:`<span class="hljs-keyword">import</span> torch

torch.backends.cuda.matmul.allow_tf32 = <span class="hljs-literal">True</span>`}}),Ge=new S({}),ze=new D({props:{code:`import torch
from diffusers import DiffusionPipeline

pipe = DiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    
    torch_dtype=torch.float16,
)
pipe = pipe.to("cuda")

prompt = "a photo of an astronaut riding a horse on mars"
image = pipe(prompt).images[0]`,highlighted:`<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> DiffusionPipeline

pipe = DiffusionPipeline.from_pretrained(
    <span class="hljs-string">&quot;runwayml/stable-diffusion-v1-5&quot;</span>,
    
    torch_dtype=torch.float16,
)
pipe = pipe.to(<span class="hljs-string">&quot;cuda&quot;</span>)

prompt = <span class="hljs-string">&quot;a photo of an astronaut riding a horse on mars&quot;</span>
image = pipe(prompt).images[<span class="hljs-number">0</span>]`}}),ue=new $n({props:{warning:!0,$$slots:{default:[jm]},$$scope:{ctx:x}}}),He=new S({}),ve=new $n({props:{$$slots:{default:[km]},$$scope:{ctx:x}}}),Be=new D({props:{code:`import torch
from diffusers import DiffusionPipeline

pipe = DiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    
    torch_dtype=torch.float16,
)
pipe = pipe.to("cuda")

prompt = "a photo of an astronaut riding a horse on mars"
pipe.enable_attention_slicing()
image = pipe(prompt).images[0]`,highlighted:`<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> DiffusionPipeline

pipe = DiffusionPipeline.from_pretrained(
    <span class="hljs-string">&quot;runwayml/stable-diffusion-v1-5&quot;</span>,
    
    torch_dtype=torch.float16,
)
pipe = pipe.to(<span class="hljs-string">&quot;cuda&quot;</span>)

prompt = <span class="hljs-string">&quot;a photo of an astronaut riding a horse on mars&quot;</span>
pipe.enable_attention_slicing()
image = pipe(prompt).images[<span class="hljs-number">0</span>]`}}),Oe=new S({}),Le=new D({props:{code:`import torch
from diffusers import StableDiffusionPipeline

pipe = StableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    
    torch_dtype=torch.float16,
)
pipe = pipe.to("cuda")

prompt = "a photo of an astronaut riding a horse on mars"
pipe.enable_vae_slicing()
images = pipe([prompt] * 32).images`,highlighted:`<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> StableDiffusionPipeline

pipe = StableDiffusionPipeline.from_pretrained(
    <span class="hljs-string">&quot;runwayml/stable-diffusion-v1-5&quot;</span>,
    
    torch_dtype=torch.float16,
)
pipe = pipe.to(<span class="hljs-string">&quot;cuda&quot;</span>)

prompt = <span class="hljs-string">&quot;a photo of an astronaut riding a horse on mars&quot;</span>
pipe.enable_vae_slicing()
images = pipe([prompt] * <span class="hljs-number">32</span>).images`}}),Xe=new S({}),Ye=new D({props:{code:`import torch
from diffusers import StableDiffusionPipeline, UniPCMultistepScheduler

pipe = StableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    torch_dtype=torch.float16,
)
pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
pipe = pipe.to("cuda")
prompt = "a beautiful landscape photograph"
pipe.enable_vae_tiling()
pipe.enable_xformers_memory_efficient_attention()

image = pipe([prompt], width=3840, height=2224, num_inference_steps=20).images[0]`,highlighted:`<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> StableDiffusionPipeline, UniPCMultistepScheduler

pipe = StableDiffusionPipeline.from_pretrained(
    <span class="hljs-string">&quot;runwayml/stable-diffusion-v1-5&quot;</span>,
    torch_dtype=torch.float16,
)
pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
pipe = pipe.to(<span class="hljs-string">&quot;cuda&quot;</span>)
prompt = <span class="hljs-string">&quot;a beautiful landscape photograph&quot;</span>
pipe.enable_vae_tiling()
pipe.enable_xformers_memory_efficient_attention()

image = pipe([prompt], width=<span class="hljs-number">3840</span>, height=<span class="hljs-number">2224</span>, num_inference_steps=<span class="hljs-number">20</span>).images[<span class="hljs-number">0</span>]`}}),We=new S({}),Ke=new D({props:{code:`import torch
from diffusers import StableDiffusionPipeline

pipe = StableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    
    torch_dtype=torch.float16,
)

prompt = "a photo of an astronaut riding a horse on mars"
pipe.enable_sequential_cpu_offload()
image = pipe(prompt).images[0]`,highlighted:`<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> StableDiffusionPipeline

pipe = StableDiffusionPipeline.from_pretrained(
    <span class="hljs-string">&quot;runwayml/stable-diffusion-v1-5&quot;</span>,
    
    torch_dtype=torch.float16,
)

prompt = <span class="hljs-string">&quot;a photo of an astronaut riding a horse on mars&quot;</span>
pipe.enable_sequential_cpu_offload()
image = pipe(prompt).images[<span class="hljs-number">0</span>]`}}),Te=new $n({props:{$$slots:{default:[Tm]},$$scope:{ctx:x}}}),Qe=new D({props:{code:`import torch
from diffusers import StableDiffusionPipeline

pipe = StableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    
    torch_dtype=torch.float16,
)

prompt = "a photo of an astronaut riding a horse on mars"
pipe.enable_sequential_cpu_offload()
pipe.enable_attention_slicing(1)

image = pipe(prompt).images[0]`,highlighted:`<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> StableDiffusionPipeline

pipe = StableDiffusionPipeline.from_pretrained(
    <span class="hljs-string">&quot;runwayml/stable-diffusion-v1-5&quot;</span>,
    
    torch_dtype=torch.float16,
)

prompt = <span class="hljs-string">&quot;a photo of an astronaut riding a horse on mars&quot;</span>
pipe.enable_sequential_cpu_offload()
pipe.enable_attention_slicing(<span class="hljs-number">1</span>)

image = pipe(prompt).images[<span class="hljs-number">0</span>]`}}),Ze=new S({}),tt=new D({props:{code:`import torch
from diffusers import StableDiffusionPipeline

pipe = StableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",  
    torch_dtype=torch.float16,
)

prompt = "a photo of an astronaut riding a horse on mars"
pipe.enable_model_cpu_offload()
image = pipe(prompt).images[0]`,highlighted:`<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> StableDiffusionPipeline

pipe = StableDiffusionPipeline.from_pretrained(
    <span class="hljs-string">&quot;runwayml/stable-diffusion-v1-5&quot;</span>,  
    torch_dtype=torch.float16,
)

prompt = <span class="hljs-string">&quot;a photo of an astronaut riding a horse on mars&quot;</span>
pipe.enable_model_cpu_offload()
image = pipe(prompt).images[<span class="hljs-number">0</span>]`}}),st=new D({props:{code:`import torch
from diffusers import StableDiffusionPipeline

pipe = StableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    torch_dtype=torch.float16,
)

prompt = "a photo of an astronaut riding a horse on mars"
pipe.enable_model_cpu_offload()
pipe.enable_attention_slicing(1)

image = pipe(prompt).images[0]`,highlighted:`<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> StableDiffusionPipeline

pipe = StableDiffusionPipeline.from_pretrained(
    <span class="hljs-string">&quot;runwayml/stable-diffusion-v1-5&quot;</span>,
    torch_dtype=torch.float16,
)

prompt = <span class="hljs-string">&quot;a photo of an astronaut riding a horse on mars&quot;</span>
pipe.enable_model_cpu_offload()
pipe.enable_attention_slicing(<span class="hljs-number">1</span>)

image = pipe(prompt).images[<span class="hljs-number">0</span>]`}}),De=new $n({props:{$$slots:{default:[Pm]},$$scope:{ctx:x}}}),at=new S({}),ot=new D({props:{code:`print(pipe.unet.conv_out.state_dict()["weight"].stride())  # (2880, 9, 3, 1)
pipe.unet.to(memory_format=torch.channels_last)  # in-place operation
print(
    pipe.unet.conv_out.state_dict()["weight"].stride()
)  # (2880, 1, 960, 320) having a stride of 1 for the 2nd dimension proves that it works`,highlighted:`<span class="hljs-built_in">print</span>(pipe.unet.conv_out.state_dict()[<span class="hljs-string">&quot;weight&quot;</span>].stride())  <span class="hljs-comment"># (2880, 9, 3, 1)</span>
pipe.unet.to(memory_format=torch.channels_last)  <span class="hljs-comment"># in-place operation</span>
<span class="hljs-built_in">print</span>(
    pipe.unet.conv_out.state_dict()[<span class="hljs-string">&quot;weight&quot;</span>].stride()
)  <span class="hljs-comment"># (2880, 1, 960, 320) having a stride of 1 for the 2nd dimension proves that it works</span>`}}),nt=new S({}),it=new D({props:{code:`import time
import torch
from diffusers import StableDiffusionPipeline
import functools

# torch disable grad
torch.set_grad_enabled(False)

# set variables
n_experiments = 2
unet_runs_per_experiment = 50


# load inputs
def generate_inputs():
    sample = torch.randn(2, 4, 64, 64).half().cuda()
    timestep = torch.rand(1).half().cuda() * 999
    encoder_hidden_states = torch.randn(2, 77, 768).half().cuda()
    return sample, timestep, encoder_hidden_states


pipe = StableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    torch_dtype=torch.float16,
).to("cuda")
unet = pipe.unet
unet.eval()
unet.to(memory_format=torch.channels_last)  # use channels_last memory format
unet.forward = functools.partial(unet.forward, return_dict=False)  # set return_dict=False as default

# warmup
for _ in range(3):
    with torch.inference_mode():
        inputs = generate_inputs()
        orig_output = unet(*inputs)

# trace
print("tracing..")
unet_traced = torch.jit.trace(unet, inputs)
unet_traced.eval()
print("done tracing")


# warmup and optimize graph
for _ in range(5):
    with torch.inference_mode():
        inputs = generate_inputs()
        orig_output = unet_traced(*inputs)


# benchmarking
with torch.inference_mode():
    for _ in range(n_experiments):
        torch.cuda.synchronize()
        start_time = time.time()
        for _ in range(unet_runs_per_experiment):
            orig_output = unet_traced(*inputs)
        torch.cuda.synchronize()
        print(f"unet traced inference took {time.time() - start_time:.2f} seconds")
    for _ in range(n_experiments):
        torch.cuda.synchronize()
        start_time = time.time()
        for _ in range(unet_runs_per_experiment):
            orig_output = unet(*inputs)
        torch.cuda.synchronize()
        print(f"unet inference took {time.time() - start_time:.2f} seconds")

# save the model
unet_traced.save("unet_traced.pt")`,highlighted:`<span class="hljs-keyword">import</span> time
<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> StableDiffusionPipeline
<span class="hljs-keyword">import</span> functools

<span class="hljs-comment"># torch disable grad</span>
torch.set_grad_enabled(<span class="hljs-literal">False</span>)

<span class="hljs-comment"># set variables</span>
n_experiments = <span class="hljs-number">2</span>
unet_runs_per_experiment = <span class="hljs-number">50</span>


<span class="hljs-comment"># load inputs</span>
<span class="hljs-keyword">def</span> <span class="hljs-title function_">generate_inputs</span>():
    sample = torch.randn(<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">64</span>, <span class="hljs-number">64</span>).half().cuda()
    timestep = torch.rand(<span class="hljs-number">1</span>).half().cuda() * <span class="hljs-number">999</span>
    encoder_hidden_states = torch.randn(<span class="hljs-number">2</span>, <span class="hljs-number">77</span>, <span class="hljs-number">768</span>).half().cuda()
    <span class="hljs-keyword">return</span> sample, timestep, encoder_hidden_states


pipe = StableDiffusionPipeline.from_pretrained(
    <span class="hljs-string">&quot;runwayml/stable-diffusion-v1-5&quot;</span>,
    torch_dtype=torch.float16,
).to(<span class="hljs-string">&quot;cuda&quot;</span>)
unet = pipe.unet
unet.<span class="hljs-built_in">eval</span>()
unet.to(memory_format=torch.channels_last)  <span class="hljs-comment"># use channels_last memory format</span>
unet.forward = functools.partial(unet.forward, return_dict=<span class="hljs-literal">False</span>)  <span class="hljs-comment"># set return_dict=False as default</span>

<span class="hljs-comment"># warmup</span>
<span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">3</span>):
    <span class="hljs-keyword">with</span> torch.inference_mode():
        inputs = generate_inputs()
        orig_output = unet(*inputs)

<span class="hljs-comment"># trace</span>
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;tracing..&quot;</span>)
unet_traced = torch.jit.trace(unet, inputs)
unet_traced.<span class="hljs-built_in">eval</span>()
<span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;done tracing&quot;</span>)


<span class="hljs-comment"># warmup and optimize graph</span>
<span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">5</span>):
    <span class="hljs-keyword">with</span> torch.inference_mode():
        inputs = generate_inputs()
        orig_output = unet_traced(*inputs)


<span class="hljs-comment"># benchmarking</span>
<span class="hljs-keyword">with</span> torch.inference_mode():
    <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(n_experiments):
        torch.cuda.synchronize()
        start_time = time.time()
        <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(unet_runs_per_experiment):
            orig_output = unet_traced(*inputs)
        torch.cuda.synchronize()
        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;unet traced inference took <span class="hljs-subst">{time.time() - start_time:<span class="hljs-number">.2</span>f}</span> seconds&quot;</span>)
    <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(n_experiments):
        torch.cuda.synchronize()
        start_time = time.time()
        <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(unet_runs_per_experiment):
            orig_output = unet(*inputs)
        torch.cuda.synchronize()
        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;unet inference took <span class="hljs-subst">{time.time() - start_time:<span class="hljs-number">.2</span>f}</span> seconds&quot;</span>)

<span class="hljs-comment"># save the model</span>
unet_traced.save(<span class="hljs-string">&quot;unet_traced.pt&quot;</span>)`}}),rt=new D({props:{code:`from diffusers import StableDiffusionPipeline
import torch
from dataclasses import dataclass


@dataclass
class UNet2DConditionOutput:
    sample: torch.FloatTensor


pipe = StableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    torch_dtype=torch.float16,
).to("cuda")

# use jitted unet
unet_traced = torch.jit.load("unet_traced.pt")


# del pipe.unet
class TracedUNet(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.in_channels = pipe.unet.in_channels
        self.device = pipe.unet.device

    def forward(self, latent_model_input, t, encoder_hidden_states):
        sample = unet_traced(latent_model_input, t, encoder_hidden_states)[0]
        return UNet2DConditionOutput(sample=sample)


pipe.unet = TracedUNet()

with torch.inference_mode():
    image = pipe([prompt] * 1, num_inference_steps=50).images[0]`,highlighted:`<span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> StableDiffusionPipeline
<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> dataclass


<span class="hljs-meta">@dataclass</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">UNet2DConditionOutput</span>:
    sample: torch.FloatTensor


pipe = StableDiffusionPipeline.from_pretrained(
    <span class="hljs-string">&quot;runwayml/stable-diffusion-v1-5&quot;</span>,
    torch_dtype=torch.float16,
).to(<span class="hljs-string">&quot;cuda&quot;</span>)

<span class="hljs-comment"># use jitted unet</span>
unet_traced = torch.jit.load(<span class="hljs-string">&quot;unet_traced.pt&quot;</span>)


<span class="hljs-comment"># del pipe.unet</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">TracedUNet</span>(torch.nn.Module):
    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self</span>):
        <span class="hljs-built_in">super</span>().__init__()
        self.in_channels = pipe.unet.in_channels
        self.device = pipe.unet.device

    <span class="hljs-keyword">def</span> <span class="hljs-title function_">forward</span>(<span class="hljs-params">self, latent_model_input, t, encoder_hidden_states</span>):
        sample = unet_traced(latent_model_input, t, encoder_hidden_states)[<span class="hljs-number">0</span>]
        <span class="hljs-keyword">return</span> UNet2DConditionOutput(sample=sample)


pipe.unet = TracedUNet()

<span class="hljs-keyword">with</span> torch.inference_mode():
    image = pipe([prompt] * <span class="hljs-number">1</span>, num_inference_steps=<span class="hljs-number">50</span>).images[<span class="hljs-number">0</span>]`}}),lt=new S({}),mt=new D({props:{code:`from diffusers import DiffusionPipeline
import torch

pipe = DiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5",
    torch_dtype=torch.float16,
).to("cuda")

pipe.enable_xformers_memory_efficient_attention()

with torch.inference_mode():
    sample = pipe("a small cat")

# optional: You can disable it via
# pipe.disable_xformers_memory_efficient_attention()`,highlighted:`<span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> DiffusionPipeline
<span class="hljs-keyword">import</span> torch

pipe = DiffusionPipeline.from_pretrained(
    <span class="hljs-string">&quot;runwayml/stable-diffusion-v1-5&quot;</span>,
    torch_dtype=torch.float16,
).to(<span class="hljs-string">&quot;cuda&quot;</span>)

pipe.enable_xformers_memory_efficient_attention()

<span class="hljs-keyword">with</span> torch.inference_mode():
    sample = pipe(<span class="hljs-string">&quot;a small cat&quot;</span>)

<span class="hljs-comment"># optional: You can disable it via</span>
<span class="hljs-comment"># pipe.disable_xformers_memory_efficient_attention()</span>`}}),{c(){c=a("meta"),d=f(),w=a("h1"),T=a("a"),$=a("span"),u(j.$$.fragment),En=f(),ms=a("span"),jn=i("Memory and speed"),Va=f(),q=a("p"),kn=i("We present some techniques and ideas to optimize \u{1F917} Diffusers "),hs=a("em"),Tn=i("inference"),Pn=i(" for memory or speed. As a general rule, we recommend the use of "),Fe=a("a"),An=i("xFormers"),Dn=i(" for memory efficient attention, please see the recommended "),dt=a("a"),qn=i("installation instructions"),Sn=i("."),Ma=f(),ct=a("p"),xn=i("We\u2019ll discuss how the following settings impact performance and memory."),Ra=f(),me=a("table"),ds=a("thead"),R=a("tr"),Ga=a("th"),Un=f(),cs=a("th"),Nn=i("Latency"),Cn=f(),us=a("th"),In=i("Speedup"),Fn=f(),P=a("tbody"),G=a("tr"),_s=a("td"),Vn=i("original"),Mn=f(),vs=a("td"),Rn=i("9.50s"),Gn=f(),ys=a("td"),zn=i("x1"),Hn=f(),z=a("tr"),bs=a("td"),Bn=i("fp16"),On=f(),gs=a("td"),Ln=i("3.61s"),Xn=f(),ws=a("td"),Yn=i("x2.63"),Wn=f(),H=a("tr"),$s=a("td"),Kn=i("channels last"),Qn=f(),Es=a("td"),Jn=i("3.30s"),Zn=f(),js=a("td"),ei=i("x2.88"),ti=f(),B=a("tr"),ks=a("td"),si=i("traced UNet"),ai=f(),Ts=a("td"),oi=i("3.21s"),ni=f(),Ps=a("td"),ii=i("x2.96"),ri=f(),O=a("tr"),As=a("td"),li=i("memory efficient attention"),pi=f(),Ds=a("td"),fi=i("2.63s"),mi=f(),qs=a("td"),hi=i("x3.61"),za=f(),ut=a("em"),di=i(`obtained on NVIDIA TITAN RTX by generating a single image of size 512x512 from
  the prompt "a photo of an astronaut riding a horse on mars" with 50 DDIM
  steps.`),Ha=f(),L=a("h3"),he=a("a"),Ss=a("span"),u(Ve.$$.fragment),ci=f(),xs=a("span"),ui=i("Use tf32 instead of fp32 (on Ampere and later CUDA devices)"),Ba=f(),de=a("p"),_i=i("On Ampere and later CUDA devices matrix multiplications and convolutions can use the TensorFloat32 (TF32) mode for faster but slightly less accurate computations. By default PyTorch enables TF32 mode for convolutions but not matrix multiplications, and unless a network requires full float32 precision we recommend enabling this setting for matrix multiplications, too. It can significantly speed up computations with typically negligible loss of numerical accuracy. You can read more about it "),Me=a("a"),vi=i("here"),yi=i(". All you need to do is to add this before your inference:"),Oa=f(),u(Re.$$.fragment),La=f(),X=a("h2"),ce=a("a"),Us=a("span"),u(Ge.$$.fragment),bi=f(),Ns=a("span"),gi=i("Half precision weights"),Xa=f(),U=a("p"),wi=i("To save more GPU memory and get more speed, you can load and run the model weights directly in half precision. This involves loading the float16 version of the weights, which was saved to a branch named "),Cs=a("code"),$i=i("fp16"),Ei=i(", and telling PyTorch to use the "),Is=a("code"),ji=i("float16"),ki=i(" type when loading them:"),Ya=f(),u(ze.$$.fragment),Wa=f(),u(ue.$$.fragment),Ka=f(),Y=a("h2"),_e=a("a"),Fs=a("span"),u(He.$$.fragment),Ti=f(),Vs=a("span"),Pi=i("Sliced attention for additional memory savings"),Qa=f(),_t=a("p"),Ai=i("For even additional memory savings, you can use a sliced version of attention that performs the computation in steps instead of all at once."),Ja=f(),u(ve.$$.fragment),Za=f(),ye=a("p"),Di=i("To perform the attention computation sequentially over each head, you only need to invoke "),vt=a("a"),qi=i("enable_attention_slicing()"),Si=i(" in your pipeline before inference, like here:"),eo=f(),u(Be.$$.fragment),to=f(),yt=a("p"),xi=i("There\u2019s a small performance penalty of about 10% slower inference times, but this method allows you to use Stable Diffusion in as little as 3.2 GB of VRAM!"),so=f(),W=a("h2"),be=a("a"),Ms=a("span"),u(Oe.$$.fragment),Ui=f(),Rs=a("span"),Ni=i("Sliced VAE decode for larger batches"),ao=f(),bt=a("p"),Ci=i("To decode large batches of images with limited VRAM, or to enable batches with 32 images or more, you can use sliced VAE decode that decodes the batch latents one image at a time."),oo=f(),N=a("p"),Ii=i("You likely want to couple this with "),gt=a("a"),Fi=i("enable_attention_slicing()"),Vi=i(" or "),wt=a("a"),Mi=i("enable_xformers_memory_efficient_attention()"),Ri=i(" to further minimize memory use."),no=f(),ge=a("p"),Gi=i("To perform the VAE decode one image at a time, invoke "),$t=a("a"),zi=i("enable_vae_slicing()"),Hi=i(" in your pipeline before inference. For example:"),io=f(),u(Le.$$.fragment),ro=f(),Et=a("p"),Bi=i("You may see a small performance boost in VAE decode on multi-image batches. There should be no performance impact on single-image batches."),lo=f(),K=a("h2"),we=a("a"),Gs=a("span"),u(Xe.$$.fragment),Oi=f(),zs=a("span"),Li=i("Tiled VAE decode and encode for large images"),po=f(),jt=a("p"),Xi=i("Tiled VAE processing makes it possible to work with large images on limited VRAM. For example, generating 4k images in 8GB of VRAM. Tiled VAE decoder splits the image into overlapping tiles, decodes the tiles, and blends the outputs to make the final image."),fo=f(),C=a("p"),Yi=i("You want to couple this with "),kt=a("a"),Wi=i("enable_attention_slicing()"),Ki=i(" or "),Tt=a("a"),Qi=i("enable_xformers_memory_efficient_attention()"),Ji=i(" to further minimize memory use."),mo=f(),$e=a("p"),Zi=i("To use tiled VAE processing, invoke "),Pt=a("a"),er=i("enable_vae_tiling()"),tr=i(" in your pipeline before inference. For example:"),ho=f(),u(Ye.$$.fragment),co=f(),At=a("p"),sr=i("The output image will have some tile-to-tile tone variation from the tiles having separate decoders, but you shouldn\u2019t see sharp seams between the tiles. The tiling is turned off for images that are 512x512 or smaller."),uo=f(),Dt=a("a"),_o=f(),Q=a("h2"),Ee=a("a"),Hs=a("span"),u(We.$$.fragment),ar=f(),Bs=a("span"),or=i("Offloading to CPU with accelerate for memory savings"),vo=f(),qt=a("p"),nr=i("For additional memory savings, you can offload the weights to CPU and only load them to GPU when performing the forward pass."),yo=f(),je=a("p"),ir=i("To perform CPU offloading, all you have to do is invoke "),St=a("a"),rr=i("enable_sequential_cpu_offload()"),lr=i(":"),bo=f(),u(Ke.$$.fragment),go=f(),xt=a("p"),pr=i("And you can get the memory consumption to < 3GB."),wo=f(),ke=a("p"),fr=i("Note that this method works at the submodule level, not on whole models. This is the best way to minimize memory consumption, but inference is much slower due to the iterative nature of the process. The UNet component of the pipeline runs several times (as many as "),Os=a("code"),mr=i("num_inference_steps"),hr=i("); each time, the different submodules of the UNet are sequentially onloaded and then offloaded as they are needed, so the number of memory transfers is large."),$o=f(),u(Te.$$.fragment),Eo=f(),Ut=a("p"),dr=i("It is also possible to chain offloading with attention slicing for minimal memory consumption (< 2GB)."),jo=f(),u(Qe.$$.fragment),ko=f(),A=a("p"),Ls=a("strong"),cr=i("Note"),ur=i(": When using "),Xs=a("code"),_r=i("enable_sequential_cpu_offload()"),vr=i(", it is important to "),Ys=a("strong"),yr=i("not"),br=i(" move the pipeline to CUDA beforehand or else the gain in memory consumption will only be minimal. See "),Je=a("a"),gr=i("this issue"),wr=i(" for more information."),To=f(),Nt=a("a"),Po=f(),J=a("h2"),Pe=a("a"),Ws=a("span"),u(Ze.$$.fragment),$r=f(),Ks=a("span"),Er=i("Model offloading for fast inference and memory savings"),Ao=f(),et=a("p"),Ct=a("a"),jr=i("Sequential CPU offloading"),kr=i(", as discussed in the previous section, preserves a lot of memory but makes inference slower, because submodules are moved to GPU as needed, and immediately returned to CPU when a new module runs."),Do=f(),I=a("p"),Tr=i("Full-model offloading is an alternative that moves whole models to the GPU, instead of handling each model\u2019s constituent "),Qs=a("em"),Pr=i("modules"),Ar=i(". This results in a negligible impact on inference time (compared with moving the pipeline to "),Js=a("code"),Dr=i("cuda"),qr=i("), while still providing some memory savings."),qo=f(),It=a("p"),Sr=i(`In this scenario, only one of the main components of the pipeline (typically: text encoder, unet and vae)
will be in the GPU while the others wait in the CPU. Components like the UNet that run for multiple iterations will stay on GPU until they are no longer needed.`),So=f(),Ae=a("p"),xr=i("This feature can be enabled by invoking "),Zs=a("code"),Ur=i("enable_model_cpu_offload()"),Nr=i(" on the pipeline, as shown below."),xo=f(),u(tt.$$.fragment),Uo=f(),Ft=a("p"),Cr=i("This is also compatible with attention slicing for additional memory savings."),No=f(),u(st.$$.fragment),Co=f(),u(De.$$.fragment),Io=f(),Z=a("h2"),qe=a("a"),ea=a("span"),u(at.$$.fragment),Ir=f(),ta=a("span"),Fr=i("Using Channels Last memory format"),Fo=f(),Vt=a("p"),Vr=i("Channels last memory format is an alternative way of ordering NCHW tensors in memory preserving dimensions ordering. Channels last tensors ordered in such a way that channels become the densest dimension (aka storing images pixel-per-pixel). Since not all operators currently support channels last format it may result in a worst performance, so it\u2019s better to try it and see if it works for your model."),Vo=f(),Mt=a("p"),Mr=i("For example, in order to set the UNet model in our pipeline to use channels last format, we can use the following:"),Mo=f(),u(ot.$$.fragment),Ro=f(),ee=a("h2"),Se=a("a"),sa=a("span"),u(nt.$$.fragment),Rr=f(),aa=a("span"),Gr=i("Tracing"),Go=f(),xe=a("p"),zr=i("Tracing runs an example input tensor through your model, and captures the operations that are invoked as that input makes its way through the model\u2019s layers so that an executable or "),oa=a("code"),Hr=i("ScriptFunction"),Br=i(" is returned that will be optimized using just-in-time compilation."),zo=f(),Rt=a("p"),Or=i("To trace our UNet model, we can use the following:"),Ho=f(),u(it.$$.fragment),Bo=f(),Ue=a("p"),Lr=i("Then we can replace the "),na=a("code"),Xr=i("unet"),Yr=i(" attribute of the pipeline with the traced model like the following"),Oo=f(),u(rt.$$.fragment),Lo=f(),te=a("h2"),Ne=a("a"),ia=a("span"),u(lt.$$.fragment),Wr=f(),ra=a("span"),Kr=i("Memory Efficient Attention"),Xo=f(),F=a("p"),Qr=i("Recent work on optimizing the bandwitdh in the attention block has generated huge speed ups and gains in GPU memory usage. The most recent being Flash Attention from @tridao: "),pt=a("a"),Jr=i("code"),Zr=i(", "),ft=a("a"),el=i("paper"),tl=i("."),Yo=f(),Gt=a("p"),sl=i("Here are the speedups we obtain on a few Nvidia GPUs when running the inference at 512x512 with a batch size of 1 (one prompt):"),Wo=f(),Ce=a("table"),la=a("thead"),se=a("tr"),pa=a("th"),al=i("GPU"),ol=f(),fa=a("th"),nl=i("Base Attention FP16"),il=f(),ma=a("th"),rl=i("Memory Efficient Attention FP16"),ll=f(),E=a("tbody"),ae=a("tr"),ha=a("td"),pl=i("NVIDIA Tesla T4"),fl=f(),da=a("td"),ml=i("3.5it/s"),hl=f(),ca=a("td"),dl=i("5.5it/s"),cl=f(),oe=a("tr"),ua=a("td"),ul=i("NVIDIA 3060 RTX"),_l=f(),_a=a("td"),vl=i("4.6it/s"),yl=f(),va=a("td"),bl=i("7.8it/s"),gl=f(),ne=a("tr"),ya=a("td"),wl=i("NVIDIA A10G"),$l=f(),ba=a("td"),El=i("8.88it/s"),jl=f(),ga=a("td"),kl=i("15.6it/s"),Tl=f(),ie=a("tr"),wa=a("td"),Pl=i("NVIDIA RTX A6000"),Al=f(),$a=a("td"),Dl=i("11.7it/s"),ql=f(),Ea=a("td"),Sl=i("21.09it/s"),xl=f(),re=a("tr"),ja=a("td"),Ul=i("NVIDIA TITAN RTX"),Nl=f(),ka=a("td"),Cl=i("12.51it/s"),Il=f(),Ta=a("td"),Fl=i("18.22it/s"),Vl=f(),le=a("tr"),Pa=a("td"),Ml=i("A100-SXM4-40GB"),Rl=f(),Aa=a("td"),Gl=i("18.6it/s"),zl=f(),Da=a("td"),Hl=i("29.it/s"),Bl=f(),pe=a("tr"),qa=a("td"),Ol=i("A100-SXM-80GB"),Ll=f(),Sa=a("td"),Xl=i("18.7it/s"),Yl=f(),xa=a("td"),Wl=i("29.5it/s"),Ko=f(),zt=a("p"),Kl=i("To leverage it just make sure you have:"),Qo=f(),V=a("ul"),Ua=a("li"),Ql=i("PyTorch > 1.12"),Jl=f(),Na=a("li"),Zl=i("Cuda available"),ep=f(),Ht=a("li"),Bt=a("a"),tp=i("Installed the xformers library"),sp=i("."),Jo=f(),u(mt.$$.fragment),this.h()},l(e){const l=$m('[data-svelte="svelte-1phssyn"]',document.head);c=o(l,"META",{name:!0,content:!0}),l.forEach(s),d=m(e),w=o(e,"H1",{class:!0});var ht=n(w);T=o(ht,"A",{id:!0,class:!0,href:!0});var Ca=n(T);$=o(Ca,"SPAN",{});var Ia=n($);_(j.$$.fragment,Ia),Ia.forEach(s),Ca.forEach(s),En=m(ht),ms=o(ht,"SPAN",{});var Fa=n(ms);jn=r(Fa,"Memory and speed"),Fa.forEach(s),ht.forEach(s),Va=m(e),q=o(e,"P",{});var Ie=n(q);kn=r(Ie,"We present some techniques and ideas to optimize \u{1F917} Diffusers "),hs=o(Ie,"EM",{});var np=n(hs);Tn=r(np,"inference"),np.forEach(s),Pn=r(Ie," for memory or speed. As a general rule, we recommend the use of "),Fe=o(Ie,"A",{href:!0,rel:!0});var ip=n(Fe);An=r(ip,"xFormers"),ip.forEach(s),Dn=r(Ie," for memory efficient attention, please see the recommended "),dt=o(Ie,"A",{href:!0});var rp=n(dt);qn=r(rp,"installation instructions"),rp.forEach(s),Sn=r(Ie,"."),Ie.forEach(s),Ma=m(e),ct=o(e,"P",{});var lp=n(ct);xn=r(lp,"We\u2019ll discuss how the following settings impact performance and memory."),lp.forEach(s),Ra=m(e),me=o(e,"TABLE",{});var en=n(me);ds=o(en,"THEAD",{});var pp=n(ds);R=o(pp,"TR",{});var Ot=n(R);Ga=o(Ot,"TH",{}),n(Ga).forEach(s),Un=m(Ot),cs=o(Ot,"TH",{});var fp=n(cs);Nn=r(fp,"Latency"),fp.forEach(s),Cn=m(Ot),us=o(Ot,"TH",{});var mp=n(us);In=r(mp,"Speedup"),mp.forEach(s),Ot.forEach(s),pp.forEach(s),Fn=m(en),P=o(en,"TBODY",{});var M=n(P);G=o(M,"TR",{});var Lt=n(G);_s=o(Lt,"TD",{});var hp=n(_s);Vn=r(hp,"original"),hp.forEach(s),Mn=m(Lt),vs=o(Lt,"TD",{});var dp=n(vs);Rn=r(dp,"9.50s"),dp.forEach(s),Gn=m(Lt),ys=o(Lt,"TD",{});var cp=n(ys);zn=r(cp,"x1"),cp.forEach(s),Lt.forEach(s),Hn=m(M),z=o(M,"TR",{});var Xt=n(z);bs=o(Xt,"TD",{});var up=n(bs);Bn=r(up,"fp16"),up.forEach(s),On=m(Xt),gs=o(Xt,"TD",{});var _p=n(gs);Ln=r(_p,"3.61s"),_p.forEach(s),Xn=m(Xt),ws=o(Xt,"TD",{});var vp=n(ws);Yn=r(vp,"x2.63"),vp.forEach(s),Xt.forEach(s),Wn=m(M),H=o(M,"TR",{});var Yt=n(H);$s=o(Yt,"TD",{});var yp=n($s);Kn=r(yp,"channels last"),yp.forEach(s),Qn=m(Yt),Es=o(Yt,"TD",{});var bp=n(Es);Jn=r(bp,"3.30s"),bp.forEach(s),Zn=m(Yt),js=o(Yt,"TD",{});var gp=n(js);ei=r(gp,"x2.88"),gp.forEach(s),Yt.forEach(s),ti=m(M),B=o(M,"TR",{});var Wt=n(B);ks=o(Wt,"TD",{});var wp=n(ks);si=r(wp,"traced UNet"),wp.forEach(s),ai=m(Wt),Ts=o(Wt,"TD",{});var $p=n(Ts);oi=r($p,"3.21s"),$p.forEach(s),ni=m(Wt),Ps=o(Wt,"TD",{});var Ep=n(Ps);ii=r(Ep,"x2.96"),Ep.forEach(s),Wt.forEach(s),ri=m(M),O=o(M,"TR",{});var Kt=n(O);As=o(Kt,"TD",{});var jp=n(As);li=r(jp,"memory efficient attention"),jp.forEach(s),pi=m(Kt),Ds=o(Kt,"TD",{});var kp=n(Ds);fi=r(kp,"2.63s"),kp.forEach(s),mi=m(Kt),qs=o(Kt,"TD",{});var Tp=n(qs);hi=r(Tp,"x3.61"),Tp.forEach(s),Kt.forEach(s),M.forEach(s),en.forEach(s),za=m(e),ut=o(e,"EM",{});var Pp=n(ut);di=r(Pp,`obtained on NVIDIA TITAN RTX by generating a single image of size 512x512 from
  the prompt "a photo of an astronaut riding a horse on mars" with 50 DDIM
  steps.`),Pp.forEach(s),Ha=m(e),L=o(e,"H3",{class:!0});var tn=n(L);he=o(tn,"A",{id:!0,class:!0,href:!0});var Ap=n(he);Ss=o(Ap,"SPAN",{});var Dp=n(Ss);_(Ve.$$.fragment,Dp),Dp.forEach(s),Ap.forEach(s),ci=m(tn),xs=o(tn,"SPAN",{});var qp=n(xs);ui=r(qp,"Use tf32 instead of fp32 (on Ampere and later CUDA devices)"),qp.forEach(s),tn.forEach(s),Ba=m(e),de=o(e,"P",{});var sn=n(de);_i=r(sn,"On Ampere and later CUDA devices matrix multiplications and convolutions can use the TensorFloat32 (TF32) mode for faster but slightly less accurate computations. By default PyTorch enables TF32 mode for convolutions but not matrix multiplications, and unless a network requires full float32 precision we recommend enabling this setting for matrix multiplications, too. It can significantly speed up computations with typically negligible loss of numerical accuracy. You can read more about it "),Me=o(sn,"A",{href:!0,rel:!0});var Sp=n(Me);vi=r(Sp,"here"),Sp.forEach(s),yi=r(sn,". All you need to do is to add this before your inference:"),sn.forEach(s),Oa=m(e),_(Re.$$.fragment,e),La=m(e),X=o(e,"H2",{class:!0});var an=n(X);ce=o(an,"A",{id:!0,class:!0,href:!0});var xp=n(ce);Us=o(xp,"SPAN",{});var Up=n(Us);_(Ge.$$.fragment,Up),Up.forEach(s),xp.forEach(s),bi=m(an),Ns=o(an,"SPAN",{});var Np=n(Ns);gi=r(Np,"Half precision weights"),Np.forEach(s),an.forEach(s),Xa=m(e),U=o(e,"P",{});var Qt=n(U);wi=r(Qt,"To save more GPU memory and get more speed, you can load and run the model weights directly in half precision. This involves loading the float16 version of the weights, which was saved to a branch named "),Cs=o(Qt,"CODE",{});var Cp=n(Cs);$i=r(Cp,"fp16"),Cp.forEach(s),Ei=r(Qt,", and telling PyTorch to use the "),Is=o(Qt,"CODE",{});var Ip=n(Is);ji=r(Ip,"float16"),Ip.forEach(s),ki=r(Qt," type when loading them:"),Qt.forEach(s),Ya=m(e),_(ze.$$.fragment,e),Wa=m(e),_(ue.$$.fragment,e),Ka=m(e),Y=o(e,"H2",{class:!0});var on=n(Y);_e=o(on,"A",{id:!0,class:!0,href:!0});var Fp=n(_e);Fs=o(Fp,"SPAN",{});var Vp=n(Fs);_(He.$$.fragment,Vp),Vp.forEach(s),Fp.forEach(s),Ti=m(on),Vs=o(on,"SPAN",{});var Mp=n(Vs);Pi=r(Mp,"Sliced attention for additional memory savings"),Mp.forEach(s),on.forEach(s),Qa=m(e),_t=o(e,"P",{});var Rp=n(_t);Ai=r(Rp,"For even additional memory savings, you can use a sliced version of attention that performs the computation in steps instead of all at once."),Rp.forEach(s),Ja=m(e),_(ve.$$.fragment,e),Za=m(e),ye=o(e,"P",{});var nn=n(ye);Di=r(nn,"To perform the attention computation sequentially over each head, you only need to invoke "),vt=o(nn,"A",{href:!0});var Gp=n(vt);qi=r(Gp,"enable_attention_slicing()"),Gp.forEach(s),Si=r(nn," in your pipeline before inference, like here:"),nn.forEach(s),eo=m(e),_(Be.$$.fragment,e),to=m(e),yt=o(e,"P",{});var zp=n(yt);xi=r(zp,"There\u2019s a small performance penalty of about 10% slower inference times, but this method allows you to use Stable Diffusion in as little as 3.2 GB of VRAM!"),zp.forEach(s),so=m(e),W=o(e,"H2",{class:!0});var rn=n(W);be=o(rn,"A",{id:!0,class:!0,href:!0});var Hp=n(be);Ms=o(Hp,"SPAN",{});var Bp=n(Ms);_(Oe.$$.fragment,Bp),Bp.forEach(s),Hp.forEach(s),Ui=m(rn),Rs=o(rn,"SPAN",{});var Op=n(Rs);Ni=r(Op,"Sliced VAE decode for larger batches"),Op.forEach(s),rn.forEach(s),ao=m(e),bt=o(e,"P",{});var Lp=n(bt);Ci=r(Lp,"To decode large batches of images with limited VRAM, or to enable batches with 32 images or more, you can use sliced VAE decode that decodes the batch latents one image at a time."),Lp.forEach(s),oo=m(e),N=o(e,"P",{});var Jt=n(N);Ii=r(Jt,"You likely want to couple this with "),gt=o(Jt,"A",{href:!0});var Xp=n(gt);Fi=r(Xp,"enable_attention_slicing()"),Xp.forEach(s),Vi=r(Jt," or "),wt=o(Jt,"A",{href:!0});var Yp=n(wt);Mi=r(Yp,"enable_xformers_memory_efficient_attention()"),Yp.forEach(s),Ri=r(Jt," to further minimize memory use."),Jt.forEach(s),no=m(e),ge=o(e,"P",{});var ln=n(ge);Gi=r(ln,"To perform the VAE decode one image at a time, invoke "),$t=o(ln,"A",{href:!0});var Wp=n($t);zi=r(Wp,"enable_vae_slicing()"),Wp.forEach(s),Hi=r(ln," in your pipeline before inference. For example:"),ln.forEach(s),io=m(e),_(Le.$$.fragment,e),ro=m(e),Et=o(e,"P",{});var Kp=n(Et);Bi=r(Kp,"You may see a small performance boost in VAE decode on multi-image batches. There should be no performance impact on single-image batches."),Kp.forEach(s),lo=m(e),K=o(e,"H2",{class:!0});var pn=n(K);we=o(pn,"A",{id:!0,class:!0,href:!0});var Qp=n(we);Gs=o(Qp,"SPAN",{});var Jp=n(Gs);_(Xe.$$.fragment,Jp),Jp.forEach(s),Qp.forEach(s),Oi=m(pn),zs=o(pn,"SPAN",{});var Zp=n(zs);Li=r(Zp,"Tiled VAE decode and encode for large images"),Zp.forEach(s),pn.forEach(s),po=m(e),jt=o(e,"P",{});var ef=n(jt);Xi=r(ef,"Tiled VAE processing makes it possible to work with large images on limited VRAM. For example, generating 4k images in 8GB of VRAM. Tiled VAE decoder splits the image into overlapping tiles, decodes the tiles, and blends the outputs to make the final image."),ef.forEach(s),fo=m(e),C=o(e,"P",{});var Zt=n(C);Yi=r(Zt,"You want to couple this with "),kt=o(Zt,"A",{href:!0});var tf=n(kt);Wi=r(tf,"enable_attention_slicing()"),tf.forEach(s),Ki=r(Zt," or "),Tt=o(Zt,"A",{href:!0});var sf=n(Tt);Qi=r(sf,"enable_xformers_memory_efficient_attention()"),sf.forEach(s),Ji=r(Zt," to further minimize memory use."),Zt.forEach(s),mo=m(e),$e=o(e,"P",{});var fn=n($e);Zi=r(fn,"To use tiled VAE processing, invoke "),Pt=o(fn,"A",{href:!0});var af=n(Pt);er=r(af,"enable_vae_tiling()"),af.forEach(s),tr=r(fn," in your pipeline before inference. For example:"),fn.forEach(s),ho=m(e),_(Ye.$$.fragment,e),co=m(e),At=o(e,"P",{});var of=n(At);sr=r(of,"The output image will have some tile-to-tile tone variation from the tiles having separate decoders, but you shouldn\u2019t see sharp seams between the tiles. The tiling is turned off for images that are 512x512 or smaller."),of.forEach(s),uo=m(e),Dt=o(e,"A",{name:!0}),n(Dt).forEach(s),_o=m(e),Q=o(e,"H2",{class:!0});var mn=n(Q);Ee=o(mn,"A",{id:!0,class:!0,href:!0});var nf=n(Ee);Hs=o(nf,"SPAN",{});var rf=n(Hs);_(We.$$.fragment,rf),rf.forEach(s),nf.forEach(s),ar=m(mn),Bs=o(mn,"SPAN",{});var lf=n(Bs);or=r(lf,"Offloading to CPU with accelerate for memory savings"),lf.forEach(s),mn.forEach(s),vo=m(e),qt=o(e,"P",{});var pf=n(qt);nr=r(pf,"For additional memory savings, you can offload the weights to CPU and only load them to GPU when performing the forward pass."),pf.forEach(s),yo=m(e),je=o(e,"P",{});var hn=n(je);ir=r(hn,"To perform CPU offloading, all you have to do is invoke "),St=o(hn,"A",{href:!0});var ff=n(St);rr=r(ff,"enable_sequential_cpu_offload()"),ff.forEach(s),lr=r(hn,":"),hn.forEach(s),bo=m(e),_(Ke.$$.fragment,e),go=m(e),xt=o(e,"P",{});var mf=n(xt);pr=r(mf,"And you can get the memory consumption to < 3GB."),mf.forEach(s),wo=m(e),ke=o(e,"P",{});var dn=n(ke);fr=r(dn,"Note that this method works at the submodule level, not on whole models. This is the best way to minimize memory consumption, but inference is much slower due to the iterative nature of the process. The UNet component of the pipeline runs several times (as many as "),Os=o(dn,"CODE",{});var hf=n(Os);mr=r(hf,"num_inference_steps"),hf.forEach(s),hr=r(dn,"); each time, the different submodules of the UNet are sequentially onloaded and then offloaded as they are needed, so the number of memory transfers is large."),dn.forEach(s),$o=m(e),_(Te.$$.fragment,e),Eo=m(e),Ut=o(e,"P",{});var df=n(Ut);dr=r(df,"It is also possible to chain offloading with attention slicing for minimal memory consumption (< 2GB)."),df.forEach(s),jo=m(e),_(Qe.$$.fragment,e),ko=m(e),A=o(e,"P",{});var fe=n(A);Ls=o(fe,"STRONG",{});var cf=n(Ls);cr=r(cf,"Note"),cf.forEach(s),ur=r(fe,": When using "),Xs=o(fe,"CODE",{});var uf=n(Xs);_r=r(uf,"enable_sequential_cpu_offload()"),uf.forEach(s),vr=r(fe,", it is important to "),Ys=o(fe,"STRONG",{});var _f=n(Ys);yr=r(_f,"not"),_f.forEach(s),br=r(fe," move the pipeline to CUDA beforehand or else the gain in memory consumption will only be minimal. See "),Je=o(fe,"A",{href:!0,rel:!0});var vf=n(Je);gr=r(vf,"this issue"),vf.forEach(s),wr=r(fe," for more information."),fe.forEach(s),To=m(e),Nt=o(e,"A",{name:!0}),n(Nt).forEach(s),Po=m(e),J=o(e,"H2",{class:!0});var cn=n(J);Pe=o(cn,"A",{id:!0,class:!0,href:!0});var yf=n(Pe);Ws=o(yf,"SPAN",{});var bf=n(Ws);_(Ze.$$.fragment,bf),bf.forEach(s),yf.forEach(s),$r=m(cn),Ks=o(cn,"SPAN",{});var gf=n(Ks);Er=r(gf,"Model offloading for fast inference and memory savings"),gf.forEach(s),cn.forEach(s),Ao=m(e),et=o(e,"P",{});var ap=n(et);Ct=o(ap,"A",{href:!0});var wf=n(Ct);jr=r(wf,"Sequential CPU offloading"),wf.forEach(s),kr=r(ap,", as discussed in the previous section, preserves a lot of memory but makes inference slower, because submodules are moved to GPU as needed, and immediately returned to CPU when a new module runs."),ap.forEach(s),Do=m(e),I=o(e,"P",{});var es=n(I);Tr=r(es,"Full-model offloading is an alternative that moves whole models to the GPU, instead of handling each model\u2019s constituent "),Qs=o(es,"EM",{});var $f=n(Qs);Pr=r($f,"modules"),$f.forEach(s),Ar=r(es,". This results in a negligible impact on inference time (compared with moving the pipeline to "),Js=o(es,"CODE",{});var Ef=n(Js);Dr=r(Ef,"cuda"),Ef.forEach(s),qr=r(es,"), while still providing some memory savings."),es.forEach(s),qo=m(e),It=o(e,"P",{});var jf=n(It);Sr=r(jf,`In this scenario, only one of the main components of the pipeline (typically: text encoder, unet and vae)
will be in the GPU while the others wait in the CPU. Components like the UNet that run for multiple iterations will stay on GPU until they are no longer needed.`),jf.forEach(s),So=m(e),Ae=o(e,"P",{});var un=n(Ae);xr=r(un,"This feature can be enabled by invoking "),Zs=o(un,"CODE",{});var kf=n(Zs);Ur=r(kf,"enable_model_cpu_offload()"),kf.forEach(s),Nr=r(un," on the pipeline, as shown below."),un.forEach(s),xo=m(e),_(tt.$$.fragment,e),Uo=m(e),Ft=o(e,"P",{});var Tf=n(Ft);Cr=r(Tf,"This is also compatible with attention slicing for additional memory savings."),Tf.forEach(s),No=m(e),_(st.$$.fragment,e),Co=m(e),_(De.$$.fragment,e),Io=m(e),Z=o(e,"H2",{class:!0});var _n=n(Z);qe=o(_n,"A",{id:!0,class:!0,href:!0});var Pf=n(qe);ea=o(Pf,"SPAN",{});var Af=n(ea);_(at.$$.fragment,Af),Af.forEach(s),Pf.forEach(s),Ir=m(_n),ta=o(_n,"SPAN",{});var Df=n(ta);Fr=r(Df,"Using Channels Last memory format"),Df.forEach(s),_n.forEach(s),Fo=m(e),Vt=o(e,"P",{});var qf=n(Vt);Vr=r(qf,"Channels last memory format is an alternative way of ordering NCHW tensors in memory preserving dimensions ordering. Channels last tensors ordered in such a way that channels become the densest dimension (aka storing images pixel-per-pixel). Since not all operators currently support channels last format it may result in a worst performance, so it\u2019s better to try it and see if it works for your model."),qf.forEach(s),Vo=m(e),Mt=o(e,"P",{});var Sf=n(Mt);Mr=r(Sf,"For example, in order to set the UNet model in our pipeline to use channels last format, we can use the following:"),Sf.forEach(s),Mo=m(e),_(ot.$$.fragment,e),Ro=m(e),ee=o(e,"H2",{class:!0});var vn=n(ee);Se=o(vn,"A",{id:!0,class:!0,href:!0});var xf=n(Se);sa=o(xf,"SPAN",{});var Uf=n(sa);_(nt.$$.fragment,Uf),Uf.forEach(s),xf.forEach(s),Rr=m(vn),aa=o(vn,"SPAN",{});var Nf=n(aa);Gr=r(Nf,"Tracing"),Nf.forEach(s),vn.forEach(s),Go=m(e),xe=o(e,"P",{});var yn=n(xe);zr=r(yn,"Tracing runs an example input tensor through your model, and captures the operations that are invoked as that input makes its way through the model\u2019s layers so that an executable or "),oa=o(yn,"CODE",{});var Cf=n(oa);Hr=r(Cf,"ScriptFunction"),Cf.forEach(s),Br=r(yn," is returned that will be optimized using just-in-time compilation."),yn.forEach(s),zo=m(e),Rt=o(e,"P",{});var If=n(Rt);Or=r(If,"To trace our UNet model, we can use the following:"),If.forEach(s),Ho=m(e),_(it.$$.fragment,e),Bo=m(e),Ue=o(e,"P",{});var bn=n(Ue);Lr=r(bn,"Then we can replace the "),na=o(bn,"CODE",{});var Ff=n(na);Xr=r(Ff,"unet"),Ff.forEach(s),Yr=r(bn," attribute of the pipeline with the traced model like the following"),bn.forEach(s),Oo=m(e),_(rt.$$.fragment,e),Lo=m(e),te=o(e,"H2",{class:!0});var gn=n(te);Ne=o(gn,"A",{id:!0,class:!0,href:!0});var Vf=n(Ne);ia=o(Vf,"SPAN",{});var Mf=n(ia);_(lt.$$.fragment,Mf),Mf.forEach(s),Vf.forEach(s),Wr=m(gn),ra=o(gn,"SPAN",{});var Rf=n(ra);Kr=r(Rf,"Memory Efficient Attention"),Rf.forEach(s),gn.forEach(s),Xo=m(e),F=o(e,"P",{});var ts=n(F);Qr=r(ts,"Recent work on optimizing the bandwitdh in the attention block has generated huge speed ups and gains in GPU memory usage. The most recent being Flash Attention from @tridao: "),pt=o(ts,"A",{href:!0,rel:!0});var Gf=n(pt);Jr=r(Gf,"code"),Gf.forEach(s),Zr=r(ts,", "),ft=o(ts,"A",{href:!0,rel:!0});var zf=n(ft);el=r(zf,"paper"),zf.forEach(s),tl=r(ts,"."),ts.forEach(s),Yo=m(e),Gt=o(e,"P",{});var Hf=n(Gt);sl=r(Hf,"Here are the speedups we obtain on a few Nvidia GPUs when running the inference at 512x512 with a batch size of 1 (one prompt):"),Hf.forEach(s),Wo=m(e),Ce=o(e,"TABLE",{});var wn=n(Ce);la=o(wn,"THEAD",{});var Bf=n(la);se=o(Bf,"TR",{});var ss=n(se);pa=o(ss,"TH",{});var Of=n(pa);al=r(Of,"GPU"),Of.forEach(s),ol=m(ss),fa=o(ss,"TH",{});var Lf=n(fa);nl=r(Lf,"Base Attention FP16"),Lf.forEach(s),il=m(ss),ma=o(ss,"TH",{});var Xf=n(ma);rl=r(Xf,"Memory Efficient Attention FP16"),Xf.forEach(s),ss.forEach(s),Bf.forEach(s),ll=m(wn),E=o(wn,"TBODY",{});var k=n(E);ae=o(k,"TR",{});var as=n(ae);ha=o(as,"TD",{});var Yf=n(ha);pl=r(Yf,"NVIDIA Tesla T4"),Yf.forEach(s),fl=m(as),da=o(as,"TD",{});var Wf=n(da);ml=r(Wf,"3.5it/s"),Wf.forEach(s),hl=m(as),ca=o(as,"TD",{});var Kf=n(ca);dl=r(Kf,"5.5it/s"),Kf.forEach(s),as.forEach(s),cl=m(k),oe=o(k,"TR",{});var os=n(oe);ua=o(os,"TD",{});var Qf=n(ua);ul=r(Qf,"NVIDIA 3060 RTX"),Qf.forEach(s),_l=m(os),_a=o(os,"TD",{});var Jf=n(_a);vl=r(Jf,"4.6it/s"),Jf.forEach(s),yl=m(os),va=o(os,"TD",{});var Zf=n(va);bl=r(Zf,"7.8it/s"),Zf.forEach(s),os.forEach(s),gl=m(k),ne=o(k,"TR",{});var ns=n(ne);ya=o(ns,"TD",{});var em=n(ya);wl=r(em,"NVIDIA A10G"),em.forEach(s),$l=m(ns),ba=o(ns,"TD",{});var tm=n(ba);El=r(tm,"8.88it/s"),tm.forEach(s),jl=m(ns),ga=o(ns,"TD",{});var sm=n(ga);kl=r(sm,"15.6it/s"),sm.forEach(s),ns.forEach(s),Tl=m(k),ie=o(k,"TR",{});var is=n(ie);wa=o(is,"TD",{});var am=n(wa);Pl=r(am,"NVIDIA RTX A6000"),am.forEach(s),Al=m(is),$a=o(is,"TD",{});var om=n($a);Dl=r(om,"11.7it/s"),om.forEach(s),ql=m(is),Ea=o(is,"TD",{});var nm=n(Ea);Sl=r(nm,"21.09it/s"),nm.forEach(s),is.forEach(s),xl=m(k),re=o(k,"TR",{});var rs=n(re);ja=o(rs,"TD",{});var im=n(ja);Ul=r(im,"NVIDIA TITAN RTX"),im.forEach(s),Nl=m(rs),ka=o(rs,"TD",{});var rm=n(ka);Cl=r(rm,"12.51it/s"),rm.forEach(s),Il=m(rs),Ta=o(rs,"TD",{});var lm=n(Ta);Fl=r(lm,"18.22it/s"),lm.forEach(s),rs.forEach(s),Vl=m(k),le=o(k,"TR",{});var ls=n(le);Pa=o(ls,"TD",{});var pm=n(Pa);Ml=r(pm,"A100-SXM4-40GB"),pm.forEach(s),Rl=m(ls),Aa=o(ls,"TD",{});var fm=n(Aa);Gl=r(fm,"18.6it/s"),fm.forEach(s),zl=m(ls),Da=o(ls,"TD",{});var mm=n(Da);Hl=r(mm,"29.it/s"),mm.forEach(s),ls.forEach(s),Bl=m(k),pe=o(k,"TR",{});var ps=n(pe);qa=o(ps,"TD",{});var hm=n(qa);Ol=r(hm,"A100-SXM-80GB"),hm.forEach(s),Ll=m(ps),Sa=o(ps,"TD",{});var dm=n(Sa);Xl=r(dm,"18.7it/s"),dm.forEach(s),Yl=m(ps),xa=o(ps,"TD",{});var cm=n(xa);Wl=r(cm,"29.5it/s"),cm.forEach(s),ps.forEach(s),k.forEach(s),wn.forEach(s),Ko=m(e),zt=o(e,"P",{});var um=n(zt);Kl=r(um,"To leverage it just make sure you have:"),um.forEach(s),Qo=m(e),V=o(e,"UL",{});var fs=n(V);Ua=o(fs,"LI",{});var _m=n(Ua);Ql=r(_m,"PyTorch > 1.12"),_m.forEach(s),Jl=m(fs),Na=o(fs,"LI",{});var vm=n(Na);Zl=r(vm,"Cuda available"),vm.forEach(s),ep=m(fs),Ht=o(fs,"LI",{});var op=n(Ht);Bt=o(op,"A",{href:!0});var ym=n(Bt);tp=r(ym,"Installed the xformers library"),ym.forEach(s),sp=r(op,"."),op.forEach(s),fs.forEach(s),Jo=m(e),_(mt.$$.fragment,e),this.h()},h(){h(c,"name","hf:doc:metadata"),h(c,"content",JSON.stringify(Dm)),h(T,"id","memory-and-speed"),h(T,"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"),h(T,"href","#memory-and-speed"),h(w,"class","relative group"),h(Fe,"href","https://github.com/facebookresearch/xformers"),h(Fe,"rel","nofollow"),h(dt,"href","xformers"),h(he,"id","use-tf32-instead-of-fp32-on-ampere-and-later-cuda-devices"),h(he,"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"),h(he,"href","#use-tf32-instead-of-fp32-on-ampere-and-later-cuda-devices"),h(L,"class","relative group"),h(Me,"href","https://huggingface.co/docs/transformers/v4.18.0/en/performance#tf32"),h(Me,"rel","nofollow"),h(ce,"id","half-precision-weights"),h(ce,"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"),h(ce,"href","#half-precision-weights"),h(X,"class","relative group"),h(_e,"id","sliced-attention-for-additional-memory-savings"),h(_e,"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"),h(_e,"href","#sliced-attention-for-additional-memory-savings"),h(Y,"class","relative group"),h(vt,"href","/docs/diffusers/v0.16.0/en/api/pipelines/stable_diffusion/latent_upscale#diffusers.StableDiffusionLatentUpscalePipeline.enable_attention_slicing"),h(be,"id","sliced-vae-decode-for-larger-batches"),h(be,"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"),h(be,"href","#sliced-vae-decode-for-larger-batches"),h(W,"class","relative group"),h(gt,"href","/docs/diffusers/v0.16.0/en/api/pipelines/stable_diffusion/latent_upscale#diffusers.StableDiffusionLatentUpscalePipeline.enable_attention_slicing"),h(wt,"href","/docs/diffusers/v0.16.0/en/api/pipelines/stable_diffusion/latent_upscale#diffusers.StableDiffusionLatentUpscalePipeline.enable_xformers_memory_efficient_attention"),h($t,"href","/docs/diffusers/v0.16.0/en/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline.enable_vae_slicing"),h(we,"id","tiled-vae-decode-and-encode-for-large-images"),h(we,"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"),h(we,"href","#tiled-vae-decode-and-encode-for-large-images"),h(K,"class","relative group"),h(kt,"href","/docs/diffusers/v0.16.0/en/api/pipelines/stable_diffusion/latent_upscale#diffusers.StableDiffusionLatentUpscalePipeline.enable_attention_slicing"),h(Tt,"href","/docs/diffusers/v0.16.0/en/api/pipelines/stable_diffusion/latent_upscale#diffusers.StableDiffusionLatentUpscalePipeline.enable_xformers_memory_efficient_attention"),h(Pt,"href","/docs/diffusers/v0.16.0/en/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline.enable_vae_tiling"),h(Dt,"name","sequential_offloading"),h(Ee,"id","offloading-to-cpu-with-accelerate-for-memory-savings"),h(Ee,"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"),h(Ee,"href","#offloading-to-cpu-with-accelerate-for-memory-savings"),h(Q,"class","relative group"),h(St,"href","/docs/diffusers/v0.16.0/en/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline.enable_sequential_cpu_offload"),h(Je,"href","https://github.com/huggingface/diffusers/issues/1934"),h(Je,"rel","nofollow"),h(Nt,"name","model_offloading"),h(Pe,"id","model-offloading-for-fast-inference-and-memory-savings"),h(Pe,"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"),h(Pe,"href","#model-offloading-for-fast-inference-and-memory-savings"),h(J,"class","relative group"),h(Ct,"href","#sequential_offloading"),h(qe,"id","using-channels-last-memory-format"),h(qe,"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"),h(qe,"href","#using-channels-last-memory-format"),h(Z,"class","relative group"),h(Se,"id","tracing"),h(Se,"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"),h(Se,"href","#tracing"),h(ee,"class","relative group"),h(Ne,"id","memory-efficient-attention"),h(Ne,"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"),h(Ne,"href","#memory-efficient-attention"),h(te,"class","relative group"),h(pt,"href","https://github.com/HazyResearch/flash-attention"),h(pt,"rel","nofollow"),h(ft,"href","https://arxiv.org/pdf/2205.14135.pdf"),h(ft,"rel","nofollow"),h(Bt,"href","xformers")},m(e,l){t(document.head,c),p(e,d,l),p(e,w,l),t(w,T),t(T,$),v(j,$,null),t(w,En),t(w,ms),t(ms,jn),p(e,Va,l),p(e,q,l),t(q,kn),t(q,hs),t(hs,Tn),t(q,Pn),t(q,Fe),t(Fe,An),t(q,Dn),t(q,dt),t(dt,qn),t(q,Sn),p(e,Ma,l),p(e,ct,l),t(ct,xn),p(e,Ra,l),p(e,me,l),t(me,ds),t(ds,R),t(R,Ga),t(R,Un),t(R,cs),t(cs,Nn),t(R,Cn),t(R,us),t(us,In),t(me,Fn),t(me,P),t(P,G),t(G,_s),t(_s,Vn),t(G,Mn),t(G,vs),t(vs,Rn),t(G,Gn),t(G,ys),t(ys,zn),t(P,Hn),t(P,z),t(z,bs),t(bs,Bn),t(z,On),t(z,gs),t(gs,Ln),t(z,Xn),t(z,ws),t(ws,Yn),t(P,Wn),t(P,H),t(H,$s),t($s,Kn),t(H,Qn),t(H,Es),t(Es,Jn),t(H,Zn),t(H,js),t(js,ei),t(P,ti),t(P,B),t(B,ks),t(ks,si),t(B,ai),t(B,Ts),t(Ts,oi),t(B,ni),t(B,Ps),t(Ps,ii),t(P,ri),t(P,O),t(O,As),t(As,li),t(O,pi),t(O,Ds),t(Ds,fi),t(O,mi),t(O,qs),t(qs,hi),p(e,za,l),p(e,ut,l),t(ut,di),p(e,Ha,l),p(e,L,l),t(L,he),t(he,Ss),v(Ve,Ss,null),t(L,ci),t(L,xs),t(xs,ui),p(e,Ba,l),p(e,de,l),t(de,_i),t(de,Me),t(Me,vi),t(de,yi),p(e,Oa,l),v(Re,e,l),p(e,La,l),p(e,X,l),t(X,ce),t(ce,Us),v(Ge,Us,null),t(X,bi),t(X,Ns),t(Ns,gi),p(e,Xa,l),p(e,U,l),t(U,wi),t(U,Cs),t(Cs,$i),t(U,Ei),t(U,Is),t(Is,ji),t(U,ki),p(e,Ya,l),v(ze,e,l),p(e,Wa,l),v(ue,e,l),p(e,Ka,l),p(e,Y,l),t(Y,_e),t(_e,Fs),v(He,Fs,null),t(Y,Ti),t(Y,Vs),t(Vs,Pi),p(e,Qa,l),p(e,_t,l),t(_t,Ai),p(e,Ja,l),v(ve,e,l),p(e,Za,l),p(e,ye,l),t(ye,Di),t(ye,vt),t(vt,qi),t(ye,Si),p(e,eo,l),v(Be,e,l),p(e,to,l),p(e,yt,l),t(yt,xi),p(e,so,l),p(e,W,l),t(W,be),t(be,Ms),v(Oe,Ms,null),t(W,Ui),t(W,Rs),t(Rs,Ni),p(e,ao,l),p(e,bt,l),t(bt,Ci),p(e,oo,l),p(e,N,l),t(N,Ii),t(N,gt),t(gt,Fi),t(N,Vi),t(N,wt),t(wt,Mi),t(N,Ri),p(e,no,l),p(e,ge,l),t(ge,Gi),t(ge,$t),t($t,zi),t(ge,Hi),p(e,io,l),v(Le,e,l),p(e,ro,l),p(e,Et,l),t(Et,Bi),p(e,lo,l),p(e,K,l),t(K,we),t(we,Gs),v(Xe,Gs,null),t(K,Oi),t(K,zs),t(zs,Li),p(e,po,l),p(e,jt,l),t(jt,Xi),p(e,fo,l),p(e,C,l),t(C,Yi),t(C,kt),t(kt,Wi),t(C,Ki),t(C,Tt),t(Tt,Qi),t(C,Ji),p(e,mo,l),p(e,$e,l),t($e,Zi),t($e,Pt),t(Pt,er),t($e,tr),p(e,ho,l),v(Ye,e,l),p(e,co,l),p(e,At,l),t(At,sr),p(e,uo,l),p(e,Dt,l),p(e,_o,l),p(e,Q,l),t(Q,Ee),t(Ee,Hs),v(We,Hs,null),t(Q,ar),t(Q,Bs),t(Bs,or),p(e,vo,l),p(e,qt,l),t(qt,nr),p(e,yo,l),p(e,je,l),t(je,ir),t(je,St),t(St,rr),t(je,lr),p(e,bo,l),v(Ke,e,l),p(e,go,l),p(e,xt,l),t(xt,pr),p(e,wo,l),p(e,ke,l),t(ke,fr),t(ke,Os),t(Os,mr),t(ke,hr),p(e,$o,l),v(Te,e,l),p(e,Eo,l),p(e,Ut,l),t(Ut,dr),p(e,jo,l),v(Qe,e,l),p(e,ko,l),p(e,A,l),t(A,Ls),t(Ls,cr),t(A,ur),t(A,Xs),t(Xs,_r),t(A,vr),t(A,Ys),t(Ys,yr),t(A,br),t(A,Je),t(Je,gr),t(A,wr),p(e,To,l),p(e,Nt,l),p(e,Po,l),p(e,J,l),t(J,Pe),t(Pe,Ws),v(Ze,Ws,null),t(J,$r),t(J,Ks),t(Ks,Er),p(e,Ao,l),p(e,et,l),t(et,Ct),t(Ct,jr),t(et,kr),p(e,Do,l),p(e,I,l),t(I,Tr),t(I,Qs),t(Qs,Pr),t(I,Ar),t(I,Js),t(Js,Dr),t(I,qr),p(e,qo,l),p(e,It,l),t(It,Sr),p(e,So,l),p(e,Ae,l),t(Ae,xr),t(Ae,Zs),t(Zs,Ur),t(Ae,Nr),p(e,xo,l),v(tt,e,l),p(e,Uo,l),p(e,Ft,l),t(Ft,Cr),p(e,No,l),v(st,e,l),p(e,Co,l),v(De,e,l),p(e,Io,l),p(e,Z,l),t(Z,qe),t(qe,ea),v(at,ea,null),t(Z,Ir),t(Z,ta),t(ta,Fr),p(e,Fo,l),p(e,Vt,l),t(Vt,Vr),p(e,Vo,l),p(e,Mt,l),t(Mt,Mr),p(e,Mo,l),v(ot,e,l),p(e,Ro,l),p(e,ee,l),t(ee,Se),t(Se,sa),v(nt,sa,null),t(ee,Rr),t(ee,aa),t(aa,Gr),p(e,Go,l),p(e,xe,l),t(xe,zr),t(xe,oa),t(oa,Hr),t(xe,Br),p(e,zo,l),p(e,Rt,l),t(Rt,Or),p(e,Ho,l),v(it,e,l),p(e,Bo,l),p(e,Ue,l),t(Ue,Lr),t(Ue,na),t(na,Xr),t(Ue,Yr),p(e,Oo,l),v(rt,e,l),p(e,Lo,l),p(e,te,l),t(te,Ne),t(Ne,ia),v(lt,ia,null),t(te,Wr),t(te,ra),t(ra,Kr),p(e,Xo,l),p(e,F,l),t(F,Qr),t(F,pt),t(pt,Jr),t(F,Zr),t(F,ft),t(ft,el),t(F,tl),p(e,Yo,l),p(e,Gt,l),t(Gt,sl),p(e,Wo,l),p(e,Ce,l),t(Ce,la),t(la,se),t(se,pa),t(pa,al),t(se,ol),t(se,fa),t(fa,nl),t(se,il),t(se,ma),t(ma,rl),t(Ce,ll),t(Ce,E),t(E,ae),t(ae,ha),t(ha,pl),t(ae,fl),t(ae,da),t(da,ml),t(ae,hl),t(ae,ca),t(ca,dl),t(E,cl),t(E,oe),t(oe,ua),t(ua,ul),t(oe,_l),t(oe,_a),t(_a,vl),t(oe,yl),t(oe,va),t(va,bl),t(E,gl),t(E,ne),t(ne,ya),t(ya,wl),t(ne,$l),t(ne,ba),t(ba,El),t(ne,jl),t(ne,ga),t(ga,kl),t(E,Tl),t(E,ie),t(ie,wa),t(wa,Pl),t(ie,Al),t(ie,$a),t($a,Dl),t(ie,ql),t(ie,Ea),t(Ea,Sl),t(E,xl),t(E,re),t(re,ja),t(ja,Ul),t(re,Nl),t(re,ka),t(ka,Cl),t(re,Il),t(re,Ta),t(Ta,Fl),t(E,Vl),t(E,le),t(le,Pa),t(Pa,Ml),t(le,Rl),t(le,Aa),t(Aa,Gl),t(le,zl),t(le,Da),t(Da,Hl),t(E,Bl),t(E,pe),t(pe,qa),t(qa,Ol),t(pe,Ll),t(pe,Sa),t(Sa,Xl),t(pe,Yl),t(pe,xa),t(xa,Wl),p(e,Ko,l),p(e,zt,l),t(zt,Kl),p(e,Qo,l),p(e,V,l),t(V,Ua),t(Ua,Ql),t(V,Jl),t(V,Na),t(Na,Zl),t(V,ep),t(V,Ht),t(Ht,Bt),t(Bt,tp),t(Ht,sp),p(e,Jo,l),v(mt,e,l),Zo=!0},p(e,[l]){const ht={};l&2&&(ht.$$scope={dirty:l,ctx:e}),ue.$set(ht);const Ca={};l&2&&(Ca.$$scope={dirty:l,ctx:e}),ve.$set(Ca);const Ia={};l&2&&(Ia.$$scope={dirty:l,ctx:e}),Te.$set(Ia);const Fa={};l&2&&(Fa.$$scope={dirty:l,ctx:e}),De.$set(Fa)},i(e){Zo||(y(j.$$.fragment,e),y(Ve.$$.fragment,e),y(Re.$$.fragment,e),y(Ge.$$.fragment,e),y(ze.$$.fragment,e),y(ue.$$.fragment,e),y(He.$$.fragment,e),y(ve.$$.fragment,e),y(Be.$$.fragment,e),y(Oe.$$.fragment,e),y(Le.$$.fragment,e),y(Xe.$$.fragment,e),y(Ye.$$.fragment,e),y(We.$$.fragment,e),y(Ke.$$.fragment,e),y(Te.$$.fragment,e),y(Qe.$$.fragment,e),y(Ze.$$.fragment,e),y(tt.$$.fragment,e),y(st.$$.fragment,e),y(De.$$.fragment,e),y(at.$$.fragment,e),y(ot.$$.fragment,e),y(nt.$$.fragment,e),y(it.$$.fragment,e),y(rt.$$.fragment,e),y(lt.$$.fragment,e),y(mt.$$.fragment,e),Zo=!0)},o(e){b(j.$$.fragment,e),b(Ve.$$.fragment,e),b(Re.$$.fragment,e),b(Ge.$$.fragment,e),b(ze.$$.fragment,e),b(ue.$$.fragment,e),b(He.$$.fragment,e),b(ve.$$.fragment,e),b(Be.$$.fragment,e),b(Oe.$$.fragment,e),b(Le.$$.fragment,e),b(Xe.$$.fragment,e),b(Ye.$$.fragment,e),b(We.$$.fragment,e),b(Ke.$$.fragment,e),b(Te.$$.fragment,e),b(Qe.$$.fragment,e),b(Ze.$$.fragment,e),b(tt.$$.fragment,e),b(st.$$.fragment,e),b(De.$$.fragment,e),b(at.$$.fragment,e),b(ot.$$.fragment,e),b(nt.$$.fragment,e),b(it.$$.fragment,e),b(rt.$$.fragment,e),b(lt.$$.fragment,e),b(mt.$$.fragment,e),Zo=!1},d(e){s(c),e&&s(d),e&&s(w),g(j),e&&s(Va),e&&s(q),e&&s(Ma),e&&s(ct),e&&s(Ra),e&&s(me),e&&s(za),e&&s(ut),e&&s(Ha),e&&s(L),g(Ve),e&&s(Ba),e&&s(de),e&&s(Oa),g(Re,e),e&&s(La),e&&s(X),g(Ge),e&&s(Xa),e&&s(U),e&&s(Ya),g(ze,e),e&&s(Wa),g(ue,e),e&&s(Ka),e&&s(Y),g(He),e&&s(Qa),e&&s(_t),e&&s(Ja),g(ve,e),e&&s(Za),e&&s(ye),e&&s(eo),g(Be,e),e&&s(to),e&&s(yt),e&&s(so),e&&s(W),g(Oe),e&&s(ao),e&&s(bt),e&&s(oo),e&&s(N),e&&s(no),e&&s(ge),e&&s(io),g(Le,e),e&&s(ro),e&&s(Et),e&&s(lo),e&&s(K),g(Xe),e&&s(po),e&&s(jt),e&&s(fo),e&&s(C),e&&s(mo),e&&s($e),e&&s(ho),g(Ye,e),e&&s(co),e&&s(At),e&&s(uo),e&&s(Dt),e&&s(_o),e&&s(Q),g(We),e&&s(vo),e&&s(qt),e&&s(yo),e&&s(je),e&&s(bo),g(Ke,e),e&&s(go),e&&s(xt),e&&s(wo),e&&s(ke),e&&s($o),g(Te,e),e&&s(Eo),e&&s(Ut),e&&s(jo),g(Qe,e),e&&s(ko),e&&s(A),e&&s(To),e&&s(Nt),e&&s(Po),e&&s(J),g(Ze),e&&s(Ao),e&&s(et),e&&s(Do),e&&s(I),e&&s(qo),e&&s(It),e&&s(So),e&&s(Ae),e&&s(xo),g(tt,e),e&&s(Uo),e&&s(Ft),e&&s(No),g(st,e),e&&s(Co),g(De,e),e&&s(Io),e&&s(Z),g(at),e&&s(Fo),e&&s(Vt),e&&s(Vo),e&&s(Mt),e&&s(Mo),g(ot,e),e&&s(Ro),e&&s(ee),g(nt),e&&s(Go),e&&s(xe),e&&s(zo),e&&s(Rt),e&&s(Ho),g(it,e),e&&s(Bo),e&&s(Ue),e&&s(Oo),g(rt,e),e&&s(Lo),e&&s(te),g(lt),e&&s(Xo),e&&s(F),e&&s(Yo),e&&s(Gt),e&&s(Wo),e&&s(Ce),e&&s(Ko),e&&s(zt),e&&s(Qo),e&&s(V),e&&s(Jo),g(mt,e)}}}const Dm={local:"memory-and-speed",sections:[{local:null,sections:[{local:"use-tf32-instead-of-fp32-on-ampere-and-later-cuda-devices",title:"Use tf32 instead of fp32 (on Ampere and later CUDA devices)"}],title:null},{local:"half-precision-weights",title:"Half precision weights"},{local:"sliced-attention-for-additional-memory-savings",title:"Sliced attention for additional memory savings"},{local:"sliced-vae-decode-for-larger-batches",title:"Sliced VAE decode for larger batches"},{local:"tiled-vae-decode-and-encode-for-large-images",title:"Tiled VAE decode and encode for large images"},{local:"offloading-to-cpu-with-accelerate-for-memory-savings",title:"Offloading to CPU with accelerate for memory savings"},{local:"model-offloading-for-fast-inference-and-memory-savings",title:"Model offloading for fast inference and memory savings"},{local:"using-channels-last-memory-format",title:"Using Channels Last memory format"},{local:"tracing",title:"Tracing"},{local:"memory-efficient-attention",title:"Memory Efficient Attention"}],title:"Memory and speed"};function qm(x){return Em(()=>{new URLSearchParams(window.location.search).get("fw")}),[]}class Cm extends bm{constructor(c){super();gm(this,c,qm,Am,wm,{})}}export{Cm as default,Dm as metadata};
