インテルにより適用された OpenVINO を使用した Stable Diffusion v2.1

この Jupyter ノートブックは、ローカルへのインストール後にのみ起動できます。

GitHub

image0

目次

Optimum Intel は、インテル® アーキテクチャー上のエンドツーエンドのパイプラインを高速化するため、Transformers および Diffuser ライブラリーと、インテルが提供するさまざまなツールとライブラリー間のインターフェイスです。詳細については、このリポジトリーをご覧ください。

Note: We suggest you to create a different environment and run the following installation command there.

%pip install -q "optimum-intel[openvino,diffusers]@git+https://github.com/huggingface/optimum-intel.git" "ipywidgets" "transformers>=4.33" --extra-index-url https://download.pytorch.org/whl/cpu
Note: you may need to restart the kernel to use updated packages.

Stable Diffusion パイプラインは、トークナイザーを備えたテキスト・エンコーダー・モデル、スケジューラーを備えた UNet モデル、およびデコーダーモデルとエンコーダー・モデルを備えたオート・エンコーダーの 6 つの要素を統合する必要があります。

image

画像

この例で使用される基本モデルは、stabilityai/stable-diffusion-2-1-base です。このモデルは、OpenVINO を optimum-intel に統合することで、CPU またはインテル® GPU で推論を高速化するため OpenVINO 形式に変換されました。モデルの重みは FP16 精度で保存されるため、モデルのサイズが半分になります。このノートブックで使用されているモデルは helenai/stabilityai-stable-diffusion-2-1-base-ov です。変換済みモデル Stable Diffusion 2.1 中間表現形式 (IR) をダウンロードします。

利用可能なデバイスの情報を表示

available_devices プロパティーには、システム内で使用可能なデバイスが表示されます。ie.get_property() の “FULL_DEVICE_NAME” オプションはデバイスの名前を表示します。個別 GPU の ID 名を確認します。統合 GPU (iGPU) と専用 GPU (dGPU) がある場合、iGPU の場合は device_name="GPU.0"、dGPU の場合は device_name="GPU.1" と表示されます。
GPU に割り当てられる iGPU または dGPU のいずれかのみがある場合: "GPU"

注: OpenVINO を使用した GPU の詳細については、このリンクを参照してください。Ubuntu* 20.04 または Windows* 11 で問題が発生した場合は、このブログをご覧ください。

from openvino.runtime import Core

ie = Core()
devices = ie.available_devices

for device in devices:
                                        device_name = ie.get_property(device, "FULL_DEVICE_NAME")
                                        print(f"{device}: {device_name}")
CPU: 13th Gen Intel(R) Core(TM) i9-13900K
GPU.0: Intel(R) UHD Graphics 770 (iGPU)
GPU.1: Intel(R) Arc(TM) A770 Graphics (dGPU)

変換済みの Stable Diffusion 2.1 IR をダウンロード

from optimum.intel.openvino import OVStableDiffusionPipeline
# download the pre-converted SD v2.1 model from Hugging Face Hub
name = "helenai/stabilityai-stable-diffusion-2-1-base-ov"

pipe = OVStableDiffusionPipeline.from_pretrained(name, compile=False)
pipe.reshape(batch_size=1, height=512, width=512, num_images_per_prompt=1)
2023-07-03 11:16:29.469651: I tensorflow/core/util/port.cc:110] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable TF_ENABLE_ONEDNN_OPTS=0.
2023-07-03 11:16:29.507431: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: AVX2 AVX512F AVX512_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
2023-07-03 11:16:30.127586: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT
INFO:nncf:NNCF initialized successfully. Supported frameworks detected: torch, tensorflow, onnx, openvino
No CUDA runtime is found, using CUDA_HOME='/usr/local/cuda'
/home/ea/work/notebooks_convert/notebooks_conv_env/lib/python3.8/site-packages/diffusers/models/cross_attention.py:30: FutureWarning: Importing from cross_attention is deprecated. Please import from diffusers.models.attention_processor instead.
  deprecate(
comet_ml is installed but COMET_API_KEY is not set.
The config attributes {'requires_safety_checker': False, 'safety_checker': [None, None]} were passed to OVStableDiffusionPipeline, but are not expected and will be ignored. Please verify your model_index.json configuration file.
Fetching 13 files:   0%|          | 0/13 [00:00<?, ?it/s]
/home/ea/work/notebooks_convert/notebooks_conv_env/lib/python3.8/site-packages/transformers/models/clip/feature_extraction_clip.py:28: FutureWarning: The class CLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please use CLIPImageProcessor instead.
                                        warnings.warn(
OVStableDiffusionPipeline {
                                        "_class_name": "OVStableDiffusionPipeline",
                                        "_diffusers_version": "0.16.1",
                                        "feature_extractor": [
                                        "transformers",
                                        "CLIPFeatureExtractor"
                                        ],
                                        "requires_safety_checker": false,
                                        "safety_checker": [
                                        null,
                                        null
                                        ],
                                        "scheduler": [
                                        "diffusers",
                                        "PNDMScheduler"
                                        ],
                                        "text_encoder": [
                                        "optimum",
                                        "OVModelTextEncoder"
                                        ],
                                        "tokenizer": [
                                        "transformers",
                                        "CLIPTokenizer"
                                        ],
                                        "unet": [
                                        "optimum",
                                        "OVModelUnet"
                                        ],
                                        "vae_decoder": [
                                        "optimum",
                                        "OVModelVaeDecoder"
                                        ],
                                        "vae_encoder": [
                                        null,
                                        null
                                        ]
}

事前トレーニングされたモデルを保存し推論デバイスを選択してコンパイル

後でダウンロードしなくてもいいように、モデルをローカルに保存できます。モデルはキャッシュにも保存されます。

# pipe.save_pretrained("./openvino_ir") # Uncomment if you need the model for further compilations
pipe.to("GPU")
pipe.compile()
Compiling the text_encoder...
Compiling the vae_decoder...
Compiling the unet...

創造力を発揮してプロンプトを追加して結果を楽しんでください

import gc

# Generate an image.
prompt = "red car in snowy forest, epic vista, beautiful landscape, 4k, 8k"
output = pipe(prompt, num_inference_steps=17, output_type="pil").images[0]
output.save("image.png")
output
0%|          | 0/18 [00:00<?, ?it/s]
../_images/236-stable-diffusion-v2-optimum-demo-with-output_13_1.png
del pipe
gc.collect()