import{S as ur,i as wr,s as yr,e as i,k as h,w as m,t as s,M as br,c as n,d as t,m as f,a as r,x as d,h as o,b as c,N as dr,G as l,g as p,y as u,L as vr,q as w,o as y,B as b,v as Mr}from"../../chunks/vendor-hf-doc-builder.js";import{I as ce}from"../../chunks/IconCopyLink-hf-doc-builder.js";import{C as v}from"../../chunks/CodeBlock-hf-doc-builder.js";import{D as gr}from"../../chunks/DocNotebookDropdown-hf-doc-builder.js";function jr(xi){let G,Jl,Z,V,bt,me,ls,vt,as,Tl,de,$l,U,ss,ue,os,is,Mt,ns,rs,_l,N,ps,we,hs,fs,kl,j,cs,gt,ms,ds,jt,us,ws,Jt,ys,bs,Ul,Oe,vs,El,x,Y,Tt,ye,Ms,$t,gs,Il,Ke,js,Bl,be,Wl,ve,Cl,Me,Gl,ge,Zl,et,Js,xl,je,Xl,X,H,_t,Je,Ts,kt,$s,Fl,E,_s,Ut,ks,Us,Et,Es,Is,Al,Te,zl,D,Bs,It,Ws,Cs,Pl,$e,Sl,F,Q,Bt,_e,Gs,Wt,Zs,Vl,tt,xs,Nl,R,Xs,Ct,Fs,As,Yl,ke,Hl,Ue,Dl,A,L,Gt,Ee,zs,Zt,Ps,Ql,I,Ss,xt,Vs,Ns,Xt,Ys,Hs,Rl,Ie,Ll,Be,ql,We,Ol,M,Ds,Ft,Qs,Rs,At,Ls,qs,zt,Os,Ks,Pt,eo,to,St,lo,ao,Kl,lt,so,ea,at,oo,ta,Ce,la,st,io,aa,Ge,sa,ot,no,oa,q,ro,Vt,po,ho,ia,O,fo,Nt,Yt,co,mo,na,Ze,ra,xe,pa,B,uo,Ht,wo,yo,Dt,bo,vo,ha,Xe,fa,z,K,Qt,Fe,Mo,Rt,go,ca,Ae,ma,it,nt,Xi,da,P,ee,Lt,ze,jo,qt,Jo,ua,te,To,Ot,$o,_o,wa,rt,ko,ya,Pe,ba,Se,va,pt,ht,Fi,Ma,S,le,Kt,Ve,Uo,el,Eo,ga,ae,Io,tl,Bo,Wo,ja,J,Co,ll,Go,Zo,Ne,xo,Xo,se,al,Fo,Ao,zo,Ja,Ye,sl,Po,So,Ta,oe,k,Vo,ol,No,Yo,il,Ho,Do,nl,Qo,Ro,Lo,rl,qo,$a,T,Oo,pl,Ko,ei,hl,ti,li,fl,ai,si,_a,He,ka,W,oi,cl,ii,ni,ml,ri,pi,Ua,ie,De,hi,dl,fi,ci,mi,g,di,ul,ui,wi,wl,yi,bi,yl,vi,Mi,bl,gi,ji,vl,Ji,Ti,Ea,C,$i,Ml,_i,ki,gl,Ui,Ei,Ia,ft,Ii,Ba,Qe,Wa,Re,Ca,Le,Ga,qe,Za,ne,Bi,jl,Wi,Ci,xa;return me=new ce({}),de=new gr({props:{classNames:"absolute z-10 right-0 top-0",options:[{label:"Mixed",value:"https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers_doc/en/stable_diffusion_jax_how_to.ipynb"},{label:"PyTorch",value:"https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers_doc/en/pytorch/stable_diffusion_jax_how_to.ipynb"},{label:"TensorFlow",value:"https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers_doc/en/tensorflow/stable_diffusion_jax_how_to.ipynb"},{label:"Mixed",value:"https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/diffusers_doc/en/stable_diffusion_jax_how_to.ipynb"},{label:"PyTorch",value:"https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/diffusers_doc/en/pytorch/stable_diffusion_jax_how_to.ipynb"},{label:"TensorFlow",value:"https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/diffusers_doc/en/tensorflow/stable_diffusion_jax_how_to.ipynb"}]}}),ye=new ce({}),be=new v({props:{code:"JTIzJTIwdW5jb21tZW50JTIwdG8lMjBpbnN0YWxsJTIwdGhlJTIwbmVjZXNzYXJ5JTIwbGlicmFyaWVzJTIwaW4lMjBDb2xhYiUwQSUyMyFwaXAlMjBpbnN0YWxsJTIwamF4JTNEJTNEMC4zLjI1JTIwamF4bGliJTNEJTNEMC4zLjI1JTIwZmxheCUyMHRyYW5zZm9ybWVycyUyMGZ0ZnklMEElMjMhcGlwJTIwaW5zdGFsbCUyMGRpZmZ1c2Vycw==",highlighted:`<span class="hljs-comment"># uncomment to install the necessary libraries in Colab</span>
<span class="hljs-comment">#!pip install jax==0.3.25 jaxlib==0.3.25 flax transformers ftfy</span>
<span class="hljs-comment">#!pip install diffusers</span>`}}),ve=new v({props:{code:"aW1wb3J0JTIwamF4LnRvb2xzLmNvbGFiX3RwdSUwQSUwQWpheC50b29scy5jb2xhYl90cHUuc2V0dXBfdHB1KCklMEFpbXBvcnQlMjBqYXg=",highlighted:`<span class="hljs-keyword">import</span> jax.tools.colab_tpu

jax.tools.colab_tpu.setup_tpu()
<span class="hljs-keyword">import</span> jax`}}),Me=new v({props:{code:"bnVtX2RldmljZXMlMjAlM0QlMjBqYXguZGV2aWNlX2NvdW50KCklMEFkZXZpY2VfdHlwZSUyMCUzRCUyMGpheC5kZXZpY2VzKCklNUIwJTVELmRldmljZV9raW5kJTBBJTBBcHJpbnQoZiUyMkZvdW5kJTIwJTdCbnVtX2RldmljZXMlN0QlMjBKQVglMjBkZXZpY2VzJTIwb2YlMjB0eXBlJTIwJTdCZGV2aWNlX3R5cGUlN0QuJTIyKSUwQWFzc2VydCUyMCglMEElMjAlMjAlMjAlMjAlMjJUUFUlMjIlMjBpbiUyMGRldmljZV90eXBlJTBBKSUyQyUyMCUyMkF2YWlsYWJsZSUyMGRldmljZSUyMGlzJTIwbm90JTIwYSUyMFRQVSUyQyUyMHBsZWFzZSUyMHNlbGVjdCUyMFRQVSUyMGZyb20lMjBFZGl0JTIwJTNFJTIwTm90ZWJvb2slMjBzZXR0aW5ncyUyMCUzRSUyMEhhcmR3YXJlJTIwYWNjZWxlcmF0b3IlMjI=",highlighted:`num_devices = jax.device_count()
device_type = jax.devices()[<span class="hljs-number">0</span>].device_kind

<span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;Found <span class="hljs-subst">{num_devices}</span> JAX devices of type <span class="hljs-subst">{device_type}</span>.&quot;</span>)
<span class="hljs-keyword">assert</span> (
    <span class="hljs-string">&quot;TPU&quot;</span> <span class="hljs-keyword">in</span> device_type
), <span class="hljs-string">&quot;Available device is not a TPU, please select TPU from Edit &gt; Notebook settings &gt; Hardware accelerator&quot;</span>`}}),ge=new v({props:{code:"Rm91bmQlMjA4JTIwSkFYJTIwZGV2aWNlcyUyMG9mJTIwdHlwZSUyMENsb3VkJTIwVFBVLg==",highlighted:'Found <span class="hljs-number">8</span> JAX devices of <span class="hljs-built_in">type</span> Cloud TPU.'}}),je=new v({props:{code:"aW1wb3J0JTIwbnVtcHklMjBhcyUyMG5wJTBBaW1wb3J0JTIwamF4JTBBaW1wb3J0JTIwamF4Lm51bXB5JTIwYXMlMjBqbnAlMEElMEFmcm9tJTIwcGF0aGxpYiUyMGltcG9ydCUyMFBhdGglMEFmcm9tJTIwamF4JTIwaW1wb3J0JTIwcG1hcCUwQWZyb20lMjBmbGF4LmpheF91dGlscyUyMGltcG9ydCUyMHJlcGxpY2F0ZSUwQWZyb20lMjBmbGF4LnRyYWluaW5nLmNvbW1vbl91dGlscyUyMGltcG9ydCUyMHNoYXJkJTBBZnJvbSUyMFBJTCUyMGltcG9ydCUyMEltYWdlJTBBJTBBZnJvbSUyMGh1Z2dpbmdmYWNlX2h1YiUyMGltcG9ydCUyMG5vdGVib29rX2xvZ2luJTBBZnJvbSUyMGRpZmZ1c2VycyUyMGltcG9ydCUyMEZsYXhTdGFibGVEaWZmdXNpb25QaXBlbGluZQ==",highlighted:`<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">import</span> jax
<span class="hljs-keyword">import</span> jax.numpy <span class="hljs-keyword">as</span> jnp

<span class="hljs-keyword">from</span> pathlib <span class="hljs-keyword">import</span> Path
<span class="hljs-keyword">from</span> jax <span class="hljs-keyword">import</span> pmap
<span class="hljs-keyword">from</span> flax.jax_utils <span class="hljs-keyword">import</span> replicate
<span class="hljs-keyword">from</span> flax.training.common_utils <span class="hljs-keyword">import</span> shard
<span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image

<span class="hljs-keyword">from</span> huggingface_hub <span class="hljs-keyword">import</span> notebook_login
<span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> FlaxStableDiffusionPipeline`}}),Je=new ce({}),Te=new v({props:{code:"ZHR5cGUlMjAlM0QlMjBqbnAuYmZsb2F0MTY=",highlighted:"dtype = jnp.bfloat16"}}),$e=new v({props:{code:"cGlwZWxpbmUlMkMlMjBwYXJhbXMlMjAlM0QlMjBGbGF4U3RhYmxlRGlmZnVzaW9uUGlwZWxpbmUuZnJvbV9wcmV0cmFpbmVkKCUwQSUyMCUyMCUyMCUyMCUyMkNvbXBWaXMlMkZzdGFibGUtZGlmZnVzaW9uLXYxLTQlMjIlMkMlMEElMjAlMjAlMjAlMjByZXZpc2lvbiUzRCUyMmJmMTYlMjIlMkMlMEElMjAlMjAlMjAlMjBkdHlwZSUzRGR0eXBlJTJDJTBBKQ==",highlighted:`pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
    <span class="hljs-string">&quot;CompVis/stable-diffusion-v1-4&quot;</span>,
    revision=<span class="hljs-string">&quot;bf16&quot;</span>,
    dtype=dtype,
)`}}),_e=new ce({}),ke=new v({props:{code:"cHJvbXB0JTIwJTNEJTIwJTIyQSUyMGNpbmVtYXRpYyUyMGZpbG0lMjBzdGlsbCUyMG9mJTIwTW9yZ2FuJTIwRnJlZW1hbiUyMHN0YXJyaW5nJTIwYXMlMjBKaW1pJTIwSGVuZHJpeCUyQyUyMHBvcnRyYWl0JTJDJTIwNDBtbSUyMGxlbnMlMkMlMjBzaGFsbG93JTIwZGVwdGglMjBvZiUyMGZpZWxkJTJDJTIwY2xvc2UlMjB1cCUyQyUyMHNwbGl0JTIwbGlnaHRpbmclMkMlMjBjaW5lbWF0aWMlMjIlMEFwcm9tcHQlMjAlM0QlMjAlNUJwcm9tcHQlNUQlMjAqJTIwamF4LmRldmljZV9jb3VudCgpJTBBcHJvbXB0X2lkcyUyMCUzRCUyMHBpcGVsaW5lLnByZXBhcmVfaW5wdXRzKHByb21wdCklMEFwcm9tcHRfaWRzLnNoYXBl",highlighted:`prompt = <span class="hljs-string">&quot;A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of field, close up, split lighting, cinematic&quot;</span>
prompt = [prompt] * jax.device_count()
prompt_ids = pipeline.prepare_inputs(prompt)
prompt_ids.shape`}}),Ue=new v({props:{code:"KDglMkMlMjA3Nyk=",highlighted:'(<span class="hljs-number">8</span>, <span class="hljs-number">77</span>)'}}),Ee=new ce({}),Ie=new v({props:{code:"cF9wYXJhbXMlMjAlM0QlMjByZXBsaWNhdGUocGFyYW1zKQ==",highlighted:"p_params = replicate(params)"}}),Be=new v({props:{code:"cHJvbXB0X2lkcyUyMCUzRCUyMHNoYXJkKHByb21wdF9pZHMpJTBBcHJvbXB0X2lkcy5zaGFwZQ==",highlighted:`prompt_ids = shard(prompt_ids)
prompt_ids.shape`}}),We=new v({props:{code:"KDglMkMlMjAxJTJDJTIwNzcp",highlighted:'(<span class="hljs-number">8</span>, <span class="hljs-number">1</span>, <span class="hljs-number">77</span>)'}}),Ce=new v({props:{code:"ZGVmJTIwY3JlYXRlX2tleShzZWVkJTNEMCklM0ElMEElMjAlMjAlMjAlMjByZXR1cm4lMjBqYXgucmFuZG9tLlBSTkdLZXkoc2VlZCk=",highlighted:`<span class="hljs-keyword">def</span> <span class="hljs-title function_">create_key</span>(<span class="hljs-params">seed=<span class="hljs-number">0</span></span>):
    <span class="hljs-keyword">return</span> jax.random.PRNGKey(seed)`}}),Ge=new v({props:{code:"cm5nJTIwJTNEJTIwY3JlYXRlX2tleSgwKSUwQXJuZyUyMCUzRCUyMGpheC5yYW5kb20uc3BsaXQocm5nJTJDJTIwamF4LmRldmljZV9jb3VudCgpKQ==",highlighted:`rng = create_key(<span class="hljs-number">0</span>)
rng = jax.random.split(rng, jax.device_count())`}}),Ze=new v({props:{code:"JTI1JTI1dGltZSUwQWltYWdlcyUyMCUzRCUyMHBpcGVsaW5lKHByb21wdF9pZHMlMkMlMjBwX3BhcmFtcyUyQyUyMHJuZyUyQyUyMGppdCUzRFRydWUpJTVCMCU1RA==",highlighted:`%%time
images = pipeline(prompt_ids, p_params, rng, <span class="hljs-attribute">jit</span>=<span class="hljs-literal">True</span>)[0]`}}),xe=new v({props:{code:"Q1BVJTIwdGltZXMlM0ElMjB1c2VyJTIwNTYuMiUyMHMlMkMlMjBzeXMlM0ElMjA0Mi41JTIwcyUyQyUyMHRvdGFsJTNBJTIwMW1pbiUyMDM4cyUwQVdhbGwlMjB0aW1lJTNBJTIwMW1pbiUyMDI5cw==",highlighted:`CPU times: user <span class="hljs-number">56.2</span> s, sys: <span class="hljs-number">42.5</span> s, total: 1<span class="hljs-built_in">min</span> 38s
Wall time: 1<span class="hljs-built_in">min</span> 29s`}}),Xe=new v({props:{code:"aW1hZ2VzJTIwJTNEJTIwaW1hZ2VzLnJlc2hhcGUoKGltYWdlcy5zaGFwZSU1QjAlNUQlMjAqJTIwaW1hZ2VzLnNoYXBlJTVCMSU1RCUyQyklMjAlMkIlMjBpbWFnZXMuc2hhcGUlNUItMyUzQSU1RCklMEFpbWFnZXMlMjAlM0QlMjBwaXBlbGluZS5udW1weV90b19waWwoaW1hZ2VzKQ==",highlighted:`images = images.reshape((images.shape[<span class="hljs-number">0</span>] * images.shape[<span class="hljs-number">1</span>],) + images.shape[-<span class="hljs-number">3</span>:])
images = pipeline.numpy_to_pil(images)`}}),Fe=new ce({}),Ae=new v({props:{code:"ZnJvbSUyMGRpZmZ1c2VycyUyMGltcG9ydCUyMG1ha2VfaW1hZ2VfZ3JpZCUwQSUwQW1ha2VfaW1hZ2VfZ3JpZChpbWFnZXMlMkMlMjAyJTJDJTIwNCk=",highlighted:`<span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> make_image_grid

make_image_grid(images, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>)`}}),ze=new ce({}),Pe=new v({props:{code:"cHJvbXB0cyUyMCUzRCUyMCU1QiUwQSUyMCUyMCUyMCUyMCUyMkxhYnJhZG9yJTIwaW4lMjB0aGUlMjBzdHlsZSUyMG9mJTIwSG9rdXNhaSUyMiUyQyUwQSUyMCUyMCUyMCUyMCUyMlBhaW50aW5nJTIwb2YlMjBhJTIwc3F1aXJyZWwlMjBza2F0aW5nJTIwaW4lMjBOZXclMjBZb3JrJTIyJTJDJTBBJTIwJTIwJTIwJTIwJTIySEFMLTkwMDAlMjBpbiUyMHRoZSUyMHN0eWxlJTIwb2YlMjBWYW4lMjBHb2doJTIyJTJDJTBBJTIwJTIwJTIwJTIwJTIyVGltZXMlMjBTcXVhcmUlMjB1bmRlciUyMHdhdGVyJTJDJTIwd2l0aCUyMGZpc2glMjBhbmQlMjBhJTIwZG9scGhpbiUyMHN3aW1taW5nJTIwYXJvdW5kJTIyJTJDJTBBJTIwJTIwJTIwJTIwJTIyQW5jaWVudCUyMFJvbWFuJTIwZnJlc2NvJTIwc2hvd2luZyUyMGElMjBtYW4lMjB3b3JraW5nJTIwb24lMjBoaXMlMjBsYXB0b3AlMjIlMkMlMEElMjAlMjAlMjAlMjAlMjJDbG9zZS11cCUyMHBob3RvZ3JhcGglMjBvZiUyMHlvdW5nJTIwYmxhY2slMjB3b21hbiUyMGFnYWluc3QlMjB1cmJhbiUyMGJhY2tncm91bmQlMkMlMjBoaWdoJTIwcXVhbGl0eSUyQyUyMGJva2VoJTIyJTJDJTBBJTIwJTIwJTIwJTIwJTIyQXJtY2hhaXIlMjBpbiUyMHRoZSUyMHNoYXBlJTIwb2YlMjBhbiUyMGF2b2NhZG8lMjIlMkMlMEElMjAlMjAlMjAlMjAlMjJDbG93biUyMGFzdHJvbmF1dCUyMGluJTIwc3BhY2UlMkMlMjB3aXRoJTIwRWFydGglMjBpbiUyMHRoZSUyMGJhY2tncm91bmQlMjIlMkMlMEElNUQ=",highlighted:`prompts = [
    <span class="hljs-string">&quot;Labrador in the style of Hokusai&quot;</span>,
    <span class="hljs-string">&quot;Painting of a squirrel skating in New York&quot;</span>,
    <span class="hljs-string">&quot;HAL-9000 in the style of Van Gogh&quot;</span>,
    <span class="hljs-string">&quot;Times Square under water, with fish and a dolphin swimming around&quot;</span>,
    <span class="hljs-string">&quot;Ancient Roman fresco showing a man working on his laptop&quot;</span>,
    <span class="hljs-string">&quot;Close-up photograph of young black woman against urban background, high quality, bokeh&quot;</span>,
    <span class="hljs-string">&quot;Armchair in the shape of an avocado&quot;</span>,
    <span class="hljs-string">&quot;Clown astronaut in space, with Earth in the background&quot;</span>,
]`}}),Se=new v({props:{code:"cHJvbXB0X2lkcyUyMCUzRCUyMHBpcGVsaW5lLnByZXBhcmVfaW5wdXRzKHByb21wdHMpJTBBcHJvbXB0X2lkcyUyMCUzRCUyMHNoYXJkKHByb21wdF9pZHMpJTBBJTBBaW1hZ2VzJTIwJTNEJTIwcGlwZWxpbmUocHJvbXB0X2lkcyUyQyUyMHBfcGFyYW1zJTJDJTIwcm5nJTJDJTIwaml0JTNEVHJ1ZSkuaW1hZ2VzJTBBaW1hZ2VzJTIwJTNEJTIwaW1hZ2VzLnJlc2hhcGUoKGltYWdlcy5zaGFwZSU1QjAlNUQlMjAqJTIwaW1hZ2VzLnNoYXBlJTVCMSU1RCUyQyklMjAlMkIlMjBpbWFnZXMuc2hhcGUlNUItMyUzQSU1RCklMEFpbWFnZXMlMjAlM0QlMjBwaXBlbGluZS5udW1weV90b19waWwoaW1hZ2VzKSUwQSUwQW1ha2VfaW1hZ2VfZ3JpZChpbWFnZXMlMkMlMjAyJTJDJTIwNCk=",highlighted:`prompt_ids = pipeline.prepare_inputs(prompts)
prompt_ids = shard(prompt_ids)

images = pipeline(prompt_ids, p_params, rng, jit=<span class="hljs-literal">True</span>).images
images = images.reshape((images.shape[<span class="hljs-number">0</span>] * images.shape[<span class="hljs-number">1</span>],) + images.shape[-<span class="hljs-number">3</span>:])
images = pipeline.numpy_to_pil(images)

make_image_grid(images, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>)`}}),Ve=new ce({}),He=new v({props:{code:"cF9nZW5lcmF0ZSUyMCUzRCUyMHBtYXAocGlwZWxpbmUuX2dlbmVyYXRlKQ==",highlighted:"p_generate = pmap(pipeline._generate)"}}),Qe=new v({props:{code:"JTI1JTI1dGltZSUwQWltYWdlcyUyMCUzRCUyMHBfZ2VuZXJhdGUocHJvbXB0X2lkcyUyQyUyMHBfcGFyYW1zJTJDJTIwcm5nKSUwQWltYWdlcyUyMCUzRCUyMGltYWdlcy5ibG9ja191bnRpbF9yZWFkeSgpJTBBaW1hZ2VzLnNoYXBl",highlighted:`%%time
images = p<span class="hljs-constructor">_generate(<span class="hljs-params">prompt_ids</span>, <span class="hljs-params">p_params</span>, <span class="hljs-params">rng</span>)</span>
images = images.block<span class="hljs-constructor">_until_ready()</span>
images.shape`}}),Re=new v({props:{code:"Q1BVJTIwdGltZXMlM0ElMjB1c2VyJTIwMW1pbiUyMDE1cyUyQyUyMHN5cyUzQSUyMDE4LjIlMjBzJTJDJTIwdG90YWwlM0ElMjAxbWluJTIwMzRzJTBBV2FsbCUyMHRpbWUlM0ElMjAxbWluJTIwMTVz",highlighted:`CPU times: user 1<span class="hljs-built_in">min</span> 15s, sys: <span class="hljs-number">18.2</span> s, total: 1<span class="hljs-built_in">min</span> 34s
Wall time: 1<span class="hljs-built_in">min</span> 15s`}}),Le=new v({props:{code:"aW1hZ2VzLnNoYXBl",highlighted:"images.shape"}}),qe=new v({props:{code:"KDglMkMlMjAxJTJDJTIwNTEyJTJDJTIwNTEyJTJDJTIwMyk=",highlighted:'(<span class="hljs-number">8</span>, <span class="hljs-number">1</span>, <span class="hljs-number">512</span>, <span class="hljs-number">512</span>, <span class="hljs-number">3</span>)'}}),{c(){G=i("meta"),Jl=h(),Z=i("h1"),V=i("a"),bt=i("span"),m(me.$$.fragment),ls=h(),vt=i("span"),as=s("\u{1F9E8} Stable Diffusion in JAX / Flax !"),Tl=h(),m(de.$$.fragment),$l=h(),U=i("p"),ss=s("\u{1F917} Hugging Face "),ue=i("a"),os=s("Diffusers"),is=s(" supports Flax since version "),Mt=i("code"),ns=s("0.5.1"),rs=s("! This allows for super fast inference on Google TPUs, such as those available in Colab, Kaggle or Google Cloud Platform."),_l=h(),N=i("p"),ps=s("This notebook shows how to run inference using JAX / Flax. If you want more details about how Stable Diffusion works or want to run it in GPU, please refer to "),we=i("a"),hs=s("this notebook"),fs=s("."),kl=h(),j=i("p"),cs=s("First, make sure you are using a TPU backend. If you are running this notebook in Colab, select "),gt=i("code"),ms=s("Runtime"),ds=s(" in the menu above, then select the option \u201CChange runtime type\u201D and then select "),jt=i("code"),us=s("TPU"),ws=s(" under the "),Jt=i("code"),ys=s("Hardware accelerator"),bs=s(" setting."),Ul=h(),Oe=i("p"),vs=s("Note that JAX is not exclusive to TPUs, but it shines on that hardware because each TPU server has 8 TPU accelerators working in parallel."),El=h(),x=i("h2"),Y=i("a"),Tt=i("span"),m(ye.$$.fragment),Ms=h(),$t=i("span"),gs=s("Setup"),Il=h(),Ke=i("p"),js=s("First make sure diffusers is installed."),Bl=h(),m(be.$$.fragment),Wl=h(),m(ve.$$.fragment),Cl=h(),m(Me.$$.fragment),Gl=h(),m(ge.$$.fragment),Zl=h(),et=i("p"),Js=s("Then we import all the dependencies."),xl=h(),m(je.$$.fragment),Xl=h(),X=i("h2"),H=i("a"),_t=i("span"),m(Je.$$.fragment),Ts=h(),kt=i("span"),$s=s("Model Loading"),Fl=h(),E=i("p"),_s=s("TPU devices support "),Ut=i("code"),ks=s("bfloat16"),Us=s(", an efficient half-float type. We\u2019ll use it for our tests, but you can also use "),Et=i("code"),Es=s("float32"),Is=s(" to use full precision instead."),Al=h(),m(Te.$$.fragment),zl=h(),D=i("p"),Bs=s("Flax is a functional framework, so models are stateless and parameters are stored outside them. Loading the pre-trained Flax pipeline will return both the pipeline itself and the model weights (or parameters). We are using a "),It=i("code"),Ws=s("bf16"),Cs=s(" version of the weights, which leads to type warnings that you can safely ignore."),Pl=h(),m($e.$$.fragment),Sl=h(),F=i("h2"),Q=i("a"),Bt=i("span"),m(_e.$$.fragment),Gs=h(),Wt=i("span"),Zs=s("Inference"),Vl=h(),tt=i("p"),xs=s("Since TPUs usually have 8 devices working in parallel, we\u2019ll replicate our prompt as many times as devices we have. Then we\u2019ll perform inference on the 8 devices at once, each responsible for generating one image. Thus, we\u2019ll get 8 images in the same amount of time it takes for one chip to generate a single one."),Nl=h(),R=i("p"),Xs=s("After replicating the prompt, we obtain the tokenized text ids by invoking the "),Ct=i("code"),Fs=s("prepare_inputs"),As=s(" function of the pipeline. The length of the tokenized text is set to 77 tokens, as required by the configuration of the underlying CLIP Text model."),Yl=h(),m(ke.$$.fragment),Hl=h(),m(Ue.$$.fragment),Dl=h(),A=i("h3"),L=i("a"),Gt=i("span"),m(Ee.$$.fragment),zs=h(),Zt=i("span"),Ps=s("Replication and parallelization"),Ql=h(),I=i("p"),Ss=s("Model parameters and inputs have to be replicated across the 8 parallel devices we have. The parameters dictionary is replicated using "),xt=i("code"),Vs=s("flax.jax_utils.replicate"),Ns=s(", which traverses the dictionary and changes the shape of the weights so they are repeated 8 times. Arrays are replicated using "),Xt=i("code"),Ys=s("shard"),Hs=s("."),Rl=h(),m(Ie.$$.fragment),Ll=h(),m(Be.$$.fragment),ql=h(),m(We.$$.fragment),Ol=h(),M=i("p"),Ds=s("That shape means that each one of the "),Ft=i("code"),Qs=s("8"),Rs=s(" devices will receive as an input a "),At=i("code"),Ls=s("jnp"),qs=s(" array with shape "),zt=i("code"),Os=s("(1, 77)"),Ks=s(". "),Pt=i("code"),eo=s("1"),to=s(" is therefore the batch size per device. In TPUs with sufficient memory, it could be larger than "),St=i("code"),lo=s("1"),ao=s(" if we wanted to generate multiple images (per chip) at once."),Kl=h(),lt=i("p"),so=s("We are almost ready to generate images! We just need to create a random number generator to pass to the generation function. This is the standard procedure in Flax, which is very serious and opinionated about random numbers \u2013 all functions that deal with random numbers are expected to receive a generator. This ensures reproducibility, even when we are training across multiple distributed devices."),ea=h(),at=i("p"),oo=s("The helper function below uses a seed to initialize a random number generator. As long as we use the same seed, we\u2019ll get the exact same results. Feel free to use different seeds when exploring results later in the notebook."),ta=h(),m(Ce.$$.fragment),la=h(),st=i("p"),io=s("We obtain a rng and then \u201Csplit\u201D it 8 times so each device receives a different generator. Therefore, each device will create a different image, and the full process is reproducible."),aa=h(),m(Ge.$$.fragment),sa=h(),ot=i("p"),no=s("JAX code can be compiled to an efficient representation that runs very fast. However, we need to ensure that all inputs have the same shape in subsequent calls; otherwise, JAX will have to recompile the code, and we wouldn\u2019t be able to take advantage of the optimized speed."),oa=h(),q=i("p"),ro=s("The Flax pipeline can compile the code for us if we pass "),Vt=i("code"),po=s("jit = True"),ho=s(" as an argument. It will also ensure that the model runs in parallel in the 8 available devices."),ia=h(),O=i("p"),fo=s("The first time we run the following cell it will take a long time to compile, but subequent calls (even with different inputs) will be much faster. For example, it took more than a minute to compile in a TPU v2-8 when I tested, but then it takes about "),Nt=i("strong"),Yt=i("code"),co=s("7s"),mo=s(" for future inference runs."),na=h(),m(Ze.$$.fragment),ra=h(),m(xe.$$.fragment),pa=h(),B=i("p"),uo=s("The returned array has shape "),Ht=i("code"),wo=s("(8, 1, 512, 512, 3)"),yo=s(". We reshape it to get rid of the second dimension and obtain 8 images of "),Dt=i("code"),bo=s("512 \xD7 512 \xD7 3"),vo=s(" and then convert them to PIL."),ha=h(),m(Xe.$$.fragment),fa=h(),z=i("h3"),K=i("a"),Qt=i("span"),m(Fe.$$.fragment),Mo=h(),Rt=i("span"),go=s("Visualization"),ca=h(),m(Ae.$$.fragment),ma=h(),it=i("p"),nt=i("img"),da=h(),P=i("h2"),ee=i("a"),Lt=i("span"),m(ze.$$.fragment),jo=h(),qt=i("span"),Jo=s("Using different prompts"),ua=h(),te=i("p"),To=s("We don\u2019t have to replicate the "),Ot=i("em"),$o=s("same"),_o=s(" prompt in all the devices. We can do whatever we want: generate 2 prompts 4 times each, or even generate 8 different prompts at once. Let\u2019s do that!"),wa=h(),rt=i("p"),ko=s("First, we\u2019ll refactor the input preparation code into a handy function:"),ya=h(),m(Pe.$$.fragment),ba=h(),m(Se.$$.fragment),va=h(),pt=i("p"),ht=i("img"),Ma=h(),S=i("h2"),le=i("a"),Kt=i("span"),m(Ve.$$.fragment),Uo=h(),el=i("span"),Eo=s("How does parallelization work?"),ga=h(),ae=i("p"),Io=s("We said before that the "),tl=i("code"),Bo=s("diffusers"),Wo=s(" Flax pipeline automatically compiles the model and runs it in parallel on all available devices. We\u2019ll now briefly look inside that process to show how it works."),ja=h(),J=i("p"),Co=s("JAX parallelization can be done in multiple ways. The easiest one revolves around using the "),ll=i("code"),Go=s("jax.pmap"),Zo=s(" function to achieve single-program, multiple-data (SPMD) parallelization. It means we\u2019ll run several copies of the same code, each on different data inputs. More sophisticated approaches are possible, we invite you to go over the "),Ne=i("a"),xo=s("JAX documentation"),Xo=s(" and the "),se=i("a"),al=i("code"),Fo=s("pjit"),Ao=s(" pages"),zo=s(" to explore this topic if you are interested!"),Ja=h(),Ye=i("p"),sl=i("code"),Po=s("jax.pmap"),So=s(" does two things for us:"),Ta=h(),oe=i("ul"),k=i("li"),Vo=s("Compiles (or "),ol=i("code"),No=s("jit"),Yo=s("s) the code, as if we had invoked "),il=i("code"),Ho=s("jax.jit()"),Do=s(". This does not happen when we call "),nl=i("code"),Qo=s("pmap"),Ro=s(", but the first time the pmapped function is invoked."),Lo=h(),rl=i("li"),qo=s("Ensures the compiled code runs in parallel in all the available devices."),$a=h(),T=i("p"),Oo=s("To show how it works we "),pl=i("code"),Ko=s("pmap"),ei=s(" the "),hl=i("code"),ti=s("_generate"),li=s(" method of the pipeline, which is the private method that runs generates images. Please, note that this method may be renamed or removed in future releases of "),fl=i("code"),ai=s("diffusers"),si=s("."),_a=h(),m(He.$$.fragment),ka=h(),W=i("p"),oi=s("After we use "),cl=i("code"),ii=s("pmap"),ni=s(", the prepared function "),ml=i("code"),ri=s("p_generate"),pi=s(" will conceptually do the following:"),Ua=h(),ie=i("ul"),De=i("li"),hi=s("Invoke a copy of the underlying function "),dl=i("code"),fi=s("pipeline._generate"),ci=s(" in each device."),mi=h(),g=i("li"),di=s("Send each device a different portion of the input arguments. That\u2019s what sharding is used for. In our case, "),ul=i("code"),ui=s("prompt_ids"),wi=s(" has shape "),wl=i("code"),yi=s("(8, 1, 77, 768)"),bi=s(". This array will be split in "),yl=i("code"),vi=s("8"),Mi=s(" and each copy of "),bl=i("code"),gi=s("_generate"),ji=s(" will receive an input with shape "),vl=i("code"),Ji=s("(1, 77, 768)"),Ti=s("."),Ea=h(),C=i("p"),$i=s("We can code "),Ml=i("code"),_i=s("_generate"),ki=s(" completely ignoring the fact that it will be invoked in parallel. We just care about our batch size ("),gl=i("code"),Ui=s("1"),Ei=s(" in this example) and the dimensions that make sense for our code, and don\u2019t have to change anything to make it work in parallel."),Ia=h(),ft=i("p"),Ii=s("The same way as when we used the pipeline call, the first time we run the following cell it will take a while, but then it will be much faster."),Ba=h(),m(Qe.$$.fragment),Wa=h(),m(Re.$$.fragment),Ca=h(),m(Le.$$.fragment),Ga=h(),m(qe.$$.fragment),Za=h(),ne=i("p"),Bi=s("We use "),jl=i("code"),Wi=s("block_until_ready()"),Ci=s(" to correctly measure inference time, because JAX uses asynchronous dispatch and returns control to the Python loop as soon as it can. You don\u2019t need to use that in your code; blocking will occur automatically when you want to use the result of a computation that has not yet been materialized."),this.h()},l(e){const a=br('[data-svelte="svelte-1phssyn"]',document.head);G=n(a,"META",{name:!0,content:!0}),a.forEach(t),Jl=f(e),Z=n(e,"H1",{class:!0});var Xa=r(Z);V=n(Xa,"A",{id:!0,class:!0,href:!0});var Ai=r(V);bt=n(Ai,"SPAN",{});var zi=r(bt);d(me.$$.fragment,zi),zi.forEach(t),Ai.forEach(t),ls=f(Xa),vt=n(Xa,"SPAN",{});var Pi=r(vt);as=o(Pi,"\u{1F9E8} Stable Diffusion in JAX / Flax !"),Pi.forEach(t),Xa.forEach(t),Tl=f(e),d(de.$$.fragment,e),$l=f(e),U=n(e,"P",{});var ct=r(U);ss=o(ct,"\u{1F917} Hugging Face "),ue=n(ct,"A",{href:!0,rel:!0});var Si=r(ue);os=o(Si,"Diffusers"),Si.forEach(t),is=o(ct," supports Flax since version "),Mt=n(ct,"CODE",{});var Vi=r(Mt);ns=o(Vi,"0.5.1"),Vi.forEach(t),rs=o(ct,"! This allows for super fast inference on Google TPUs, such as those available in Colab, Kaggle or Google Cloud Platform."),ct.forEach(t),_l=f(e),N=n(e,"P",{});var Fa=r(N);ps=o(Fa,"This notebook shows how to run inference using JAX / Flax. If you want more details about how Stable Diffusion works or want to run it in GPU, please refer to "),we=n(Fa,"A",{href:!0,rel:!0});var Ni=r(we);hs=o(Ni,"this notebook"),Ni.forEach(t),fs=o(Fa,"."),Fa.forEach(t),kl=f(e),j=n(e,"P",{});var re=r(j);cs=o(re,"First, make sure you are using a TPU backend. If you are running this notebook in Colab, select "),gt=n(re,"CODE",{});var Yi=r(gt);ms=o(Yi,"Runtime"),Yi.forEach(t),ds=o(re," in the menu above, then select the option \u201CChange runtime type\u201D and then select "),jt=n(re,"CODE",{});var Hi=r(jt);us=o(Hi,"TPU"),Hi.forEach(t),ws=o(re," under the "),Jt=n(re,"CODE",{});var Di=r(Jt);ys=o(Di,"Hardware accelerator"),Di.forEach(t),bs=o(re," setting."),re.forEach(t),Ul=f(e),Oe=n(e,"P",{});var Qi=r(Oe);vs=o(Qi,"Note that JAX is not exclusive to TPUs, but it shines on that hardware because each TPU server has 8 TPU accelerators working in parallel."),Qi.forEach(t),El=f(e),x=n(e,"H2",{class:!0});var Aa=r(x);Y=n(Aa,"A",{id:!0,class:!0,href:!0});var Ri=r(Y);Tt=n(Ri,"SPAN",{});var Li=r(Tt);d(ye.$$.fragment,Li),Li.forEach(t),Ri.forEach(t),Ms=f(Aa),$t=n(Aa,"SPAN",{});var qi=r($t);gs=o(qi,"Setup"),qi.forEach(t),Aa.forEach(t),Il=f(e),Ke=n(e,"P",{});var Oi=r(Ke);js=o(Oi,"First make sure diffusers is installed."),Oi.forEach(t),Bl=f(e),d(be.$$.fragment,e),Wl=f(e),d(ve.$$.fragment,e),Cl=f(e),d(Me.$$.fragment,e),Gl=f(e),d(ge.$$.fragment,e),Zl=f(e),et=n(e,"P",{});var Ki=r(et);Js=o(Ki,"Then we import all the dependencies."),Ki.forEach(t),xl=f(e),d(je.$$.fragment,e),Xl=f(e),X=n(e,"H2",{class:!0});var za=r(X);H=n(za,"A",{id:!0,class:!0,href:!0});var en=r(H);_t=n(en,"SPAN",{});var tn=r(_t);d(Je.$$.fragment,tn),tn.forEach(t),en.forEach(t),Ts=f(za),kt=n(za,"SPAN",{});var ln=r(kt);$s=o(ln,"Model Loading"),ln.forEach(t),za.forEach(t),Fl=f(e),E=n(e,"P",{});var mt=r(E);_s=o(mt,"TPU devices support "),Ut=n(mt,"CODE",{});var an=r(Ut);ks=o(an,"bfloat16"),an.forEach(t),Us=o(mt,", an efficient half-float type. We\u2019ll use it for our tests, but you can also use "),Et=n(mt,"CODE",{});var sn=r(Et);Es=o(sn,"float32"),sn.forEach(t),Is=o(mt," to use full precision instead."),mt.forEach(t),Al=f(e),d(Te.$$.fragment,e),zl=f(e),D=n(e,"P",{});var Pa=r(D);Bs=o(Pa,"Flax is a functional framework, so models are stateless and parameters are stored outside them. Loading the pre-trained Flax pipeline will return both the pipeline itself and the model weights (or parameters). We are using a "),It=n(Pa,"CODE",{});var on=r(It);Ws=o(on,"bf16"),on.forEach(t),Cs=o(Pa," version of the weights, which leads to type warnings that you can safely ignore."),Pa.forEach(t),Pl=f(e),d($e.$$.fragment,e),Sl=f(e),F=n(e,"H2",{class:!0});var Sa=r(F);Q=n(Sa,"A",{id:!0,class:!0,href:!0});var nn=r(Q);Bt=n(nn,"SPAN",{});var rn=r(Bt);d(_e.$$.fragment,rn),rn.forEach(t),nn.forEach(t),Gs=f(Sa),Wt=n(Sa,"SPAN",{});var pn=r(Wt);Zs=o(pn,"Inference"),pn.forEach(t),Sa.forEach(t),Vl=f(e),tt=n(e,"P",{});var hn=r(tt);xs=o(hn,"Since TPUs usually have 8 devices working in parallel, we\u2019ll replicate our prompt as many times as devices we have. Then we\u2019ll perform inference on the 8 devices at once, each responsible for generating one image. Thus, we\u2019ll get 8 images in the same amount of time it takes for one chip to generate a single one."),hn.forEach(t),Nl=f(e),R=n(e,"P",{});var Va=r(R);Xs=o(Va,"After replicating the prompt, we obtain the tokenized text ids by invoking the "),Ct=n(Va,"CODE",{});var fn=r(Ct);Fs=o(fn,"prepare_inputs"),fn.forEach(t),As=o(Va," function of the pipeline. The length of the tokenized text is set to 77 tokens, as required by the configuration of the underlying CLIP Text model."),Va.forEach(t),Yl=f(e),d(ke.$$.fragment,e),Hl=f(e),d(Ue.$$.fragment,e),Dl=f(e),A=n(e,"H3",{class:!0});var Na=r(A);L=n(Na,"A",{id:!0,class:!0,href:!0});var cn=r(L);Gt=n(cn,"SPAN",{});var mn=r(Gt);d(Ee.$$.fragment,mn),mn.forEach(t),cn.forEach(t),zs=f(Na),Zt=n(Na,"SPAN",{});var dn=r(Zt);Ps=o(dn,"Replication and parallelization"),dn.forEach(t),Na.forEach(t),Ql=f(e),I=n(e,"P",{});var dt=r(I);Ss=o(dt,"Model parameters and inputs have to be replicated across the 8 parallel devices we have. The parameters dictionary is replicated using "),xt=n(dt,"CODE",{});var un=r(xt);Vs=o(un,"flax.jax_utils.replicate"),un.forEach(t),Ns=o(dt,", which traverses the dictionary and changes the shape of the weights so they are repeated 8 times. Arrays are replicated using "),Xt=n(dt,"CODE",{});var wn=r(Xt);Ys=o(wn,"shard"),wn.forEach(t),Hs=o(dt,"."),dt.forEach(t),Rl=f(e),d(Ie.$$.fragment,e),Ll=f(e),d(Be.$$.fragment,e),ql=f(e),d(We.$$.fragment,e),Ol=f(e),M=n(e,"P",{});var $=r(M);Ds=o($,"That shape means that each one of the "),Ft=n($,"CODE",{});var yn=r(Ft);Qs=o(yn,"8"),yn.forEach(t),Rs=o($," devices will receive as an input a "),At=n($,"CODE",{});var bn=r(At);Ls=o(bn,"jnp"),bn.forEach(t),qs=o($," array with shape "),zt=n($,"CODE",{});var vn=r(zt);Os=o(vn,"(1, 77)"),vn.forEach(t),Ks=o($,". "),Pt=n($,"CODE",{});var Mn=r(Pt);eo=o(Mn,"1"),Mn.forEach(t),to=o($," is therefore the batch size per device. In TPUs with sufficient memory, it could be larger than "),St=n($,"CODE",{});var gn=r(St);lo=o(gn,"1"),gn.forEach(t),ao=o($," if we wanted to generate multiple images (per chip) at once."),$.forEach(t),Kl=f(e),lt=n(e,"P",{});var jn=r(lt);so=o(jn,"We are almost ready to generate images! We just need to create a random number generator to pass to the generation function. This is the standard procedure in Flax, which is very serious and opinionated about random numbers \u2013 all functions that deal with random numbers are expected to receive a generator. This ensures reproducibility, even when we are training across multiple distributed devices."),jn.forEach(t),ea=f(e),at=n(e,"P",{});var Jn=r(at);oo=o(Jn,"The helper function below uses a seed to initialize a random number generator. As long as we use the same seed, we\u2019ll get the exact same results. Feel free to use different seeds when exploring results later in the notebook."),Jn.forEach(t),ta=f(e),d(Ce.$$.fragment,e),la=f(e),st=n(e,"P",{});var Tn=r(st);io=o(Tn,"We obtain a rng and then \u201Csplit\u201D it 8 times so each device receives a different generator. Therefore, each device will create a different image, and the full process is reproducible."),Tn.forEach(t),aa=f(e),d(Ge.$$.fragment,e),sa=f(e),ot=n(e,"P",{});var $n=r(ot);no=o($n,"JAX code can be compiled to an efficient representation that runs very fast. However, we need to ensure that all inputs have the same shape in subsequent calls; otherwise, JAX will have to recompile the code, and we wouldn\u2019t be able to take advantage of the optimized speed."),$n.forEach(t),oa=f(e),q=n(e,"P",{});var Ya=r(q);ro=o(Ya,"The Flax pipeline can compile the code for us if we pass "),Vt=n(Ya,"CODE",{});var _n=r(Vt);po=o(_n,"jit = True"),_n.forEach(t),ho=o(Ya," as an argument. It will also ensure that the model runs in parallel in the 8 available devices."),Ya.forEach(t),ia=f(e),O=n(e,"P",{});var Ha=r(O);fo=o(Ha,"The first time we run the following cell it will take a long time to compile, but subequent calls (even with different inputs) will be much faster. For example, it took more than a minute to compile in a TPU v2-8 when I tested, but then it takes about "),Nt=n(Ha,"STRONG",{});var kn=r(Nt);Yt=n(kn,"CODE",{});var Un=r(Yt);co=o(Un,"7s"),Un.forEach(t),kn.forEach(t),mo=o(Ha," for future inference runs."),Ha.forEach(t),na=f(e),d(Ze.$$.fragment,e),ra=f(e),d(xe.$$.fragment,e),pa=f(e),B=n(e,"P",{});var ut=r(B);uo=o(ut,"The returned array has shape "),Ht=n(ut,"CODE",{});var En=r(Ht);wo=o(En,"(8, 1, 512, 512, 3)"),En.forEach(t),yo=o(ut,". We reshape it to get rid of the second dimension and obtain 8 images of "),Dt=n(ut,"CODE",{});var In=r(Dt);bo=o(In,"512 \xD7 512 \xD7 3"),In.forEach(t),vo=o(ut," and then convert them to PIL."),ut.forEach(t),ha=f(e),d(Xe.$$.fragment,e),fa=f(e),z=n(e,"H3",{class:!0});var Da=r(z);K=n(Da,"A",{id:!0,class:!0,href:!0});var Bn=r(K);Qt=n(Bn,"SPAN",{});var Wn=r(Qt);d(Fe.$$.fragment,Wn),Wn.forEach(t),Bn.forEach(t),Mo=f(Da),Rt=n(Da,"SPAN",{});var Cn=r(Rt);go=o(Cn,"Visualization"),Cn.forEach(t),Da.forEach(t),ca=f(e),d(Ae.$$.fragment,e),ma=f(e),it=n(e,"P",{});var Gn=r(it);nt=n(Gn,"IMG",{src:!0,alt:!0}),Gn.forEach(t),da=f(e),P=n(e,"H2",{class:!0});var Qa=r(P);ee=n(Qa,"A",{id:!0,class:!0,href:!0});var Zn=r(ee);Lt=n(Zn,"SPAN",{});var xn=r(Lt);d(ze.$$.fragment,xn),xn.forEach(t),Zn.forEach(t),jo=f(Qa),qt=n(Qa,"SPAN",{});var Xn=r(qt);Jo=o(Xn,"Using different prompts"),Xn.forEach(t),Qa.forEach(t),ua=f(e),te=n(e,"P",{});var Ra=r(te);To=o(Ra,"We don\u2019t have to replicate the "),Ot=n(Ra,"EM",{});var Fn=r(Ot);$o=o(Fn,"same"),Fn.forEach(t),_o=o(Ra," prompt in all the devices. We can do whatever we want: generate 2 prompts 4 times each, or even generate 8 different prompts at once. Let\u2019s do that!"),Ra.forEach(t),wa=f(e),rt=n(e,"P",{});var An=r(rt);ko=o(An,"First, we\u2019ll refactor the input preparation code into a handy function:"),An.forEach(t),ya=f(e),d(Pe.$$.fragment,e),ba=f(e),d(Se.$$.fragment,e),va=f(e),pt=n(e,"P",{});var zn=r(pt);ht=n(zn,"IMG",{src:!0,alt:!0}),zn.forEach(t),Ma=f(e),S=n(e,"H2",{class:!0});var La=r(S);le=n(La,"A",{id:!0,class:!0,href:!0});var Pn=r(le);Kt=n(Pn,"SPAN",{});var Sn=r(Kt);d(Ve.$$.fragment,Sn),Sn.forEach(t),Pn.forEach(t),Uo=f(La),el=n(La,"SPAN",{});var Vn=r(el);Eo=o(Vn,"How does parallelization work?"),Vn.forEach(t),La.forEach(t),ga=f(e),ae=n(e,"P",{});var qa=r(ae);Io=o(qa,"We said before that the "),tl=n(qa,"CODE",{});var Nn=r(tl);Bo=o(Nn,"diffusers"),Nn.forEach(t),Wo=o(qa," Flax pipeline automatically compiles the model and runs it in parallel on all available devices. We\u2019ll now briefly look inside that process to show how it works."),qa.forEach(t),ja=f(e),J=n(e,"P",{});var pe=r(J);Co=o(pe,"JAX parallelization can be done in multiple ways. The easiest one revolves around using the "),ll=n(pe,"CODE",{});var Yn=r(ll);Go=o(Yn,"jax.pmap"),Yn.forEach(t),Zo=o(pe," function to achieve single-program, multiple-data (SPMD) parallelization. It means we\u2019ll run several copies of the same code, each on different data inputs. More sophisticated approaches are possible, we invite you to go over the "),Ne=n(pe,"A",{href:!0,rel:!0});var Hn=r(Ne);xo=o(Hn,"JAX documentation"),Hn.forEach(t),Xo=o(pe," and the "),se=n(pe,"A",{href:!0,rel:!0});var Gi=r(se);al=n(Gi,"CODE",{});var Dn=r(al);Fo=o(Dn,"pjit"),Dn.forEach(t),Ao=o(Gi," pages"),Gi.forEach(t),zo=o(pe," to explore this topic if you are interested!"),pe.forEach(t),Ja=f(e),Ye=n(e,"P",{});var Zi=r(Ye);sl=n(Zi,"CODE",{});var Qn=r(sl);Po=o(Qn,"jax.pmap"),Qn.forEach(t),So=o(Zi," does two things for us:"),Zi.forEach(t),Ta=f(e),oe=n(e,"UL",{});var Oa=r(oe);k=n(Oa,"LI",{});var he=r(k);Vo=o(he,"Compiles (or "),ol=n(he,"CODE",{});var Rn=r(ol);No=o(Rn,"jit"),Rn.forEach(t),Yo=o(he,"s) the code, as if we had invoked "),il=n(he,"CODE",{});var Ln=r(il);Ho=o(Ln,"jax.jit()"),Ln.forEach(t),Do=o(he,". This does not happen when we call "),nl=n(he,"CODE",{});var qn=r(nl);Qo=o(qn,"pmap"),qn.forEach(t),Ro=o(he,", but the first time the pmapped function is invoked."),he.forEach(t),Lo=f(Oa),rl=n(Oa,"LI",{});var On=r(rl);qo=o(On,"Ensures the compiled code runs in parallel in all the available devices."),On.forEach(t),Oa.forEach(t),$a=f(e),T=n(e,"P",{});var fe=r(T);Oo=o(fe,"To show how it works we "),pl=n(fe,"CODE",{});var Kn=r(pl);Ko=o(Kn,"pmap"),Kn.forEach(t),ei=o(fe," the "),hl=n(fe,"CODE",{});var er=r(hl);ti=o(er,"_generate"),er.forEach(t),li=o(fe," method of the pipeline, which is the private method that runs generates images. Please, note that this method may be renamed or removed in future releases of "),fl=n(fe,"CODE",{});var tr=r(fl);ai=o(tr,"diffusers"),tr.forEach(t),si=o(fe,"."),fe.forEach(t),_a=f(e),d(He.$$.fragment,e),ka=f(e),W=n(e,"P",{});var wt=r(W);oi=o(wt,"After we use "),cl=n(wt,"CODE",{});var lr=r(cl);ii=o(lr,"pmap"),lr.forEach(t),ni=o(wt,", the prepared function "),ml=n(wt,"CODE",{});var ar=r(ml);ri=o(ar,"p_generate"),ar.forEach(t),pi=o(wt," will conceptually do the following:"),wt.forEach(t),Ua=f(e),ie=n(e,"UL",{});var Ka=r(ie);De=n(Ka,"LI",{});var es=r(De);hi=o(es,"Invoke a copy of the underlying function "),dl=n(es,"CODE",{});var sr=r(dl);fi=o(sr,"pipeline._generate"),sr.forEach(t),ci=o(es," in each device."),es.forEach(t),mi=f(Ka),g=n(Ka,"LI",{});var _=r(g);di=o(_,"Send each device a different portion of the input arguments. That\u2019s what sharding is used for. In our case, "),ul=n(_,"CODE",{});var or=r(ul);ui=o(or,"prompt_ids"),or.forEach(t),wi=o(_," has shape "),wl=n(_,"CODE",{});var ir=r(wl);yi=o(ir,"(8, 1, 77, 768)"),ir.forEach(t),bi=o(_,". This array will be split in "),yl=n(_,"CODE",{});var nr=r(yl);vi=o(nr,"8"),nr.forEach(t),Mi=o(_," and each copy of "),bl=n(_,"CODE",{});var rr=r(bl);gi=o(rr,"_generate"),rr.forEach(t),ji=o(_," will receive an input with shape "),vl=n(_,"CODE",{});var pr=r(vl);Ji=o(pr,"(1, 77, 768)"),pr.forEach(t),Ti=o(_,"."),_.forEach(t),Ka.forEach(t),Ea=f(e),C=n(e,"P",{});var yt=r(C);$i=o(yt,"We can code "),Ml=n(yt,"CODE",{});var hr=r(Ml);_i=o(hr,"_generate"),hr.forEach(t),ki=o(yt," completely ignoring the fact that it will be invoked in parallel. We just care about our batch size ("),gl=n(yt,"CODE",{});var fr=r(gl);Ui=o(fr,"1"),fr.forEach(t),Ei=o(yt," in this example) and the dimensions that make sense for our code, and don\u2019t have to change anything to make it work in parallel."),yt.forEach(t),Ia=f(e),ft=n(e,"P",{});var cr=r(ft);Ii=o(cr,"The same way as when we used the pipeline call, the first time we run the following cell it will take a while, but then it will be much faster."),cr.forEach(t),Ba=f(e),d(Qe.$$.fragment,e),Wa=f(e),d(Re.$$.fragment,e),Ca=f(e),d(Le.$$.fragment,e),Ga=f(e),d(qe.$$.fragment,e),Za=f(e),ne=n(e,"P",{});var ts=r(ne);Bi=o(ts,"We use "),jl=n(ts,"CODE",{});var mr=r(jl);Wi=o(mr,"block_until_ready()"),mr.forEach(t),Ci=o(ts," to correctly measure inference time, because JAX uses asynchronous dispatch and returns control to the Python loop as soon as it can. You don\u2019t need to use that in your code; blocking will occur automatically when you want to use the result of a computation that has not yet been materialized."),ts.forEach(t),this.h()},h(){c(G,"name","hf:doc:metadata"),c(G,"content",JSON.stringify(Jr)),c(V,"id","stable-diffusion-in-jax-flax"),c(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"),c(V,"href","#stable-diffusion-in-jax-flax"),c(Z,"class","relative group"),c(ue,"href","https://github.com/huggingface/diffusers"),c(ue,"rel","nofollow"),c(we,"href","https://huggingface.co/docs/diffusers/stable_diffusion"),c(we,"rel","nofollow"),c(Y,"id","setup"),c(Y,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),c(Y,"href","#setup"),c(x,"class","relative group"),c(H,"id","model-loading"),c(H,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),c(H,"href","#model-loading"),c(X,"class","relative group"),c(Q,"id","inference"),c(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"),c(Q,"href","#inference"),c(F,"class","relative group"),c(L,"id","replication-and-parallelization"),c(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"),c(L,"href","#replication-and-parallelization"),c(A,"class","relative group"),c(K,"id","visualization"),c(K,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),c(K,"href","#visualization"),c(z,"class","relative group"),dr(nt.src,Xi="https://huggingface.co/datasets/YiYiXu/test-doc-assets/resolve/main/stable_diffusion_jax_how_to_cell_38_output_0.jpeg")||c(nt,"src",Xi),c(nt,"alt","img"),c(ee,"id","using-different-prompts"),c(ee,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),c(ee,"href","#using-different-prompts"),c(P,"class","relative group"),dr(ht.src,Fi="https://huggingface.co/datasets/YiYiXu/test-doc-assets/resolve/main/stable_diffusion_jax_how_to_cell_43_output_0.jpeg")||c(ht,"src",Fi),c(ht,"alt","img"),c(le,"id","how-does-parallelization-work"),c(le,"class","header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full"),c(le,"href","#how-does-parallelization-work"),c(S,"class","relative group"),c(Ne,"href","https://jax.readthedocs.io/en/latest/index.html"),c(Ne,"rel","nofollow"),c(se,"href","https://jax.readthedocs.io/en/latest/jax-101/08-pjit.html?highlight=pjit"),c(se,"rel","nofollow")},m(e,a){l(document.head,G),p(e,Jl,a),p(e,Z,a),l(Z,V),l(V,bt),u(me,bt,null),l(Z,ls),l(Z,vt),l(vt,as),p(e,Tl,a),u(de,e,a),p(e,$l,a),p(e,U,a),l(U,ss),l(U,ue),l(ue,os),l(U,is),l(U,Mt),l(Mt,ns),l(U,rs),p(e,_l,a),p(e,N,a),l(N,ps),l(N,we),l(we,hs),l(N,fs),p(e,kl,a),p(e,j,a),l(j,cs),l(j,gt),l(gt,ms),l(j,ds),l(j,jt),l(jt,us),l(j,ws),l(j,Jt),l(Jt,ys),l(j,bs),p(e,Ul,a),p(e,Oe,a),l(Oe,vs),p(e,El,a),p(e,x,a),l(x,Y),l(Y,Tt),u(ye,Tt,null),l(x,Ms),l(x,$t),l($t,gs),p(e,Il,a),p(e,Ke,a),l(Ke,js),p(e,Bl,a),u(be,e,a),p(e,Wl,a),u(ve,e,a),p(e,Cl,a),u(Me,e,a),p(e,Gl,a),u(ge,e,a),p(e,Zl,a),p(e,et,a),l(et,Js),p(e,xl,a),u(je,e,a),p(e,Xl,a),p(e,X,a),l(X,H),l(H,_t),u(Je,_t,null),l(X,Ts),l(X,kt),l(kt,$s),p(e,Fl,a),p(e,E,a),l(E,_s),l(E,Ut),l(Ut,ks),l(E,Us),l(E,Et),l(Et,Es),l(E,Is),p(e,Al,a),u(Te,e,a),p(e,zl,a),p(e,D,a),l(D,Bs),l(D,It),l(It,Ws),l(D,Cs),p(e,Pl,a),u($e,e,a),p(e,Sl,a),p(e,F,a),l(F,Q),l(Q,Bt),u(_e,Bt,null),l(F,Gs),l(F,Wt),l(Wt,Zs),p(e,Vl,a),p(e,tt,a),l(tt,xs),p(e,Nl,a),p(e,R,a),l(R,Xs),l(R,Ct),l(Ct,Fs),l(R,As),p(e,Yl,a),u(ke,e,a),p(e,Hl,a),u(Ue,e,a),p(e,Dl,a),p(e,A,a),l(A,L),l(L,Gt),u(Ee,Gt,null),l(A,zs),l(A,Zt),l(Zt,Ps),p(e,Ql,a),p(e,I,a),l(I,Ss),l(I,xt),l(xt,Vs),l(I,Ns),l(I,Xt),l(Xt,Ys),l(I,Hs),p(e,Rl,a),u(Ie,e,a),p(e,Ll,a),u(Be,e,a),p(e,ql,a),u(We,e,a),p(e,Ol,a),p(e,M,a),l(M,Ds),l(M,Ft),l(Ft,Qs),l(M,Rs),l(M,At),l(At,Ls),l(M,qs),l(M,zt),l(zt,Os),l(M,Ks),l(M,Pt),l(Pt,eo),l(M,to),l(M,St),l(St,lo),l(M,ao),p(e,Kl,a),p(e,lt,a),l(lt,so),p(e,ea,a),p(e,at,a),l(at,oo),p(e,ta,a),u(Ce,e,a),p(e,la,a),p(e,st,a),l(st,io),p(e,aa,a),u(Ge,e,a),p(e,sa,a),p(e,ot,a),l(ot,no),p(e,oa,a),p(e,q,a),l(q,ro),l(q,Vt),l(Vt,po),l(q,ho),p(e,ia,a),p(e,O,a),l(O,fo),l(O,Nt),l(Nt,Yt),l(Yt,co),l(O,mo),p(e,na,a),u(Ze,e,a),p(e,ra,a),u(xe,e,a),p(e,pa,a),p(e,B,a),l(B,uo),l(B,Ht),l(Ht,wo),l(B,yo),l(B,Dt),l(Dt,bo),l(B,vo),p(e,ha,a),u(Xe,e,a),p(e,fa,a),p(e,z,a),l(z,K),l(K,Qt),u(Fe,Qt,null),l(z,Mo),l(z,Rt),l(Rt,go),p(e,ca,a),u(Ae,e,a),p(e,ma,a),p(e,it,a),l(it,nt),p(e,da,a),p(e,P,a),l(P,ee),l(ee,Lt),u(ze,Lt,null),l(P,jo),l(P,qt),l(qt,Jo),p(e,ua,a),p(e,te,a),l(te,To),l(te,Ot),l(Ot,$o),l(te,_o),p(e,wa,a),p(e,rt,a),l(rt,ko),p(e,ya,a),u(Pe,e,a),p(e,ba,a),u(Se,e,a),p(e,va,a),p(e,pt,a),l(pt,ht),p(e,Ma,a),p(e,S,a),l(S,le),l(le,Kt),u(Ve,Kt,null),l(S,Uo),l(S,el),l(el,Eo),p(e,ga,a),p(e,ae,a),l(ae,Io),l(ae,tl),l(tl,Bo),l(ae,Wo),p(e,ja,a),p(e,J,a),l(J,Co),l(J,ll),l(ll,Go),l(J,Zo),l(J,Ne),l(Ne,xo),l(J,Xo),l(J,se),l(se,al),l(al,Fo),l(se,Ao),l(J,zo),p(e,Ja,a),p(e,Ye,a),l(Ye,sl),l(sl,Po),l(Ye,So),p(e,Ta,a),p(e,oe,a),l(oe,k),l(k,Vo),l(k,ol),l(ol,No),l(k,Yo),l(k,il),l(il,Ho),l(k,Do),l(k,nl),l(nl,Qo),l(k,Ro),l(oe,Lo),l(oe,rl),l(rl,qo),p(e,$a,a),p(e,T,a),l(T,Oo),l(T,pl),l(pl,Ko),l(T,ei),l(T,hl),l(hl,ti),l(T,li),l(T,fl),l(fl,ai),l(T,si),p(e,_a,a),u(He,e,a),p(e,ka,a),p(e,W,a),l(W,oi),l(W,cl),l(cl,ii),l(W,ni),l(W,ml),l(ml,ri),l(W,pi),p(e,Ua,a),p(e,ie,a),l(ie,De),l(De,hi),l(De,dl),l(dl,fi),l(De,ci),l(ie,mi),l(ie,g),l(g,di),l(g,ul),l(ul,ui),l(g,wi),l(g,wl),l(wl,yi),l(g,bi),l(g,yl),l(yl,vi),l(g,Mi),l(g,bl),l(bl,gi),l(g,ji),l(g,vl),l(vl,Ji),l(g,Ti),p(e,Ea,a),p(e,C,a),l(C,$i),l(C,Ml),l(Ml,_i),l(C,ki),l(C,gl),l(gl,Ui),l(C,Ei),p(e,Ia,a),p(e,ft,a),l(ft,Ii),p(e,Ba,a),u(Qe,e,a),p(e,Wa,a),u(Re,e,a),p(e,Ca,a),u(Le,e,a),p(e,Ga,a),u(qe,e,a),p(e,Za,a),p(e,ne,a),l(ne,Bi),l(ne,jl),l(jl,Wi),l(ne,Ci),xa=!0},p:vr,i(e){xa||(w(me.$$.fragment,e),w(de.$$.fragment,e),w(ye.$$.fragment,e),w(be.$$.fragment,e),w(ve.$$.fragment,e),w(Me.$$.fragment,e),w(ge.$$.fragment,e),w(je.$$.fragment,e),w(Je.$$.fragment,e),w(Te.$$.fragment,e),w($e.$$.fragment,e),w(_e.$$.fragment,e),w(ke.$$.fragment,e),w(Ue.$$.fragment,e),w(Ee.$$.fragment,e),w(Ie.$$.fragment,e),w(Be.$$.fragment,e),w(We.$$.fragment,e),w(Ce.$$.fragment,e),w(Ge.$$.fragment,e),w(Ze.$$.fragment,e),w(xe.$$.fragment,e),w(Xe.$$.fragment,e),w(Fe.$$.fragment,e),w(Ae.$$.fragment,e),w(ze.$$.fragment,e),w(Pe.$$.fragment,e),w(Se.$$.fragment,e),w(Ve.$$.fragment,e),w(He.$$.fragment,e),w(Qe.$$.fragment,e),w(Re.$$.fragment,e),w(Le.$$.fragment,e),w(qe.$$.fragment,e),xa=!0)},o(e){y(me.$$.fragment,e),y(de.$$.fragment,e),y(ye.$$.fragment,e),y(be.$$.fragment,e),y(ve.$$.fragment,e),y(Me.$$.fragment,e),y(ge.$$.fragment,e),y(je.$$.fragment,e),y(Je.$$.fragment,e),y(Te.$$.fragment,e),y($e.$$.fragment,e),y(_e.$$.fragment,e),y(ke.$$.fragment,e),y(Ue.$$.fragment,e),y(Ee.$$.fragment,e),y(Ie.$$.fragment,e),y(Be.$$.fragment,e),y(We.$$.fragment,e),y(Ce.$$.fragment,e),y(Ge.$$.fragment,e),y(Ze.$$.fragment,e),y(xe.$$.fragment,e),y(Xe.$$.fragment,e),y(Fe.$$.fragment,e),y(Ae.$$.fragment,e),y(ze.$$.fragment,e),y(Pe.$$.fragment,e),y(Se.$$.fragment,e),y(Ve.$$.fragment,e),y(He.$$.fragment,e),y(Qe.$$.fragment,e),y(Re.$$.fragment,e),y(Le.$$.fragment,e),y(qe.$$.fragment,e),xa=!1},d(e){t(G),e&&t(Jl),e&&t(Z),b(me),e&&t(Tl),b(de,e),e&&t($l),e&&t(U),e&&t(_l),e&&t(N),e&&t(kl),e&&t(j),e&&t(Ul),e&&t(Oe),e&&t(El),e&&t(x),b(ye),e&&t(Il),e&&t(Ke),e&&t(Bl),b(be,e),e&&t(Wl),b(ve,e),e&&t(Cl),b(Me,e),e&&t(Gl),b(ge,e),e&&t(Zl),e&&t(et),e&&t(xl),b(je,e),e&&t(Xl),e&&t(X),b(Je),e&&t(Fl),e&&t(E),e&&t(Al),b(Te,e),e&&t(zl),e&&t(D),e&&t(Pl),b($e,e),e&&t(Sl),e&&t(F),b(_e),e&&t(Vl),e&&t(tt),e&&t(Nl),e&&t(R),e&&t(Yl),b(ke,e),e&&t(Hl),b(Ue,e),e&&t(Dl),e&&t(A),b(Ee),e&&t(Ql),e&&t(I),e&&t(Rl),b(Ie,e),e&&t(Ll),b(Be,e),e&&t(ql),b(We,e),e&&t(Ol),e&&t(M),e&&t(Kl),e&&t(lt),e&&t(ea),e&&t(at),e&&t(ta),b(Ce,e),e&&t(la),e&&t(st),e&&t(aa),b(Ge,e),e&&t(sa),e&&t(ot),e&&t(oa),e&&t(q),e&&t(ia),e&&t(O),e&&t(na),b(Ze,e),e&&t(ra),b(xe,e),e&&t(pa),e&&t(B),e&&t(ha),b(Xe,e),e&&t(fa),e&&t(z),b(Fe),e&&t(ca),b(Ae,e),e&&t(ma),e&&t(it),e&&t(da),e&&t(P),b(ze),e&&t(ua),e&&t(te),e&&t(wa),e&&t(rt),e&&t(ya),b(Pe,e),e&&t(ba),b(Se,e),e&&t(va),e&&t(pt),e&&t(Ma),e&&t(S),b(Ve),e&&t(ga),e&&t(ae),e&&t(ja),e&&t(J),e&&t(Ja),e&&t(Ye),e&&t(Ta),e&&t(oe),e&&t($a),e&&t(T),e&&t(_a),b(He,e),e&&t(ka),e&&t(W),e&&t(Ua),e&&t(ie),e&&t(Ea),e&&t(C),e&&t(Ia),e&&t(ft),e&&t(Ba),b(Qe,e),e&&t(Wa),b(Re,e),e&&t(Ca),b(Le,e),e&&t(Ga),b(qe,e),e&&t(Za),e&&t(ne)}}}const Jr={local:"stable-diffusion-in-jax-flax",sections:[{local:"setup",title:"Setup"},{local:"model-loading",title:"Model Loading"},{local:"inference",sections:[{local:"replication-and-parallelization",title:"Replication and parallelization"},{local:"visualization",title:"Visualization"}],title:"Inference"},{local:"using-different-prompts",title:"Using different prompts"},{local:"how-does-parallelization-work",title:"How does parallelization work?"}],title:"\u{1F9E8} Stable Diffusion in JAX / Flax !"};function Tr(xi){return Mr(()=>{new URLSearchParams(window.location.search).get("fw")}),[]}class Er extends ur{constructor(G){super();wr(this,G,Tr,jr,yr,{})}}export{Er as default,Jr as metadata};
