Buckets:
| <meta charset="utf-8" /><meta name="hf:doc:metadata" content="{"title":"Evaluating Diffusion Models","local":"evaluating-diffusion-models","sections":[{"title":"Scenarios","local":"scenarios","sections":[],"depth":2},{"title":"Qualitative Evaluation","local":"qualitative-evaluation","sections":[],"depth":2},{"title":"Quantitative Evaluation","local":"quantitative-evaluation","sections":[{"title":"Text-guided image generation","local":"text-guided-image-generation","sections":[],"depth":3},{"title":"Image-conditioned text-to-image generation","local":"image-conditioned-text-to-image-generation","sections":[],"depth":3},{"title":"Class-conditioned image generation","local":"class-conditioned-image-generation","sections":[],"depth":3}],"depth":2}],"depth":1}"> | |
| <link href="/docs/diffusers/main/en/_app/immutable/assets/0.e3b0c442.css" rel="modulepreload"> | |
| <link rel="modulepreload" href="/docs/diffusers/main/en/_app/immutable/entry/start.21e27d66.js"> | |
| <link rel="modulepreload" href="/docs/diffusers/main/en/_app/immutable/chunks/scheduler.8c3d61f6.js"> | |
| <link rel="modulepreload" href="/docs/diffusers/main/en/_app/immutable/chunks/singletons.1db06f6d.js"> | |
| <link rel="modulepreload" href="/docs/diffusers/main/en/_app/immutable/chunks/index.0997d446.js"> | |
| <link rel="modulepreload" href="/docs/diffusers/main/en/_app/immutable/chunks/paths.085e8bc8.js"> | |
| <link rel="modulepreload" href="/docs/diffusers/main/en/_app/immutable/entry/app.de4fb612.js"> | |
| <link rel="modulepreload" href="/docs/diffusers/main/en/_app/immutable/chunks/index.da70eac4.js"> | |
| <link rel="modulepreload" href="/docs/diffusers/main/en/_app/immutable/nodes/0.f6117ae5.js"> | |
| <link rel="modulepreload" href="/docs/diffusers/main/en/_app/immutable/chunks/each.e59479a4.js"> | |
| <link rel="modulepreload" href="/docs/diffusers/main/en/_app/immutable/nodes/162.cae9aa32.js"> | |
| <link rel="modulepreload" href="/docs/diffusers/main/en/_app/immutable/chunks/Tip.1d9b8c37.js"> | |
| <link rel="modulepreload" href="/docs/diffusers/main/en/_app/immutable/chunks/CodeBlock.00a903b3.js"> | |
| <link rel="modulepreload" href="/docs/diffusers/main/en/_app/immutable/chunks/EditOnGithub.1e64e623.js"><!-- HEAD_svelte-u9bgzb_START --><meta name="hf:doc:metadata" content="{"title":"Evaluating Diffusion Models","local":"evaluating-diffusion-models","sections":[{"title":"Scenarios","local":"scenarios","sections":[],"depth":2},{"title":"Qualitative Evaluation","local":"qualitative-evaluation","sections":[],"depth":2},{"title":"Quantitative Evaluation","local":"quantitative-evaluation","sections":[{"title":"Text-guided image generation","local":"text-guided-image-generation","sections":[],"depth":3},{"title":"Image-conditioned text-to-image generation","local":"image-conditioned-text-to-image-generation","sections":[],"depth":3},{"title":"Class-conditioned image generation","local":"class-conditioned-image-generation","sections":[],"depth":3}],"depth":2}],"depth":1}"><!-- HEAD_svelte-u9bgzb_END --> <p></p> <h1 class="relative group"><a id="evaluating-diffusion-models" 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" href="#evaluating-diffusion-models"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Evaluating Diffusion Models</span></h1> <a target="_blank" href="https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/evaluation.ipynb" data-svelte-h="svelte-1fn2wis"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a> <p data-svelte-h="svelte-z81vpv">Evaluation of generative models like <a href="https://huggingface.co/docs/diffusers/stable_diffusion" rel="nofollow">Stable Diffusion</a> is subjective in nature. But as practitioners and researchers, we often have to make careful choices amongst many different possibilities. So, when working with different generative models (like GANs, Diffusion, etc.), how do we choose one over the other?</p> <p data-svelte-h="svelte-14o42r">Qualitative evaluation of such models can be error-prone and might incorrectly influence a decision. | |
| However, quantitative metrics don’t necessarily correspond to image quality. So, usually, a combination | |
| of both qualitative and quantitative evaluations provides a stronger signal when choosing one model | |
| over the other.</p> <p data-svelte-h="svelte-tqblgl">In this document, we provide a non-exhaustive overview of qualitative and quantitative methods to evaluate Diffusion models. For quantitative methods, we specifically focus on how to implement them alongside <code>diffusers</code>.</p> <p data-svelte-h="svelte-1on511i">The methods shown in this document can also be used to evaluate different <a href="https://huggingface.co/docs/diffusers/main/en/api/schedulers/overview" rel="nofollow">noise schedulers</a> keeping the underlying generation model fixed.</p> <h2 class="relative group"><a id="scenarios" 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" href="#scenarios"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Scenarios</span></h2> <p data-svelte-h="svelte-cqau2t">We cover Diffusion models with the following pipelines:</p> <ul data-svelte-h="svelte-1izcxm8"><li>Text-guided image generation (such as the <a href="https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/text2img" rel="nofollow"><code>StableDiffusionPipeline</code></a>).</li> <li>Text-guided image generation, additionally conditioned on an input image (such as the <a href="https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/img2img" rel="nofollow"><code>StableDiffusionImg2ImgPipeline</code></a> and <a href="https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix" rel="nofollow"><code>StableDiffusionInstructPix2PixPipeline</code></a>).</li> <li>Class-conditioned image generation models (such as the <a href="https://huggingface.co/docs/diffusers/main/en/api/pipelines/dit" rel="nofollow"><code>DiTPipeline</code></a>).</li></ul> <h2 class="relative group"><a id="qualitative-evaluation" 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" href="#qualitative-evaluation"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Qualitative Evaluation</span></h2> <p data-svelte-h="svelte-cad463">Qualitative evaluation typically involves human assessment of generated images. Quality is measured across aspects such as compositionality, image-text alignment, and spatial relations. Common prompts provide a degree of uniformity for subjective metrics. | |
| DrawBench and PartiPrompts are prompt datasets used for qualitative benchmarking. DrawBench and PartiPrompts were introduced by <a href="https://imagen.research.google/" rel="nofollow">Imagen</a> and <a href="https://parti.research.google/" rel="nofollow">Parti</a> respectively.</p> <p data-svelte-h="svelte-15hirvk">From the <a href="https://parti.research.google/" rel="nofollow">official Parti website</a>:</p> <blockquote data-svelte-h="svelte-191e550"><p>PartiPrompts (P2) is a rich set of over 1600 prompts in English that we release as part of this work. P2 can be used to measure model capabilities across various categories and challenge aspects.</p></blockquote> <p data-svelte-h="svelte-19xz367"><img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/parti-prompts.png" alt="parti-prompts"></p> <p data-svelte-h="svelte-76ujpq">PartiPrompts has the following columns:</p> <ul data-svelte-h="svelte-umnjz5"><li>Prompt</li> <li>Category of the prompt (such as “Abstract”, “World Knowledge”, etc.)</li> <li>Challenge reflecting the difficulty (such as “Basic”, “Complex”, “Writing & Symbols”, etc.)</li></ul> <p data-svelte-h="svelte-ybl15o">These benchmarks allow for side-by-side human evaluation of different image generation models.</p> <p data-svelte-h="svelte-f7spg1">For this, the 🧨 Diffusers team has built <strong>Open Parti Prompts</strong>, which is a community-driven qualitative benchmark based on Parti Prompts to compare state-of-the-art open-source diffusion models:</p> <ul data-svelte-h="svelte-18glkk1"><li><a href="https://huggingface.co/spaces/OpenGenAI/open-parti-prompts" rel="nofollow">Open Parti Prompts Game</a>: For 10 parti prompts, 4 generated images are shown and the user selects the image that suits the prompt best.</li> <li><a href="https://huggingface.co/spaces/OpenGenAI/parti-prompts-leaderboard" rel="nofollow">Open Parti Prompts Leaderboard</a>: The leaderboard comparing the currently best open-sourced diffusion models to each other.</li></ul> <p data-svelte-h="svelte-e5mnz8">To manually compare images, let’s see how we can use <code>diffusers</code> on a couple of PartiPrompts.</p> <p data-svelte-h="svelte-304bv6">Below we show some prompts sampled across different challenges: Basic, Complex, Linguistic Structures, Imagination, and Writing & Symbols. Here we are using PartiPrompts as a <a href="https://huggingface.co/datasets/nateraw/parti-prompts" rel="nofollow">dataset</a>.</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> datasets <span class="hljs-keyword">import</span> load_dataset | |
| <span class="hljs-comment"># prompts = load_dataset("nateraw/parti-prompts", split="train")</span> | |
| <span class="hljs-comment"># prompts = prompts.shuffle()</span> | |
| <span class="hljs-comment"># sample_prompts = [prompts[i]["Prompt"] for i in range(5)]</span> | |
| <span class="hljs-comment"># Fixing these sample prompts in the interest of reproducibility.</span> | |
| sample_prompts = [ | |
| <span class="hljs-string">"a corgi"</span>, | |
| <span class="hljs-string">"a hot air balloon with a yin-yang symbol, with the moon visible in the daytime sky"</span>, | |
| <span class="hljs-string">"a car with no windows"</span>, | |
| <span class="hljs-string">"a cube made of porcupine"</span>, | |
| <span class="hljs-string">'The saying "BE EXCELLENT TO EACH OTHER" written on a red brick wall with a graffiti image of a green alien wearing a tuxedo. A yellow fire hydrant is on a sidewalk in the foreground.'</span>, | |
| ]<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-tpmlzv">Now we can use these prompts to generate some images using Stable Diffusion (<a href="https://huggingface.co/CompVis/stable-diffusion-v1-4" rel="nofollow">v1-4 checkpoint</a>):</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">import</span> torch | |
| seed = <span class="hljs-number">0</span> | |
| generator = torch.manual_seed(seed) | |
| images = sd_pipeline(sample_prompts, num_images_per_prompt=<span class="hljs-number">1</span>, generator=generator).images<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-4i7yd5"><img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/parti-prompts-14.png" alt="parti-prompts-14"></p> <p data-svelte-h="svelte-1iqix0j">We can also set <code>num_images_per_prompt</code> accordingly to compare different images for the same prompt. Running the same pipeline but with a different checkpoint (<a href="https://huggingface.co/runwayml/stable-diffusion-v1-5" rel="nofollow">v1-5</a>), yields:</p> <p data-svelte-h="svelte-gipltn"><img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/parti-prompts-15.png" alt="parti-prompts-15"></p> <p data-svelte-h="svelte-1vqr9z3">Once several images are generated from all the prompts using multiple models (under evaluation), these results are presented to human evaluators for scoring. For | |
| more details on the DrawBench and PartiPrompts benchmarks, refer to their respective papers.</p> <div class="course-tip bg-gradient-to-br dark:bg-gradient-to-r before:border-green-500 dark:before:border-green-800 from-green-50 dark:from-gray-900 to-white dark:to-gray-950 border border-green-50 text-green-700 dark:text-gray-400"><p data-svelte-h="svelte-1yulmeg">It is useful to look at some inference samples while a model is training to measure the | |
| training progress. In our <a href="https://github.com/huggingface/diffusers/tree/main/examples/" rel="nofollow">training scripts</a>, we support this utility with additional support for | |
| logging to TensorBoard and Weights & Biases.</p></div> <h2 class="relative group"><a id="quantitative-evaluation" 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" href="#quantitative-evaluation"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Quantitative Evaluation</span></h2> <p data-svelte-h="svelte-6557l0">In this section, we will walk you through how to evaluate three different diffusion pipelines using:</p> <ul data-svelte-h="svelte-dg8xrl"><li>CLIP score</li> <li>CLIP directional similarity</li> <li>FID</li></ul> <h3 class="relative group"><a id="text-guided-image-generation" 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" href="#text-guided-image-generation"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Text-guided image generation</span></h3> <p data-svelte-h="svelte-17jh2lx"><a href="https://arxiv.org/abs/2104.08718" rel="nofollow">CLIP score</a> measures the compatibility of image-caption pairs. Higher CLIP scores imply higher compatibility 🔼. The CLIP score is a quantitative measurement of the qualitative concept “compatibility”. Image-caption pair compatibility can also be thought of as the semantic similarity between the image and the caption. CLIP score was found to have high correlation with human judgement.</p> <p data-svelte-h="svelte-7rr7b3">Let’s first load a <a href="/docs/diffusers/main/en/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline">StableDiffusionPipeline</a>:</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> StableDiffusionPipeline | |
| <span class="hljs-keyword">import</span> torch | |
| model_ckpt = <span class="hljs-string">"CompVis/stable-diffusion-v1-4"</span> | |
| sd_pipeline = StableDiffusionPipeline.from_pretrained(model_ckpt, torch_dtype=torch.float16).to(<span class="hljs-string">"cuda"</span>)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-6rdsa0">Generate some images with multiple prompts:</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->prompts = [ | |
| <span class="hljs-string">"a photo of an astronaut riding a horse on mars"</span>, | |
| <span class="hljs-string">"A high tech solarpunk utopia in the Amazon rainforest"</span>, | |
| <span class="hljs-string">"A pikachu fine dining with a view to the Eiffel Tower"</span>, | |
| <span class="hljs-string">"A mecha robot in a favela in expressionist style"</span>, | |
| <span class="hljs-string">"an insect robot preparing a delicious meal"</span>, | |
| <span class="hljs-string">"A small cabin on top of a snowy mountain in the style of Disney, artstation"</span>, | |
| ] | |
| images = sd_pipeline(prompts, num_images_per_prompt=<span class="hljs-number">1</span>, output_type=<span class="hljs-string">"np"</span>).images | |
| <span class="hljs-built_in">print</span>(images.shape) | |
| <span class="hljs-comment"># (6, 512, 512, 3)</span><!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1iembt3">And then, we calculate the CLIP score.</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> torchmetrics.functional.multimodal <span class="hljs-keyword">import</span> clip_score | |
| <span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> partial | |
| clip_score_fn = partial(clip_score, model_name_or_path=<span class="hljs-string">"openai/clip-vit-base-patch16"</span>) | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">calculate_clip_score</span>(<span class="hljs-params">images, prompts</span>): | |
| images_int = (images * <span class="hljs-number">255</span>).astype(<span class="hljs-string">"uint8"</span>) | |
| clip_score = clip_score_fn(torch.from_numpy(images_int).permute(<span class="hljs-number">0</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>), prompts).detach() | |
| <span class="hljs-keyword">return</span> <span class="hljs-built_in">round</span>(<span class="hljs-built_in">float</span>(clip_score), <span class="hljs-number">4</span>) | |
| sd_clip_score = calculate_clip_score(images, prompts) | |
| <span class="hljs-built_in">print</span>(<span class="hljs-string">f"CLIP score: <span class="hljs-subst">{sd_clip_score}</span>"</span>) | |
| <span class="hljs-comment"># CLIP score: 35.7038</span><!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1a3tn0d">In the above example, we generated one image per prompt. If we generated multiple images per prompt, we would have to take the average score from the generated images per prompt.</p> <p data-svelte-h="svelte-1ibhx6s">Now, if we wanted to compare two checkpoints compatible with the <a href="/docs/diffusers/main/en/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline">StableDiffusionPipeline</a> we should pass a generator while calling the pipeline. First, we generate images with a | |
| fixed seed with the <a href="https://huggingface.co/CompVis/stable-diffusion-v1-4" rel="nofollow">v1-4 Stable Diffusion checkpoint</a>:</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->seed = <span class="hljs-number">0</span> | |
| generator = torch.manual_seed(seed) | |
| images = sd_pipeline(prompts, num_images_per_prompt=<span class="hljs-number">1</span>, generator=generator, output_type=<span class="hljs-string">"np"</span>).images<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-qym5mj">Then we load the <a href="https://huggingface.co/runwayml/stable-diffusion-v1-5" rel="nofollow">v1-5 checkpoint</a> to generate images:</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->model_ckpt_1_5 = <span class="hljs-string">"runwayml/stable-diffusion-v1-5"</span> | |
| sd_pipeline_1_5 = StableDiffusionPipeline.from_pretrained(model_ckpt_1_5, torch_dtype=weight_dtype).to(device) | |
| images_1_5 = sd_pipeline_1_5(prompts, num_images_per_prompt=<span class="hljs-number">1</span>, generator=generator, output_type=<span class="hljs-string">"np"</span>).images<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-ni3sdy">And finally, we compare their CLIP scores:</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->sd_clip_score_1_4 = calculate_clip_score(images, prompts) | |
| <span class="hljs-built_in">print</span>(<span class="hljs-string">f"CLIP Score with v-1-4: <span class="hljs-subst">{sd_clip_score_1_4}</span>"</span>) | |
| <span class="hljs-comment"># CLIP Score with v-1-4: 34.9102</span> | |
| sd_clip_score_1_5 = calculate_clip_score(images_1_5, prompts) | |
| <span class="hljs-built_in">print</span>(<span class="hljs-string">f"CLIP Score with v-1-5: <span class="hljs-subst">{sd_clip_score_1_5}</span>"</span>) | |
| <span class="hljs-comment"># CLIP Score with v-1-5: 36.2137</span><!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1xnoaz5">It seems like the <a href="https://huggingface.co/runwayml/stable-diffusion-v1-5" rel="nofollow">v1-5</a> checkpoint performs better than its predecessor. Note, however, that the number of prompts we used to compute the CLIP scores is quite low. For a more practical evaluation, this number should be way higher, and the prompts should be diverse.</p> <div class="course-tip course-tip-orange bg-gradient-to-br dark:bg-gradient-to-r before:border-orange-500 dark:before:border-orange-800 from-orange-50 dark:from-gray-900 to-white dark:to-gray-950 border border-orange-50 text-orange-700 dark:text-gray-400"><p data-svelte-h="svelte-17jek1b">By construction, there are some limitations in this score. The captions in the training dataset | |
| were crawled from the web and extracted from <code>alt</code> and similar tags associated an image on the internet. | |
| They are not necessarily representative of what a human being would use to describe an image. Hence we | |
| had to “engineer” some prompts here.</p></div> <h3 class="relative group"><a id="image-conditioned-text-to-image-generation" 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" href="#image-conditioned-text-to-image-generation"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Image-conditioned text-to-image generation</span></h3> <p data-svelte-h="svelte-18ubjo5">In this case, we condition the generation pipeline with an input image as well as a text prompt. Let’s take the <a href="/docs/diffusers/main/en/api/pipelines/pix2pix#diffusers.StableDiffusionInstructPix2PixPipeline">StableDiffusionInstructPix2PixPipeline</a>, as an example. It takes an edit instruction as an input prompt and an input image to be edited.</p> <p data-svelte-h="svelte-r4qmx2">Here is one example:</p> <p data-svelte-h="svelte-tnn31f"><img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/edit-instruction.png" alt="edit-instruction"></p> <p data-svelte-h="svelte-oghx7t">One strategy to evaluate such a model is to measure the consistency of the change between the two images (in <a href="https://huggingface.co/docs/transformers/model_doc/clip" rel="nofollow">CLIP</a> space) with the change between the two image captions (as shown in <a href="https://arxiv.org/abs/2108.00946" rel="nofollow">CLIP-Guided Domain Adaptation of Image Generators</a>). This is referred to as the ”<strong>CLIP directional similarity</strong>“.</p> <ul data-svelte-h="svelte-yda35x"><li>Caption 1 corresponds to the input image (image 1) that is to be edited.</li> <li>Caption 2 corresponds to the edited image (image 2). It should reflect the edit instruction.</li></ul> <p data-svelte-h="svelte-1bn7xvw">Following is a pictorial overview:</p> <p data-svelte-h="svelte-fs1abj"><img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/edit-consistency.png" alt="edit-consistency"></p> <p data-svelte-h="svelte-1t03m2p">We have prepared a mini dataset to implement this metric. Let’s first load the dataset.</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> datasets <span class="hljs-keyword">import</span> load_dataset | |
| dataset = load_dataset(<span class="hljs-string">"sayakpaul/instructpix2pix-demo"</span>, split=<span class="hljs-string">"train"</span>) | |
| dataset.features<!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->{<span class="hljs-string">'input'</span>: Value(dtype=<span class="hljs-string">'string'</span>, <span class="hljs-built_in">id</span>=None), | |
| <span class="hljs-string">'edit'</span>: Value(dtype=<span class="hljs-string">'string'</span>, <span class="hljs-built_in">id</span>=None), | |
| <span class="hljs-string">'output'</span>: Value(dtype=<span class="hljs-string">'string'</span>, <span class="hljs-built_in">id</span>=None), | |
| <span class="hljs-string">'image'</span>: Image(decode=True, <span class="hljs-built_in">id</span>=None)}<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1q1xt9i">Here we have:</p> <ul data-svelte-h="svelte-mhcjab"><li><code>input</code> is a caption corresponding to the <code>image</code>.</li> <li><code>edit</code> denotes the edit instruction.</li> <li><code>output</code> denotes the modified caption reflecting the <code>edit</code> instruction.</li></ul> <p data-svelte-h="svelte-9q1iss">Let’s take a look at a sample.</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->idx = <span class="hljs-number">0</span> | |
| <span class="hljs-built_in">print</span>(<span class="hljs-string">f"Original caption: <span class="hljs-subst">{dataset[idx][<span class="hljs-string">'input'</span>]}</span>"</span>) | |
| <span class="hljs-built_in">print</span>(<span class="hljs-string">f"Edit instruction: <span class="hljs-subst">{dataset[idx][<span class="hljs-string">'edit'</span>]}</span>"</span>) | |
| <span class="hljs-built_in">print</span>(<span class="hljs-string">f"Modified caption: <span class="hljs-subst">{dataset[idx][<span class="hljs-string">'output'</span>]}</span>"</span>)<!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->Original caption: 2. FAROE ISLANDS: An archipelago of 18 mountainous isles <span class="hljs-keyword">in</span> the North Atlantic Ocean between Norway and Iceland, the Faroe Islands has <span class="hljs-string">'everything you could hope for'</span>, according to Big 7 Travel. It boasts <span class="hljs-string">'crystal clear waterfalls, rocky cliffs that seem to jut out of nowhere and velvety green hills'</span> | |
| Edit instruction: make the isles all white marble | |
| Modified caption: 2. WHITE MARBLE ISLANDS: An archipelago of 18 mountainous white marble isles <span class="hljs-keyword">in</span> the North Atlantic Ocean between Norway and Iceland, the White Marble Islands has <span class="hljs-string">'everything you could hope for'</span>, according to Big 7 Travel. It boasts <span class="hljs-string">'crystal clear waterfalls, rocky cliffs that seem to jut out of nowhere and velvety green hills'</span><!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-5rwzaj">And here is the image:</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->dataset[idx][<span class="hljs-string">"image"</span>]<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1r4pb3b"><img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/edit-dataset.png" alt="edit-dataset"></p> <p data-svelte-h="svelte-1n3s9hn">We will first edit the images of our dataset with the edit instruction and compute the directional similarity.</p> <p data-svelte-h="svelte-ss3jc3">Let’s first load the <a href="/docs/diffusers/main/en/api/pipelines/pix2pix#diffusers.StableDiffusionInstructPix2PixPipeline">StableDiffusionInstructPix2PixPipeline</a>:</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> StableDiffusionInstructPix2PixPipeline | |
| instruct_pix2pix_pipeline = StableDiffusionInstructPix2PixPipeline.from_pretrained( | |
| <span class="hljs-string">"timbrooks/instruct-pix2pix"</span>, torch_dtype=torch.float16 | |
| ).to(device)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-pfw8ud">Now, we perform the edits:</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">edit_image</span>(<span class="hljs-params">input_image, instruction</span>): | |
| image = instruct_pix2pix_pipeline( | |
| instruction, | |
| image=input_image, | |
| output_type=<span class="hljs-string">"np"</span>, | |
| generator=generator, | |
| ).images[<span class="hljs-number">0</span>] | |
| <span class="hljs-keyword">return</span> image | |
| input_images = [] | |
| original_captions = [] | |
| modified_captions = [] | |
| edited_images = [] | |
| <span class="hljs-keyword">for</span> idx <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(dataset)): | |
| input_image = dataset[idx][<span class="hljs-string">"image"</span>] | |
| edit_instruction = dataset[idx][<span class="hljs-string">"edit"</span>] | |
| edited_image = edit_image(input_image, edit_instruction) | |
| input_images.append(np.array(input_image)) | |
| original_captions.append(dataset[idx][<span class="hljs-string">"input"</span>]) | |
| modified_captions.append(dataset[idx][<span class="hljs-string">"output"</span>]) | |
| edited_images.append(edited_image)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1nzzrqn">To measure the directional similarity, we first load CLIP’s image and text encoders:</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> ( | |
| CLIPTokenizer, | |
| CLIPTextModelWithProjection, | |
| CLIPVisionModelWithProjection, | |
| CLIPImageProcessor, | |
| ) | |
| clip_id = <span class="hljs-string">"openai/clip-vit-large-patch14"</span> | |
| tokenizer = CLIPTokenizer.from_pretrained(clip_id) | |
| text_encoder = CLIPTextModelWithProjection.from_pretrained(clip_id).to(device) | |
| image_processor = CLIPImageProcessor.from_pretrained(clip_id) | |
| image_encoder = CLIPVisionModelWithProjection.from_pretrained(clip_id).to(device)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1c659ih">Notice that we are using a particular CLIP checkpoint, i.e., <code>openai/clip-vit-large-patch14</code>. This is because the Stable Diffusion pre-training was performed with this CLIP variant. For more details, refer to the <a href="https://huggingface.co/docs/transformers/model_doc/clip" rel="nofollow">documentation</a>.</p> <p data-svelte-h="svelte-k3cp0u">Next, we prepare a PyTorch <code>nn.Module</code> to compute directional similarity:</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">import</span> torch.nn <span class="hljs-keyword">as</span> nn | |
| <span class="hljs-keyword">import</span> torch.nn.functional <span class="hljs-keyword">as</span> F | |
| <span class="hljs-keyword">class</span> <span class="hljs-title class_">DirectionalSimilarity</span>(nn.Module): | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, tokenizer, text_encoder, image_processor, image_encoder</span>): | |
| <span class="hljs-built_in">super</span>().__init__() | |
| self.tokenizer = tokenizer | |
| self.text_encoder = text_encoder | |
| self.image_processor = image_processor | |
| self.image_encoder = image_encoder | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">preprocess_image</span>(<span class="hljs-params">self, image</span>): | |
| image = self.image_processor(image, return_tensors=<span class="hljs-string">"pt"</span>)[<span class="hljs-string">"pixel_values"</span>] | |
| <span class="hljs-keyword">return</span> {<span class="hljs-string">"pixel_values"</span>: image.to(device)} | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">tokenize_text</span>(<span class="hljs-params">self, text</span>): | |
| inputs = self.tokenizer( | |
| text, | |
| max_length=self.tokenizer.model_max_length, | |
| padding=<span class="hljs-string">"max_length"</span>, | |
| truncation=<span class="hljs-literal">True</span>, | |
| return_tensors=<span class="hljs-string">"pt"</span>, | |
| ) | |
| <span class="hljs-keyword">return</span> {<span class="hljs-string">"input_ids"</span>: inputs.input_ids.to(device)} | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">encode_image</span>(<span class="hljs-params">self, image</span>): | |
| preprocessed_image = self.preprocess_image(image) | |
| image_features = self.image_encoder(**preprocessed_image).image_embeds | |
| image_features = image_features / image_features.norm(dim=<span class="hljs-number">1</span>, keepdim=<span class="hljs-literal">True</span>) | |
| <span class="hljs-keyword">return</span> image_features | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">encode_text</span>(<span class="hljs-params">self, text</span>): | |
| tokenized_text = self.tokenize_text(text) | |
| text_features = self.text_encoder(**tokenized_text).text_embeds | |
| text_features = text_features / text_features.norm(dim=<span class="hljs-number">1</span>, keepdim=<span class="hljs-literal">True</span>) | |
| <span class="hljs-keyword">return</span> text_features | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">compute_directional_similarity</span>(<span class="hljs-params">self, img_feat_one, img_feat_two, text_feat_one, text_feat_two</span>): | |
| sim_direction = F.cosine_similarity(img_feat_two - img_feat_one, text_feat_two - text_feat_one) | |
| <span class="hljs-keyword">return</span> sim_direction | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">forward</span>(<span class="hljs-params">self, image_one, image_two, caption_one, caption_two</span>): | |
| img_feat_one = self.encode_image(image_one) | |
| img_feat_two = self.encode_image(image_two) | |
| text_feat_one = self.encode_text(caption_one) | |
| text_feat_two = self.encode_text(caption_two) | |
| directional_similarity = self.compute_directional_similarity( | |
| img_feat_one, img_feat_two, text_feat_one, text_feat_two | |
| ) | |
| <span class="hljs-keyword">return</span> directional_similarity<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1tdcjay">Let’s put <code>DirectionalSimilarity</code> to use now.</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->dir_similarity = DirectionalSimilarity(tokenizer, text_encoder, image_processor, image_encoder) | |
| scores = [] | |
| <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(input_images)): | |
| original_image = input_images[i] | |
| original_caption = original_captions[i] | |
| edited_image = edited_images[i] | |
| modified_caption = modified_captions[i] | |
| similarity_score = dir_similarity(original_image, edited_image, original_caption, modified_caption) | |
| scores.append(<span class="hljs-built_in">float</span>(similarity_score.detach().cpu())) | |
| <span class="hljs-built_in">print</span>(<span class="hljs-string">f"CLIP directional similarity: <span class="hljs-subst">{np.mean(scores)}</span>"</span>) | |
| <span class="hljs-comment"># CLIP directional similarity: 0.0797976553440094</span><!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-14mrga2">Like the CLIP Score, the higher the CLIP directional similarity, the better it is.</p> <p data-svelte-h="svelte-vck7qn">It should be noted that the <code>StableDiffusionInstructPix2PixPipeline</code> exposes two arguments, namely, <code>image_guidance_scale</code> and <code>guidance_scale</code> that let you control the quality of the final edited image. We encourage you to experiment with these two arguments and see the impact of that on the directional similarity.</p> <p data-svelte-h="svelte-nbfdj7">We can extend the idea of this metric to measure how similar the original image and edited version are. To do that, we can just do <code>F.cosine_similarity(img_feat_two, img_feat_one)</code>. For these kinds of edits, we would still want the primary semantics of the images to be preserved as much as possible, i.e., a high similarity score.</p> <p data-svelte-h="svelte-9ga2iu">We can use these metrics for similar pipelines such as the <a href="https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix_zero#diffusers.StableDiffusionPix2PixZeroPipeline" rel="nofollow"><code>StableDiffusionPix2PixZeroPipeline</code></a>.</p> <div class="course-tip bg-gradient-to-br dark:bg-gradient-to-r before:border-green-500 dark:before:border-green-800 from-green-50 dark:from-gray-900 to-white dark:to-gray-950 border border-green-50 text-green-700 dark:text-gray-400"><p data-svelte-h="svelte-1jj27lk">Both CLIP score and CLIP direction similarity rely on the CLIP model, which can make the evaluations biased.</p></div> <p data-svelte-h="svelte-7qwtg3"><strong><em>Extending metrics like IS, FID (discussed later), or KID can be difficult</em></strong> when the model under evaluation was pre-trained on a large image-captioning dataset (such as the <a href="https://laion.ai/blog/laion-5b/" rel="nofollow">LAION-5B dataset</a>). This is because underlying these metrics is an InceptionNet (pre-trained on the ImageNet-1k dataset) used for extracting intermediate image features. The pre-training dataset of Stable Diffusion may have limited overlap with the pre-training dataset of InceptionNet, so it is not a good candidate here for feature extraction.</p> <p data-svelte-h="svelte-hcc15s"><strong><em>Using the above metrics helps evaluate models that are class-conditioned. For example, <a href="https://huggingface.co/docs/diffusers/main/en/api/pipelines/dit" rel="nofollow">DiT</a>. It was pre-trained being conditioned on the ImageNet-1k classes.</em></strong></p> <h3 class="relative group"><a id="class-conditioned-image-generation" 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" href="#class-conditioned-image-generation"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Class-conditioned image generation</span></h3> <p data-svelte-h="svelte-1jmn10t">Class-conditioned generative models are usually pre-trained on a class-labeled dataset such as <a href="https://huggingface.co/datasets/imagenet-1k" rel="nofollow">ImageNet-1k</a>. Popular metrics for evaluating these models include Fréchet Inception Distance (FID), Kernel Inception Distance (KID), and Inception Score (IS). In this document, we focus on FID (<a href="https://arxiv.org/abs/1706.08500" rel="nofollow">Heusel et al.</a>). We show how to compute it with the <a href="https://huggingface.co/docs/diffusers/api/pipelines/dit" rel="nofollow"><code>DiTPipeline</code></a>, which uses the <a href="https://arxiv.org/abs/2212.09748" rel="nofollow">DiT model</a> under the hood.</p> <p data-svelte-h="svelte-1rk18fl">FID aims to measure how similar are two datasets of images. As per <a href="https://mmgeneration.readthedocs.io/en/latest/quick_run.html#fid" rel="nofollow">this resource</a>:</p> <blockquote data-svelte-h="svelte-7e4j74"><p>Fréchet Inception Distance is a measure of similarity between two datasets of images. It was shown to correlate well with the human judgment of visual quality and is most often used to evaluate the quality of samples of Generative Adversarial Networks. FID is calculated by computing the Fréchet distance between two Gaussians fitted to feature representations of the Inception network.</p></blockquote> <p data-svelte-h="svelte-simh2d">These two datasets are essentially the dataset of real images and the dataset of fake images (generated images in our case). FID is usually calculated with two large datasets. However, for this document, we will work with two mini datasets.</p> <p data-svelte-h="svelte-1h659dy">Let’s first download a few images from the ImageNet-1k training set:</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> zipfile <span class="hljs-keyword">import</span> ZipFile | |
| <span class="hljs-keyword">import</span> requests | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">download</span>(<span class="hljs-params">url, local_filepath</span>): | |
| r = requests.get(url) | |
| <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(local_filepath, <span class="hljs-string">"wb"</span>) <span class="hljs-keyword">as</span> f: | |
| f.write(r.content) | |
| <span class="hljs-keyword">return</span> local_filepath | |
| dummy_dataset_url = <span class="hljs-string">"https://hf.co/datasets/sayakpaul/sample-datasets/resolve/main/sample-imagenet-images.zip"</span> | |
| local_filepath = download(dummy_dataset_url, dummy_dataset_url.split(<span class="hljs-string">"/"</span>)[-<span class="hljs-number">1</span>]) | |
| <span class="hljs-keyword">with</span> ZipFile(local_filepath, <span class="hljs-string">"r"</span>) <span class="hljs-keyword">as</span> zipper: | |
| zipper.extractall(<span class="hljs-string">"."</span>)<!-- HTML_TAG_END --></pre></div> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image | |
| <span class="hljs-keyword">import</span> os | |
| dataset_path = <span class="hljs-string">"sample-imagenet-images"</span> | |
| image_paths = <span class="hljs-built_in">sorted</span>([os.path.join(dataset_path, x) <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> os.listdir(dataset_path)]) | |
| real_images = [np.array(Image.<span class="hljs-built_in">open</span>(path).convert(<span class="hljs-string">"RGB"</span>)) <span class="hljs-keyword">for</span> path <span class="hljs-keyword">in</span> image_paths]<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1jd4ltz">These are 10 images from the following ImageNet-1k classes: “cassette_player”, “chain_saw” (x2), “church”, “gas_pump” (x3), “parachute” (x2), and “tench”.</p> <p align="center" data-svelte-h="svelte-94lw7t"><img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/real-images.png" alt="real-images"><br> <em>Real images.</em></p> <p data-svelte-h="svelte-iw90qp">Now that the images are loaded, let’s apply some lightweight pre-processing on them to use them for FID calculation.</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> torchvision.transforms <span class="hljs-keyword">import</span> functional <span class="hljs-keyword">as</span> F | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">preprocess_image</span>(<span class="hljs-params">image</span>): | |
| image = torch.tensor(image).unsqueeze(<span class="hljs-number">0</span>) | |
| image = image.permute(<span class="hljs-number">0</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>) / <span class="hljs-number">255.0</span> | |
| <span class="hljs-keyword">return</span> F.center_crop(image, (<span class="hljs-number">256</span>, <span class="hljs-number">256</span>)) | |
| real_images = torch.cat([preprocess_image(image) <span class="hljs-keyword">for</span> image <span class="hljs-keyword">in</span> real_images]) | |
| <span class="hljs-built_in">print</span>(real_images.shape) | |
| <span class="hljs-comment"># torch.Size([10, 3, 256, 256])</span><!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-a40j2v">We now load the <a href="https://huggingface.co/docs/diffusers/api/pipelines/dit" rel="nofollow"><code>DiTPipeline</code></a> to generate images conditioned on the above-mentioned classes.</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> diffusers <span class="hljs-keyword">import</span> DiTPipeline, DPMSolverMultistepScheduler | |
| dit_pipeline = DiTPipeline.from_pretrained(<span class="hljs-string">"facebook/DiT-XL-2-256"</span>, torch_dtype=torch.float16) | |
| dit_pipeline.scheduler = DPMSolverMultistepScheduler.from_config(dit_pipeline.scheduler.config) | |
| dit_pipeline = dit_pipeline.to(<span class="hljs-string">"cuda"</span>) | |
| words = [ | |
| <span class="hljs-string">"cassette player"</span>, | |
| <span class="hljs-string">"chainsaw"</span>, | |
| <span class="hljs-string">"chainsaw"</span>, | |
| <span class="hljs-string">"church"</span>, | |
| <span class="hljs-string">"gas pump"</span>, | |
| <span class="hljs-string">"gas pump"</span>, | |
| <span class="hljs-string">"gas pump"</span>, | |
| <span class="hljs-string">"parachute"</span>, | |
| <span class="hljs-string">"parachute"</span>, | |
| <span class="hljs-string">"tench"</span>, | |
| ] | |
| class_ids = dit_pipeline.get_label_ids(words) | |
| output = dit_pipeline(class_labels=class_ids, generator=generator, output_type=<span class="hljs-string">"np"</span>) | |
| fake_images = output.images | |
| fake_images = torch.tensor(fake_images) | |
| fake_images = fake_images.permute(<span class="hljs-number">0</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>) | |
| <span class="hljs-built_in">print</span>(fake_images.shape) | |
| <span class="hljs-comment"># torch.Size([10, 3, 256, 256])</span><!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1nlt7gv">Now, we can compute the FID using <a href="https://torchmetrics.readthedocs.io/" rel="nofollow"><code>torchmetrics</code></a>.</p> <div class="code-block relative"><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> torchmetrics.image.fid <span class="hljs-keyword">import</span> FrechetInceptionDistance | |
| fid = FrechetInceptionDistance(normalize=<span class="hljs-literal">True</span>) | |
| fid.update(real_images, real=<span class="hljs-literal">True</span>) | |
| fid.update(fake_images, real=<span class="hljs-literal">False</span>) | |
| <span class="hljs-built_in">print</span>(<span class="hljs-string">f"FID: <span class="hljs-subst">{<span class="hljs-built_in">float</span>(fid.compute())}</span>"</span>) | |
| <span class="hljs-comment"># FID: 177.7147216796875</span><!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-17lmdw3">The lower the FID, the better it is. Several things can influence FID here:</p> <ul data-svelte-h="svelte-16n90lm"><li>Number of images (both real and fake)</li> <li>Randomness induced in the diffusion process</li> <li>Number of inference steps in the diffusion process</li> <li>The scheduler being used in the diffusion process</li></ul> <p data-svelte-h="svelte-1evgdla">For the last two points, it is, therefore, a good practice to run the evaluation across different seeds and inference steps, and then report an average result.</p> <div class="course-tip course-tip-orange bg-gradient-to-br dark:bg-gradient-to-r before:border-orange-500 dark:before:border-orange-800 from-orange-50 dark:from-gray-900 to-white dark:to-gray-950 border border-orange-50 text-orange-700 dark:text-gray-400"><p data-svelte-h="svelte-nu8das">FID results tend to be fragile as they depend on a lot of factors:</p> <ul data-svelte-h="svelte-1u7ggn4"><li>The specific Inception model used during computation.</li> <li>The implementation accuracy of the computation.</li> <li>The image format (not the same if we start from PNGs vs JPGs).</li></ul> <p data-svelte-h="svelte-tbdsq8">Keeping that in mind, FID is often most useful when comparing similar runs, but it is | |
| hard to reproduce paper results unless the authors carefully disclose the FID | |
| measurement code.</p> <p data-svelte-h="svelte-11vfq1v">These points apply to other related metrics too, such as KID and IS.</p></div> <p data-svelte-h="svelte-ptrlon">As a final step, let’s visually inspect the <code>fake_images</code>.</p> <p align="center" data-svelte-h="svelte-16e5oh4"><img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/fake-images.png" alt="fake-images"><br> <em>Fake images.</em></p> <a class="!text-gray-400 !no-underline text-sm flex items-center not-prose mt-4" href="https://github.com/huggingface/diffusers/blob/main/docs/source/en/conceptual/evaluation.md" target="_blank"><span data-svelte-h="svelte-1kd6by1"><</span> <span data-svelte-h="svelte-x0xyl0">></span> <span data-svelte-h="svelte-1dajgef"><span class="underline ml-1.5">Update</span> on GitHub</span></a> <p></p> | |
| <script> | |
| { | |
| __sveltekit_1eu7tzz = { | |
| assets: "/docs/diffusers/main/en", | |
| base: "/docs/diffusers/main/en", | |
| env: {} | |
| }; | |
| const element = document.currentScript.parentElement; | |
| const data = [null,null]; | |
| Promise.all([ | |
| import("/docs/diffusers/main/en/_app/immutable/entry/start.21e27d66.js"), | |
| import("/docs/diffusers/main/en/_app/immutable/entry/app.de4fb612.js") | |
| ]).then(([kit, app]) => { | |
| kit.start(app, element, { | |
| node_ids: [0, 162], | |
| data, | |
| form: null, | |
| error: null | |
| }); | |
| }); | |
| } | |
| </script> | |
Xet Storage Details
- Size:
- 81.3 kB
- Xet hash:
- bbd38d4db22705fcd1c262e36d575940cbe17c968e0c608882a9eb76d0598a02
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.