import{S as Jn,i as jn,s as Nn,e as n,k as c,w as y,t as r,M as Bn,c as o,d as a,m as d,a as i,x as w,h as l,b as s,G as e,g as p,y as S,q as A,o as G,B as D,v as Ln,L as Zn}from"../../../chunks/vendor-hf-doc-builder.js";import{D as tt}from"../../../chunks/Docstring-hf-doc-builder.js";import{C as Cn}from"../../../chunks/CodeBlock-hf-doc-builder.js";import{I as at}from"../../../chunks/IconCopyLink-hf-doc-builder.js";import{E as Wn}from"../../../chunks/ExampleCodeBlock-hf-doc-builder.js";function Fn(nt){let m,N,_,g,P;return g=new Cn({props:{code:"aW1wb3J0JTIwdG9yY2glMEFmcm9tJTIwZGlmZnVzZXJzJTIwaW1wb3J0JTIwU3RhYmxlRGlmZnVzaW9uU0FHUGlwZWxpbmUlMEElMEFwaXBlJTIwJTNEJTIwU3RhYmxlRGlmZnVzaW9uU0FHUGlwZWxpbmUuZnJvbV9wcmV0cmFpbmVkKCUwQSUyMCUyMCUyMCUyMCUyMnJ1bndheW1sJTJGc3RhYmxlLWRpZmZ1c2lvbi12MS01JTIyJTJDJTIwdG9yY2hfZHR5cGUlM0R0b3JjaC5mbG9hdDE2JTBBKSUwQXBpcGUlMjAlM0QlMjBwaXBlLnRvKCUyMmN1ZGElMjIpJTBBJTBBcHJvbXB0JTIwJTNEJTIwJTIyYSUyMHBob3RvJTIwb2YlMjBhbiUyMGFzdHJvbmF1dCUyMHJpZGluZyUyMGElMjBob3JzZSUyMG9uJTIwbWFycyUyMiUwQWltYWdlJTIwJTNEJTIwcGlwZShwcm9tcHQlMkMlMjBzYWdfc2NhbGUlM0QwLjc1KS5pbWFnZXMlNUIwJTVE",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=n("p"),N=r("Examples:"),_=c(),y(g.$$.fragment)},l(u){m=o(u,"P",{});var x=i(m);N=l(x,"Examples:"),x.forEach(a),_=d(u),w(g.$$.fragment,u)},m(u,x){p(u,m,x),e(m,N),p(u,_,x),S(g,u,x),P=!0},p:Zn,i(u){P||(A(g.$$.fragment,u),P=!0)},o(u){G(g.$$.fragment,u),P=!1},d(u){u&&a(m),u&&a(_),D(g,u)}}}function Vn(nt){let m,N,_,g,P,u,x,Te,Pt,ot,T,B,ke,H,xt,Ue,Et,it,O,R,Mt,$t,st,me,Tt,rt,ge,Ie,kt,lt,_e,Ut,ct,b,be,Q,It,Ct,Jt,ve,Y,jt,Nt,Bt,ye,X,Lt,Zt,Wt,we,K,Ft,Vt,zt,Se,ee,qt,Ht,dt,k,L,Ce,te,Ot,Je,Rt,ft,Z,je,U,Ne,Qt,Yt,Be,Xt,Kt,Ae,ea,ta,Le,I,Ze,ae,aa,na,We,Fe,oa,ia,Ge,ne,sa,pt,C,W,Ve,oe,ra,ze,la,ut,ie,ht,J,F,qe,se,ca,He,da,mt,h,re,fa,Oe,pa,ua,le,ha,De,ma,ga,_a,E,ce,ba,Re,va,ya,V,wa,z,de,Sa,fe,Aa,Qe,Ga,Da,Pa,q,pe,xa,j,Ea,Ye,Ma,$a,Xe,Ta,ka,Ua,M,ue,Ia,Ke,Ca,Ja,et,ja,gt;return u=new at({}),H=new at({}),te=new at({}),oe=new at({}),ie=new Cn({props:{code:"aW1wb3J0JTIwdG9yY2glMEFmcm9tJTIwZGlmZnVzZXJzJTIwaW1wb3J0JTIwU3RhYmxlRGlmZnVzaW9uU0FHUGlwZWxpbmUlMEFmcm9tJTIwYWNjZWxlcmF0ZS51dGlscyUyMGltcG9ydCUyMHNldF9zZWVkJTBBJTBBcGlwZSUyMCUzRCUyMFN0YWJsZURpZmZ1c2lvblNBR1BpcGVsaW5lLmZyb21fcHJldHJhaW5lZCglMjJDb21wVmlzJTJGc3RhYmxlLWRpZmZ1c2lvbi12MS00JTIyJTJDJTIwdG9yY2hfZHR5cGUlM0R0b3JjaC5mbG9hdDE2KSUwQXBpcGUlMjAlM0QlMjBwaXBlLnRvKCUyMmN1ZGElMjIpJTBBJTBBc2VlZCUyMCUzRCUyMDg5NzglMEFwcm9tcHQlMjAlM0QlMjAlMjIuJTIyJTBBZ3VpZGFuY2Vfc2NhbGUlMjAlM0QlMjA3LjUlMEFudW1faW1hZ2VzX3Blcl9wcm9tcHQlMjAlM0QlMjAxJTBBJTBBc2FnX3NjYWxlJTIwJTNEJTIwMS4wJTBBJTBBc2V0X3NlZWQoc2VlZCklMEFpbWFnZXMlMjAlM0QlMjBwaXBlKCUwQSUyMCUyMCUyMCUyMHByb21wdCUyQyUyMG51bV9pbWFnZXNfcGVyX3Byb21wdCUzRG51bV9pbWFnZXNfcGVyX3Byb21wdCUyQyUyMGd1aWRhbmNlX3NjYWxlJTNEZ3VpZGFuY2Vfc2NhbGUlMkMlMjBzYWdfc2NhbGUlM0RzYWdfc2NhbGUlMEEpLmltYWdlcyUwQWltYWdlcyU1QjAlNUQuc2F2ZSglMjJleGFtcGxlLnBuZyUyMik=",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.17.1/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.17.1/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.17.1/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.17.1/en/api/schedulers/ddim#diffusers.DDIMScheduler">DDIMScheduler</a>, <a href="/docs/diffusers/v0.17.1/en/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler">LMSDiscreteScheduler</a>, or <a href="/docs/diffusers/v0.17.1/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.17.1/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py#L93"}}),ce=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.17.1/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.17.1/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.17.1/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py#L479",returnDescription:`
<p><a
  href="/docs/diffusers/v0.17.1/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.17.1/en/api/pipelines/stable_diffusion/overview#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput"
>StableDiffusionPipelineOutput</a> or <code>tuple</code></p>
`}}),V=new Wn({props:{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.example",$$slots:{default:[Fn]},$$scope:{ctx:nt}}}),de=new tt({props:{name:"disable_vae_slicing",anchor:"diffusers.StableDiffusionSAGPipeline.disable_vae_slicing",parameters:[],source:"https://github.com/huggingface/diffusers/blob/v0.17.1/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py#L159"}}),pe=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.17.1/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py#L167"}}),ue=new tt({props:{name:"enable_vae_slicing",anchor:"diffusers.StableDiffusionSAGPipeline.enable_vae_slicing",parameters:[],source:"https://github.com/huggingface/diffusers/blob/v0.17.1/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py#L149"}}),{c(){m=n("meta"),N=c(),_=n("h1"),g=n("a"),P=n("span"),y(u.$$.fragment),x=c(),Te=n("span"),Pt=r("Self-Attention Guidance (SAG)"),ot=c(),T=n("h2"),B=n("a"),ke=n("span"),y(H.$$.fragment),xt=c(),Ue=n("span"),Et=r("Overview"),it=c(),O=n("p"),R=n("a"),Mt=r("Improving Sample Quality of Diffusion Models Using Self-Attention Guidance"),$t=r(" by Susung Hong et al."),st=c(),me=n("p"),Tt=r("The abstract of the paper is the following:"),rt=c(),ge=n("p"),Ie=n("em"),kt=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=c(),_e=n("p"),Ut=r("Resources:"),ct=c(),b=n("ul"),be=n("li"),Q=n("a"),It=r("Project Page"),Ct=r("."),Jt=c(),ve=n("li"),Y=n("a"),jt=r("Paper"),Nt=r("."),Bt=c(),ye=n("li"),X=n("a"),Lt=r("Original Code"),Zt=r("."),Wt=c(),we=n("li"),K=n("a"),Ft=r("Hugging Face Demo"),Vt=r("."),zt=c(),Se=n("li"),ee=n("a"),qt=r("Colab Demo"),Ht=r("."),dt=c(),k=n("h2"),L=n("a"),Ce=n("span"),y(te.$$.fragment),Ot=c(),Je=n("span"),Rt=r("Available Pipelines:"),ft=c(),Z=n("table"),je=n("thead"),U=n("tr"),Ne=n("th"),Qt=r("Pipeline"),Yt=c(),Be=n("th"),Xt=r("Tasks"),Kt=c(),Ae=n("th"),ea=r("Demo"),ta=c(),Le=n("tbody"),I=n("tr"),Ze=n("td"),ae=n("a"),aa=r("StableDiffusionSAGPipeline"),na=c(),We=n("td"),Fe=n("em"),oa=r("Text-to-Image Generation"),ia=c(),Ge=n("td"),ne=n("a"),sa=r("\u{1F917} Space"),pt=c(),C=n("h2"),W=n("a"),Ve=n("span"),y(oe.$$.fragment),ra=c(),ze=n("span"),la=r("Usage example"),ut=c(),y(ie.$$.fragment),ht=c(),J=n("h2"),F=n("a"),qe=n("span"),y(se.$$.fragment),ca=c(),He=n("span"),da=r("StableDiffusionSAGPipeline"),mt=c(),h=n("div"),y(re.$$.fragment),fa=c(),Oe=n("p"),pa=r("Pipeline for text-to-image generation using Stable Diffusion."),ua=c(),le=n("p"),ha=r("This model inherits from "),De=n("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=c(),E=n("div"),y(ce.$$.fragment),ba=c(),Re=n("p"),va=r("Function invoked when calling the pipeline for generation."),ya=c(),y(V.$$.fragment),wa=c(),z=n("div"),y(de.$$.fragment),Sa=c(),fe=n("p"),Aa=r("Disable sliced VAE decoding. If "),Qe=n("code"),Ga=r("enable_vae_slicing"),Da=r(` was previously invoked, this method will go back to
computing decoding in one step.`),Pa=c(),q=n("div"),y(pe.$$.fragment),xa=c(),j=n("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=n("code"),Ma=r("torch.device('meta') and loaded to GPU only when their specific submodule has its "),$a=r("forward"),Xe=n("code"),Ta=r("method called. Note that offloading happens on a submodule basis. Memory savings are higher than with"),ka=r("enable_model_cpu_offload`, but performance is lower."),Ua=c(),M=n("div"),y(ue.$$.fragment),Ia=c(),Ke=n("p"),Ca=r("Enable sliced VAE decoding."),Ja=c(),et=n("p"),ja=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 f=Bn('[data-svelte="svelte-1phssyn"]',document.head);m=o(f,"META",{name:!0,content:!0}),f.forEach(a),N=d(t),_=o(t,"H1",{class:!0});var he=i(_);g=o(he,"A",{id:!0,class:!0,href:!0});var Va=i(g);P=o(Va,"SPAN",{});var za=i(P);w(u.$$.fragment,za),za.forEach(a),Va.forEach(a),x=d(he),Te=o(he,"SPAN",{});var qa=i(Te);Pt=l(qa,"Self-Attention Guidance (SAG)"),qa.forEach(a),he.forEach(a),ot=d(t),T=o(t,"H2",{class:!0});var _t=i(T);B=o(_t,"A",{id:!0,class:!0,href:!0});var Ha=i(B);ke=o(Ha,"SPAN",{});var Oa=i(ke);w(H.$$.fragment,Oa),Oa.forEach(a),Ha.forEach(a),xt=d(_t),Ue=o(_t,"SPAN",{});var Ra=i(Ue);Et=l(Ra,"Overview"),Ra.forEach(a),_t.forEach(a),it=d(t),O=o(t,"P",{});var Na=i(O);R=o(Na,"A",{href:!0,rel:!0});var Qa=i(R);Mt=l(Qa,"Improving Sample Quality of Diffusion Models Using Self-Attention Guidance"),Qa.forEach(a),$t=l(Na," by Susung Hong et al."),Na.forEach(a),st=d(t),me=o(t,"P",{});var Ya=i(me);Tt=l(Ya,"The abstract of the paper is the following:"),Ya.forEach(a),rt=d(t),ge=o(t,"P",{});var Xa=i(ge);Ie=o(Xa,"EM",{});var Ka=i(Ie);kt=l(Ka,"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."),Ka.forEach(a),Xa.forEach(a),lt=d(t),_e=o(t,"P",{});var en=i(_e);Ut=l(en,"Resources:"),en.forEach(a),ct=d(t),b=o(t,"UL",{});var $=i(b);be=o($,"LI",{});var Ba=i(be);Q=o(Ba,"A",{href:!0,rel:!0});var tn=i(Q);It=l(tn,"Project Page"),tn.forEach(a),Ct=l(Ba,"."),Ba.forEach(a),Jt=d($),ve=o($,"LI",{});var La=i(ve);Y=o(La,"A",{href:!0,rel:!0});var an=i(Y);jt=l(an,"Paper"),an.forEach(a),Nt=l(La,"."),La.forEach(a),Bt=d($),ye=o($,"LI",{});var Za=i(ye);X=o(Za,"A",{href:!0,rel:!0});var nn=i(X);Lt=l(nn,"Original Code"),nn.forEach(a),Zt=l(Za,"."),Za.forEach(a),Wt=d($),we=o($,"LI",{});var Wa=i(we);K=o(Wa,"A",{href:!0,rel:!0});var on=i(K);Ft=l(on,"Hugging Face Demo"),on.forEach(a),Vt=l(Wa,"."),Wa.forEach(a),zt=d($),Se=o($,"LI",{});var Fa=i(Se);ee=o(Fa,"A",{href:!0,rel:!0});var sn=i(ee);qt=l(sn,"Colab Demo"),sn.forEach(a),Ht=l(Fa,"."),Fa.forEach(a),$.forEach(a),dt=d(t),k=o(t,"H2",{class:!0});var bt=i(k);L=o(bt,"A",{id:!0,class:!0,href:!0});var rn=i(L);Ce=o(rn,"SPAN",{});var ln=i(Ce);w(te.$$.fragment,ln),ln.forEach(a),rn.forEach(a),Ot=d(bt),Je=o(bt,"SPAN",{});var cn=i(Je);Rt=l(cn,"Available Pipelines:"),cn.forEach(a),bt.forEach(a),ft=d(t),Z=o(t,"TABLE",{});var vt=i(Z);je=o(vt,"THEAD",{});var dn=i(je);U=o(dn,"TR",{});var Pe=i(U);Ne=o(Pe,"TH",{});var fn=i(Ne);Qt=l(fn,"Pipeline"),fn.forEach(a),Yt=d(Pe),Be=o(Pe,"TH",{});var pn=i(Be);Xt=l(pn,"Tasks"),pn.forEach(a),Kt=d(Pe),Ae=o(Pe,"TH",{align:!0});var un=i(Ae);ea=l(un,"Demo"),un.forEach(a),Pe.forEach(a),dn.forEach(a),ta=d(vt),Le=o(vt,"TBODY",{});var hn=i(Le);I=o(hn,"TR",{});var xe=i(I);Ze=o(xe,"TD",{});var mn=i(Ze);ae=o(mn,"A",{href:!0,rel:!0});var gn=i(ae);aa=l(gn,"StableDiffusionSAGPipeline"),gn.forEach(a),mn.forEach(a),na=d(xe),We=o(xe,"TD",{});var _n=i(We);Fe=o(_n,"EM",{});var bn=i(Fe);oa=l(bn,"Text-to-Image Generation"),bn.forEach(a),_n.forEach(a),ia=d(xe),Ge=o(xe,"TD",{align:!0});var vn=i(Ge);ne=o(vn,"A",{href:!0,rel:!0});var yn=i(ne);sa=l(yn,"\u{1F917} Space"),yn.forEach(a),vn.forEach(a),xe.forEach(a),hn.forEach(a),vt.forEach(a),pt=d(t),C=o(t,"H2",{class:!0});var yt=i(C);W=o(yt,"A",{id:!0,class:!0,href:!0});var wn=i(W);Ve=o(wn,"SPAN",{});var Sn=i(Ve);w(oe.$$.fragment,Sn),Sn.forEach(a),wn.forEach(a),ra=d(yt),ze=o(yt,"SPAN",{});var An=i(ze);la=l(An,"Usage example"),An.forEach(a),yt.forEach(a),ut=d(t),w(ie.$$.fragment,t),ht=d(t),J=o(t,"H2",{class:!0});var wt=i(J);F=o(wt,"A",{id:!0,class:!0,href:!0});var Gn=i(F);qe=o(Gn,"SPAN",{});var Dn=i(qe);w(se.$$.fragment,Dn),Dn.forEach(a),Gn.forEach(a),ca=d(wt),He=o(wt,"SPAN",{});var Pn=i(He);da=l(Pn,"StableDiffusionSAGPipeline"),Pn.forEach(a),wt.forEach(a),mt=d(t),h=o(t,"DIV",{class:!0});var v=i(h);w(re.$$.fragment,v),fa=d(v),Oe=o(v,"P",{});var xn=i(Oe);pa=l(xn,"Pipeline for text-to-image generation using Stable Diffusion."),xn.forEach(a),ua=d(v),le=o(v,"P",{});var St=i(le);ha=l(St,"This model inherits from "),De=o(St,"A",{href:!0});var En=i(De);ma=l(En,"DiffusionPipeline"),En.forEach(a),ga=l(St,`. 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.)`),St.forEach(a),_a=d(v),E=o(v,"DIV",{class:!0});var Ee=i(E);w(ce.$$.fragment,Ee),ba=d(Ee),Re=o(Ee,"P",{});var Mn=i(Re);va=l(Mn,"Function invoked when calling the pipeline for generation."),Mn.forEach(a),ya=d(Ee),w(V.$$.fragment,Ee),Ee.forEach(a),wa=d(v),z=o(v,"DIV",{class:!0});var At=i(z);w(de.$$.fragment,At),Sa=d(At),fe=o(At,"P",{});var Gt=i(fe);Aa=l(Gt,"Disable sliced VAE decoding. If "),Qe=o(Gt,"CODE",{});var $n=i(Qe);Ga=l($n,"enable_vae_slicing"),$n.forEach(a),Da=l(Gt,` was previously invoked, this method will go back to
computing decoding in one step.`),Gt.forEach(a),At.forEach(a),Pa=d(v),q=o(v,"DIV",{class:!0});var Dt=i(q);w(pe.$$.fragment,Dt),xa=d(Dt),j=o(Dt,"P",{});var Me=i(j);Ea=l(Me,`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=o(Me,"CODE",{});var Tn=i(Ye);Ma=l(Tn,"torch.device('meta') and loaded to GPU only when their specific submodule has its "),Tn.forEach(a),$a=l(Me,"forward"),Xe=o(Me,"CODE",{});var kn=i(Xe);Ta=l(kn,"method called. Note that offloading happens on a submodule basis. Memory savings are higher than with"),kn.forEach(a),ka=l(Me,"enable_model_cpu_offload`, but performance is lower."),Me.forEach(a),Dt.forEach(a),Ua=d(v),M=o(v,"DIV",{class:!0});var $e=i(M);w(ue.$$.fragment,$e),Ia=d($e),Ke=o($e,"P",{});var Un=i(Ke);Ca=l(Un,"Enable sliced VAE decoding."),Un.forEach(a),Ja=d($e),et=o($e,"P",{});var In=i(et);ja=l(In,`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.`),In.forEach(a),$e.forEach(a),v.forEach(a),this.h()},h(){s(m,"name","hf:doc:metadata"),s(m,"content",JSON.stringify(zn)),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(B,"id","overview"),s(B,"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(B,"href","#overview"),s(T,"class","relative group"),s(R,"href","https://arxiv.org/abs/2210.00939"),s(R,"rel","nofollow"),s(Q,"href","https://ku-cvlab.github.io/Self-Attention-Guidance"),s(Q,"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(K,"href","https://huggingface.co/spaces/susunghong/Self-Attention-Guidance"),s(K,"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(L,"id","available-pipelines"),s(L,"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(L,"href","#available-pipelines"),s(k,"class","relative group"),s(Ae,"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(ne,"href","https://huggingface.co/spaces/susunghong/Self-Attention-Guidance"),s(ne,"rel","nofollow"),s(Ge,"align","center"),s(W,"id","usage-example"),s(W,"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(W,"href","#usage-example"),s(C,"class","relative group"),s(F,"id","diffusers.StableDiffusionSAGPipeline"),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","#diffusers.StableDiffusionSAGPipeline"),s(J,"class","relative group"),s(De,"href","/docs/diffusers/v0.17.1/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(z,"class","docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8"),s(q,"class","docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8"),s(M,"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,f){e(document.head,m),p(t,N,f),p(t,_,f),e(_,g),e(g,P),S(u,P,null),e(_,x),e(_,Te),e(Te,Pt),p(t,ot,f),p(t,T,f),e(T,B),e(B,ke),S(H,ke,null),e(T,xt),e(T,Ue),e(Ue,Et),p(t,it,f),p(t,O,f),e(O,R),e(R,Mt),e(O,$t),p(t,st,f),p(t,me,f),e(me,Tt),p(t,rt,f),p(t,ge,f),e(ge,Ie),e(Ie,kt),p(t,lt,f),p(t,_e,f),e(_e,Ut),p(t,ct,f),p(t,b,f),e(b,be),e(be,Q),e(Q,It),e(be,Ct),e(b,Jt),e(b,ve),e(ve,Y),e(Y,jt),e(ve,Nt),e(b,Bt),e(b,ye),e(ye,X),e(X,Lt),e(ye,Zt),e(b,Wt),e(b,we),e(we,K),e(K,Ft),e(we,Vt),e(b,zt),e(b,Se),e(Se,ee),e(ee,qt),e(Se,Ht),p(t,dt,f),p(t,k,f),e(k,L),e(L,Ce),S(te,Ce,null),e(k,Ot),e(k,Je),e(Je,Rt),p(t,ft,f),p(t,Z,f),e(Z,je),e(je,U),e(U,Ne),e(Ne,Qt),e(U,Yt),e(U,Be),e(Be,Xt),e(U,Kt),e(U,Ae),e(Ae,ea),e(Z,ta),e(Z,Le),e(Le,I),e(I,Ze),e(Ze,ae),e(ae,aa),e(I,na),e(I,We),e(We,Fe),e(Fe,oa),e(I,ia),e(I,Ge),e(Ge,ne),e(ne,sa),p(t,pt,f),p(t,C,f),e(C,W),e(W,Ve),S(oe,Ve,null),e(C,ra),e(C,ze),e(ze,la),p(t,ut,f),S(ie,t,f),p(t,ht,f),p(t,J,f),e(J,F),e(F,qe),S(se,qe,null),e(J,ca),e(J,He),e(He,da),p(t,mt,f),p(t,h,f),S(re,h,null),e(h,fa),e(h,Oe),e(Oe,pa),e(h,ua),e(h,le),e(le,ha),e(le,De),e(De,ma),e(le,ga),e(h,_a),e(h,E),S(ce,E,null),e(E,ba),e(E,Re),e(Re,va),e(E,ya),S(V,E,null),e(h,wa),e(h,z),S(de,z,null),e(z,Sa),e(z,fe),e(fe,Aa),e(fe,Qe),e(Qe,Ga),e(fe,Da),e(h,Pa),e(h,q),S(pe,q,null),e(q,xa),e(q,j),e(j,Ea),e(j,Ye),e(Ye,Ma),e(j,$a),e(j,Xe),e(Xe,Ta),e(j,ka),e(h,Ua),e(h,M),S(ue,M,null),e(M,Ia),e(M,Ke),e(Ke,Ca),e(M,Ja),e(M,et),e(et,ja),gt=!0},p(t,[f]){const he={};f&2&&(he.$$scope={dirty:f,ctx:t}),V.$set(he)},i(t){gt||(A(u.$$.fragment,t),A(H.$$.fragment,t),A(te.$$.fragment,t),A(oe.$$.fragment,t),A(ie.$$.fragment,t),A(se.$$.fragment,t),A(re.$$.fragment,t),A(ce.$$.fragment,t),A(V.$$.fragment,t),A(de.$$.fragment,t),A(pe.$$.fragment,t),A(ue.$$.fragment,t),gt=!0)},o(t){G(u.$$.fragment,t),G(H.$$.fragment,t),G(te.$$.fragment,t),G(oe.$$.fragment,t),G(ie.$$.fragment,t),G(se.$$.fragment,t),G(re.$$.fragment,t),G(ce.$$.fragment,t),G(V.$$.fragment,t),G(de.$$.fragment,t),G(pe.$$.fragment,t),G(ue.$$.fragment,t),gt=!1},d(t){a(m),t&&a(N),t&&a(_),D(u),t&&a(ot),t&&a(T),D(H),t&&a(it),t&&a(O),t&&a(st),t&&a(me),t&&a(rt),t&&a(ge),t&&a(lt),t&&a(_e),t&&a(ct),t&&a(b),t&&a(dt),t&&a(k),D(te),t&&a(ft),t&&a(Z),t&&a(pt),t&&a(C),D(oe),t&&a(ut),D(ie,t),t&&a(ht),t&&a(J),D(se),t&&a(mt),t&&a(h),D(re),D(ce),D(V),D(de),D(pe),D(ue)}}}const zn={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 qn(nt){return Ln(()=>{new URLSearchParams(window.location.search).get("fw")}),[]}class Xn extends Jn{constructor(m){super();jn(this,m,qn,Vn,Nn,{})}}export{Xn as default,zn as metadata};
