Path: blob/main/tests/pipelines/stable_diffusion/test_onnx_stable_diffusion_img2img.py
1448 views
# coding=utf-81# Copyright 2023 HuggingFace Inc.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.1415import random16import unittest1718import numpy as np1920from diffusers import (21DPMSolverMultistepScheduler,22EulerAncestralDiscreteScheduler,23EulerDiscreteScheduler,24LMSDiscreteScheduler,25OnnxStableDiffusionImg2ImgPipeline,26PNDMScheduler,27)28from diffusers.utils import floats_tensor29from diffusers.utils.testing_utils import (30is_onnx_available,31load_image,32nightly,33require_onnxruntime,34require_torch_gpu,35)3637from ...test_pipelines_onnx_common import OnnxPipelineTesterMixin383940if is_onnx_available():41import onnxruntime as ort424344class OnnxStableDiffusionImg2ImgPipelineFastTests(OnnxPipelineTesterMixin, unittest.TestCase):45hub_checkpoint = "hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline"4647def get_dummy_inputs(self, seed=0):48image = floats_tensor((1, 3, 128, 128), rng=random.Random(seed))49generator = np.random.RandomState(seed)50inputs = {51"prompt": "A painting of a squirrel eating a burger",52"image": image,53"generator": generator,54"num_inference_steps": 3,55"strength": 0.75,56"guidance_scale": 7.5,57"output_type": "numpy",58}59return inputs6061def test_pipeline_default_ddim(self):62pipe = OnnxStableDiffusionImg2ImgPipeline.from_pretrained(self.hub_checkpoint, provider="CPUExecutionProvider")63pipe.set_progress_bar_config(disable=None)6465inputs = self.get_dummy_inputs()66image = pipe(**inputs).images67image_slice = image[0, -3:, -3:, -1].flatten()6869assert image.shape == (1, 128, 128, 3)70expected_slice = np.array([0.69643, 0.58484, 0.50314, 0.58760, 0.55368, 0.59643, 0.51529, 0.41217, 0.49087])71assert np.abs(image_slice - expected_slice).max() < 1e-17273def test_pipeline_pndm(self):74pipe = OnnxStableDiffusionImg2ImgPipeline.from_pretrained(self.hub_checkpoint, provider="CPUExecutionProvider")75pipe.scheduler = PNDMScheduler.from_config(pipe.scheduler.config, skip_prk_steps=True)76pipe.set_progress_bar_config(disable=None)7778inputs = self.get_dummy_inputs()79image = pipe(**inputs).images80image_slice = image[0, -3:, -3:, -1]8182assert image.shape == (1, 128, 128, 3)83expected_slice = np.array([0.61710, 0.53390, 0.49310, 0.55622, 0.50982, 0.58240, 0.50716, 0.38629, 0.46856])8485assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-18687def test_pipeline_lms(self):88pipe = OnnxStableDiffusionImg2ImgPipeline.from_pretrained(self.hub_checkpoint, provider="CPUExecutionProvider")89pipe.scheduler = LMSDiscreteScheduler.from_config(pipe.scheduler.config)90pipe.set_progress_bar_config(disable=None)9192# warmup pass to apply optimizations93_ = pipe(**self.get_dummy_inputs())9495inputs = self.get_dummy_inputs()96image = pipe(**inputs).images97image_slice = image[0, -3:, -3:, -1]9899assert image.shape == (1, 128, 128, 3)100expected_slice = np.array([0.52761, 0.59977, 0.49033, 0.49619, 0.54282, 0.50311, 0.47600, 0.40918, 0.45203])101102assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1103104def test_pipeline_euler(self):105pipe = OnnxStableDiffusionImg2ImgPipeline.from_pretrained(self.hub_checkpoint, provider="CPUExecutionProvider")106pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config)107pipe.set_progress_bar_config(disable=None)108109inputs = self.get_dummy_inputs()110image = pipe(**inputs).images111image_slice = image[0, -3:, -3:, -1]112113assert image.shape == (1, 128, 128, 3)114expected_slice = np.array([0.52911, 0.60004, 0.49229, 0.49805, 0.54502, 0.50680, 0.47777, 0.41028, 0.45304])115116assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1117118def test_pipeline_euler_ancestral(self):119pipe = OnnxStableDiffusionImg2ImgPipeline.from_pretrained(self.hub_checkpoint, provider="CPUExecutionProvider")120pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)121pipe.set_progress_bar_config(disable=None)122123inputs = self.get_dummy_inputs()124image = pipe(**inputs).images125image_slice = image[0, -3:, -3:, -1]126127assert image.shape == (1, 128, 128, 3)128expected_slice = np.array([0.52911, 0.60004, 0.49229, 0.49805, 0.54502, 0.50680, 0.47777, 0.41028, 0.45304])129130assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1131132def test_pipeline_dpm_multistep(self):133pipe = OnnxStableDiffusionImg2ImgPipeline.from_pretrained(self.hub_checkpoint, provider="CPUExecutionProvider")134pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)135pipe.set_progress_bar_config(disable=None)136137inputs = self.get_dummy_inputs()138image = pipe(**inputs).images139image_slice = image[0, -3:, -3:, -1]140141assert image.shape == (1, 128, 128, 3)142expected_slice = np.array([0.65331, 0.58277, 0.48204, 0.56059, 0.53665, 0.56235, 0.50969, 0.40009, 0.46552])143144assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1145146147@nightly148@require_onnxruntime149@require_torch_gpu150class OnnxStableDiffusionImg2ImgPipelineIntegrationTests(unittest.TestCase):151@property152def gpu_provider(self):153return (154"CUDAExecutionProvider",155{156"gpu_mem_limit": "15000000000", # 15GB157"arena_extend_strategy": "kSameAsRequested",158},159)160161@property162def gpu_options(self):163options = ort.SessionOptions()164options.enable_mem_pattern = False165return options166167def test_inference_default_pndm(self):168init_image = load_image(169"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"170"/img2img/sketch-mountains-input.jpg"171)172init_image = init_image.resize((768, 512))173# using the PNDM scheduler by default174pipe = OnnxStableDiffusionImg2ImgPipeline.from_pretrained(175"CompVis/stable-diffusion-v1-4",176revision="onnx",177safety_checker=None,178feature_extractor=None,179provider=self.gpu_provider,180sess_options=self.gpu_options,181)182pipe.set_progress_bar_config(disable=None)183184prompt = "A fantasy landscape, trending on artstation"185186generator = np.random.RandomState(0)187output = pipe(188prompt=prompt,189image=init_image,190strength=0.75,191guidance_scale=7.5,192num_inference_steps=10,193generator=generator,194output_type="np",195)196images = output.images197image_slice = images[0, 255:258, 383:386, -1]198199assert images.shape == (1, 512, 768, 3)200expected_slice = np.array([0.4909, 0.5059, 0.5372, 0.4623, 0.4876, 0.5049, 0.4820, 0.4956, 0.5019])201# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues202203assert np.abs(image_slice.flatten() - expected_slice).max() < 2e-2204205def test_inference_k_lms(self):206init_image = load_image(207"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"208"/img2img/sketch-mountains-input.jpg"209)210init_image = init_image.resize((768, 512))211lms_scheduler = LMSDiscreteScheduler.from_pretrained(212"runwayml/stable-diffusion-v1-5", subfolder="scheduler", revision="onnx"213)214pipe = OnnxStableDiffusionImg2ImgPipeline.from_pretrained(215"runwayml/stable-diffusion-v1-5",216revision="onnx",217scheduler=lms_scheduler,218safety_checker=None,219feature_extractor=None,220provider=self.gpu_provider,221sess_options=self.gpu_options,222)223pipe.set_progress_bar_config(disable=None)224225prompt = "A fantasy landscape, trending on artstation"226227generator = np.random.RandomState(0)228output = pipe(229prompt=prompt,230image=init_image,231strength=0.75,232guidance_scale=7.5,233num_inference_steps=20,234generator=generator,235output_type="np",236)237images = output.images238image_slice = images[0, 255:258, 383:386, -1]239240assert images.shape == (1, 512, 768, 3)241expected_slice = np.array([0.8043, 0.926, 0.9581, 0.8119, 0.8954, 0.913, 0.7209, 0.7463, 0.7431])242# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues243244assert np.abs(image_slice.flatten() - expected_slice).max() < 2e-2245246247