import{S as Mi,i as qi,s as Ni,e as i,k as f,w as S,t as r,M as ji,c as n,d as a,m as d,a as o,x as y,h as l,b as s,G as e,g as c,y as w,q as D,o as A,B as P,v as Oi,L as Ui}from"../../../../chunks/vendor-hf-doc-builder.js";import{D as tt}from"../../../../chunks/Docstring-hf-doc-builder.js";import{C as Li}from"../../../../chunks/CodeBlock-hf-doc-builder.js";import{I as at}from"../../../../chunks/IconCopyLink-hf-doc-builder.js";import{E as zi}from"../../../../chunks/ExampleCodeBlock-hf-doc-builder.js";function Fi(it){let m,j,_,g,$;return g=new Li({props:{code:`import torch
from diffusers import StableDiffusionSAGPipeline

pipe = StableDiffusionSAGPipeline.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, sag_scale=0.75).images[0]`,highlighted:`<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> torch
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> StableDiffusionSAGPipeline

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

<span class="hljs-meta">&gt;&gt;&gt; </span>prompt = <span class="hljs-string">&quot;a photo of an astronaut riding a horse on mars&quot;</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>image = pipe(prompt, sag_scale=<span class="hljs-number">0.75</span>).images[<span class="hljs-number">0</span>]`}}),{c(){m=i("p"),j=r("Examples:"),_=f(),S(g.$$.fragment)},l(u){m=n(u,"P",{});var x=o(m);j=l(x,"Examples:"),x.forEach(a),_=d(u),y(g.$$.fragment,u)},m(u,x){c(u,m,x),e(m,j),c(u,_,x),w(g,u,x),$=!0},p:Ui,i(u){$||(D(g.$$.fragment,u),$=!0)},o(u){A(g.$$.fragment,u),$=!1},d(u){u&&a(m),u&&a(_),P(g,u)}}}function Vi(it){let m,j,_,g,$,u,x,Te,$t,nt,T,O,Ie,K,xt,Ce,Et,ot,R,Q,Gt,kt,st,me,Tt,rt,ge,Le,It,lt,_e,Ct,ft,v,ve,J,Lt,Mt,qt,be,Y,Nt,jt,Ot,Se,X,Ut,zt,Ft,ye,Z,Vt,Ht,Bt,we,ee,Wt,Kt,dt,I,U,Me,te,Rt,qe,Qt,pt,z,Ne,C,je,Jt,Yt,Oe,Xt,Zt,De,ea,ta,Ue,L,ze,ae,aa,ia,Fe,Ve,na,oa,Ae,ie,sa,ct,M,F,He,ne,ra,Be,la,ut,oe,ht,q,V,We,se,fa,Ke,da,mt,h,re,pa,Re,ca,ua,le,ha,Pe,ma,ga,_a,E,fe,va,Qe,ba,Sa,H,ya,B,de,wa,pe,Da,Je,Aa,Pa,$a,W,ce,xa,N,Ea,Ye,Ga,ka,Xe,Ta,Ia,Ca,G,ue,La,Ze,Ma,qa,et,Na,gt;return u=new at({}),K=new at({}),te=new at({}),ne=new at({}),oe=new Li({props:{code:`import torch
from diffusers import StableDiffusionSAGPipeline
from accelerate.utils import set_seed

pipe = StableDiffusionSAGPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16)
pipe = pipe.to("cuda")

seed = 8978
prompt = "."
guidance_scale = 7.5
num_images_per_prompt = 1

sag_scale = 1.0

set_seed(seed)
images = pipe(
    prompt, num_images_per_prompt=num_images_per_prompt, guidance_scale=guidance_scale, sag_scale=sag_scale
).images
images[0].save("example.png")`,highlighted:`<span class="hljs-keyword">import</span> torch
<span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> StableDiffusionSAGPipeline
<span class="hljs-keyword">from</span> accelerate.utils <span class="hljs-keyword">import</span> set_seed

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

seed = <span class="hljs-number">8978</span>
prompt = <span class="hljs-string">&quot;.&quot;</span>
guidance_scale = <span class="hljs-number">7.5</span>
num_images_per_prompt = <span class="hljs-number">1</span>

sag_scale = <span class="hljs-number">1.0</span>

set_seed(seed)
images = pipe(
    prompt, num_images_per_prompt=num_images_per_prompt, guidance_scale=guidance_scale, sag_scale=sag_scale
).images
images[<span class="hljs-number">0</span>].save(<span class="hljs-string">&quot;example.png&quot;</span>)`}}),se=new at({}),re=new tt({props:{name:"class diffusers.StableDiffusionSAGPipeline",anchor:"diffusers.StableDiffusionSAGPipeline",parameters:[{name:"vae",val:": AutoencoderKL"},{name:"text_encoder",val:": CLIPTextModel"},{name:"tokenizer",val:": CLIPTokenizer"},{name:"unet",val:": UNet2DConditionModel"},{name:"scheduler",val:": KarrasDiffusionSchedulers"},{name:"safety_checker",val:": StableDiffusionSafetyChecker"},{name:"feature_extractor",val:": CLIPImageProcessor"},{name:"requires_safety_checker",val:": bool = True"}],parametersDescription:[{anchor:"diffusers.StableDiffusionSAGPipeline.vae",description:`<strong>vae</strong> (<a href="/docs/diffusers/v0.16.0/en/api/models#diffusers.AutoencoderKL">AutoencoderKL</a>) &#x2014;
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.`,name:"vae"},{anchor:"diffusers.StableDiffusionSAGPipeline.text_encoder",description:`<strong>text_encoder</strong> (<code>CLIPTextModel</code>) &#x2014;
Frozen text-encoder. Stable Diffusion uses the text portion of
<a href="https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel" rel="nofollow">CLIP</a>, specifically
the <a href="https://huggingface.co/openai/clip-vit-large-patch14" rel="nofollow">clip-vit-large-patch14</a> variant.`,name:"text_encoder"},{anchor:"diffusers.StableDiffusionSAGPipeline.tokenizer",description:`<strong>tokenizer</strong> (<code>CLIPTokenizer</code>) &#x2014;
Tokenizer of class
<a href="https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer" rel="nofollow">CLIPTokenizer</a>.`,name:"tokenizer"},{anchor:"diffusers.StableDiffusionSAGPipeline.unet",description:'<strong>unet</strong> (<a href="/docs/diffusers/v0.16.0/en/api/models#diffusers.UNet2DConditionModel">UNet2DConditionModel</a>) &#x2014; Conditional U-Net architecture to denoise the encoded image latents.',name:"unet"},{anchor:"diffusers.StableDiffusionSAGPipeline.scheduler",description:`<strong>scheduler</strong> (<a href="/docs/diffusers/v0.16.0/en/api/schedulers/overview#diffusers.SchedulerMixin">SchedulerMixin</a>) &#x2014;
A scheduler to be used in combination with <code>unet</code> to denoise the encoded image latents. Can be one of
<a href="/docs/diffusers/v0.16.0/en/api/schedulers/ddim#diffusers.DDIMScheduler">DDIMScheduler</a>, <a href="/docs/diffusers/v0.16.0/en/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler">LMSDiscreteScheduler</a>, or <a href="/docs/diffusers/v0.16.0/en/api/schedulers/pndm#diffusers.PNDMScheduler">PNDMScheduler</a>.`,name:"scheduler"},{anchor:"diffusers.StableDiffusionSAGPipeline.safety_checker",description:`<strong>safety_checker</strong> (<code>StableDiffusionSafetyChecker</code>) &#x2014;
Classification module that estimates whether generated images could be considered offensive or harmful.
Please, refer to the <a href="https://huggingface.co/runwayml/stable-diffusion-v1-5" rel="nofollow">model card</a> for details.`,name:"safety_checker"},{anchor:"diffusers.StableDiffusionSAGPipeline.feature_extractor",description:`<strong>feature_extractor</strong> (<code>CLIPImageProcessor</code>) &#x2014;
Model that extracts features from generated images to be used as inputs for the <code>safety_checker</code>.`,name:"feature_extractor"}],source:"https://github.com/huggingface/diffusers/blob/v0.16.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py#L91"}}),fe=new tt({props:{name:"__call__",anchor:"diffusers.StableDiffusionSAGPipeline.__call__",parameters:[{name:"prompt",val:": typing.Union[str, typing.List[str]] = None"},{name:"height",val:": typing.Optional[int] = None"},{name:"width",val:": typing.Optional[int] = None"},{name:"num_inference_steps",val:": int = 50"},{name:"guidance_scale",val:": float = 7.5"},{name:"sag_scale",val:": float = 0.75"},{name:"negative_prompt",val:": typing.Union[str, typing.List[str], NoneType] = None"},{name:"num_images_per_prompt",val:": typing.Optional[int] = 1"},{name:"eta",val:": float = 0.0"},{name:"generator",val:": typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None"},{name:"latents",val:": typing.Optional[torch.FloatTensor] = None"},{name:"prompt_embeds",val:": typing.Optional[torch.FloatTensor] = None"},{name:"negative_prompt_embeds",val:": typing.Optional[torch.FloatTensor] = None"},{name:"output_type",val:": typing.Optional[str] = 'pil'"},{name:"return_dict",val:": bool = True"},{name:"callback",val:": typing.Union[typing.Callable[[int, int, torch.FloatTensor], NoneType], NoneType] = None"},{name:"callback_steps",val:": typing.Optional[int] = 1"},{name:"cross_attention_kwargs",val:": typing.Union[typing.Dict[str, typing.Any], NoneType] = None"}],parametersDescription:[{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.prompt",description:`<strong>prompt</strong> (<code>str</code> or <code>List[str]</code>, <em>optional</em>) &#x2014;
The prompt or prompts to guide the image generation. If not defined, one has to pass <code>prompt_embeds</code>.
instead.`,name:"prompt"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.height",description:`<strong>height</strong> (<code>int</code>, <em>optional</em>, defaults to self.unet.config.sample_size * self.vae_scale_factor) &#x2014;
The height in pixels of the generated image.`,name:"height"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.width",description:`<strong>width</strong> (<code>int</code>, <em>optional</em>, defaults to self.unet.config.sample_size * self.vae_scale_factor) &#x2014;
The width in pixels of the generated image.`,name:"width"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.num_inference_steps",description:`<strong>num_inference_steps</strong> (<code>int</code>, <em>optional</em>, defaults to 50) &#x2014;
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference.`,name:"num_inference_steps"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.guidance_scale",description:`<strong>guidance_scale</strong> (<code>float</code>, <em>optional</em>, defaults to 7.5) &#x2014;
Guidance scale as defined in <a href="https://arxiv.org/abs/2207.12598" rel="nofollow">Classifier-Free Diffusion Guidance</a>.
<code>guidance_scale</code> is defined as <code>w</code> of equation 2. of <a href="https://arxiv.org/pdf/2205.11487.pdf" rel="nofollow">Imagen
Paper</a>. Guidance scale is enabled by setting <code>guidance_scale &gt; 1</code>. Higher guidance scale encourages to generate images that are closely linked to the text <code>prompt</code>,
usually at the expense of lower image quality.`,name:"guidance_scale"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.sag_scale",description:`<strong>sag_scale</strong> (<code>float</code>, <em>optional</em>, defaults to 0.75) &#x2014;
SAG scale as defined in [Improving Sample Quality of Diffusion Models Using Self-Attention Guidance]
(<a href="https://arxiv.org/abs/2210.00939" rel="nofollow">https://arxiv.org/abs/2210.00939</a>). <code>sag_scale</code> is defined as <code>s_s</code> of equation (24) of SAG paper:
<a href="https://arxiv.org/pdf/2210.00939.pdf" rel="nofollow">https://arxiv.org/pdf/2210.00939.pdf</a>. Typically chosen between [0, 1.0] for better quality.`,name:"sag_scale"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.negative_prompt",description:`<strong>negative_prompt</strong> (<code>str</code> or <code>List[str]</code>, <em>optional</em>) &#x2014;
The prompt or prompts not to guide the image generation. If not defined, one has to pass
<code>negative_prompt_embeds</code> instead. Ignored when not using guidance (i.e., ignored if <code>guidance_scale</code> is
less than <code>1</code>).`,name:"negative_prompt"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.num_images_per_prompt",description:`<strong>num_images_per_prompt</strong> (<code>int</code>, <em>optional</em>, defaults to 1) &#x2014;
The number of images to generate per prompt.`,name:"num_images_per_prompt"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.eta",description:`<strong>eta</strong> (<code>float</code>, <em>optional</em>, defaults to 0.0) &#x2014;
Corresponds to parameter eta (&#x3B7;) in the DDIM paper: <a href="https://arxiv.org/abs/2010.02502" rel="nofollow">https://arxiv.org/abs/2010.02502</a>. Only applies to
<a href="/docs/diffusers/v0.16.0/en/api/schedulers/ddim#diffusers.DDIMScheduler">schedulers.DDIMScheduler</a>, will be ignored for others.`,name:"eta"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.generator",description:`<strong>generator</strong> (<code>torch.Generator</code> or <code>List[torch.Generator]</code>, <em>optional</em>) &#x2014;
One or a list of <a href="https://pytorch.org/docs/stable/generated/torch.Generator.html" rel="nofollow">torch generator(s)</a>
to make generation deterministic.`,name:"generator"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.latents",description:`<strong>latents</strong> (<code>torch.FloatTensor</code>, <em>optional</em>) &#x2014;
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
tensor will ge generated by sampling using the supplied random <code>generator</code>.`,name:"latents"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.prompt_embeds",description:`<strong>prompt_embeds</strong> (<code>torch.FloatTensor</code>, <em>optional</em>) &#x2014;
Pre-generated text embeddings. Can be used to easily tweak text inputs, <em>e.g.</em> prompt weighting. If not
provided, text embeddings will be generated from <code>prompt</code> input argument.`,name:"prompt_embeds"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.negative_prompt_embeds",description:`<strong>negative_prompt_embeds</strong> (<code>torch.FloatTensor</code>, <em>optional</em>) &#x2014;
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, <em>e.g.</em> prompt
weighting. If not provided, negative_prompt_embeds will be generated from <code>negative_prompt</code> input
argument.`,name:"negative_prompt_embeds"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.output_type",description:`<strong>output_type</strong> (<code>str</code>, <em>optional</em>, defaults to <code>&quot;pil&quot;</code>) &#x2014;
The output format of the generate image. Choose between
<a href="https://pillow.readthedocs.io/en/stable/" rel="nofollow">PIL</a>: <code>PIL.Image.Image</code> or <code>np.array</code>.`,name:"output_type"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.return_dict",description:`<strong>return_dict</strong> (<code>bool</code>, <em>optional</em>, defaults to <code>True</code>) &#x2014;
Whether or not to return a <a href="/docs/diffusers/v0.16.0/en/api/pipelines/stable_diffusion/overview#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput">StableDiffusionPipelineOutput</a> instead of a
plain tuple.`,name:"return_dict"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.callback",description:`<strong>callback</strong> (<code>Callable</code>, <em>optional</em>) &#x2014;
A function that will be called every <code>callback_steps</code> steps during inference. The function will be
called with the following arguments: <code>callback(step: int, timestep: int, latents: torch.FloatTensor)</code>.`,name:"callback"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.callback_steps",description:`<strong>callback_steps</strong> (<code>int</code>, <em>optional</em>, defaults to 1) &#x2014;
The frequency at which the <code>callback</code> function will be called. If not specified, the callback will be
called at every step.`,name:"callback_steps"},{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.cross_attention_kwargs",description:`<strong>cross_attention_kwargs</strong> (<code>dict</code>, <em>optional</em>) &#x2014;
A kwargs dictionary that if specified is passed along to the <code>AttentionProcessor</code> as defined under
<code>self.processor</code> in
<a href="https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py" rel="nofollow">diffusers.cross_attention</a>.`,name:"cross_attention_kwargs"}],source:"https://github.com/huggingface/diffusers/blob/v0.16.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py#L459",returnDescription:`
<p><a
  href="/docs/diffusers/v0.16.0/en/api/pipelines/stable_diffusion/overview#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput"
>StableDiffusionPipelineOutput</a> if <code>return_dict</code> is True, otherwise a <code>tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of </code>bool<code>s denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) content, according to the </code>safety_checker\`.</p>
`,returnType:`
<p><a
  href="/docs/diffusers/v0.16.0/en/api/pipelines/stable_diffusion/overview#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput"
>StableDiffusionPipelineOutput</a> or <code>tuple</code></p>
`}}),H=new zi({props:{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.example",$$slots:{default:[Fi]},$$scope:{ctx:it}}}),de=new tt({props:{name:"disable_vae_slicing",anchor:"diffusers.StableDiffusionSAGPipeline.disable_vae_slicing",parameters:[],source:"https://github.com/huggingface/diffusers/blob/v0.16.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py#L156"}}),ce=new tt({props:{name:"enable_sequential_cpu_offload",anchor:"diffusers.StableDiffusionSAGPipeline.enable_sequential_cpu_offload",parameters:[{name:"gpu_id",val:" = 0"}],source:"https://github.com/huggingface/diffusers/blob/v0.16.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py#L164"}}),ue=new tt({props:{name:"enable_vae_slicing",anchor:"diffusers.StableDiffusionSAGPipeline.enable_vae_slicing",parameters:[],source:"https://github.com/huggingface/diffusers/blob/v0.16.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py#L146"}}),{c(){m=i("meta"),j=f(),_=i("h1"),g=i("a"),$=i("span"),S(u.$$.fragment),x=f(),Te=i("span"),$t=r("Self-Attention Guidance (SAG)"),nt=f(),T=i("h2"),O=i("a"),Ie=i("span"),S(K.$$.fragment),xt=f(),Ce=i("span"),Et=r("Overview"),ot=f(),R=i("p"),Q=i("a"),Gt=r("Improving Sample Quality of Diffusion Models Using Self-Attention Guidance"),kt=r(" by Susung Hong et al."),st=f(),me=i("p"),Tt=r("The abstract of the paper is the following:"),rt=f(),ge=i("p"),Le=i("em"),It=r("Denoising diffusion models (DDMs) have attracted attention for their exceptional generation quality and diversity. This success is largely attributed to the use of class- or text-conditional diffusion guidance methods, such as classifier and classifier-free guidance. In this paper, we present a more comprehensive perspective that goes beyond the traditional guidance methods. From this generalized perspective, we introduce novel condition- and training-free strategies to enhance the quality of generated images. As a simple solution, blur guidance improves the suitability of intermediate samples for their fine-scale information and structures, enabling diffusion models to generate higher quality samples with a moderate guidance scale. Improving upon this, Self-Attention Guidance (SAG) uses the intermediate self-attention maps of diffusion models to enhance their stability and efficacy. Specifically, SAG adversarially blurs only the regions that diffusion models attend to at each iteration and guides them accordingly. Our experimental results show that our SAG improves the performance of various diffusion models, including ADM, IDDPM, Stable Diffusion, and DiT. Moreover, combining SAG with conventional guidance methods leads to further improvement."),lt=f(),_e=i("p"),Ct=r("Resources:"),ft=f(),v=i("ul"),ve=i("li"),J=i("a"),Lt=r("Project Page"),Mt=r("."),qt=f(),be=i("li"),Y=i("a"),Nt=r("Paper"),jt=r("."),Ot=f(),Se=i("li"),X=i("a"),Ut=r("Original Code"),zt=r("."),Ft=f(),ye=i("li"),Z=i("a"),Vt=r("Hugging Face Demo"),Ht=r("."),Bt=f(),we=i("li"),ee=i("a"),Wt=r("Colab Demo"),Kt=r("."),dt=f(),I=i("h2"),U=i("a"),Me=i("span"),S(te.$$.fragment),Rt=f(),qe=i("span"),Qt=r("Available Pipelines:"),pt=f(),z=i("table"),Ne=i("thead"),C=i("tr"),je=i("th"),Jt=r("Pipeline"),Yt=f(),Oe=i("th"),Xt=r("Tasks"),Zt=f(),De=i("th"),ea=r("Demo"),ta=f(),Ue=i("tbody"),L=i("tr"),ze=i("td"),ae=i("a"),aa=r("StableDiffusionSAGPipeline"),ia=f(),Fe=i("td"),Ve=i("em"),na=r("Text-to-Image Generation"),oa=f(),Ae=i("td"),ie=i("a"),sa=r("\u{1F917} Space"),ct=f(),M=i("h2"),F=i("a"),He=i("span"),S(ne.$$.fragment),ra=f(),Be=i("span"),la=r("Usage example"),ut=f(),S(oe.$$.fragment),ht=f(),q=i("h2"),V=i("a"),We=i("span"),S(se.$$.fragment),fa=f(),Ke=i("span"),da=r("StableDiffusionSAGPipeline"),mt=f(),h=i("div"),S(re.$$.fragment),pa=f(),Re=i("p"),ca=r("Pipeline for text-to-image generation using Stable Diffusion."),ua=f(),le=i("p"),ha=r("This model inherits from "),Pe=i("a"),ma=r("DiffusionPipeline"),ga=r(`. Check the superclass documentation for the generic methods the
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)`),_a=f(),E=i("div"),S(fe.$$.fragment),va=f(),Qe=i("p"),ba=r("Function invoked when calling the pipeline for generation."),Sa=f(),S(H.$$.fragment),ya=f(),B=i("div"),S(de.$$.fragment),wa=f(),pe=i("p"),Da=r("Disable sliced VAE decoding. If "),Je=i("code"),Aa=r("enable_vae_slicing"),Pa=r(` was previously invoked, this method will go back to
computing decoding in one step.`),$a=f(),W=i("div"),S(ce.$$.fragment),xa=f(),N=i("p"),Ea=r(`Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
`),Ye=i("code"),Ga=r("torch.device('meta') and loaded to GPU only when their specific submodule has its "),ka=r("forward"),Xe=i("code"),Ta=r("method called. Note that offloading happens on a submodule basis. Memory savings are higher than with"),Ia=r("enable_model_cpu_offload`, but performance is lower."),Ca=f(),G=i("div"),S(ue.$$.fragment),La=f(),Ze=i("p"),Ma=r("Enable sliced VAE decoding."),qa=f(),et=i("p"),Na=r(`When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
steps. This is useful to save some memory and allow larger batch sizes.`),this.h()},l(t){const p=ji('[data-svelte="svelte-1phssyn"]',document.head);m=n(p,"META",{name:!0,content:!0}),p.forEach(a),j=d(t),_=n(t,"H1",{class:!0});var he=o(_);g=n(he,"A",{id:!0,class:!0,href:!0});var Ha=o(g);$=n(Ha,"SPAN",{});var Ba=o($);y(u.$$.fragment,Ba),Ba.forEach(a),Ha.forEach(a),x=d(he),Te=n(he,"SPAN",{});var Wa=o(Te);$t=l(Wa,"Self-Attention Guidance (SAG)"),Wa.forEach(a),he.forEach(a),nt=d(t),T=n(t,"H2",{class:!0});var _t=o(T);O=n(_t,"A",{id:!0,class:!0,href:!0});var Ka=o(O);Ie=n(Ka,"SPAN",{});var Ra=o(Ie);y(K.$$.fragment,Ra),Ra.forEach(a),Ka.forEach(a),xt=d(_t),Ce=n(_t,"SPAN",{});var Qa=o(Ce);Et=l(Qa,"Overview"),Qa.forEach(a),_t.forEach(a),ot=d(t),R=n(t,"P",{});var ja=o(R);Q=n(ja,"A",{href:!0,rel:!0});var Ja=o(Q);Gt=l(Ja,"Improving Sample Quality of Diffusion Models Using Self-Attention Guidance"),Ja.forEach(a),kt=l(ja," by Susung Hong et al."),ja.forEach(a),st=d(t),me=n(t,"P",{});var Ya=o(me);Tt=l(Ya,"The abstract of the paper is the following:"),Ya.forEach(a),rt=d(t),ge=n(t,"P",{});var Xa=o(ge);Le=n(Xa,"EM",{});var Za=o(Le);It=l(Za,"Denoising diffusion models (DDMs) have attracted attention for their exceptional generation quality and diversity. This success is largely attributed to the use of class- or text-conditional diffusion guidance methods, such as classifier and classifier-free guidance. In this paper, we present a more comprehensive perspective that goes beyond the traditional guidance methods. From this generalized perspective, we introduce novel condition- and training-free strategies to enhance the quality of generated images. As a simple solution, blur guidance improves the suitability of intermediate samples for their fine-scale information and structures, enabling diffusion models to generate higher quality samples with a moderate guidance scale. Improving upon this, Self-Attention Guidance (SAG) uses the intermediate self-attention maps of diffusion models to enhance their stability and efficacy. Specifically, SAG adversarially blurs only the regions that diffusion models attend to at each iteration and guides them accordingly. Our experimental results show that our SAG improves the performance of various diffusion models, including ADM, IDDPM, Stable Diffusion, and DiT. Moreover, combining SAG with conventional guidance methods leads to further improvement."),Za.forEach(a),Xa.forEach(a),lt=d(t),_e=n(t,"P",{});var ei=o(_e);Ct=l(ei,"Resources:"),ei.forEach(a),ft=d(t),v=n(t,"UL",{});var k=o(v);ve=n(k,"LI",{});var Oa=o(ve);J=n(Oa,"A",{href:!0,rel:!0});var ti=o(J);Lt=l(ti,"Project Page"),ti.forEach(a),Mt=l(Oa,"."),Oa.forEach(a),qt=d(k),be=n(k,"LI",{});var Ua=o(be);Y=n(Ua,"A",{href:!0,rel:!0});var ai=o(Y);Nt=l(ai,"Paper"),ai.forEach(a),jt=l(Ua,"."),Ua.forEach(a),Ot=d(k),Se=n(k,"LI",{});var za=o(Se);X=n(za,"A",{href:!0,rel:!0});var ii=o(X);Ut=l(ii,"Original Code"),ii.forEach(a),zt=l(za,"."),za.forEach(a),Ft=d(k),ye=n(k,"LI",{});var Fa=o(ye);Z=n(Fa,"A",{href:!0,rel:!0});var ni=o(Z);Vt=l(ni,"Hugging Face Demo"),ni.forEach(a),Ht=l(Fa,"."),Fa.forEach(a),Bt=d(k),we=n(k,"LI",{});var Va=o(we);ee=n(Va,"A",{href:!0,rel:!0});var oi=o(ee);Wt=l(oi,"Colab Demo"),oi.forEach(a),Kt=l(Va,"."),Va.forEach(a),k.forEach(a),dt=d(t),I=n(t,"H2",{class:!0});var vt=o(I);U=n(vt,"A",{id:!0,class:!0,href:!0});var si=o(U);Me=n(si,"SPAN",{});var ri=o(Me);y(te.$$.fragment,ri),ri.forEach(a),si.forEach(a),Rt=d(vt),qe=n(vt,"SPAN",{});var li=o(qe);Qt=l(li,"Available Pipelines:"),li.forEach(a),vt.forEach(a),pt=d(t),z=n(t,"TABLE",{});var bt=o(z);Ne=n(bt,"THEAD",{});var fi=o(Ne);C=n(fi,"TR",{});var $e=o(C);je=n($e,"TH",{});var di=o(je);Jt=l(di,"Pipeline"),di.forEach(a),Yt=d($e),Oe=n($e,"TH",{});var pi=o(Oe);Xt=l(pi,"Tasks"),pi.forEach(a),Zt=d($e),De=n($e,"TH",{align:!0});var ci=o(De);ea=l(ci,"Demo"),ci.forEach(a),$e.forEach(a),fi.forEach(a),ta=d(bt),Ue=n(bt,"TBODY",{});var ui=o(Ue);L=n(ui,"TR",{});var xe=o(L);ze=n(xe,"TD",{});var hi=o(ze);ae=n(hi,"A",{href:!0,rel:!0});var mi=o(ae);aa=l(mi,"StableDiffusionSAGPipeline"),mi.forEach(a),hi.forEach(a),ia=d(xe),Fe=n(xe,"TD",{});var gi=o(Fe);Ve=n(gi,"EM",{});var _i=o(Ve);na=l(_i,"Text-to-Image Generation"),_i.forEach(a),gi.forEach(a),oa=d(xe),Ae=n(xe,"TD",{align:!0});var vi=o(Ae);ie=n(vi,"A",{href:!0,rel:!0});var bi=o(ie);sa=l(bi,"\u{1F917} Space"),bi.forEach(a),vi.forEach(a),xe.forEach(a),ui.forEach(a),bt.forEach(a),ct=d(t),M=n(t,"H2",{class:!0});var St=o(M);F=n(St,"A",{id:!0,class:!0,href:!0});var Si=o(F);He=n(Si,"SPAN",{});var yi=o(He);y(ne.$$.fragment,yi),yi.forEach(a),Si.forEach(a),ra=d(St),Be=n(St,"SPAN",{});var wi=o(Be);la=l(wi,"Usage example"),wi.forEach(a),St.forEach(a),ut=d(t),y(oe.$$.fragment,t),ht=d(t),q=n(t,"H2",{class:!0});var yt=o(q);V=n(yt,"A",{id:!0,class:!0,href:!0});var Di=o(V);We=n(Di,"SPAN",{});var Ai=o(We);y(se.$$.fragment,Ai),Ai.forEach(a),Di.forEach(a),fa=d(yt),Ke=n(yt,"SPAN",{});var Pi=o(Ke);da=l(Pi,"StableDiffusionSAGPipeline"),Pi.forEach(a),yt.forEach(a),mt=d(t),h=n(t,"DIV",{class:!0});var b=o(h);y(re.$$.fragment,b),pa=d(b),Re=n(b,"P",{});var $i=o(Re);ca=l($i,"Pipeline for text-to-image generation using Stable Diffusion."),$i.forEach(a),ua=d(b),le=n(b,"P",{});var wt=o(le);ha=l(wt,"This model inherits from "),Pe=n(wt,"A",{href:!0});var xi=o(Pe);ma=l(xi,"DiffusionPipeline"),xi.forEach(a),ga=l(wt,`. Check the superclass documentation for the generic methods the
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)`),wt.forEach(a),_a=d(b),E=n(b,"DIV",{class:!0});var Ee=o(E);y(fe.$$.fragment,Ee),va=d(Ee),Qe=n(Ee,"P",{});var Ei=o(Qe);ba=l(Ei,"Function invoked when calling the pipeline for generation."),Ei.forEach(a),Sa=d(Ee),y(H.$$.fragment,Ee),Ee.forEach(a),ya=d(b),B=n(b,"DIV",{class:!0});var Dt=o(B);y(de.$$.fragment,Dt),wa=d(Dt),pe=n(Dt,"P",{});var At=o(pe);Da=l(At,"Disable sliced VAE decoding. If "),Je=n(At,"CODE",{});var Gi=o(Je);Aa=l(Gi,"enable_vae_slicing"),Gi.forEach(a),Pa=l(At,` was previously invoked, this method will go back to
computing decoding in one step.`),At.forEach(a),Dt.forEach(a),$a=d(b),W=n(b,"DIV",{class:!0});var Pt=o(W);y(ce.$$.fragment,Pt),xa=d(Pt),N=n(Pt,"P",{});var Ge=o(N);Ea=l(Ge,`Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
`),Ye=n(Ge,"CODE",{});var ki=o(Ye);Ga=l(ki,"torch.device('meta') and loaded to GPU only when their specific submodule has its "),ki.forEach(a),ka=l(Ge,"forward"),Xe=n(Ge,"CODE",{});var Ti=o(Xe);Ta=l(Ti,"method called. Note that offloading happens on a submodule basis. Memory savings are higher than with"),Ti.forEach(a),Ia=l(Ge,"enable_model_cpu_offload`, but performance is lower."),Ge.forEach(a),Pt.forEach(a),Ca=d(b),G=n(b,"DIV",{class:!0});var ke=o(G);y(ue.$$.fragment,ke),La=d(ke),Ze=n(ke,"P",{});var Ii=o(Ze);Ma=l(Ii,"Enable sliced VAE decoding."),Ii.forEach(a),qa=d(ke),et=n(ke,"P",{});var Ci=o(et);Na=l(Ci,`When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
steps. This is useful to save some memory and allow larger batch sizes.`),Ci.forEach(a),ke.forEach(a),b.forEach(a),this.h()},h(){s(m,"name","hf:doc:metadata"),s(m,"content",JSON.stringify(Hi)),s(g,"id","selfattention-guidance-sag"),s(g,"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"),s(g,"href","#selfattention-guidance-sag"),s(_,"class","relative group"),s(O,"id","overview"),s(O,"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"),s(O,"href","#overview"),s(T,"class","relative group"),s(Q,"href","https://arxiv.org/abs/2210.00939"),s(Q,"rel","nofollow"),s(J,"href","https://ku-cvlab.github.io/Self-Attention-Guidance"),s(J,"rel","nofollow"),s(Y,"href","https://arxiv.org/abs/2210.00939"),s(Y,"rel","nofollow"),s(X,"href","https://github.com/KU-CVLAB/Self-Attention-Guidance"),s(X,"rel","nofollow"),s(Z,"href","https://huggingface.co/spaces/susunghong/Self-Attention-Guidance"),s(Z,"rel","nofollow"),s(ee,"href","https://colab.research.google.com/github/SusungHong/Self-Attention-Guidance/blob/main/SAG_Stable.ipynb"),s(ee,"rel","nofollow"),s(U,"id","available-pipelines"),s(U,"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"),s(U,"href","#available-pipelines"),s(I,"class","relative group"),s(De,"align","center"),s(ae,"href","https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py"),s(ae,"rel","nofollow"),s(ie,"href","https://huggingface.co/spaces/susunghong/Self-Attention-Guidance"),s(ie,"rel","nofollow"),s(Ae,"align","center"),s(F,"id","usage-example"),s(F,"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"),s(F,"href","#usage-example"),s(M,"class","relative group"),s(V,"id","diffusers.StableDiffusionSAGPipeline"),s(V,"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"),s(V,"href","#diffusers.StableDiffusionSAGPipeline"),s(q,"class","relative group"),s(Pe,"href","/docs/diffusers/v0.16.0/en/api/diffusion_pipeline#diffusers.DiffusionPipeline"),s(E,"class","docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8"),s(B,"class","docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8"),s(W,"class","docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8"),s(G,"class","docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8"),s(h,"class","docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8")},m(t,p){e(document.head,m),c(t,j,p),c(t,_,p),e(_,g),e(g,$),w(u,$,null),e(_,x),e(_,Te),e(Te,$t),c(t,nt,p),c(t,T,p),e(T,O),e(O,Ie),w(K,Ie,null),e(T,xt),e(T,Ce),e(Ce,Et),c(t,ot,p),c(t,R,p),e(R,Q),e(Q,Gt),e(R,kt),c(t,st,p),c(t,me,p),e(me,Tt),c(t,rt,p),c(t,ge,p),e(ge,Le),e(Le,It),c(t,lt,p),c(t,_e,p),e(_e,Ct),c(t,ft,p),c(t,v,p),e(v,ve),e(ve,J),e(J,Lt),e(ve,Mt),e(v,qt),e(v,be),e(be,Y),e(Y,Nt),e(be,jt),e(v,Ot),e(v,Se),e(Se,X),e(X,Ut),e(Se,zt),e(v,Ft),e(v,ye),e(ye,Z),e(Z,Vt),e(ye,Ht),e(v,Bt),e(v,we),e(we,ee),e(ee,Wt),e(we,Kt),c(t,dt,p),c(t,I,p),e(I,U),e(U,Me),w(te,Me,null),e(I,Rt),e(I,qe),e(qe,Qt),c(t,pt,p),c(t,z,p),e(z,Ne),e(Ne,C),e(C,je),e(je,Jt),e(C,Yt),e(C,Oe),e(Oe,Xt),e(C,Zt),e(C,De),e(De,ea),e(z,ta),e(z,Ue),e(Ue,L),e(L,ze),e(ze,ae),e(ae,aa),e(L,ia),e(L,Fe),e(Fe,Ve),e(Ve,na),e(L,oa),e(L,Ae),e(Ae,ie),e(ie,sa),c(t,ct,p),c(t,M,p),e(M,F),e(F,He),w(ne,He,null),e(M,ra),e(M,Be),e(Be,la),c(t,ut,p),w(oe,t,p),c(t,ht,p),c(t,q,p),e(q,V),e(V,We),w(se,We,null),e(q,fa),e(q,Ke),e(Ke,da),c(t,mt,p),c(t,h,p),w(re,h,null),e(h,pa),e(h,Re),e(Re,ca),e(h,ua),e(h,le),e(le,ha),e(le,Pe),e(Pe,ma),e(le,ga),e(h,_a),e(h,E),w(fe,E,null),e(E,va),e(E,Qe),e(Qe,ba),e(E,Sa),w(H,E,null),e(h,ya),e(h,B),w(de,B,null),e(B,wa),e(B,pe),e(pe,Da),e(pe,Je),e(Je,Aa),e(pe,Pa),e(h,$a),e(h,W),w(ce,W,null),e(W,xa),e(W,N),e(N,Ea),e(N,Ye),e(Ye,Ga),e(N,ka),e(N,Xe),e(Xe,Ta),e(N,Ia),e(h,Ca),e(h,G),w(ue,G,null),e(G,La),e(G,Ze),e(Ze,Ma),e(G,qa),e(G,et),e(et,Na),gt=!0},p(t,[p]){const he={};p&2&&(he.$$scope={dirty:p,ctx:t}),H.$set(he)},i(t){gt||(D(u.$$.fragment,t),D(K.$$.fragment,t),D(te.$$.fragment,t),D(ne.$$.fragment,t),D(oe.$$.fragment,t),D(se.$$.fragment,t),D(re.$$.fragment,t),D(fe.$$.fragment,t),D(H.$$.fragment,t),D(de.$$.fragment,t),D(ce.$$.fragment,t),D(ue.$$.fragment,t),gt=!0)},o(t){A(u.$$.fragment,t),A(K.$$.fragment,t),A(te.$$.fragment,t),A(ne.$$.fragment,t),A(oe.$$.fragment,t),A(se.$$.fragment,t),A(re.$$.fragment,t),A(fe.$$.fragment,t),A(H.$$.fragment,t),A(de.$$.fragment,t),A(ce.$$.fragment,t),A(ue.$$.fragment,t),gt=!1},d(t){a(m),t&&a(j),t&&a(_),P(u),t&&a(nt),t&&a(T),P(K),t&&a(ot),t&&a(R),t&&a(st),t&&a(me),t&&a(rt),t&&a(ge),t&&a(lt),t&&a(_e),t&&a(ft),t&&a(v),t&&a(dt),t&&a(I),P(te),t&&a(pt),t&&a(z),t&&a(ct),t&&a(M),P(ne),t&&a(ut),P(oe,t),t&&a(ht),t&&a(q),P(se),t&&a(mt),t&&a(h),P(re),P(fe),P(H),P(de),P(ce),P(ue)}}}const Hi={local:"selfattention-guidance-sag",sections:[{local:"overview",title:"Overview"},{local:"available-pipelines",title:"Available Pipelines:"},{local:"usage-example",title:"Usage example"},{local:"diffusers.StableDiffusionSAGPipeline",title:"StableDiffusionSAGPipeline"}],title:"Self-Attention Guidance (SAG)"};function Bi(it){return Oi(()=>{new URLSearchParams(window.location.search).get("fw")}),[]}class Yi extends Mi{constructor(m){super();qi(this,m,Bi,Vi,Ni,{})}}export{Yi as default,Hi as metadata};
