diff --git a/.ci/ignore_treon_docker.txt b/.ci/ignore_treon_docker.txt index 6373cdcb838..b9aafa5bef8 100644 --- a/.ci/ignore_treon_docker.txt +++ b/.ci/ignore_treon_docker.txt @@ -78,4 +78,5 @@ notebooks/qwen2.5-omni-chatbot/qwen2.5-omni-chatbot.ipynb notebooks/intern-video2-classiciation/intern-video2-classification.ipynb notebooks/flex.2-image-generation/flex.2-image-generation.ipynb notebooks/wan2.1-text-to-video/wan2.1-text-to-video.ipynb -notebooks/ace-step-music-generation/ace-step-music-generation.ipynb \ No newline at end of file +notebooks/ace-step-music-generation/ace-step-music-generation.ipynb +notebooks/qwen-image/qwen-image.ipynb \ No newline at end of file diff --git a/notebooks/qwen-image/README.md b/notebooks/qwen-image/README.md new file mode 100644 index 00000000000..996d83ca324 --- /dev/null +++ b/notebooks/qwen-image/README.md @@ -0,0 +1,31 @@ +# Text-to-image generation with Qwen-Image and OpenVINO + +Qwen-Image, an image generation foundation model in the Qwen series that achieves significant advances in complex text rendering and precise image editing. Experiments show strong general capabilities in both image generation and editing, with exceptional performance in text rendering, especially for Chinese. More details about model can be found in [blog post](https://qwenlm.github.io/blog/qwen-image/) and [model card](https://huggingface.co/Qwen/Qwen-Image). + + + + +In this tutorial we consider how to convert and optimize Qwen-Image model using OpenVINO. + +>**Note**: Some demonstrated models can require at least 64GB RAM for conversion and running. + +### Notebook Contents + +In this demonstration, you will learn how to perform text-to-image generation using Qwen-Image and OpenVINO. + +The tutorial consists of the following steps: + +- Install prerequisites +- Collect Pytorch model pipeline +- Convert model to OpenVINO intermediate representation (IR) format +- Compress weights using NNCF +- Prepare OpenVINO Inference pipeline +- Run Text-to-Image generation +- Launch interactive demo + +## Installation Instructions + +This is a self-contained example that relies solely on its own code.
+We recommend running the notebook in a virtual environment. You only need a Jupyter server to start. +For further details, please refer to [Installation Guide](../../README.md). + diff --git a/notebooks/qwen-image/gradio_helper.py b/notebooks/qwen-image/gradio_helper.py new file mode 100644 index 00000000000..57283d19612 --- /dev/null +++ b/notebooks/qwen-image/gradio_helper.py @@ -0,0 +1,199 @@ +import gradio as gr +import numpy as np +import random +import torch + + +def make_demo(ov_pipe): + def get_caption_language(prompt): + ranges = [ + ("\u4e00", "\u9fff"), # CJK Unified Ideographs + # ('\u3400', '\u4dbf'), # CJK Unified Ideographs Extension A + # ('\u20000', '\u2a6df'), # CJK Unified Ideographs Extension B + ] + for char in prompt: + if any(start <= char <= end for start, end in ranges): + return "zh" + return "en" + + def polish_prompt_en(original_prompt): + magic_prompt = "Ultra HD, 4K, cinematic composition" + return original_prompt + ", " + magic_prompt + + def polish_prompt_zh(original_prompt): + magic_prompt = "超清,4K,电影级构图" + return original_prompt + "," + magic_prompt + + def rewrite(input_prompt): + lang = get_caption_language(input_prompt) + if lang == "zh": + return polish_prompt_zh(input_prompt) + elif lang == "en": + + return polish_prompt_en(input_prompt) + + # --- Model Loading --- + dtype = torch.bfloat16 + device = "cuda" if torch.cuda.is_available() else "cpu" + + # --- UI Constants and Helpers --- + MAX_SEED = np.iinfo(np.int32).max + + def get_image_size(aspect_ratio): + """Converts aspect ratio string to width, height tuple.""" + if aspect_ratio == "1:1": + return 1328, 1328 + elif aspect_ratio == "16:9": + return 1664, 928 + elif aspect_ratio == "9:16": + return 928, 1664 + elif aspect_ratio == "4:3": + return 1472, 1104 + elif aspect_ratio == "3:4": + return 1104, 1472 + elif aspect_ratio == "3:2": + return 1584, 1056 + elif aspect_ratio == "2:3": + return 1056, 1584 + else: + # Default to 1:1 if something goes wrong + return 1328, 1328 + + def infer( + prompt, + seed=42, + randomize_seed=False, + aspect_ratio="16:9", + guidance_scale=4.0, + num_inference_steps=50, + prompt_enhance=True, + progress=gr.Progress(track_tqdm=True), + ): + """ + Generates an image using the local Qwen-Image diffusers pipeline. + """ + # Hardcode the negative prompt as requested + negative_prompt = "text, watermark, copyright, blurry, low resolution" + + if randomize_seed: + seed = random.randint(0, MAX_SEED) + + # Convert aspect ratio to width and height + width, height = get_image_size(aspect_ratio) + + # Set up the generator for reproducibility + generator = torch.Generator(device=device).manual_seed(seed) + + print(f"Calling pipeline with prompt: '{prompt}'") + if prompt_enhance: + prompt = rewrite(prompt) + print(f"Actual Prompt: '{prompt}'") + print(f"Negative Prompt: '{negative_prompt}'") + print(f"Seed: {seed}, Size: {width}x{height}, Steps: {num_inference_steps}, Guidance: {guidance_scale}") + + # Generate the image + image = ov_pipe( + prompt=prompt, + negative_prompt=negative_prompt, + width=width, + height=height, + num_inference_steps=num_inference_steps, + generator=generator, + true_cfg_scale=guidance_scale, + guidance_scale=1.0, # Use a fixed default for distilled guidance + ).images[0] + + return image, seed + + # --- Examples and UI Layout --- + examples = [ + "A capybara wearing a suit holding a sign that reads Hello World", + "一幅精致细腻的工笔画,画面中心是一株蓬勃生长的红色牡丹,花朵繁茂,既有盛开的硕大花瓣,也有含苞待放的花蕾,层次丰富,色彩艳丽而不失典雅。牡丹枝叶舒展,叶片浓绿饱满,脉络清晰可见,与红花相映成趣。一只蓝紫色蝴蝶仿佛被画中花朵吸引,停驻在画面中央的一朵盛开牡丹上,流连忘返,蝶翼轻展,细节逼真,仿佛随时会随风飞舞。整幅画作笔触工整严谨,色彩浓郁鲜明,展现出中国传统工笔画的精妙与神韵,画面充满生机与灵动之感。", + "一位身着淡雅水粉色交领襦裙的年轻女子背对镜头而坐,俯身专注地手持毛笔在素白宣纸上书写“通義千問”四个遒劲汉字。古色古香的室内陈设典雅考究,案头错落摆放着青瓷茶盏与鎏金香炉,一缕熏香轻盈升腾;柔和光线洒落肩头,勾勒出她衣裙的柔美质感与专注神情,仿佛凝固了一段宁静温润的旧时光。", + " 一个可抽取式的纸巾盒子,上面写着'Face, CLEAN & SOFT TISSUE'下面写着'亲肤可湿水',左上角是品牌名'洁柔',整体是白色和浅黄色的色调", + "手绘风格的水循环示意图,整体画面呈现出一幅生动形象的水循环过程图解。画面中央是一片起伏的山脉和山谷,山谷中流淌着一条清澈的河流,河流最终汇入一片广阔的海洋。山体和陆地上绘制有绿色植被。画面下方为地下水层,用蓝色渐变色块表现,与地表水形成层次分明的空间关系。太阳位于画面右上角,促使地表水蒸发,用上升的曲线箭头表示蒸发过程。云朵漂浮在空中,由白色棉絮状绘制而成,部分云层厚重,表示水汽凝结成雨,用向下箭头连接表示降雨过程。雨水以蓝色线条和点状符号表示,从云中落下,补充河流与地下水。整幅图以卡通手绘风格呈现,线条柔和,色彩明亮,标注清晰。背景为浅黄色纸张质感,带有轻微的手绘纹理。", + '一个会议室,墙上写着"3.14159265-358979-32384626-4338327950",一个小陀螺在桌上转动', + "一个咖啡店门口有一个黑板,上面写着通义千问咖啡,2美元一杯,旁边有个霓虹灯,写着阿里巴巴,旁边有个海报,海报上面是一个中国美女,海报下方写着qwen newbee", + """A young girl wearing school uniform stands in a classroom, writing on a chalkboard. The text "Introducing Qwen-Image, a foundational image generation model that excels in complex text rendering and precise image editing" appears in neat white chalk at the center of the blackboard. Soft natural light filters through windows, casting gentle shadows. The scene is rendered in a realistic photography style with fine details, shallow depth of field, and warm tones. The girl's focused expression and chalk dust in the air add dynamism. Background elements include desks and educational posters, subtly blurred to emphasize the central action. Ultra-detailed 32K resolution, DSLR-quality, soft bokeh effect, documentary-style composition""", + "Realistic still life photography style: A single, fresh apple resting on a clean, soft-textured surface. The apple is slightly off-center, softly backlit to highlight its natural gloss and subtle color gradients—deep crimson red blending into light golden hues. Fine details such as small blemishes, dew drops, and a few light highlights enhance its lifelike appearance. A shallow depth of field gently blurs the neutral background, drawing full attention to the apple. Hyper-detailed 8K resolution, studio lighting, photorealistic render, emphasizing texture and form.", + ] + + css = """ + #col-container { + margin: 0 auto; + max-width: 1024px; + } + """ + + with gr.Blocks(css=css) as demo: + with gr.Column(elem_id="col-container"): + gr.Markdown( + 'Qwen-Image Logo' + ) + with gr.Row(): + prompt = gr.Text( + label="Prompt", + show_label=False, + placeholder="Enter your prompt", + container=False, + ) + run_button = gr.Button("Run", scale=0, variant="primary") + + result = gr.Image(label="Result", show_label=False, type="pil") + + with gr.Accordion("Advanced Settings", open=False): + # Negative prompt UI element is removed here + + seed = gr.Slider( + label="Seed", + minimum=0, + maximum=MAX_SEED, + step=1, + value=0, + ) + + randomize_seed = gr.Checkbox(label="Randomize seed", value=True) + + with gr.Row(): + aspect_ratio = gr.Radio( + label="Aspect ratio (width:height)", + choices=["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3"], + value="16:9", + ) + prompt_enhance = gr.Checkbox(label="Prompt Enhance", value=True) + + with gr.Row(): + guidance_scale = gr.Slider( + label="Guidance scale", + minimum=0.0, + maximum=10.0, + step=0.1, + value=4.0, + ) + + num_inference_steps = gr.Slider( + label="Number of inference steps", + minimum=1, + maximum=50, + step=1, + value=50, + ) + + gr.Examples(examples=examples, inputs=[prompt], outputs=[result, seed], fn=infer, cache_examples=False) + + gr.on( + triggers=[run_button.click, prompt.submit], + fn=infer, + inputs=[ + prompt, + # negative_prompt is no longer an input from the UI + seed, + randomize_seed, + aspect_ratio, + guidance_scale, + num_inference_steps, + prompt_enhance, + ], + outputs=[result, seed], + ) + return demo diff --git a/notebooks/qwen-image/qwen-image.ipynb b/notebooks/qwen-image/qwen-image.ipynb new file mode 100644 index 00000000000..670eb124419 --- /dev/null +++ b/notebooks/qwen-image/qwen-image.ipynb @@ -0,0 +1,579 @@ +{ + "cells": [ + { + "attachments": {}, + "cell_type": "markdown", + "id": "c31fcb69-002f-47bc-92b5-71b36eb2977e", + "metadata": {}, + "source": [ + "# Text-to-image generation with Qwen-Image and OpenVINO\n", + "\n", + "Qwen-Image, an image generation foundation model in the Qwen series that achieves significant advances in complex text rendering and precise image editing. Experiments show strong general capabilities in both image generation and editing, with exceptional performance in text rendering, especially for Chinese. More details about model can be found in [blog post](https://qwenlm.github.io/blog/qwen-image/) and [model card](https://huggingface.co/Qwen/Qwen-Image).\n", + "\n", + "\n", + "\n", + "\n", + "In this tutorial we consider how to convert and optimize Qwen-Image model using OpenVINO.\n", + "\n", + ">**Note**: Some demonstrated models can require at least 64GB RAM for conversion and running.\n", + "\n", + "#### Table of contents:\n", + "\n", + "- [Prerequisites](#Prerequisites)\n", + "- [Select model](#Select-model)\n", + "- [Convert model with OpenVINO](#Convert-model-with-OpenVINO)\n", + " - [Convert model using Optimum Intel](#Convert-model-using-Optimum-Intel)\n", + " - [Compress model weights](#Compress-model-weights)\n", + "- [Run OpenVINO model inference](#Run-OpenVINO-model-inference)\n", + "- [Interactive demo](#Interactive-demo)\n", + "\n", + "\n", + "\n", + "### Installation Instructions\n", + "\n", + "This is a self-contained example that relies solely on its own code.\n", + "\n", + "We recommend running the notebook in a virtual environment. You only need a Jupyter server to start.\n", + "For details, please refer to [Installation Guide](https://github.com/openvinotoolkit/openvino_notebooks/blob/latest/README.md#-installation-guide).\n", + "\n", + "\n", + "\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "id": "97ce9e70-fdce-4187-a0ea-c69e0001e25a", + "metadata": {}, + "source": [ + "## Prerequisites\n", + "[back to top ⬆️](#Table-of-contents:)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "64fff924", + "metadata": { + "test_replace": { + "import platform\n": "%pip uninstall -y torchvision\nimport platform\n" + } + }, + "outputs": [], + "source": [ + "import platform\n", + "import requests\n", + "from pathlib import Path\n", + "\n", + "if not Path(\"cmd_helper.py\").exists():\n", + " r = requests.get(url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/cmd_helper.py\")\n", + " open(\"cmd_helper.py\", \"w\").write(r.text)\n", + "\n", + "if not Path(\"gradio_helper.py\").exists():\n", + " r = requests.get(url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/notebooks/qwen-image/gradio_helper.py\")\n", + " open(\"gradio_helper.py\", \"w\").write(r.text)\n", + "\n", + "if not Path(\"notebook_utils.py\").exists():\n", + " r = requests.get(url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/notebook_utils.py\")\n", + " open(\"notebook_utils.py\", \"w\").write(r.text)\n", + "\n", + "if not Path(\"pip_helper.py\").exists():\n", + " r = requests.get(\n", + " url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/pip_helper.py\",\n", + " )\n", + " open(\"pip_helper.py\", \"w\").write(r.text)\n", + "\n", + "from pip_helper import pip_install\n", + "\n", + "%pip uninstall -q -y diffusers optimum-intel\n", + "\n", + "pip_install(\n", + " \"-q\",\n", + " \"gradio>=4.19,<6\",\n", + " \"torch==2.8\",\n", + " \"transformers==4.55.4\",\n", + " \"nncf>=2.15.0\",\n", + " \"opencv-python\",\n", + " \"pillow\",\n", + " \"soxr==1.0.0\",\n", + " \"peft>=0.17.0\",\n", + " \"--extra-index-url\",\n", + " \"https://download.pytorch.org/whl/cpu\",\n", + ")\n", + "pip_install(\"-q\", \"sentencepiece\", \"protobuf\")\n", + "pip_install(\"-q\", \"diffusers>=0.35.0\")\n", + "pip_install(\"-q\", \"git+https://github.com/openvino-dev-samples/optimum-intel.git@qwen-image\")\n", + "pip_install(\"-qU\", \"openvino>=2025.3\")\n", + "\n", + "if platform.system() == \"Darwin\":\n", + " pip_install(\"numpy<2.0.0\")\n", + "\n", + "\n", + "# Read more about telemetry collection at https://github.com/openvinotoolkit/openvino_notebooks?tab=readme-ov-file#-telemetry\n", + "from notebook_utils import collect_telemetry\n", + "\n", + "collect_telemetry(\"qwen-image.ipynb\")" + ] + }, + { + "cell_type": "markdown", + "id": "54948f6e", + "metadata": {}, + "source": [ + "## Select model\n", + "[back to top ⬆️](#Table-of-contents:)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "43ffcb63", + "metadata": {}, + "outputs": [], + "source": [ + "import ipywidgets as widgets\n", + "\n", + "model_id = \"Qwen/Qwen-Image\"" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "id": "2578fc91-dda4-4a0b-9353-5654d2763905", + "metadata": {}, + "source": [ + ">**Note**: run Flux.1 kontext model with notebook, you will need to accept license agreement. \n", + ">You must be a registered user in 🤗 Hugging Face Hub. Please visit [HuggingFace model card](https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev), carefully read terms of usage and click accept button. You will need to use an access token for the code below to run. For more information on access tokens, refer to [this section of the documentation](https://huggingface.co/docs/hub/security-tokens).\n", + ">You can login on Hugging Face Hub in notebook environment, using following code:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "c2676359", + "metadata": {}, + "outputs": [], + "source": [ + "# uncomment these lines to login to huggingfacehub to get access to pretrained model\n", + "\n", + "# from huggingface_hub import notebook_login, whoami\n", + "\n", + "# try:\n", + "# whoami()\n", + "# print('Authorization token already provided')\n", + "# except OSError:\n", + "# notebook_login()" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "id": "10fee712-3dbe-4c2e-9bb2-b8a760a4d1f3", + "metadata": {}, + "source": [ + "## Convert model with OpenVINO\n", + "[back to top ⬆️](#Table-of-contents:)\n", + "\n", + "Starting from 2023.0 release, OpenVINO supports PyTorch models directly via Model Conversion API. `ov.convert_model` function accepts instance of PyTorch model and example inputs for tracing and returns object of `ov.Model` class, ready to use or save on disk using `ov.save_model` function. \n", + "\n", + "\n", + "The pipeline consists of four important parts:\n", + "\n", + "* Text Encoders to create condition to generate an image from a text prompt.\n", + "* Transformer for step-by-step denoising latent image representation.\n", + "* Autoencoder (VAE) for encoding and decoding image.\n", + " \n", + "### Convert model using Optimum Intel\n", + "[back to top ⬆️](#Table-of-contents:)\n", + "\n", + "For convenience, we will use OpenVINO integration with HuggingFace Optimum. 🤗 [Optimum Intel](https://huggingface.co/docs/optimum/intel/index) is the interface between the 🤗 Transformers and Diffusers libraries and the different tools and libraries provided by Intel to accelerate end-to-end pipelines on Intel architectures.\n", + "\n", + "Among other use cases, Optimum Intel provides a simple interface to optimize your Transformers and Diffusers models, convert them to the OpenVINO Intermediate Representation (IR) format and run inference using OpenVINO Runtime. `optimum-cli` provides command line interface for model conversion and optimization. \n", + "\n", + "General command format:\n", + "\n", + "```bash\n", + "optimum-cli export openvino --model --task \n", + "```\n", + "\n", + "where task is task to export the model for, if not specified, the task will be auto-inferred based on the model. You can find a mapping between tasks and model classes in Optimum TaskManager [documentation](https://huggingface.co/docs/optimum/exporters/task_manager). Additionally, you can specify weights compression using `--weight-format` argument with one of following options: `fp32`, `fp16`, `int8` and `int4`. Fro int8 and int4 [nncf](https://github.com/openvinotoolkit/nncf) will be used for weight compression. More details about model export provided in [Optimum Intel documentation](https://huggingface.co/docs/optimum/intel/openvino/export#export-your-model).\n", + "\n", + "### Compress model weights\n", + "[back to top ⬆️](#Table-of-contents:)\n", + "\n", + "For reducing model memory consumption we will use weights compression. The [Weights Compression](https://docs.openvino.ai/2024/openvino-workflow/model-optimization-guide/weight-compression.html) algorithm is aimed at compressing the weights of the models and can be used to optimize the model footprint and performance of large models where the size of weights is relatively larger than the size of activations, for example, Large Language Models (LLM). Compared to INT8 compression, INT4 compression improves performance even more, but introduces a minor drop in prediction quality. We will use [NNCF](https://github.com/openvinotoolkit/nncf) integration to `optimum-cli` tool for weight compression.\n", + "\n", + "### Use optimized models provided on HuggingFace Hub\n", + "[back to top ⬆️](#Table-of-contents:)\n", + "\n", + "For quick start, OpenVINO provides [collection](https://huggingface.co/collections/OpenVINO/image-generation-67697d9952fb1eee4a252aa8) of optimized models that are ready to use with OpenVINO GenAI. You can download them using following command:\n", + "\n", + "```bash\n", + "huggingface-cli download --local-dir \n", + "```\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "3db40234-cc40-4064-bd45-d8320c39fc89", + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "4f54837f68fb420ebabf4ed2f43c1369", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "VBox(children=(Checkbox(value=True, description='Weight compression'),))" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "to_compress = widgets.Checkbox(\n", + " value=True,\n", + " description=\"Weight compression\",\n", + " disabled=False,\n", + ")\n", + "\n", + "visible_widgets = [to_compress]\n", + "\n", + "options = widgets.VBox(visible_widgets)\n", + "\n", + "options" + ] + }, + { + "cell_type": "markdown", + "id": "19ba4937-1c98-4eb0-81c4-b1c985710118", + "metadata": {}, + "source": [ + ">**Note**: Weight compression will impact the quality of the generated image." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "8e46869c", + "metadata": {}, + "outputs": [], + "source": [ + "from pathlib import Path\n", + "\n", + "model_base_dir = Path(model_id.split(\"/\")[-1])\n", + "additional_args = {}\n", + "\n", + "if to_compress.value:\n", + " model_dir = model_base_dir / \"INT8\"\n", + " additional_args.update({\"weight-format\": \"int8\"})\n", + "else:\n", + " model_dir = model_base_dir / \"FP16\"\n", + " additional_args.update({\"weight-format\": \"fp16\"})" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "f6c7bb34", + "metadata": { + "test_replace": { + "model_id": "\"snake7gun/tiny-random-qwen-image\"" + } + }, + "outputs": [ + { + "data": { + "text/markdown": [ + "**Export command:**" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/markdown": [ + "`optimum-cli export openvino --model Qwen/Qwen-Image Qwen-Image/INT8 --weight-format int8`" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "from cmd_helper import optimum_cli\n", + "\n", + "if not model_dir.exists():\n", + " optimum_cli(model_id, model_dir, additional_args=additional_args)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "id": "2bf6b6a4-0fc0-425d-acbf-5ac0df8dd993", + "metadata": {}, + "source": [ + "## Run Optimum-intel model inference\n", + "[back to top ⬆️](#Table-of-contents:)\n", + "\n", + "Select device from dropdown list for running inference using OpenVINO." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "719aa55a", + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "b2c2931117cc4ba8af8b668756fdab30", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "Dropdown(description='Device:', options=('CPU', 'GPU', 'AUTO'), value='CPU')" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from notebook_utils import device_widget\n", + "\n", + "device = device_widget(default=\"CPU\", exclude=[\"NPU\"])\n", + "device" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "f1d71c44-761a-45f8-858c-e60a9a625dd6", + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "6e7d57c24ce54841a52a7aec03dbec79", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "Checkbox(value=True, description='Use compressed models')" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import ipywidgets as widgets\n", + "\n", + "model_available = (model_base_dir / \"INT8\").is_dir()\n", + "use_quantized_models = widgets.Checkbox(\n", + " value=model_available,\n", + " description=\"Use compressed models\",\n", + " disabled=not model_available,\n", + ")\n", + "\n", + "use_quantized_models" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "id": "cab6790e", + "metadata": {}, + "source": [ + "OpenVINO integration with Optimum Intel provides ready-to-use API for model inference that can be used for smooth integration with transformers-based solutions. For loading Qwen-Image model, we will use `OVQwenImagePipeline` class that have compatible interface with Diffusers `OVQwenImagePipeline` implementation. For loading a model, `from_pretrained` method should be used. It accepts path to the model directory or model_id from HuggingFace hub (if model is not converted to OpenVINO format, conversion will be triggered automatically). Additionally, we can provide an inference device, quantization config (if model has not been quantized yet) and device-specific OpenVINO Runtime configuration. More details about model inference with Optimum Intel can be found in [documentation](https://huggingface.co/docs/optimum/intel/openvino/inference)." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "a7230b71", + "metadata": {}, + "outputs": [], + "source": [ + "from optimum.intel import OVQwenImagePipeline\n", + "\n", + "model_dir = model_base_dir / \"INT8\" if use_quantized_models.value else model_base_dir / \"FP16\"\n", + "\n", + "ov_pipe = OVQwenImagePipeline.from_pretrained(model_dir, device=device.value)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "id": "75aeb184", + "metadata": {}, + "source": [ + "Now, you can define a text prompt and other pipeline settings for image generation and run inference pipeline." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "0b65a304-c19a-4852-9cf0-aa30127eee62", + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "548cef43c82e4424968c49f916a12e9b", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + " 0%| | 0/50 [00:00" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import torch\n", + "\n", + "positive_magic = {\"en\": \", Ultra HD, 4K, cinematic composition.\", \"zh\": \", 超清,4K,电影级构图.\"} # for english prompt # for chinese prompt\n", + "\n", + "# Generate image\n", + "prompt = \"\"\"A coffee shop entrance features a chalkboard sign reading \"Qwen Coffee 😊 $2 per cup,\" with a neon light beside it displaying \"通义千问\". Next to it hangs a poster showing a beautiful Chinese woman, and beneath the poster is written \"π≈3.1415926-53589793-23846264-33832795-02384197\". Ultra HD, 4K, cinematic composition\"\"\"\n", + "\n", + "negative_prompt = \" \" # using an empty string if you do not have specific concept to remove\n", + "\n", + "\n", + "# Generate with different aspect ratios\n", + "aspect_ratios = {\n", + " \"1:1\": (1328, 1328),\n", + " \"16:9\": (1664, 928),\n", + " \"9:16\": (928, 1664),\n", + " \"4:3\": (1472, 1140),\n", + " \"3:4\": (1140, 1472),\n", + " \"3:2\": (1584, 1056),\n", + " \"2:3\": (1056, 1584),\n", + "}\n", + "\n", + "width, height = aspect_ratios[\"16:9\"]\n", + "\n", + "image = ov_pipe(\n", + " prompt=prompt + positive_magic[\"en\"],\n", + " negative_prompt=negative_prompt,\n", + " width=width,\n", + " height=height,\n", + " num_inference_steps=50,\n", + " true_cfg_scale=4.0,\n", + " generator=torch.Generator(device=\"cpu\").manual_seed(42),\n", + ").images[0]\n", + "\n", + "image" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "id": "e7b8cee1-9e46-46f6-a4ef-b3bc132aaa01", + "metadata": {}, + "source": [ + "## Interactive demo\n", + "[back to top ⬆️](#Table-of-contents:)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "88519e1b", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "from gradio_helper import make_demo\n", + "\n", + "demo = make_demo(ov_pipe)\n", + "\n", + "# if you are launching remotely, specify server_name and server_port\n", + "# demo.launch(server_name='your server name', server_port='server port in int')\n", + "# if you have any issue to launch on your platform, you can pass share=True to launch method:\n", + "# demo.launch(share=True)\n", + "# it creates a publicly shareable link for the interface. Read more in the docs: https://gradio.app/docs/\n", + "try:\n", + " demo.launch(debug=True)\n", + "except Exception:\n", + " demo.launch(debug=True, share=True)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.7" + }, + "openvino_notebooks": { + "imageUrl": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-Image/merge3.jpg", + "tags": { + "categories": [ + "Model Demos", + "AI Trends" + ], + "libraries": [], + "other": [ + "Stable Diffusion" + ], + "tasks": [ + "Text-to-Image" + ] + } + }, + "widgets": { + "application/vnd.jupyter.widget-state+json": { + "state": {}, + "version_major": 2, + "version_minor": 0 + } + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}