import{S as En,i as Gn,s as Tn,e as n,k as d,w as v,t as r,M as Cn,c as i,d as a,m as f,a as o,x as S,h as l,b as s,G as e,g as c,y as w,q as y,o as D,B as P,v as In,L as Mn}from"../../../../chunks/vendor-hf-doc-builder.js";import{D as Ze}from"../../../../chunks/Docstring-hf-doc-builder.js";import{C as kn}from"../../../../chunks/CodeBlock-hf-doc-builder.js";import{I as et}from"../../../../chunks/IconCopyLink-hf-doc-builder.js";import{E as Ln}from"../../../../chunks/ExampleCodeBlock-hf-doc-builder.js";function Nn(tt){let m,j,_,g,$;return g=new kn({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=n("p"),j=r("Examples:"),_=d(),v(g.$$.fragment)},l(u){m=i(u,"P",{});var x=o(m);j=l(x,"Examples:"),x.forEach(a),_=f(u),S(g.$$.fragment,u)},m(u,x){c(u,m,x),e(m,j),c(u,_,x),w(g,u,x),$=!0},p:Mn,i(u){$||(y(g.$$.fragment,u),$=!0)},o(u){D(g.$$.fragment,u),$=!1},d(u){u&&a(m),u&&a(_),P(g,u)}}}function jn(tt){let m,j,_,g,$,u,x,Ee,Pt,at,G,q,Ge,K,At,Te,$t,nt,R,J,xt,kt,it,he,Et,ot,me,Ce,Gt,st,ge,Tt,rt,A,_e,Q,Ct,It,Mt,be,Y,Lt,Nt,jt,ve,X,qt,Ot,Ut,Se,Z,Vt,zt,lt,T,O,Ie,ee,Ft,Me,Ht,dt,U,Le,C,Ne,Wt,Bt,je,Kt,Rt,we,Jt,Qt,qe,I,Oe,te,Yt,Xt,Ue,Ve,Zt,ea,ye,ae,ta,ft,M,V,ze,ne,aa,Fe,na,pt,ie,ct,L,z,He,oe,ia,We,oa,ut,h,se,sa,Be,ra,la,re,da,De,fa,pa,ca,k,le,ua,Ke,ha,ma,F,ga,H,de,_a,fe,ba,Re,va,Sa,wa,W,pe,ya,N,Da,Je,Pa,Aa,Qe,$a,xa,ka,E,ce,Ea,Ye,Ga,Ta,Xe,Ca,ht;return u=new et({}),K=new et({}),ee=new et({}),ne=new et({}),ie=new kn({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>)`}}),oe=new et({}),se=new Ze({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:": CLIPFeatureExtractor"},{name:"requires_safety_checker",val:": bool = True"}],parametersDescription:[{anchor:"diffusers.StableDiffusionSAGPipeline.vae",description:`<strong>vae</strong> (<a href="/docs/diffusers/main/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/main/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/main/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/main/en/api/schedulers/ddim#diffusers.DDIMScheduler">DDIMScheduler</a>, <a href="/docs/diffusers/main/en/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler">LMSDiscreteScheduler</a>, or <a href="/docs/diffusers/main/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>CLIPFeatureExtractor</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/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py#L91"}}),le=new Ze({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. 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/main/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/main/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>AttnProcessor</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/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py#L447",returnDescription:`
<p><a
  href="/docs/diffusers/main/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/main/en/api/pipelines/stable_diffusion/overview#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput"
>StableDiffusionPipelineOutput</a> or <code>tuple</code></p>
`}}),F=new Ln({props:{anchor:"diffusers.StableDiffusionSAGPipeline.__call__.example",$$slots:{default:[Nn]},$$scope:{ctx:tt}}}),de=new Ze({props:{name:"disable_vae_slicing",anchor:"diffusers.StableDiffusionSAGPipeline.disable_vae_slicing",parameters:[],source:"https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py#L156"}}),pe=new Ze({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/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py#L164"}}),ce=new Ze({props:{name:"enable_vae_slicing",anchor:"diffusers.StableDiffusionSAGPipeline.enable_vae_slicing",parameters:[],source:"https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py#L146"}}),{c(){m=n("meta"),j=d(),_=n("h1"),g=n("a"),$=n("span"),v(u.$$.fragment),x=d(),Ee=n("span"),Pt=r("Self-Attention Guidance (SAG)"),at=d(),G=n("h2"),q=n("a"),Ge=n("span"),v(K.$$.fragment),At=d(),Te=n("span"),$t=r("Overview"),nt=d(),R=n("p"),J=n("a"),xt=r("Self-Attention Guidance"),kt=r(" by Susung Hong et al."),it=d(),he=n("p"),Et=r("The abstract of the paper is the following:"),ot=d(),me=n("p"),Ce=n("em"),Gt=r("Denoising diffusion models (DDMs) have been drawing much attention for their appreciable sample quality and diversity. Despite their remarkable performance, DDMs remain black boxes on which further study is necessary to take a profound step. Motivated by this, we delve into the design of conventional U-shaped diffusion models. More specifically, we investigate the self-attention modules within these models through carefully designed experiments and explore their characteristics. In addition, inspired by the studies that substantiate the effectiveness of the guidance schemes, we present plug-and-play diffusion guidance, namely Self-Attention Guidance (SAG), that can drastically boost the performance of existing diffusion models. Our method, SAG, extracts the intermediate attention map from a diffusion model at every iteration and selects tokens above a certain attention score for masking and blurring to obtain a partially blurred input. Subsequently, we measure the dissimilarity between the predicted noises obtained from feeding the blurred and original input to the diffusion model and leverage it as guidance. With this guidance, we observe apparent improvements in a wide range of diffusion models, e.g., ADM, IDDPM, and Stable Diffusion, and show that the results further improve by combining our method with the conventional guidance scheme. We provide extensive ablation studies to verify our choices."),st=d(),ge=n("p"),Tt=r("Resources:"),rt=d(),A=n("ul"),_e=n("li"),Q=n("a"),Ct=r("Project Page"),It=r("."),Mt=d(),be=n("li"),Y=n("a"),Lt=r("Paper"),Nt=r("."),jt=d(),ve=n("li"),X=n("a"),qt=r("Original Code"),Ot=r("."),Ut=d(),Se=n("li"),Z=n("a"),Vt=r("Demo"),zt=r("."),lt=d(),T=n("h2"),O=n("a"),Ie=n("span"),v(ee.$$.fragment),Ft=d(),Me=n("span"),Ht=r("Available Pipelines:"),dt=d(),U=n("table"),Le=n("thead"),C=n("tr"),Ne=n("th"),Wt=r("Pipeline"),Bt=d(),je=n("th"),Kt=r("Tasks"),Rt=d(),we=n("th"),Jt=r("Demo"),Qt=d(),qe=n("tbody"),I=n("tr"),Oe=n("td"),te=n("a"),Yt=r("StableDiffusionSAGPipeline"),Xt=d(),Ue=n("td"),Ve=n("em"),Zt=r("Text-to-Image Generation"),ea=d(),ye=n("td"),ae=n("a"),ta=r("Colab"),ft=d(),M=n("h2"),V=n("a"),ze=n("span"),v(ne.$$.fragment),aa=d(),Fe=n("span"),na=r("Usage example"),pt=d(),v(ie.$$.fragment),ct=d(),L=n("h2"),z=n("a"),He=n("span"),v(oe.$$.fragment),ia=d(),We=n("span"),oa=r("StableDiffusionSAGPipeline"),ut=d(),h=n("div"),v(se.$$.fragment),sa=d(),Be=n("p"),ra=r("Pipeline for text-to-image generation using Stable Diffusion."),la=d(),re=n("p"),da=r("This model inherits from "),De=n("a"),fa=r("DiffusionPipeline"),pa=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.)`),ca=d(),k=n("div"),v(le.$$.fragment),ua=d(),Ke=n("p"),ha=r("Function invoked when calling the pipeline for generation."),ma=d(),v(F.$$.fragment),ga=d(),H=n("div"),v(de.$$.fragment),_a=d(),fe=n("p"),ba=r("Disable sliced VAE decoding. If "),Re=n("code"),va=r("enable_vae_slicing"),Sa=r(` was previously invoked, this method will go back to
computing decoding in one step.`),wa=d(),W=n("div"),v(pe.$$.fragment),ya=d(),N=n("p"),Da=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
`),Je=n("code"),Pa=r("torch.device('meta') and loaded to GPU only when their specific submodule has its "),Aa=r("forward"),Qe=n("code"),$a=r("method called. Note that offloading happens on a submodule basis. Memory savings are higher than with"),xa=r("enable_model_cpu_offload`, but performance is lower."),ka=d(),E=n("div"),v(ce.$$.fragment),Ea=d(),Ye=n("p"),Ga=r("Enable sliced VAE decoding."),Ta=d(),Xe=n("p"),Ca=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=Cn('[data-svelte="svelte-1phssyn"]',document.head);m=i(p,"META",{name:!0,content:!0}),p.forEach(a),j=f(t),_=i(t,"H1",{class:!0});var ue=o(_);g=i(ue,"A",{id:!0,class:!0,href:!0});var qa=o(g);$=i(qa,"SPAN",{});var Oa=o($);S(u.$$.fragment,Oa),Oa.forEach(a),qa.forEach(a),x=f(ue),Ee=i(ue,"SPAN",{});var Ua=o(Ee);Pt=l(Ua,"Self-Attention Guidance (SAG)"),Ua.forEach(a),ue.forEach(a),at=f(t),G=i(t,"H2",{class:!0});var mt=o(G);q=i(mt,"A",{id:!0,class:!0,href:!0});var Va=o(q);Ge=i(Va,"SPAN",{});var za=o(Ge);S(K.$$.fragment,za),za.forEach(a),Va.forEach(a),At=f(mt),Te=i(mt,"SPAN",{});var Fa=o(Te);$t=l(Fa,"Overview"),Fa.forEach(a),mt.forEach(a),nt=f(t),R=i(t,"P",{});var Ia=o(R);J=i(Ia,"A",{href:!0,rel:!0});var Ha=o(J);xt=l(Ha,"Self-Attention Guidance"),Ha.forEach(a),kt=l(Ia," by Susung Hong et al."),Ia.forEach(a),it=f(t),he=i(t,"P",{});var Wa=o(he);Et=l(Wa,"The abstract of the paper is the following:"),Wa.forEach(a),ot=f(t),me=i(t,"P",{});var Ba=o(me);Ce=i(Ba,"EM",{});var Ka=o(Ce);Gt=l(Ka,"Denoising diffusion models (DDMs) have been drawing much attention for their appreciable sample quality and diversity. Despite their remarkable performance, DDMs remain black boxes on which further study is necessary to take a profound step. Motivated by this, we delve into the design of conventional U-shaped diffusion models. More specifically, we investigate the self-attention modules within these models through carefully designed experiments and explore their characteristics. In addition, inspired by the studies that substantiate the effectiveness of the guidance schemes, we present plug-and-play diffusion guidance, namely Self-Attention Guidance (SAG), that can drastically boost the performance of existing diffusion models. Our method, SAG, extracts the intermediate attention map from a diffusion model at every iteration and selects tokens above a certain attention score for masking and blurring to obtain a partially blurred input. Subsequently, we measure the dissimilarity between the predicted noises obtained from feeding the blurred and original input to the diffusion model and leverage it as guidance. With this guidance, we observe apparent improvements in a wide range of diffusion models, e.g., ADM, IDDPM, and Stable Diffusion, and show that the results further improve by combining our method with the conventional guidance scheme. We provide extensive ablation studies to verify our choices."),Ka.forEach(a),Ba.forEach(a),st=f(t),ge=i(t,"P",{});var Ra=o(ge);Tt=l(Ra,"Resources:"),Ra.forEach(a),rt=f(t),A=i(t,"UL",{});var B=o(A);_e=i(B,"LI",{});var Ma=o(_e);Q=i(Ma,"A",{href:!0,rel:!0});var Ja=o(Q);Ct=l(Ja,"Project Page"),Ja.forEach(a),It=l(Ma,"."),Ma.forEach(a),Mt=f(B),be=i(B,"LI",{});var La=o(be);Y=i(La,"A",{href:!0,rel:!0});var Qa=o(Y);Lt=l(Qa,"Paper"),Qa.forEach(a),Nt=l(La,"."),La.forEach(a),jt=f(B),ve=i(B,"LI",{});var Na=o(ve);X=i(Na,"A",{href:!0,rel:!0});var Ya=o(X);qt=l(Ya,"Original Code"),Ya.forEach(a),Ot=l(Na,"."),Na.forEach(a),Ut=f(B),Se=i(B,"LI",{});var ja=o(Se);Z=i(ja,"A",{href:!0,rel:!0});var Xa=o(Z);Vt=l(Xa,"Demo"),Xa.forEach(a),zt=l(ja,"."),ja.forEach(a),B.forEach(a),lt=f(t),T=i(t,"H2",{class:!0});var gt=o(T);O=i(gt,"A",{id:!0,class:!0,href:!0});var Za=o(O);Ie=i(Za,"SPAN",{});var en=o(Ie);S(ee.$$.fragment,en),en.forEach(a),Za.forEach(a),Ft=f(gt),Me=i(gt,"SPAN",{});var tn=o(Me);Ht=l(tn,"Available Pipelines:"),tn.forEach(a),gt.forEach(a),dt=f(t),U=i(t,"TABLE",{});var _t=o(U);Le=i(_t,"THEAD",{});var an=o(Le);C=i(an,"TR",{});var Pe=o(C);Ne=i(Pe,"TH",{});var nn=o(Ne);Wt=l(nn,"Pipeline"),nn.forEach(a),Bt=f(Pe),je=i(Pe,"TH",{});var on=o(je);Kt=l(on,"Tasks"),on.forEach(a),Rt=f(Pe),we=i(Pe,"TH",{align:!0});var sn=o(we);Jt=l(sn,"Demo"),sn.forEach(a),Pe.forEach(a),an.forEach(a),Qt=f(_t),qe=i(_t,"TBODY",{});var rn=o(qe);I=i(rn,"TR",{});var Ae=o(I);Oe=i(Ae,"TD",{});var ln=o(Oe);te=i(ln,"A",{href:!0,rel:!0});var dn=o(te);Yt=l(dn,"StableDiffusionSAGPipeline"),dn.forEach(a),ln.forEach(a),Xt=f(Ae),Ue=i(Ae,"TD",{});var fn=o(Ue);Ve=i(fn,"EM",{});var pn=o(Ve);Zt=l(pn,"Text-to-Image Generation"),pn.forEach(a),fn.forEach(a),ea=f(Ae),ye=i(Ae,"TD",{align:!0});var cn=o(ye);ae=i(cn,"A",{href:!0,rel:!0});var un=o(ae);ta=l(un,"Colab"),un.forEach(a),cn.forEach(a),Ae.forEach(a),rn.forEach(a),_t.forEach(a),ft=f(t),M=i(t,"H2",{class:!0});var bt=o(M);V=i(bt,"A",{id:!0,class:!0,href:!0});var hn=o(V);ze=i(hn,"SPAN",{});var mn=o(ze);S(ne.$$.fragment,mn),mn.forEach(a),hn.forEach(a),aa=f(bt),Fe=i(bt,"SPAN",{});var gn=o(Fe);na=l(gn,"Usage example"),gn.forEach(a),bt.forEach(a),pt=f(t),S(ie.$$.fragment,t),ct=f(t),L=i(t,"H2",{class:!0});var vt=o(L);z=i(vt,"A",{id:!0,class:!0,href:!0});var _n=o(z);He=i(_n,"SPAN",{});var bn=o(He);S(oe.$$.fragment,bn),bn.forEach(a),_n.forEach(a),ia=f(vt),We=i(vt,"SPAN",{});var vn=o(We);oa=l(vn,"StableDiffusionSAGPipeline"),vn.forEach(a),vt.forEach(a),ut=f(t),h=i(t,"DIV",{class:!0});var b=o(h);S(se.$$.fragment,b),sa=f(b),Be=i(b,"P",{});var Sn=o(Be);ra=l(Sn,"Pipeline for text-to-image generation using Stable Diffusion."),Sn.forEach(a),la=f(b),re=i(b,"P",{});var St=o(re);da=l(St,"This model inherits from "),De=i(St,"A",{href:!0});var wn=o(De);fa=l(wn,"DiffusionPipeline"),wn.forEach(a),pa=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),ca=f(b),k=i(b,"DIV",{class:!0});var $e=o(k);S(le.$$.fragment,$e),ua=f($e),Ke=i($e,"P",{});var yn=o(Ke);ha=l(yn,"Function invoked when calling the pipeline for generation."),yn.forEach(a),ma=f($e),S(F.$$.fragment,$e),$e.forEach(a),ga=f(b),H=i(b,"DIV",{class:!0});var wt=o(H);S(de.$$.fragment,wt),_a=f(wt),fe=i(wt,"P",{});var yt=o(fe);ba=l(yt,"Disable sliced VAE decoding. If "),Re=i(yt,"CODE",{});var Dn=o(Re);va=l(Dn,"enable_vae_slicing"),Dn.forEach(a),Sa=l(yt,` was previously invoked, this method will go back to
computing decoding in one step.`),yt.forEach(a),wt.forEach(a),wa=f(b),W=i(b,"DIV",{class:!0});var Dt=o(W);S(pe.$$.fragment,Dt),ya=f(Dt),N=i(Dt,"P",{});var xe=o(N);Da=l(xe,`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
`),Je=i(xe,"CODE",{});var Pn=o(Je);Pa=l(Pn,"torch.device('meta') and loaded to GPU only when their specific submodule has its "),Pn.forEach(a),Aa=l(xe,"forward"),Qe=i(xe,"CODE",{});var An=o(Qe);$a=l(An,"method called. Note that offloading happens on a submodule basis. Memory savings are higher than with"),An.forEach(a),xa=l(xe,"enable_model_cpu_offload`, but performance is lower."),xe.forEach(a),Dt.forEach(a),ka=f(b),E=i(b,"DIV",{class:!0});var ke=o(E);S(ce.$$.fragment,ke),Ea=f(ke),Ye=i(ke,"P",{});var $n=o(Ye);Ga=l($n,"Enable sliced VAE decoding."),$n.forEach(a),Ta=f(ke),Xe=i(ke,"P",{});var xn=o(Xe);Ca=l(xn,`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.`),xn.forEach(a),ke.forEach(a),b.forEach(a),this.h()},h(){s(m,"name","hf:doc:metadata"),s(m,"content",JSON.stringify(qn)),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(q,"id","overview"),s(q,"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(q,"href","#overview"),s(G,"class","relative group"),s(J,"href","https://arxiv.org/abs/2210.00939"),s(J,"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(Z,"href","https://colab.research.google.com/github/SusungHong/Self-Attention-Guidance/blob/main/SAG_Stable.ipynb"),s(Z,"rel","nofollow"),s(O,"id","available-pipelines"),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","#available-pipelines"),s(T,"class","relative group"),s(we,"align","center"),s(te,"href","https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py"),s(te,"rel","nofollow"),s(ae,"href","https://colab.research.google.com/github/SusungHong/Self-Attention-Guidance/blob/main/SAG_Stable.ipynb"),s(ae,"rel","nofollow"),s(ye,"align","center"),s(V,"id","usage-example"),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","#usage-example"),s(M,"class","relative group"),s(z,"id","diffusers.StableDiffusionSAGPipeline"),s(z,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),s(z,"href","#diffusers.StableDiffusionSAGPipeline"),s(L,"class","relative group"),s(De,"href","/docs/diffusers/main/en/api/diffusion_pipeline#diffusers.DiffusionPipeline"),s(k,"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"),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(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(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(_,Ee),e(Ee,Pt),c(t,at,p),c(t,G,p),e(G,q),e(q,Ge),w(K,Ge,null),e(G,At),e(G,Te),e(Te,$t),c(t,nt,p),c(t,R,p),e(R,J),e(J,xt),e(R,kt),c(t,it,p),c(t,he,p),e(he,Et),c(t,ot,p),c(t,me,p),e(me,Ce),e(Ce,Gt),c(t,st,p),c(t,ge,p),e(ge,Tt),c(t,rt,p),c(t,A,p),e(A,_e),e(_e,Q),e(Q,Ct),e(_e,It),e(A,Mt),e(A,be),e(be,Y),e(Y,Lt),e(be,Nt),e(A,jt),e(A,ve),e(ve,X),e(X,qt),e(ve,Ot),e(A,Ut),e(A,Se),e(Se,Z),e(Z,Vt),e(Se,zt),c(t,lt,p),c(t,T,p),e(T,O),e(O,Ie),w(ee,Ie,null),e(T,Ft),e(T,Me),e(Me,Ht),c(t,dt,p),c(t,U,p),e(U,Le),e(Le,C),e(C,Ne),e(Ne,Wt),e(C,Bt),e(C,je),e(je,Kt),e(C,Rt),e(C,we),e(we,Jt),e(U,Qt),e(U,qe),e(qe,I),e(I,Oe),e(Oe,te),e(te,Yt),e(I,Xt),e(I,Ue),e(Ue,Ve),e(Ve,Zt),e(I,ea),e(I,ye),e(ye,ae),e(ae,ta),c(t,ft,p),c(t,M,p),e(M,V),e(V,ze),w(ne,ze,null),e(M,aa),e(M,Fe),e(Fe,na),c(t,pt,p),w(ie,t,p),c(t,ct,p),c(t,L,p),e(L,z),e(z,He),w(oe,He,null),e(L,ia),e(L,We),e(We,oa),c(t,ut,p),c(t,h,p),w(se,h,null),e(h,sa),e(h,Be),e(Be,ra),e(h,la),e(h,re),e(re,da),e(re,De),e(De,fa),e(re,pa),e(h,ca),e(h,k),w(le,k,null),e(k,ua),e(k,Ke),e(Ke,ha),e(k,ma),w(F,k,null),e(h,ga),e(h,H),w(de,H,null),e(H,_a),e(H,fe),e(fe,ba),e(fe,Re),e(Re,va),e(fe,Sa),e(h,wa),e(h,W),w(pe,W,null),e(W,ya),e(W,N),e(N,Da),e(N,Je),e(Je,Pa),e(N,Aa),e(N,Qe),e(Qe,$a),e(N,xa),e(h,ka),e(h,E),w(ce,E,null),e(E,Ea),e(E,Ye),e(Ye,Ga),e(E,Ta),e(E,Xe),e(Xe,Ca),ht=!0},p(t,[p]){const ue={};p&2&&(ue.$$scope={dirty:p,ctx:t}),F.$set(ue)},i(t){ht||(y(u.$$.fragment,t),y(K.$$.fragment,t),y(ee.$$.fragment,t),y(ne.$$.fragment,t),y(ie.$$.fragment,t),y(oe.$$.fragment,t),y(se.$$.fragment,t),y(le.$$.fragment,t),y(F.$$.fragment,t),y(de.$$.fragment,t),y(pe.$$.fragment,t),y(ce.$$.fragment,t),ht=!0)},o(t){D(u.$$.fragment,t),D(K.$$.fragment,t),D(ee.$$.fragment,t),D(ne.$$.fragment,t),D(ie.$$.fragment,t),D(oe.$$.fragment,t),D(se.$$.fragment,t),D(le.$$.fragment,t),D(F.$$.fragment,t),D(de.$$.fragment,t),D(pe.$$.fragment,t),D(ce.$$.fragment,t),ht=!1},d(t){a(m),t&&a(j),t&&a(_),P(u),t&&a(at),t&&a(G),P(K),t&&a(nt),t&&a(R),t&&a(it),t&&a(he),t&&a(ot),t&&a(me),t&&a(st),t&&a(ge),t&&a(rt),t&&a(A),t&&a(lt),t&&a(T),P(ee),t&&a(dt),t&&a(U),t&&a(ft),t&&a(M),P(ne),t&&a(pt),P(ie,t),t&&a(ct),t&&a(L),P(oe),t&&a(ut),t&&a(h),P(se),P(le),P(F),P(de),P(pe),P(ce)}}}const qn={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 On(tt){return In(()=>{new URLSearchParams(window.location.search).get("fw")}),[]}class Wn extends En{constructor(m){super();Gn(this,m,On,jn,Tn,{})}}export{Wn as default,qn as metadata};
