Buckets:

mishig's picture
|
download
raw
192 kB
# Flux Flux は、拡散トランスフォーマーに基づくテキストから画像を生成するモデルのシリーズです。Flux の詳細については、Flux の開発元である Black Forest Labs による元の[ブログ記事](https://blackforestlabs.ai/announcing-black-forest-labs/)をご覧ください。 Fluxの元のモデルチェックポイントは[こちら](https://huggingface.co/black-forest-labs)で確認できます。元の推論コードは[こちら](https://github.com/black-forest-labs/flux)で確認できます。 > [!TIP] > Flux は、コンシューマー向けハードウェアで実行する場合、コストがかなり高くなる可能性があります。ただし、一連の最適化を行うことで、より高速かつメモリ効率の良い実行が可能です。詳細については、[このセクション](https://huggingface.co/blog/sd3#memory-optimizations-for-sd3)を参照してください。また、Flux は量子化によってメモリ効率を向上させることができますが、推論レイテンシとのトレードオフが発生します。詳細については、[このブログ記事](https://huggingface.co/blog/quanto-diffusers)を参照してください。包括的なリソースのリストについては、[この gist](https://gist.github.com/sayakpaul/b664605caf0aa3bf8585ab109dd5ac9c)をご覧ください。 > > [Caching](../../optimization/cache) は、中間出力を保存して再利用することで、推論の高速化にも貢献します。 Fluxには、以下のバリエーションがあります: | モデルタイプ | モデルID | |:----------:|:--------:| | タイムステップ蒸留 | [`black-forest-labs/FLUX.1-schnell`](https://huggingface.co/black-forest-labs/FLUX.1-schnell) | | ガイダンス蒸留 | [`black-forest-labs/FLUX.1-dev`](https://huggingface.co/black-forest-labs/FLUX.1-dev) | | Fill Inpainting/Outpainting(ガイダンス蒸留) | [`black-forest-labs/FLUX.1-Fill-dev`](https://huggingface.co/black-forest-labs/FLUX.1-Fill-dev) | | Canny Control (Guidance-distilled) | [`black-forest-labs/FLUX.1-Canny-dev`](https://huggingface.co/black-forest-labs/FLUX.1-Canny-dev) | | 深度制御(ガイダンス蒸留) | [`black-forest-labs/FLUX.1-Depth-dev`](https://huggingface.co/black-forest-labs/FLUX.1-Depth-dev) | | Canny Control (LoRA) | [`black-forest-labs/FLUX.1-Canny-dev-lora`](https://huggingface.co/black-forest-labs/FLUX.1-Canny-dev-lora) | | 深度制御 (LoRA) | [`black-forest-labs/FLUX.1-Depth-dev-lora`](https://huggingface.co/black-forest-labs/FLUX.1-Depth-dev-lora) | | Redux (Adapter) | [`black-forest-labs/FLUX.1-Redux-dev`](https://huggingface.co/black-forest-labs/FLUX.1-Redux-dev) | | コンテキスト | [`black-forest-labs/FLUX.1-kontext`](https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev) | すべてのチェックポイントには異なる用途があり、以下に詳細を説明します。 ### タイムステップ蒸留 * `max_sequence_length`は256を超えることはできません。 * `guidance_scale` は 0 である必要があります。 * これはタイムステップ蒸留モデルであるため、サンプリングステップ数を減らすことで恩恵を受けます。 ```python import torch from diffusers import FluxPipeline pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", dtype=torch.bfloat16) pipe.enable_model_cpu_offload() prompt = "A cat holding a sign that says hello world" out = pipe( prompt=prompt, guidance_scale=0., height=768, width=1360, num_inference_steps=4, max_sequence_length=256, ).images[0] out.save("image.png") ``` ### ガイダンス蒸留 * guidance-distilled バリアントは、高品質な生成に約50回のサンプリングステップを必要とします。 * `max_sequence_length`に関する制限はありません。 ```python import torch from diffusers import FluxPipeline pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", dtype=torch.bfloat16) pipe.enable_model_cpu_offload() prompt = "a tiny astronaut hatching from an egg on the moon" out = pipe( prompt=prompt, guidance_scale=3.5, height=768, width=1360, num_inference_steps=50, ).images[0] out.save("image.png") ``` ### インペインティング/アウトペインティングの埋め込み * Flux Fill パイプラインは、通常のインペインティングパイプラインとは異なり、`strength` を入力として必要としません。 * インペインティングとアウトペインティングの両方をサポートしています。 ```python import torch from diffusers import FluxFillPipeline from diffusers.utils import load_image image = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/cup.png") mask = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/cup_mask.png") repo_id = "black-forest-labs/FLUX.1-Fill-dev" pipe = FluxFillPipeline.from_pretrained(repo_id, dtype=torch.bfloat16).to("cuda") # or "mps", "xpu", "cpu" image = pipe( prompt="a white paper cup", image=image, mask_image=mask, height=1632, width=1232, max_sequence_length=512, generator=torch.Generator("cpu").manual_seed(0) ).images[0] image.save(f"output.png") ``` ### Canny Control **注:** `black-forest-labs/Flux.1-Canny-dev` は [ControlNetModel](/docs/diffusers/main/ja/api/models/controlnet#diffusers.ControlNetModel) モデルでは_ありません_。ControlNet モデルは、実際の基盤モデルに追加される残差を持つ UNet/Transformer とは独立したコンポーネントです。Canny Control は、入力制御条件とのチャネル方向の連結を使用し、条件にできるだけ忠実に従うことで構造制御を学習させることで、ControlNet モデルと実質的に同じ結果を実現する代替アーキテクチャです。 ```python # !pip install -U controlnet-aux import torch from controlnet_aux import CannyDetector from diffusers import FluxControlPipeline from diffusers.utils import load_image pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-Canny-dev", dtype=torch.bfloat16).to("cuda") # or "mps", "xpu", "cpu" prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts." control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png") processor = CannyDetector() control_image = processor(control_image, low_threshold=50, high_threshold=200, detect_resolution=1024, image_resolution=1024) image = pipe( prompt=prompt, control_image=control_image, height=1024, width=1024, num_inference_steps=50, guidance_scale=30.0, ).images[0] image.save("output.png") ``` Canny Controlは、この条件のLoRAバリアントでも可能です。使用法は以下の通りです。 ```python # !pip install -U controlnet-aux import torch from controlnet_aux import CannyDetector from diffusers import FluxControlPipeline from diffusers.utils import load_image pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", dtype=torch.bfloat16).to("cuda") # or "mps", "xpu", "cpu" pipe.load_lora_weights("black-forest-labs/FLUX.1-Canny-dev-lora") prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts." control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png") processor = CannyDetector() control_image = processor(control_image, low_threshold=50, high_threshold=200, detect_resolution=1024, image_resolution=1024) image = pipe( prompt=prompt, control_image=control_image, height=1024, width=1024, num_inference_steps=50, guidance_scale=30.0, ).images[0] image.save("output.png") ``` ### 深度制御 **注:** `black-forest-labs/Flux.1-Depth-dev` は ControlNet モデルでは_ありません_。[ControlNetModel](/docs/diffusers/main/ja/api/models/controlnet#diffusers.ControlNetModel) モデルは、実際の基盤モデルに追加される残差を持つ UNet/Transformer とは独立したコンポーネントです。Depth Control は、入力制御条件とのチャネル方向の連結を使用し、条件にできるだけ忠実に従うことで構造制御を学習させることで、ControlNet モデルと実質的に同じ結果を実現する代替アーキテクチャです。 ```python # !pip install git+https://github.com/huggingface/image_gen_aux import torch from diffusers import FluxControlPipeline, FluxTransformer2DModel from diffusers.utils import load_image from image_gen_aux import DepthPreprocessor pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-Depth-dev", dtype=torch.bfloat16).to("cuda") # or "mps", "xpu", "cpu" prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts." control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png") processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf") control_image = processor(control_image)[0].convert("RGB") image = pipe( prompt=prompt, control_image=control_image, height=1024, width=1024, num_inference_steps=30, guidance_scale=10.0, generator=torch.Generator().manual_seed(42), ).images[0] image.save("output.png") ``` この条件のLoRAバリアントでも、深度制御が可能です。使用法は以下の通りです。 ```python # !pip install git+https://github.com/huggingface/image_gen_aux import torch from diffusers import FluxControlPipeline, FluxTransformer2DModel from diffusers.utils import load_image from image_gen_aux import DepthPreprocessor pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", dtype=torch.bfloat16).to("cuda") # or "mps", "xpu", "cpu" pipe.load_lora_weights("black-forest-labs/FLUX.1-Depth-dev-lora") prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts." control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png") processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf") control_image = processor(control_image)[0].convert("RGB") image = pipe( prompt=prompt, control_image=control_image, height=1024, width=1024, num_inference_steps=30, guidance_scale=10.0, generator=torch.Generator().manual_seed(42), ).images[0] image.save("output.png") ``` ### Redux * Flux Redux パイプラインは、FLUX.1 ベースモデル用のアダプターです。flux-dev および flux-schnell の両方と組み合わせて、画像から画像への生成に使用できます。 * まず`FluxPriorReduxPipeline`を使用して`prompt_embeds`と`pooled_prompt_embeds`を取得し、その後、それらを`FluxPipeline`に渡して画像から画像への生成を行います。 * ベースパイプラインと`FluxPriorReduxPipeline`を併用する場合、VRAMを節約するために、ベースパイプラインで`text_encoder=None`および`text_encoder_2=None`を設定できます。 ```python import torch from diffusers import FluxPriorReduxPipeline, FluxPipeline from diffusers.utils import load_image device = "cuda" # or "mps", "xpu", "cpu" dtype = torch.bfloat16 repo_redux = "black-forest-labs/FLUX.1-Redux-dev" repo_base = "black-forest-labs/FLUX.1-dev" pipe_prior_redux = FluxPriorReduxPipeline.from_pretrained(repo_redux, dtype=dtype).to(device) pipe = FluxPipeline.from_pretrained( repo_base, text_encoder=None, text_encoder_2=None, dtype=torch.bfloat16 ).to(device) image = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/style_ziggy/img5.png") pipe_prior_output = pipe_prior_redux(image) images = pipe( guidance_scale=2.5, num_inference_steps=50, generator=torch.Generator("cpu").manual_seed(0), **pipe_prior_output, ).images images[0].save("flux-redux.png") ``` ### コンテキスト Flux Kontext は、画像生成プロセスのインコンテキスト制御を可能にするモデルであり、編集、リファイン、ライティングの再設定、スタイル転写、キャラクターのカスタマイズなどに対応しています。 ```python import torch from diffusers import FluxKontextPipeline from diffusers.utils import load_image pipe = FluxKontextPipeline.from_pretrained( "black-forest-labs/FLUX.1-Kontext-dev", dtype=torch.bfloat16 ) pipe.to("cuda") # or "mps", "xpu", "cpu" image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/yarn-art-pikachu.png").convert("RGB") prompt = "Make Pikachu hold a sign that says 'Black Forest Labs is awesome', yarn art style, detailed, vibrant colors" image = pipe( image=image, prompt=prompt, guidance_scale=2.5, generator=torch.Generator().manual_seed(42), ).images[0] image.save("flux-kontext.png") ``` Flux Kontextには、完全性セーフティチェッカーが同梱されています。これは画像生成ステップの実行後に実行する必要があります。セーフティチェッカーを実行するには、[black-forest-labs/flux](https://github.com/black-forest-labs/flux)の公式リポジトリをインストールし、以下のコードを追加してください。 ```python from flux.content_filters import PixtralContentFilter # ... pipeline invocation to generate images integrity_checker = PixtralContentFilter(torch.device("cuda")) image_ = np.array(image) / 255.0 image_ = 2 * image_ - 1 image_ = torch.from_numpy(image_).to("cuda", dtype=torch.float32).unsqueeze(0).permute(0, 3, 1, 2) if integrity_checker.test_image(image_): raise ValueError("Your image has been flagged. Choose another prompt/image or try again.") ``` ### Kontext Inpainting `FluxKontextInpaintPipeline` は、固定されたマスク領域内での画像修正を可能にします。現在、テキストベースの条件付けと画像参照ベースの条件付けの両方をサポートしています。 ```python import torch from diffusers import FluxKontextInpaintPipeline from diffusers.utils import load_image prompt = "Change the yellow dinosaur to green one" img_url = ( "https://github.com/ZenAI-Vietnam/Flux-Kontext-pipelines/blob/main/assets/dinosaur_input.jpeg?raw=true" ) mask_url = ( "https://github.com/ZenAI-Vietnam/Flux-Kontext-pipelines/blob/main/assets/dinosaur_mask.png?raw=true" ) source = load_image(img_url) mask = load_image(mask_url) pipe = FluxKontextInpaintPipeline.from_pretrained( "black-forest-labs/FLUX.1-Kontext-dev", dtype=torch.bfloat16 ) pipe.to("cuda") # or "mps", "xpu", "cpu" image = pipe(prompt=prompt, image=source, mask_image=mask, strength=1.0).images[0] image.save("kontext_inpainting_normal.png") ``` ```python import torch from diffusers import FluxKontextInpaintPipeline from diffusers.utils import load_image pipe = FluxKontextInpaintPipeline.from_pretrained( "black-forest-labs/FLUX.1-Kontext-dev", dtype=torch.bfloat16 ) pipe.to("cuda") # or "mps", "xpu", "cpu" prompt = "Replace this ball" img_url = "https://images.pexels.com/photos/39362/the-ball-stadion-football-the-pitch-39362.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" mask_url = "https://github.com/ZenAI-Vietnam/Flux-Kontext-pipelines/blob/main/assets/ball_mask.png?raw=true" image_reference_url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTah3x6OL_ECMBaZ5ZlJJhNsyC-OSMLWAI-xw&s" source = load_image(img_url) mask = load_image(mask_url) image_reference = load_image(image_reference_url) mask = pipe.mask_processor.blur(mask, blur_factor=12) image = pipe( prompt=prompt, image=source, mask_image=mask, image_reference=image_reference, strength=1.0 ).images[0] image.save("kontext_inpainting_ref.png") ``` ## Flux Turbo LoRAとFlux Control、Fill、Reduxの組み合わせ Flux Turbo LoRA を Flux Control や Fill、Redux などの他のパイプラインと組み合わせることで、ステップ数の少ない推論を可能にします。以下の例では、深度用の Flux Control LoRA と [`ByteDance/Hyper-SD`](https://hf.co/ByteDance/Hyper-SD) の turbo LoRA を使用する方法を示しています。 ```py from diffusers import FluxControlPipeline from image_gen_aux import DepthPreprocessor from diffusers.utils import load_image from huggingface_hub import hf_hub_download import torch control_pipe = FluxControlPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", dtype=torch.bfloat16) control_pipe.load_lora_weights("black-forest-labs/FLUX.1-Depth-dev-lora", adapter_name="depth") control_pipe.load_lora_weights( hf_hub_download("ByteDance/Hyper-SD", "Hyper-FLUX.1-dev-8steps-lora.safetensors"), adapter_name="hyper-sd" ) control_pipe.set_adapters(["depth", "hyper-sd"], adapter_weights=[0.85, 0.125]) control_pipe.enable_model_cpu_offload() prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts." control_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png") processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf") control_image = processor(control_image)[0].convert("RGB") image = control_pipe( prompt=prompt, control_image=control_image, height=1024, width=1024, num_inference_steps=8, guidance_scale=10.0, generator=torch.Generator().manual_seed(42), ).images[0] image.save("output.png") ``` ## Flux LoRAを使用する場合の`unload_lora_weights()`に関する注意 When unloading the Control LoRA weights, call `pipe.unload_lora_weights(reset_to_overwritten_params=True)` to reset the `pipe.transformer` completely back to its original form. The resultant pipeline can then be used with methods like [DiffusionPipeline.from_pipe()](/docs/diffusers/main/ja/api/pipelines/overview#diffusers.DiffusionPipeline.from_pipe). More details about this argument are available in [this PR](https://github.com/huggingface/diffusers/pull/10397). ## IP-Adapter > [!TIP] > IP-Adapter の仕組みについて詳しく知るには、[IP-Adapter](../../using-diffusers/ip_adapter) をご覧ください。 IP-Adapterを使用すると、テキストプロンプトに加えて画像でもFluxに指示を与えることができます。これは、テキストだけでは表現が難しい複雑な概念を説明する場合や、参照画像がある場合に特に役立ちます。 ```python import torch from diffusers import FluxPipeline from diffusers.utils import load_image pipe = FluxPipeline.from_pretrained( "black-forest-labs/FLUX.1-dev", dtype=torch.bfloat16 ).to("cuda") # or "mps", "xpu", "cpu" image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flux_ip_adapter_input.jpg").resize((1024, 1024)) pipe.load_ip_adapter( "XLabs-AI/flux-ip-adapter", weight_name="ip_adapter.safetensors", image_encoder_pretrained_model_name_or_path="openai/clip-vit-large-patch14" ) pipe.set_ip_adapter_scale(1.0) image = pipe( width=1024, height=1024, prompt="wearing sunglasses", negative_prompt="", true_cfg_scale=4.0, generator=torch.Generator().manual_seed(4444), ip_adapter_image=image, ).images[0] image.save('flux_ip_adapter_output.jpg') ``` プロンプト「wearing sunglasses」のIP-Adapterの例 ## 最適化 Flux は非常に大規模なモデルであり、すべてのモデリングコンポーネントを読み込むには約 50GB の RAM/VRAM が必要です。メモリ要件を下げるには、以下の最適化をいくつか有効にしてください。 ### グループオフローディング [グループオフローディング](../../optimization/memory#group-offloading)は、モデル全体や重みをオフロードするのではなく、内部レイヤーのグループをオフロードすることでVRAM使用量を削減します。パイプラインのすべてのモデルコンポーネントに対して[apply_group_offloading()](/docs/diffusers/main/ja/api/utilities#diffusers.hooks.apply_group_offloading)を使用する必要があります。`offload_type`パラメータにより、ブロックレベルとリーフレベルのオフローディングを切り替えることができます。`leaf_level`に設定すると、モジュールレベルでのオフローディングではなく、最下位のリーフレベルのパラメータをCPUにオフロードします。 非同期データストリーミングをサポートする CUDA デバイスでは、`use_stream=True` を設定することで、データ転送と計算をオーバーラップさせ、推論を高速化できます。 > [!TIP] > パイプライン内の異なるコンポーネントに対して、ブロックレベルとリーフレベルのオフローディングを混在させることができます。 ```py import torch from diffusers import FluxPipeline from diffusers.hooks import apply_group_offloading model_id = "black-forest-labs/FLUX.1-dev" dtype = torch.bfloat16 pipe = FluxPipeline.from_pretrained( model_id, dtype=dtype, ) apply_group_offloading( pipe.transformer, offload_type="leaf_level", offload_device=torch.device("cpu"), onload_device=torch.device("cuda"), use_stream=True, ) apply_group_offloading( pipe.text_encoder, offload_device=torch.device("cpu"), onload_device=torch.device("cuda"), offload_type="leaf_level", use_stream=True, ) apply_group_offloading( pipe.text_encoder_2, offload_device=torch.device("cpu"), onload_device=torch.device("cuda"), offload_type="leaf_level", use_stream=True, ) apply_group_offloading( pipe.vae, offload_device=torch.device("cpu"), onload_device=torch.device("cuda"), offload_type="leaf_level", use_stream=True, ) prompt="A cat wearing sunglasses and working as a lifeguard at pool." generator = torch.Generator().manual_seed(181201) image = pipe( prompt, width=576, height=1024, num_inference_steps=30, generator=generator ).images[0] image ``` ### FP16推論の実行 Flux は FP16(Turing/Volta GPU での推論を高速化するために使用)で高品質な画像を生成できますが、FP32/BF16 とは異なる出力になります。問題点は、FP16 で実行する場合、テキストエンコーダー内の一部の活性化値をクリップする必要があるため、画像全体に影響が出る点です。したがって、テキストエンコーダーを FP32 推論で実行するように強制することで、この出力の差異を解消できます。詳細は [こちら](https://github.com/huggingface/diffusers/pull/9097#issuecomment-2272292516) を参照してください。 FP16推論コード: ```python import torch from diffusers import FluxPipeline pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", dtype=torch.bfloat16) # can replace schnell with dev # to run on low vram GPUs (i.e. between 4 and 32 GB VRAM) pipe.enable_sequential_cpu_offload() pipe.vae.enable_slicing() pipe.vae.enable_tiling() pipe.to(torch.float16) # casting here instead of in the pipeline constructor because doing so in the constructor loads all models into CPU memory at once prompt = "A cat holding a sign that says hello world" out = pipe( prompt=prompt, guidance_scale=0., height=768, width=1360, num_inference_steps=4, max_sequence_length=256, ).images[0] out.save("image.png") ``` ### 量子化 Quantizationは、モデルの重みを低精度のデータ型で保存することで、非常に大規模なモデルのメモリ要件を軽減するのに役立ちます。ただし、動画モデルによって、Quantizationが動画の品質に与える影響は異なります。 サポートされている量子化バックエンドと、ユースケースに対応する量子化バックエンドの選択について詳しく知るには、[Quantization](../../quantization/overview)の概要を参照してください。以下の例では、bitsandbytesを使用して量子化された[FluxPipeline](/docs/diffusers/main/ja/api/pipelines/flux#diffusers.FluxPipeline)を読み込んで推論を実行する方法を示しています。 ```py import torch from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, FluxTransformer2DModel, FluxPipeline from transformers import BitsAndBytesConfig as BitsAndBytesConfig, T5EncoderModel quant_config = BitsAndBytesConfig(load_in_8bit=True) text_encoder_8bit = T5EncoderModel.from_pretrained( "black-forest-labs/FLUX.1-dev", subfolder="text_encoder_2", quantization_config=quant_config, dtype=torch.float16, ) quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True) transformer_8bit = FluxTransformer2DModel.from_pretrained( "black-forest-labs/FLUX.1-dev", subfolder="transformer", quantization_config=quant_config, dtype=torch.float16, ) pipeline = FluxPipeline.from_pretrained( "black-forest-labs/FLUX.1-dev", text_encoder_2=text_encoder_8bit, transformer=transformer_8bit, dtype=torch.float16, device_map="balanced", ) prompt = "a tiny astronaut hatching from an egg on the moon" image = pipeline(prompt, guidance_scale=3.5, height=768, width=1360, num_inference_steps=50).images[0] image.save("flux.png") ``` ## `FluxTransformer2DModel`の単一ファイル読み込み `FluxTransformer2DModel` は、Black Forest Labs が提供した元の形式のチェックポイントの読み込みに対応しています。これは、コミュニティによって公開されたモデルのファインチューン版や量子化版を読み込もうとする場合にも役立ちます。 > [!TIP] > `FP8`推論は、使用しているGPUの種類、CUDAのバージョン、`torch`のバージョンによって不安定になる場合があります。お使いの環境でFP8推論を実行するには、`optimum-quanto`ライブラリを使用することをお勧めします。 以下の例では、VRAM 16GB 未満で Flux を実行する方法を示しています。 まず、`optimum-quanto`をインストールしてください。 ```shell pip install optimum-quanto ``` 次に、以下の例を実行します ```python import torch from diffusers import FluxTransformer2DModel, FluxPipeline from transformers import T5EncoderModel, CLIPTextModel from optimum.quanto import freeze, qfloat8, quantize bfl_repo = "black-forest-labs/FLUX.1-dev" dtype = torch.bfloat16 transformer = FluxTransformer2DModel.from_single_file("https://huggingface.co/Kijai/flux-fp8/blob/main/flux1-dev-fp8.safetensors", dtype=dtype) quantize(transformer, weights=qfloat8) freeze(transformer) text_encoder_2 = T5EncoderModel.from_pretrained(bfl_repo, subfolder="text_encoder_2", dtype=dtype) quantize(text_encoder_2, weights=qfloat8) freeze(text_encoder_2) pipe = FluxPipeline.from_pretrained(bfl_repo, transformer=None, text_encoder_2=None, dtype=dtype) pipe.transformer = transformer pipe.text_encoder_2 = text_encoder_2 pipe.enable_model_cpu_offload() prompt = "A cat holding a sign that says hello world" image = pipe( prompt, guidance_scale=3.5, output_type="pil", num_inference_steps=20, generator=torch.Generator("cpu").manual_seed(0) ).images[0] image.save("flux-fp8-dev.png") ``` ## FluxPipeline[[diffusers.FluxPipeline]] #### diffusers.FluxPipeline[[diffusers.FluxPipeline]] ```python diffusers.FluxPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux.py#L146) **パラメータ:** transformer ([FluxTransformer2DModel](/docs/diffusers/main/ja/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : エンコードされた画像潜在変数をノイズ除去するための条件付き Transformer (MMDiT) アーキテクチャ。 scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。 vae ([AutoencoderKL](/docs/diffusers/main/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ(VAE)モデル。 text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)、具体的には [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) バリアントです。 text_encoder_2 (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)、具体的には [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) バリアントです。 tokenizer (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) の Tokenizer。 tokenizer_2 (`T5TokenizerFast`) : クラス [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) の2番目の Tokenizer。 テキストから画像を生成するためのFluxパイプライン。 参考: https://blackforestlabs.ai/announcing-black-forest-labs/ #### __call__[[diffusers.FluxPipeline.__call__]] ```python __call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, negative_prompt: str | list[str] = None, negative_prompt_2: str | list[str] | None = None, true_cfg_scale: float = 1.0, height: int | None = None, width: int | None = None, num_inference_steps: int = 28, sigmas: list[float] | None = None, guidance_scale: float = 3.5, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, negative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, negative_ip_adapter_image_embeds: list[torch.Tensor] | None = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux.py#L600) **パラメータ:** prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。 prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。定義されていない場合、代わりに `prompt` が使用されます。 negative_prompt (`str` または `list[str]`、*省略可能*) : 画像生成をガイドしないプロンプトです。未定義の場合、代わりに `negative_prompt_embeds` を渡す必要があります。ガイダンスを使用していない場合は無視されます(`true_cfg_scale` が `1` 以下の場合に無視されます)。 negative_prompt_2 (`str` または `list[str]`、*任意*) : 画像生成を誘導しないプロンプト、またはプロンプトのリストです。`tokenizer_2` および `text_encoder_2` に送信されます。定義されていない場合、すべてのテキストエンコーダーで `negative_prompt` が使用されます。 true_cfg_scale (`float`、*任意*、デフォルト値は 1.0) : `true_cfg_scale` > 1 かつ `negative_prompt` が指定されている場合、True classifier-free guidance(guidance scale)が有効になります。 height (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像のピクセル単位の縦幅。最適な結果を得るため、デフォルトでは 1024 に設定されています。 width (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像の幅(ピクセル単位)。最適な結果を得るため、デフォルトでは 1024 に設定されています。 num_inference_steps (`int`、*任意*、デフォルト値は 50) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。 sigmas (`list[float]`, *任意*) : `set_timesteps` メソッドで `sigmas` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムシグマ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。 guidance_scale (`float`、*任意*、デフォルト値は 3.5) : `guidance_scale` > 1 を設定することで、埋め込み型ガイダンススケールが有効になります。`guidance_scale` の値を高くすると、`prompt` により一貫性のある画像を生成するようモデルを促しますが、その代わりとして画像の品質が低下します。ガイダンス蒸留モデルは、`guidance_scale` > 1 に対して、真のクラスフリーガイダンスを近似します。詳細については、[論文](https://huggingface.co/papers/2210.03142)を参照してください。 num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。 generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : 生成を決定論的にするための [torch ジェネレーター](https://pytorch.org/docs/stable/generated/torch.Generator.html) 1 つまたはそのリスト。 latents (`torch.FloatTensor`, *任意*) : 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数(latents)。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム`generator`を使用してサンプリングを行い、潜在変数テンソルが生成されます。 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 ip_adapter_image : (`PipelineImageInput`、*任意*): IP Adapter で使用する任意の画像入力。 ip_adapter_image_embeds (`list[torch.Tensor]`、*省略可*) : IP-Adapter用の事前生成された画像埋め込み。IP-Adapterの数と同じ長さのリストである必要があります。各要素は、`(batch_size, num_images, emb_dim)` の形状を持つテンソルである必要があります。指定されない場合、`ip_adapter_image` 入力引数から埋め込みが計算されます。 negative_ip_adapter_image : (`PipelineImageInput`、*任意*): IP Adapter で使用する任意の画像入力。 negative_ip_adapter_image_embeds (`list[torch.Tensor]`、*省略可*) : IP-Adapter用の事前生成された画像埋め込み。IP-Adapterの数と同じ長さのリストである必要があります。各要素は、`(batch_size, num_images, emb_dim)` の形状を持つテンソルである必要があります。指定されない場合、`ip_adapter_image` 入力引数から埋め込みが計算されます。 negative_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたネガティブなテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`negative_prompt` 入力引数から negative_prompt_embeds が生成されます。 negative_pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたネガティブなプールのテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`negative_prompt` 入力引数からプールの negative_prompt_embeds が生成されます。 output_type (`str`、*任意*、デフォルトは `"pil"`) : 生成画像の出力形式。[PIL](https://pillow.readthedocs.io/en/stable/)(`PIL.Image.Image`)または `np.array` から選択します。 return_dict (`bool`、*任意*、デフォルトは`True`) : 通常のタプルではなく`~pipelines.flux.FluxPipelineOutput`を返すかどうか。 joint_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。 callback_on_step_end (`Callable`、*任意*) : 推論中の各デノイジングステップの終了時に呼び出される関数です。この関数は、以下の引数とともに呼び出されます: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。 `callback_kwargs` には、`callback_on_step_end_tensor_inputs` で指定されたすべてのテンソルのリストが含まれます。 callback_on_step_end_tensor_inputs (`list`, *任意*) : `callback_on_step_end` 関数へのテンソル入力のリストです。リストで指定されたテンソルは、`callback_kwargs` 引数として渡されます。パイプラインクラスの `._callback_tensor_inputs` 属性に列挙された変数のみを、リストに含めることができます。 max_sequence_length (`int`、デフォルトは 512) : `prompt` に使用する最大シーケンス長。 **戻り値:** `~pipelines.flux.FluxPipelineOutput` または `tuple` `return_dict` が True の場合は `~pipelines.flux.FluxPipelineOutput`、それ以外の場合は `tuple` を返します。tuple を返す場合、最初の要素は生成された画像のリストです。 生成用のパイプラインを呼び出したときに実行される関数。 例: ```py >>> import torch >>> from diffusers import FluxPipeline >>> pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16) >>> pipe.to("cuda") >>> prompt = "A cat holding a sign that says hello world" >>> # Depending on the variant being used, the pipeline call will slightly vary. >>> # Refer to the pipeline documentation for more details. >>> image = pipe(prompt, num_inference_steps=4, guidance_scale=0.0).images[0] >>> image.save("flux.png") ``` #### encode_prompt[[diffusers.FluxPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], prompt_2: str | list[str] | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, max_sequence_length: int = 512, lora_scale: float | None = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux.py#L312) **パラメータ:** prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。未定義の場合、すべての text-encoder で `prompt` が使用されます。 device : (`torch.device`): torch デバイス num_images_per_prompt (`int`) : プロンプトごとに生成すべき画像の数 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 lora_scale (`float`、*任意*) : LoRAレイヤーが読み込まれている場合、テキストエンコーダーのすべてのLoRAレイヤーに適用されるLoRAスケールです。 ## FluxImg2ImgPipeline[[diffusers.FluxImg2ImgPipeline]] #### diffusers.FluxImg2ImgPipeline[[diffusers.FluxImg2ImgPipeline]] ```python diffusers.FluxImg2ImgPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_img2img.py#L169) **パラメータ:** transformer ([FluxTransformer2DModel](/docs/diffusers/main/ja/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : エンコードされた画像潜在変数をノイズ除去するための条件付き Transformer (MMDiT) アーキテクチャ。 scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。 vae ([AutoencoderKL](/docs/diffusers/main/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ(VAE)モデル。 text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)、具体的には [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) バリアントです。 text_encoder_2 (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)、具体的には [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) バリアントです。 tokenizer (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) の Tokenizer。 tokenizer_2 (`T5TokenizerFast`) : クラス [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) の2番目の Tokenizer。 画像インペインティング用のFluxパイプライン。 参考: https://blackforestlabs.ai/announcing-black-forest-labs/ #### __call__[[diffusers.FluxImg2ImgPipeline.__call__]] ```python __call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, negative_prompt: str | list[str] = None, negative_prompt_2: str | list[str] | None = None, true_cfg_scale: float = 1.0, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, height: int | None = None, width: int | None = None, strength: float = 0.6, num_inference_steps: int = 28, sigmas: list[float] | None = None, guidance_scale: float = 7.0, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, negative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, negative_ip_adapter_image_embeds: list[torch.Tensor] | None = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_img2img.py#L678) **パラメータ:** prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。 prompt_2 (`str` または `list[str]`、*省略可能*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。定義されていない場合、代わりに `prompt` が使用されます。 negative_prompt (`str` または `list[str]`、*省略可能*) : 画像生成をガイドしないプロンプトです。未定義の場合、代わりに `negative_prompt_embeds` を渡す必要があります。ガイダンスを使用していない場合は無視されます(`true_cfg_scale` が `1` 以下の場合に無視されます)。 negative_prompt_2 (`str` または `list[str]`、*任意*) : 画像生成を誘導しないプロンプト、またはプロンプトのリストです。`tokenizer_2` および `text_encoder_2` に送信されます。定義されていない場合、すべてのテキストエンコーダーで `negative_prompt` が使用されます。 true_cfg_scale (`float`、*任意*、デフォルト値は 1.0) : `true_cfg_scale` > 1 かつ `negative_prompt` が指定されている場合、True classifier-free guidance(guidance scale)が有効になります。 image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、または `list[np.ndarray]`) : `Image`、numpy 配列、またはテンソル。開始点として使用される画像バッチを表します。numpy 配列および PyTorch テンソルの場合、想定される値の範囲は `[0, 1]` です。テンソルまたはテンソルのリストの場合、想定される形状は `(B, C, H, W)` または `(C, H, W)` です。numpy 配列または配列のリストの場合、想定される形状は `(B, H, W, C)` または `(H, W, C)` です。`image` として画像の潜在変数(latents)を受け取ることもできますが、潜在変数を直接渡す場合は、再度エンコードされません。 height (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像のピクセル単位の縦幅。最適な結果を得るため、デフォルトでは 1024 に設定されています。 width (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像の幅(ピクセル単位)。最適な結果を得るため、デフォルトでは 1024 に設定されています。 strength (`float`、*任意*、デフォルト値は 1.0) : 参照となる `image` を変換する度合いを示します。0 から 1 の間の値である必要があります。`image` が起点として使用され、`strength` の値が大きいほど、より多くのノイズが追加されます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。`strength` が 1 の場合、追加されるノイズは最大となり、`num_inference_steps` で指定された全イテレーション数にわたってデノイジングプロセスが実行されます。値が 1 である場合、`image` は実質的に無視されます。 num_inference_steps (`int`、*任意*、デフォルト値は 50) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。 sigmas (`list[float]`, *任意*) : `set_timesteps` メソッドで `sigmas` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムシグマ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。 guidance_scale (`float`、*任意*、デフォルト値は 7.0) : [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598) で定義されているガイダンススケールです。`guidance_scale` は、[Imagen Paper](https://huggingface.co/papers/2205.11487) の数式 2 の `w` として定義されています。`guidance_scale > 1` を設定することでガイダンススケールが有効になります。ガイダンススケールを高くすると、`prompt` のテキストと密接に関連する画像の生成が促されますが、通常は画像の品質が低下する傾向があります。 num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。 generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : 生成を決定論的にするための [torch ジェネレーター](https://pytorch.org/docs/stable/generated/torch.Generator.html) 1 つまたはそのリスト。 latents (`torch.FloatTensor`, *任意*) : 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数(latents)。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム`generator`を使用してサンプリングを行い、潜在変数テンソルが生成されます。 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 negative_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたネガティブなテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`negative_prompt` 入力引数から negative_prompt_embeds が生成されます。 negative_pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたネガティブなプールのテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`negative_prompt` 入力引数からプールの negative_prompt_embeds が生成されます。 ip_adapter_image : (`PipelineImageInput`、*任意*): IP Adapter で使用する任意の画像入力。 ip_adapter_image_embeds (`list[torch.Tensor]`、*省略可*) : IP-Adapter用の事前生成された画像埋め込み。IP-Adapterの数と同じ長さのリストである必要があります。各要素は、`(batch_size, num_images, emb_dim)` の形状を持つテンソルである必要があります。指定されない場合、`ip_adapter_image` 入力引数から埋め込みが計算されます。 negative_ip_adapter_image : (`PipelineImageInput`、*任意*): IP Adapter で使用する任意の画像入力。 negative_ip_adapter_image_embeds (`list[torch.Tensor]`、*省略可*) : IP-Adapter用の事前生成された画像埋め込み。IP-Adapterの数と同じ長さのリストである必要があります。各要素は、`(batch_size, num_images, emb_dim)` の形状を持つテンソルである必要があります。指定されない場合、`ip_adapter_image` 入力引数から埋め込みが計算されます。 output_type (`str`、*任意*、デフォルトは `"pil"`) : 生成画像の出力形式。[PIL](https://pillow.readthedocs.io/en/stable/)(`PIL.Image.Image`)または `np.array` から選択します。 return_dict (`bool`、*任意*、デフォルトは`True`) : 通常のタプルではなく`~pipelines.flux.FluxPipelineOutput`を返すかどうか。 joint_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。 callback_on_step_end (`Callable`、*任意*) : 推論中の各デノイジングステップの終了時に呼び出される関数です。この関数は、以下の引数とともに呼び出されます: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。 `callback_kwargs` には、`callback_on_step_end_tensor_inputs` で指定されたすべてのテンソルのリストが含まれます。 callback_on_step_end_tensor_inputs (`list`, *任意*) : `callback_on_step_end` 関数へのテンソル入力のリストです。リストで指定されたテンソルは、`callback_kwargs` 引数として渡されます。パイプラインクラスの `._callback_tensor_inputs` 属性に列挙された変数のみを、リストに含めることができます。 max_sequence_length (`int`、デフォルトは 512) : `prompt` に使用する最大シーケンス長。 **戻り値:** `~pipelines.flux.FluxPipelineOutput` または `tuple` `return_dict` が True の場合は `~pipelines.flux.FluxPipelineOutput`、それ以外の場合は `tuple` を返します。tuple を返す場合、最初の要素は生成された画像のリストです。 生成用のパイプラインを呼び出したときに実行される関数。 例: ```py >>> import torch >>> from diffusers import FluxImg2ImgPipeline >>> from diffusers.utils import load_image >>> device = "cuda" >>> pipe = FluxImg2ImgPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16) >>> pipe = pipe.to(device) >>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg" >>> init_image = load_image(url).resize((1024, 1024)) >>> prompt = "cat wizard, gandalf, lord of the rings, detailed, fantasy, cute, adorable, Pixar, Disney, 8k" >>> images = pipe( ... prompt=prompt, image=init_image, num_inference_steps=4, strength=0.95, guidance_scale=0.0 ... ).images[0] ``` #### encode_prompt[[diffusers.FluxImg2ImgPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], prompt_2: str | list[str] | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, max_sequence_length: int = 512, lora_scale: float | None = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_img2img.py#L335) **パラメータ:** prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。未定義の場合、すべての text-encoder で `prompt` が使用されます。 device : (`torch.device`): torch デバイス num_images_per_prompt (`int`) : プロンプトごとに生成すべき画像の数 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 lora_scale (`float`、*任意*) : LoRAレイヤーが読み込まれている場合、テキストエンコーダーのすべてのLoRAレイヤーに適用されるLoRAスケールです。 ## FluxInpaintPipeline[[diffusers.FluxInpaintPipeline]] #### diffusers.FluxInpaintPipeline[[diffusers.FluxInpaintPipeline]] ```python diffusers.FluxInpaintPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_inpaint.py#L166) **パラメータ:** transformer ([FluxTransformer2DModel](/docs/diffusers/main/ja/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : エンコードされた画像潜在変数をノイズ除去するための条件付き Transformer (MMDiT) アーキテクチャ。 scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。 vae ([AutoencoderKL](/docs/diffusers/main/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ(VAE)モデル。 text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)、具体的には [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) バリアントです。 text_encoder_2 (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)、具体的には [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) バリアントです。 tokenizer (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) の Tokenizer。 tokenizer_2 (`T5TokenizerFast`) : クラス [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) の2番目の Tokenizer。 画像インペインティング用のFluxパイプライン。 参考: https://blackforestlabs.ai/announcing-black-forest-labs/ #### __call__[[diffusers.FluxInpaintPipeline.__call__]] ```python __call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, negative_prompt: str | list[str] = None, negative_prompt_2: str | list[str] | None = None, true_cfg_scale: float = 1.0, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, masked_image_latents: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, height: int | None = None, width: int | None = None, padding_mask_crop: int | None = None, strength: float = 0.6, num_inference_steps: int = 28, sigmas: list[float] | None = None, guidance_scale: float = 7.0, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, negative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, negative_ip_adapter_image_embeds: list[torch.Tensor] | None = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_inpaint.py#L777) **パラメータ:** prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。 prompt_2 (`str` または `list[str]`、*省略可能*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。定義されていない場合、代わりに `prompt` が使用されます。 negative_prompt (`str` または `list[str]`、*省略可能*) : 画像生成をガイドしないプロンプトです。未定義の場合、代わりに `negative_prompt_embeds` を渡す必要があります。ガイダンスを使用していない場合は無視されます(`true_cfg_scale` が `1` 以下の場合に無視されます)。 negative_prompt_2 (`str` または `list[str]`、*任意*) : 画像生成を誘導しないプロンプト、またはプロンプトのリストです。`tokenizer_2` および `text_encoder_2` に送信されます。定義されていない場合、すべてのテキストエンコーダーで `negative_prompt` が使用されます。 true_cfg_scale (`float`、*任意*、デフォルト値は 1.0) : `true_cfg_scale` > 1 かつ `negative_prompt` が指定されている場合、True classifier-free guidance(guidance scale)が有効になります。 image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、または `list[np.ndarray]`) : `Image`、numpy 配列、またはテンソル。開始点として使用される画像バッチを表します。numpy 配列および PyTorch テンソルの場合、想定される値の範囲は `[0, 1]` です。テンソルまたはテンソルのリストの場合、想定される形状は `(B, C, H, W)` または `(C, H, W)` です。numpy 配列または配列のリストの場合、想定される形状は `(B, H, W, C)` または `(H, W, C)` です。`image` として画像の潜在変数(latents)を受け取ることもできますが、潜在変数を直接渡す場合は、再度エンコードされません。 mask_image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、または `list[np.ndarray]`) : `image` をマスクするための `Image`、numpy 配列、またはテンソル。マスク内の白いピクセルは再描画され、黒いピクセルは保持されます。`mask_image` が PIL イメージの場合、使用の前に単一チャネル(輝度)に変換されます。numpy 配列または PyTorch テンソルの場合は、3 チャネルではなく 1 つの色チャネル(L)を含む必要があります。そのため、PyTorch テンソルの想定される形状は `(B, 1, H, W)`、`(B, H, W)`、`(1, H, W)`、`(H, W)` となります。一方、numpy 配列の場合は `(B, H, W, 1)`、`(B, H, W)`、`(H, W, 1)`、または `(H, W)` となります。 masked_image_latents (`torch.Tensor`、`list[torch.Tensor]`) : VAEによって生成された`image`をマスクするための画像バッチを表す`Tensor`。指定されない場合、マスク用の潜変数テンソルは`mask_image`によって生成されます。 height (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像のピクセル単位の縦幅。最適な結果を得るため、デフォルトでは 1024 に設定されています。 width (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像の幅(ピクセル単位)。最適な結果を得るため、デフォルトでは 1024 に設定されています。 padding_mask_crop (`int`, *任意*、デフォルトは `None`) : 画像とマスクに適用するクロップの余白サイズ。`None` の場合、画像および mask_image にはクロップが適用されません。`padding_mask_crop` が `None` でない場合、まず画像と同じアスペクト比を持ち、すべてのマスク領域を含む長方形の領域を特定し、その後 `padding_mask_crop` に基づいてその領域を拡大します。その後、インペインティングのために元の画像サイズにリサイズする前に、拡大された領域に基づいて画像と mask_image がクロップされます。これは、マスク領域が小さく、画像が大きく、背景などインペインティングに関連しない情報が含まれている場合に有用です。 strength (`float`、*任意*、デフォルト値は 1.0) : 参照となる `image` を変換する度合いを示します。0 から 1 の間の値である必要があります。`image` が起点として使用され、`strength` の値が大きいほど、より多くのノイズが追加されます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。`strength` が 1 の場合、追加されるノイズは最大となり、`num_inference_steps` で指定された全イテレーション数にわたってデノイジングプロセスが実行されます。値が 1 である場合、`image` は実質的に無視されます。 num_inference_steps (`int`、*任意*、デフォルト値は 50) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。 sigmas (`list[float]`, *任意*) : `set_timesteps` メソッドで `sigmas` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムシグマ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。 guidance_scale (`float`、*任意*、デフォルト値は 7.0) : [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598) で定義されているガイダンススケールです。`guidance_scale` は、[Imagen Paper](https://huggingface.co/papers/2205.11487) の数式 2 の `w` として定義されています。`guidance_scale > 1` を設定することでガイダンススケールが有効になります。ガイダンススケールを高くすると、`prompt` のテキストと密接に関連する画像の生成が促されますが、通常は画像の品質が低下する傾向があります。 num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。 generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : 生成を決定論的にするための [torch ジェネレーター](https://pytorch.org/docs/stable/generated/torch.Generator.html) 1 つまたはそのリスト。 latents (`torch.FloatTensor`, *任意*) : 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数(latents)。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム`generator`を使用してサンプリングを行い、潜在変数テンソルが生成されます。 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 negative_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたネガティブなテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`negative_prompt` 入力引数から negative_prompt_embeds が生成されます。 negative_pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたネガティブなプールのテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`negative_prompt` 入力引数からプールの negative_prompt_embeds が生成されます。 ip_adapter_image : (`PipelineImageInput`、*任意*): IP Adapter で使用する任意の画像入力。 ip_adapter_image_embeds (`list[torch.Tensor]`、*省略可*) : IP-Adapter用の事前生成された画像埋め込み。IP-Adapterの数と同じ長さのリストである必要があります。各要素は、`(batch_size, num_images, emb_dim)` の形状を持つテンソルである必要があります。指定されない場合、`ip_adapter_image` 入力引数から埋め込みが計算されます。 negative_ip_adapter_image : (`PipelineImageInput`、*任意*): IP Adapter で使用する任意の画像入力。 negative_ip_adapter_image_embeds (`list[torch.Tensor]`、*省略可*) : IP-Adapter用の事前生成された画像埋め込み。IP-Adapterの数と同じ長さのリストである必要があります。各要素は、`(batch_size, num_images, emb_dim)` の形状を持つテンソルである必要があります。指定されない場合、`ip_adapter_image` 入力引数から埋め込みが計算されます。 output_type (`str`、*任意*、デフォルトは `"pil"`) : 生成画像の出力形式。[PIL](https://pillow.readthedocs.io/en/stable/)(`PIL.Image.Image`)または `np.array` から選択します。 return_dict (`bool`、*任意*、デフォルトは`True`) : 通常のタプルではなく`~pipelines.flux.FluxPipelineOutput`を返すかどうか。 joint_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。 callback_on_step_end (`Callable`、*任意*) : 推論中の各デノイジングステップの終了時に呼び出される関数です。この関数は、以下の引数とともに呼び出されます: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。 `callback_kwargs` には、`callback_on_step_end_tensor_inputs` で指定されたすべてのテンソルのリストが含まれます。 callback_on_step_end_tensor_inputs (`list`, *任意*) : `callback_on_step_end` 関数へのテンソル入力のリストです。リストで指定されたテンソルは、`callback_kwargs` 引数として渡されます。パイプラインクラスの `._callback_tensor_inputs` 属性に列挙された変数のみを、リストに含めることができます。 max_sequence_length (`int`、デフォルトは 512) : `prompt` に使用する最大シーケンス長。 **戻り値:** `~pipelines.flux.FluxPipelineOutput` または `tuple` `return_dict` が True の場合は `~pipelines.flux.FluxPipelineOutput`、それ以外の場合は `tuple` を返します。tuple を返す場合、最初の要素は生成された画像のリストです。 生成用のパイプラインを呼び出したときに実行される関数。 例: ```py >>> import torch >>> from diffusers import FluxInpaintPipeline >>> from diffusers.utils import load_image >>> pipe = FluxInpaintPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16) >>> pipe.to("cuda") >>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench" >>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png" >>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png" >>> source = load_image(img_url) >>> mask = load_image(mask_url) >>> image = pipe(prompt=prompt, image=source, mask_image=mask).images[0] >>> image.save("flux_inpainting.png") ``` #### encode_prompt[[diffusers.FluxInpaintPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], prompt_2: str | list[str] | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, max_sequence_length: int = 512, lora_scale: float | None = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_inpaint.py#L339) **パラメータ:** prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。未定義の場合、すべての text-encoder で `prompt` が使用されます。 device : (`torch.device`): torch デバイス num_images_per_prompt (`int`) : プロンプトごとに生成すべき画像の数 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 lora_scale (`float`、*任意*) : LoRAレイヤーが読み込まれている場合、テキストエンコーダーのすべてのLoRAレイヤーに適用されるLoRAスケールです。 ## FluxControlNetInpaintPipeline[[diffusers.FluxControlNetInpaintPipeline]] #### diffusers.FluxControlNetInpaintPipeline[[diffusers.FluxControlNetInpaintPipeline]] ```python diffusers.FluxControlNetInpaintPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel, controlnet: diffusers.models.controlnets.controlnet_flux.FluxControlNetModel | list[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel] | tuple[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel] | diffusers.models.controlnets.controlnet_flux.FluxMultiControlNetModel) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py#L174) **パラメータ:** transformer ([FluxTransformer2DModel](/docs/diffusers/main/ja/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : エンコードされた画像潜在変数をノイズ除去するための条件付き Transformer (MMDiT) アーキテクチャ。 scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。 vae ([AutoencoderKL](/docs/diffusers/main/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ(VAE)モデル。 text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)、具体的には [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) バリアントです。 text_encoder_2 (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)、具体的には [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) バリアントです。 tokenizer (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) の Tokenizer。 tokenizer_2 (`T5TokenizerFast`) : クラス [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) の2番目の Tokenizer。 インペインティング用のFlux controlnetパイプライン。 参考: https://blackforestlabs.ai/announcing-black-forest-labs/ #### __call__[[diffusers.FluxControlNetInpaintPipeline.__call__]] ```python __call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, masked_image_latents: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, height: int | None = None, width: int | None = None, strength: float = 0.6, padding_mask_crop: int | None = None, sigmas: list[float] | None = None, num_inference_steps: int = 28, guidance_scale: float = 7.0, control_guidance_start: float | list[float] = 0.0, control_guidance_end: float | list[float] = 1.0, control_mode: int | list[int] | None = None, controlnet_conditioning_scale: float | list[float] = 1.0, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py#L741) **パラメータ:** prompt (`str` または `list[str]`、*省略可能*) : 画像生成をガイドするためのプロンプトまたはプロンプトのリスト。 prompt_2 (`str` または `list[str]`、*任意*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトまたはプロンプトのリスト。 image (`PIL.Image.Image` または `list[PIL.Image.Image]` または `torch.FloatTensor`) : インペイントする画像です。 mask_image (`PIL.Image.Image` または `list[PIL.Image.Image]` または `torch.FloatTensor`) : インペインティングに使用するマスク画像です。マスク内の白いピクセルは再描画され、黒いピクセルは保持されます。 masked_image_latents (`torch.FloatTensor`、*任意*) : 事前に生成されたマスク付き画像の潜在変数。 control_image (`PIL.Image.Image` または `list[PIL.Image.Image]` または `torch.FloatTensor`) : ControlNet の入力条件。生成を制御するための画像。 height (`int`、*任意*、デフォルトは self.default_sample_size * self.vae_scale_factor) : 生成される画像のピクセル単位の縦幅。 width (`int`、*任意*、デフォルトは self.default_sample_size * self.vae_scale_factor) : 生成される画像の幅(ピクセル単位)。 strength (`float`、*optional*、デフォルトは 0.6) : 概念的には、マスクされた領域をどの程度インペイントするかを示します。0 から 1 の間の値である必要があります。 padding_mask_crop (`int`, *任意*) : マスクをクロップする際に使用するパディングのサイズ。 num_inference_steps (`int`、*任意*、デフォルトは 28) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。 sigmas (`list[float]`, *任意*) : `set_timesteps` メソッドで `sigmas` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムシグマ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。 guidance_scale (`float`、*任意*、デフォルト値は 7.0) : [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598) で定義されているガイダンススケール。 control_guidance_start (`float` または `list[float]`、*任意*、デフォルト値は 0.0) : ControlNet が適用を開始するステップの割合(全体のステップ数に対するパーセンテージ)。 control_guidance_end (`float` または `list[float]`、*任意*、デフォルト値は 1.0) : ControlNet が適用を停止するステップの割合(全体のステップ数に対するパーセンテージ)。 control_mode (`int` または `list[int]`、*省略可能*) : ControlNet のモードです。複数の ControlNet を使用する場合は、リストを指定してください。 controlnet_conditioning_scale (`float` または `list[float]`、*任意*、デフォルト値は 1.0) : ControlNet の出力は、元の transformer の残差に加算される前に `controlnet_conditioning_scale` 倍されます。 num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。 generator (`torch.Generator` または `list[torch.Generator]`、*省略可*) : 生成を決定論的にするための 1 つ以上の [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html)。 latents (`torch.FloatTensor`, *任意*) : 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数(noisy latents)。異なるプロンプトで同じ生成を調整するために使用できます。 prompt_embeds (`torch.FloatTensor`, *任意*) : 事前生成されたテキスト埋め込み。プロンプトの重み付けなど、*例えば*テキスト入力の調整を簡単に実行できます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。 output_type (`str`、*任意*、デフォルトは`"pil"`) : 生成画像の出力形式。`PIL.Image`または`np.array`から選択します。 return_dict (`bool`、*任意*、デフォルトは`True`) : 通常のタプルではなく`~pipelines.flux.FluxPipelineOutput`を返すかどうか。 joint_attention_kwargs (`dict`, *任意*) : 結合アテンション機構に渡す追加のキーワード引数。 callback_on_step_end (`Callable`、*任意*) : 推論中の各デノイジングステップの終了時に呼び出される関数。 callback_on_step_end_tensor_inputs (`list[str]`、*任意*) : `callback_on_step_end` 関数へのテンソル入力のリスト。 max_sequence_length (`int`、*任意*、デフォルトは 512):生成されるシーケンスの最大長です。 **戻り値:** `~pipelines.flux.FluxPipelineOutput` または `tuple` `return_dict` が True の場合は `~pipelines.flux.FluxPipelineOutput`、それ以外の場合は `tuple` を返します。tuple を返す場合、最初の要素は生成された画像のリストです。 生成用のパイプラインを呼び出したときに実行される関数。 例: ```py >>> import torch >>> from diffusers import FluxControlNetInpaintPipeline >>> from diffusers.models import FluxControlNetModel >>> from diffusers.utils import load_image >>> controlnet = FluxControlNetModel.from_pretrained( ... "InstantX/FLUX.1-dev-controlnet-canny", torch_dtype=torch.float16 ... ) >>> pipe = FluxControlNetInpaintPipeline.from_pretrained( ... "black-forest-labs/FLUX.1-schnell", controlnet=controlnet, torch_dtype=torch.float16 ... ) >>> pipe.to("cuda") >>> control_image = load_image( ... "https://huggingface.co/InstantX/FLUX.1-dev-Controlnet-Canny-alpha/resolve/main/canny.jpg" ... ) >>> init_image = load_image( ... "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png" ... ) >>> mask_image = load_image( ... "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png" ... ) >>> prompt = "A girl holding a sign that says InstantX" >>> image = pipe( ... prompt, ... image=init_image, ... mask_image=mask_image, ... control_image=control_image, ... control_guidance_start=0.2, ... control_guidance_end=0.8, ... controlnet_conditioning_scale=0.7, ... strength=0.7, ... num_inference_steps=28, ... guidance_scale=3.5, ... ).images[0] >>> image.save("flux_controlnet_inpaint.png") ``` #### encode_prompt[[diffusers.FluxControlNetInpaintPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], prompt_2: str | list[str] | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, max_sequence_length: int = 512, lora_scale: float | None = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py#L349) **パラメータ:** prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。未定義の場合、すべての text-encoder で `prompt` が使用されます。 device : (`torch.device`): torch デバイス num_images_per_prompt (`int`) : プロンプトごとに生成すべき画像の数 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 lora_scale (`float`、*任意*) : LoRAレイヤーが読み込まれている場合、テキストエンコーダーのすべてのLoRAレイヤーに適用されるLoRAスケールです。 ## FluxControlNetImg2ImgPipeline[[diffusers.FluxControlNetImg2ImgPipeline]] #### diffusers.FluxControlNetImg2ImgPipeline[[diffusers.FluxControlNetImg2ImgPipeline]] ```python diffusers.FluxControlNetImg2ImgPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel, controlnet: diffusers.models.controlnets.controlnet_flux.FluxControlNetModel | list[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel] | tuple[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel] | diffusers.models.controlnets.controlnet_flux.FluxMultiControlNetModel) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py#L172) **パラメータ:** transformer ([FluxTransformer2DModel](/docs/diffusers/main/ja/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : エンコードされた画像潜在変数をノイズ除去するための条件付き Transformer (MMDiT) アーキテクチャ。 scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。 vae ([AutoencoderKL](/docs/diffusers/main/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ(VAE)モデル。 text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)、具体的には [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) バリアントです。 text_encoder_2 (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)、具体的には [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) バリアントです。 tokenizer (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) の Tokenizer。 tokenizer_2 (`T5TokenizerFast`) : クラス [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) の2番目の Tokenizer。 画像から画像への生成を行うFlux controlnetパイプライン。 参考: https://blackforestlabs.ai/announcing-black-forest-labs/ #### __call__[[diffusers.FluxControlNetImg2ImgPipeline.__call__]] ```python __call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, height: int | None = None, width: int | None = None, strength: float = 0.6, num_inference_steps: int = 28, sigmas: list[float] | None = None, guidance_scale: float = 7.0, control_guidance_start: float | list[float] = 0.0, control_guidance_end: float | list[float] = 1.0, control_mode: int | list[int] | None = None, controlnet_conditioning_scale: float | list[float] = 1.0, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py#L637) **パラメータ:** prompt (`str` または `list[str]`、*省略可能*) : 画像生成をガイドするためのプロンプトまたはプロンプトのリスト。 prompt_2 (`str` または `list[str]`、*任意*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトまたはプロンプトのリスト。 image (`PIL.Image.Image` または `list[PIL.Image.Image]` または `torch.FloatTensor`) : パイプラインで処理する画像です。 control_image (`PIL.Image.Image` または `list[PIL.Image.Image]` または `torch.FloatTensor`) : ControlNet の入力条件。生成を制御するための画像。 height (`int`、*任意*、デフォルトは self.default_sample_size * self.vae_scale_factor) : 生成される画像のピクセル単位の縦幅。 width (`int`、*任意*、デフォルトは self.default_sample_size * self.vae_scale_factor) : 生成される画像の幅(ピクセル単位)。 strength (`float`、*任意*、デフォルトは 0.6) : 概念的には、参照 `image` をどの程度変換するかを示します。0 から 1 の間の値である必要があります。 num_inference_steps (`int`、*任意*、デフォルトは 28) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。 sigmas (`list[float]`, *任意*) : `set_timesteps` メソッドで `sigmas` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムシグマ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。 guidance_scale (`float`、*任意*、デフォルト値は 7.0) : [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598) で定義されているガイダンススケール。 control_mode (`int` または `list[int]`、*省略可能*) : ControlNet のモードです。複数の ControlNet を使用する場合は、リストを指定してください。 controlnet_conditioning_scale (`float` または `list[float]`、*任意*、デフォルト値は 1.0) : ControlNet の出力は、元の transformer の残差に加算される前に `controlnet_conditioning_scale` 倍されます。 control_guidance_start (`float` または `list[float]`、*任意*、デフォルト値は 0.0) : ControlNet が適用を開始するステップの割合(全体のステップ数に対するパーセンテージ)。 control_guidance_end (`float` または `list[float]`、*任意*、デフォルト値は 1.0) : ControlNet が適用を停止するステップの割合(全体のステップ数に対するパーセンテージ)。 num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。 generator (`torch.Generator` または `list[torch.Generator]`、*省略可*) : 生成を決定論的にするための 1 つ以上の [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html)。 latents (`torch.FloatTensor`, *任意*) : 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数(noisy latents)。異なるプロンプトで同じ生成を調整するために使用できます。 prompt_embeds (`torch.FloatTensor`, *任意*) : 事前生成されたテキスト埋め込み。プロンプトの重み付けなど、*例えば*テキスト入力の調整を簡単に実行できます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。 output_type (`str`、*任意*、デフォルトは`"pil"`) : 生成画像の出力形式。`PIL.Image`または`np.array`から選択します。 return_dict (`bool`、*任意*、デフォルトは`True`) : 通常のタプルではなく`~pipelines.flux.FluxPipelineOutput`を返すかどうか。 joint_attention_kwargs (`dict`, *任意*) : 結合アテンション機構に渡す追加のキーワード引数。 callback_on_step_end (`Callable`、*任意*) : 推論中の各デノイジングステップの終了時に呼び出される関数。 callback_on_step_end_tensor_inputs (`list[str]`、*任意*) : `callback_on_step_end` 関数へのテンソル入力のリスト。 max_sequence_length (`int`、*任意*、デフォルトは 512):生成されるシーケンスの最大長です。 **戻り値:** `~pipelines.flux.FluxPipelineOutput` または `tuple` `return_dict` が True の場合は `~pipelines.flux.FluxPipelineOutput`、それ以外の場合は `tuple` を返します。tuple を返す場合、最初の要素は生成された画像のリストです。 生成用のパイプラインを呼び出したときに実行される関数。 例: ```py >>> import torch >>> from diffusers import FluxControlNetImg2ImgPipeline, FluxControlNetModel >>> from diffusers.utils import load_image >>> device = "cuda" if torch.cuda.is_available() else "cpu" >>> controlnet = FluxControlNetModel.from_pretrained( ... "InstantX/FLUX.1-dev-Controlnet-Canny-alpha", torch_dtype=torch.bfloat16 ... ) >>> pipe = FluxControlNetImg2ImgPipeline.from_pretrained( ... "black-forest-labs/FLUX.1-schnell", controlnet=controlnet, torch_dtype=torch.float16 ... ) >>> pipe.text_encoder.to(torch.float16) >>> pipe.controlnet.to(torch.float16) >>> pipe.to("cuda") >>> control_image = load_image("https://huggingface.co/InstantX/SD3-Controlnet-Canny/resolve/main/canny.jpg") >>> init_image = load_image( ... "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg" ... ) >>> prompt = "A girl in city, 25 years old, cool, futuristic" >>> image = pipe( ... prompt, ... image=init_image, ... control_image=control_image, ... control_guidance_start=0.2, ... control_guidance_end=0.8, ... controlnet_conditioning_scale=1.0, ... strength=0.7, ... num_inference_steps=2, ... guidance_scale=3.5, ... ).images[0] >>> image.save("flux_controlnet_img2img.png") ``` #### encode_prompt[[diffusers.FluxControlNetImg2ImgPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], prompt_2: str | list[str] | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, max_sequence_length: int = 512, lora_scale: float | None = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py#L338) **パラメータ:** prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。未定義の場合、すべての text-encoder で `prompt` が使用されます。 device : (`torch.device`): torch デバイス num_images_per_prompt (`int`) : プロンプトごとに生成すべき画像の数 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 lora_scale (`float`、*任意*) : LoRAレイヤーが読み込まれている場合、テキストエンコーダーのすべてのLoRAレイヤーに適用されるLoRAスケールです。 ## FluxControlPipeline[[diffusers.FluxControlPipeline]] #### diffusers.FluxControlPipeline[[diffusers.FluxControlPipeline]] ```python diffusers.FluxControlPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_control.py#L159) **パラメータ:** transformer ([FluxTransformer2DModel](/docs/diffusers/main/ja/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : エンコードされた画像潜在変数をノイズ除去するための条件付き Transformer (MMDiT) アーキテクチャ。 scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。 vae ([AutoencoderKL](/docs/diffusers/main/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ(VAE)モデル。 text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)、具体的には [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) バリアントです。 text_encoder_2 (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)、具体的には [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) バリアントです。 tokenizer (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) の Tokenizer。 tokenizer_2 (`T5TokenizerFast`) : クラス [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) の2番目の Tokenizer。 画像条件付きの制御可能なテキストから画像への生成を行うFluxパイプライン。 参考: https://bfl.ai/flux-1-tools #### __call__[[diffusers.FluxControlPipeline.__call__]] ```python __call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 28, sigmas: list[float] | None = None, guidance_scale: float = 3.5, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_control.py#L583) **パラメータ:** prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。 prompt_2 (`str` または `list[str]`、*省略可能*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。定義されていない場合、代わりに `prompt` が使用されます。 control_image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、`list[np.ndarray]`、: `list[list[torch.Tensor]]`、`list[list[np.ndarray]]` または `list[list[PIL.Image.Image]]`): 生成において `unet` にガイダンスを与えるための ControlNet の入力条件です。型が `torch.Tensor` として指定されている場合、ControlNet にそのまま渡されます。画像として `PIL.Image.Image` も受け付けられます。出力画像の寸法は、デフォルトで `image` の寸法になります。高さおよび/または幅が渡された場合、`image` はそれに応じてリサイズされます。`init` で複数の ControlNet が指定されている場合、各 ControlNet への入力が正しくバッチ処理できるよう、リストとして画像を渡す必要があります。 height (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像のピクセル単位の縦幅。最適な結果を得るため、デフォルトでは 1024 に設定されています。 width (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像の幅(ピクセル単位)。最適な結果を得るため、デフォルトでは 1024 に設定されています。 num_inference_steps (`int`、*任意*、デフォルト値は 50) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。 sigmas (`list[float]`, *任意*) : `set_timesteps` メソッドで `sigmas` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムシグマ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。 guidance_scale (`float`、*任意*、デフォルト値は 3.5) : `guidance_scale` > 1 を設定することで、埋め込み型ガイダンススケールが有効になります。`guidance_scale` の値を高くすると、プロンプトに沿った画像の生成が促されますが、画像の品質が低下する可能性があります。ガイダンス蒸留モデルは、`guidance_scale` > 1 の場合に、真のクラスファイアフリーガイダンスを近似します。詳細については、[論文](https://huggingface.co/papers/2210.03142)を参照してください。 num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。 generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : 生成を決定論的にするための [torch ジェネレーター](https://pytorch.org/docs/stable/generated/torch.Generator.html) 1 つまたはそのリスト。 latents (`torch.FloatTensor`, *任意*) : 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数(latents)。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム`generator`を使用してサンプリングを行い、潜在変数テンソルが生成されます。 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 output_type (`str`、*任意*、デフォルトは `"pil"`) : 生成画像の出力形式。[PIL](https://pillow.readthedocs.io/en/stable/)(`PIL.Image.Image`)または `np.array` から選択します。 return_dict (`bool`、*任意*、デフォルトは`True`) : 通常のタプルではなく`~pipelines.flux.FluxPipelineOutput`を返すかどうか。 joint_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。 callback_on_step_end (`Callable`、*任意*) : 推論中の各デノイジングステップの終了時に呼び出される関数です。この関数は、以下の引数とともに呼び出されます: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。 `callback_kwargs` には、`callback_on_step_end_tensor_inputs` で指定されたすべてのテンソルのリストが含まれます。 callback_on_step_end_tensor_inputs (`list`, *任意*) : `callback_on_step_end` 関数へのテンソル入力のリストです。リストで指定されたテンソルは、`callback_kwargs` 引数として渡されます。パイプラインクラスの `._callback_tensor_inputs` 属性に列挙された変数のみを、リストに含めることができます。 max_sequence_length (`int`、デフォルトは 512) : `prompt` に使用する最大シーケンス長。 **戻り値:** `~pipelines.flux.FluxPipelineOutput` または `tuple` `return_dict` が True の場合は `~pipelines.flux.FluxPipelineOutput`、それ以外の場合は `tuple` を返します。tuple を返す場合、最初の要素は生成された画像のリストです。 生成用のパイプラインを呼び出したときに実行される関数。 例: ```py >>> import torch >>> from controlnet_aux import CannyDetector >>> from diffusers import FluxControlPipeline >>> from diffusers.utils import load_image >>> pipe = FluxControlPipeline.from_pretrained( ... "black-forest-labs/FLUX.1-Canny-dev", torch_dtype=torch.bfloat16 ... ).to("cuda") >>> prompt = "A robot made of exotic candies and chocolates of different kinds. The background is filled with confetti and celebratory gifts." >>> control_image = load_image( ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png" ... ) >>> processor = CannyDetector() >>> control_image = processor( ... control_image, low_threshold=50, high_threshold=200, detect_resolution=1024, image_resolution=1024 ... ) >>> image = pipe( ... prompt=prompt, ... control_image=control_image, ... height=1024, ... width=1024, ... num_inference_steps=50, ... guidance_scale=30.0, ... ).images[0] >>> image.save("output.png") ``` #### encode_prompt[[diffusers.FluxControlPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], prompt_2: str | list[str] | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, max_sequence_length: int = 512, lora_scale: float | None = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_control.py#L326) **パラメータ:** prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。未定義の場合、すべての text-encoder で `prompt` が使用されます。 device : (`torch.device`): torch デバイス num_images_per_prompt (`int`) : プロンプトごとに生成すべき画像の数 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 lora_scale (`float`、*任意*) : LoRAレイヤーが読み込まれている場合、テキストエンコーダーのすべてのLoRAレイヤーに適用されるLoRAスケールです。 ## FluxControlImg2ImgPipeline[[diffusers.FluxControlImg2ImgPipeline]] #### diffusers.FluxControlImg2ImgPipeline[[diffusers.FluxControlImg2ImgPipeline]] ```python diffusers.FluxControlImg2ImgPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_control_img2img.py#L178) **パラメータ:** transformer ([FluxTransformer2DModel](/docs/diffusers/main/ja/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : エンコードされた画像潜在変数をノイズ除去するための条件付き Transformer (MMDiT) アーキテクチャ。 scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。 vae ([AutoencoderKL](/docs/diffusers/main/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ(VAE)モデル。 text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)、具体的には [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) バリアントです。 text_encoder_2 (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)、具体的には [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) バリアントです。 tokenizer (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) の Tokenizer。 tokenizer_2 (`T5TokenizerFast`) : クラス [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) の2番目の Tokenizer。 画像インペインティング用のFluxパイプライン。 参考: https://blackforestlabs.ai/announcing-black-forest-labs/ #### __call__[[diffusers.FluxControlImg2ImgPipeline.__call__]] ```python __call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, height: int | None = None, width: int | None = None, strength: float = 0.6, num_inference_steps: int = 28, sigmas: list[float] | None = None, guidance_scale: float = 7.0, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_control_img2img.py#L636) **パラメータ:** prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。 prompt_2 (`str` または `list[str]`、*省略可能*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。定義されていない場合、代わりに `prompt` が使用されます。 image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、または `list[np.ndarray]`) : `Image`、numpy 配列、またはテンソル。開始点として使用される画像バッチを表します。numpy 配列および PyTorch テンソルの場合、想定される値の範囲は `[0, 1]` です。テンソルまたはテンソルのリストの場合、想定される形状は `(B, C, H, W)` または `(C, H, W)` です。numpy 配列または配列のリストの場合、想定される形状は `(B, H, W, C)` または `(H, W, C)` です。`image` として画像の潜在変数(latents)を受け取ることもできますが、潜在変数を直接渡す場合は、再度エンコードされません。 control_image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、`list[np.ndarray]`、: `list[list[torch.Tensor]]`、`list[list[np.ndarray]]` または `list[list[PIL.Image.Image]]`): 生成において `unet` にガイダンスを与えるための ControlNet の入力条件です。型が `torch.Tensor` として指定されている場合、ControlNet にそのまま渡されます。画像として `PIL.Image.Image` も受け付けられます。出力画像の寸法は、デフォルトで `image` の寸法になります。高さおよび/または幅が渡された場合、`image` はそれに応じてリサイズされます。`init` で複数の ControlNet が指定されている場合、各 ControlNet への入力が正しくバッチ処理できるよう、リストとして画像を渡す必要があります。 height (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像のピクセル単位の縦幅。最適な結果を得るため、デフォルトでは 1024 に設定されています。 width (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像の幅(ピクセル単位)。最適な結果を得るため、デフォルトでは 1024 に設定されています。 strength (`float`、*任意*、デフォルト値は 1.0) : 参照となる `image` を変換する度合いを示します。0 から 1 の間の値である必要があります。`image` が起点として使用され、`strength` の値が大きいほど、より多くのノイズが追加されます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。`strength` が 1 の場合、追加されるノイズは最大となり、`num_inference_steps` で指定された全イテレーション数にわたってデノイジングプロセスが実行されます。値が 1 である場合、`image` は実質的に無視されます。 num_inference_steps (`int`、*任意*、デフォルト値は 50) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。 sigmas (`list[float]`, *任意*) : `set_timesteps` メソッドで `sigmas` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムシグマ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。 guidance_scale (`float`、*任意*、デフォルト値は 7.0) : [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598) で定義されているガイダンススケールです。`guidance_scale` は、[Imagen Paper](https://huggingface.co/papers/2205.11487) の数式 2 の `w` として定義されています。`guidance_scale > 1` を設定することでガイダンススケールが有効になります。ガイダンススケールを高くすると、`prompt` のテキストと密接に関連する画像の生成が促されますが、通常は画像の品質が低下する傾向があります。 num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。 generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : 生成を決定論的にするための [torch ジェネレーター](https://pytorch.org/docs/stable/generated/torch.Generator.html) 1 つまたはそのリスト。 latents (`torch.FloatTensor`, *任意*) : 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数(latents)。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム`generator`を使用してサンプリングを行い、潜在変数テンソルが生成されます。 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 output_type (`str`、*任意*、デフォルトは `"pil"`) : 生成画像の出力形式。[PIL](https://pillow.readthedocs.io/en/stable/)(`PIL.Image.Image`)または `np.array` から選択します。 return_dict (`bool`、*任意*、デフォルトは`True`) : 通常のタプルではなく`~pipelines.flux.FluxPipelineOutput`を返すかどうか。 joint_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。 callback_on_step_end (`Callable`、*任意*) : 推論中の各デノイジングステップの終了時に呼び出される関数です。この関数は、以下の引数とともに呼び出されます: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。 `callback_kwargs` には、`callback_on_step_end_tensor_inputs` で指定されたすべてのテンソルのリストが含まれます。 callback_on_step_end_tensor_inputs (`list`, *任意*) : `callback_on_step_end` 関数へのテンソル入力のリストです。リストで指定されたテンソルは、`callback_kwargs` 引数として渡されます。パイプラインクラスの `._callback_tensor_inputs` 属性に列挙された変数のみを、リストに含めることができます。 max_sequence_length (`int`、デフォルトは 512) : `prompt` に使用する最大シーケンス長。 **戻り値:** `~pipelines.flux.FluxPipelineOutput` または `tuple` `return_dict` が True の場合は `~pipelines.flux.FluxPipelineOutput`、それ以外の場合は `tuple` を返します。tuple を返す場合、最初の要素は生成された画像のリストです。 生成用のパイプラインを呼び出したときに実行される関数。 例: ```py >>> import torch >>> from controlnet_aux import CannyDetector >>> from diffusers import FluxControlImg2ImgPipeline >>> from diffusers.utils import load_image >>> pipe = FluxControlImg2ImgPipeline.from_pretrained( ... "black-forest-labs/FLUX.1-Canny-dev", torch_dtype=torch.bfloat16 ... ).to("cuda") >>> prompt = "A robot made of exotic candies and chocolates of different kinds. Abstract background" >>> image = load_image( ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/watercolor-painting.jpg" ... ) >>> control_image = load_image( ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png" ... ) >>> processor = CannyDetector() >>> control_image = processor( ... control_image, low_threshold=50, high_threshold=200, detect_resolution=1024, image_resolution=1024 ... ) >>> image = pipe( ... prompt=prompt, ... image=image, ... control_image=control_image, ... strength=0.8, ... height=1024, ... width=1024, ... num_inference_steps=50, ... guidance_scale=30.0, ... ).images[0] >>> image.save("output.png") ``` #### encode_prompt[[diffusers.FluxControlImg2ImgPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], prompt_2: str | list[str] | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, max_sequence_length: int = 512, lora_scale: float | None = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_control_img2img.py#L337) **パラメータ:** prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。未定義の場合、すべての text-encoder で `prompt` が使用されます。 device : (`torch.device`): torch デバイス num_images_per_prompt (`int`) : プロンプトごとに生成すべき画像の数 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 lora_scale (`float`、*任意*) : LoRAレイヤーが読み込まれている場合、テキストエンコーダーのすべてのLoRAレイヤーに適用されるLoRAスケールです。 ## FluxPriorReduxPipeline[[diffusers.FluxPriorReduxPipeline]] #### diffusers.FluxPriorReduxPipeline[[diffusers.FluxPriorReduxPipeline]] ```python diffusers.FluxPriorReduxPipeline(image_encoder: SiglipVisionModel, feature_extractor: SiglipImageProcessorPil, image_embedder: ReduxImageEncoder, text_encoder: CLIPTextModel = None, tokenizer: CLIPTokenizer = None, text_encoder_2: T5EncoderModel = None, tokenizer_2: T5Tokenizer = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_prior_redux.py#L83) **パラメータ:** image_encoder (`SiglipVisionModel`) : 入力画像をエンコードするための SIGLIP ビジョンモデル。 feature_extractor (`SiglipImageProcessor`) : SIGLIPモデル用の画像の前処理を行う画像プロセッサ。 image_embedder (`ReduxImageEncoder`) : SIGLIP 埋め込みを処理するための Redux 画像エンコーダー。 text_encoder (`CLIPTextModel`、*任意*) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)、具体的には [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) バリアント。 text_encoder_2 (`T5EncoderModel`、*任意*) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)、具体的には [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) バリアント。 tokenizer (`CLIPTokenizer`、*任意*) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) の Tokenizer。 tokenizer_2 (`T5TokenizerFast`、*任意*) : クラス [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) の 2 つ目の Tokenizer。 画像から画像への生成を行うFlux Reduxパイプライン。 参考: https://blackforestlabs.ai/flux-1-tools/ #### __call__[[diffusers.FluxPriorReduxPipeline.__call__]] ```python __call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]], prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, prompt_embeds_scale: float | list[float] | None = 1.0, pooled_prompt_embeds_scale: float | list[float] | None = 1.0, return_dict: bool = True) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_prior_redux.py#L378) **パラメータ:** image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、または `list[np.ndarray]`) : 開始点として使用する画像バッチを表す `Image`、numpy 配列、またはテンソル。numpy 配列および PyTorch テンソルの両方において、想定される値の範囲は `[0, 1]` です。テンソルまたはテンソルのリストの場合、想定される形状は `(B, C, H, W)` または `(C, H, W)` です。numpy 配列または配列のリストの場合、想定される形状は `(B, H, W, C)` または `(H, W, C)` です。 prompt (`str` または `list[str]`、*省略可能*) : 画像生成をガイドするためのプロンプトです。**実験的機能**: この機能を使用するには、パイプラインにテキストエンコーダーを明示的に読み込む必要があります。テキストエンコーダーが読み込まれていない場合、プロンプトは無視されます。 prompt_2 (`str` または `list[str]`、*任意*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトまたはプロンプトのリスト。 prompt_embeds (`torch.FloatTensor`, *任意*) : 事前生成されたテキスト埋め込み。プロンプトの重み付けなど、*例えば*テキスト入力の調整を簡単に実行できます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。 prompt_embeds_scale (`float` または `list[float]`、*任意*、デフォルトは 1.0) : 返却前に redux プロンプトの埋め込みに適用されるスケーリング係数(または画像ごとのスケーリング係数のリスト)。 pooled_prompt_embeds_scale (`float` または `list[float]`、*任意*、デフォルトは 1.0) : 返却前に redux プールされたプロンプト埋め込みに適用されるスケール係数(または画像ごとのスケール係数のリスト)。 return_dict (`bool`、*任意*、デフォルトは`True`) : プレーンなタプルではなく`~pipelines.flux.FluxPriorReduxPipelineOutput`を返すかどうか。 **戻り値:** `~pipelines.flux.FluxPriorReduxPipelineOutput` または `tuple` `return_dict` が True の場合は `~pipelines.flux.FluxPriorReduxPipelineOutput`、それ以外の場合は `tuple` を返します。tuple を返す場合、最初の要素は生成された画像のリストです。 生成用のパイプラインを呼び出したときに実行される関数。 例: ```py >>> import torch >>> from diffusers import FluxPriorReduxPipeline, FluxPipeline >>> from diffusers.utils import load_image >>> device = "cuda" >>> dtype = torch.bfloat16 >>> repo_redux = "black-forest-labs/FLUX.1-Redux-dev" >>> repo_base = "black-forest-labs/FLUX.1-dev" >>> pipe_prior_redux = FluxPriorReduxPipeline.from_pretrained(repo_redux, torch_dtype=dtype).to(device) >>> pipe = FluxPipeline.from_pretrained( ... repo_base, text_encoder=None, text_encoder_2=None, torch_dtype=torch.bfloat16 ... ).to(device) >>> image = load_image( ... "https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/style_ziggy/img5.png" ... ) >>> pipe_prior_output = pipe_prior_redux(image) >>> images = pipe( ... guidance_scale=2.5, ... num_inference_steps=50, ... generator=torch.Generator("cpu").manual_seed(0), ... **pipe_prior_output, ... ).images >>> images[0].save("flux-redux.png") ``` #### encode_prompt[[diffusers.FluxPriorReduxPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], prompt_2: str | list[str] | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, max_sequence_length: int = 512, lora_scale: float | None = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_prior_redux.py#L299) **パラメータ:** prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。未定義の場合、すべての text-encoder で `prompt` が使用されます。 device : (`torch.device`): torch デバイス num_images_per_prompt (`int`) : プロンプトごとに生成すべき画像の数 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 lora_scale (`float`、*任意*) : LoRAレイヤーが読み込まれている場合、テキストエンコーダーのすべてのLoRAレイヤーに適用されるLoRAスケールです。 ## FluxFillPipeline[[diffusers.FluxFillPipeline]] #### diffusers.FluxFillPipeline[[diffusers.FluxFillPipeline]] ```python diffusers.FluxFillPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_fill.py#L167) **パラメータ:** transformer ([FluxTransformer2DModel](/docs/diffusers/main/ja/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : エンコードされた画像潜在変数をノイズ除去するための条件付き Transformer (MMDiT) アーキテクチャ。 scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。 vae ([AutoencoderKL](/docs/diffusers/main/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ(VAE)モデル。 text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)、具体的には [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) バリアントです。 text_encoder_2 (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)、具体的には [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) バリアントです。 tokenizer (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) の Tokenizer。 tokenizer_2 (`T5TokenizerFast`) : クラス [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) の2番目の Tokenizer。 画像のインペインティング/アウトペインティング用のFlux Fillパイプライン。 参考: https://blackforestlabs.ai/flux-1-tools/ #### __call__[[diffusers.FluxFillPipeline.__call__]] ```python __call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Optional[torch.FloatTensor] = None, mask_image: typing.Optional[torch.FloatTensor] = None, masked_image_latents: typing.Optional[torch.FloatTensor] = None, height: int | None = None, width: int | None = None, strength: float = 1.0, num_inference_steps: int = 50, sigmas: list[float] | None = None, guidance_scale: float = 30.0, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_fill.py#L700) **パラメータ:** prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。 prompt_2 (`str` または `list[str]`、*省略可能*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。定義されていない場合、代わりに `prompt` が使用されます。 image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、または `list[np.ndarray]`) : 開始点として使用される画像バッチを表す `Image`、numpy 配列、またはテンソル。numpy 配列および PyTorch テンソルの両方において、想定される値の範囲は `[0, 1]` です。テンソルまたはテンソルのリストの場合、想定される形状は `(B, C, H, W)` または `(C, H, W)` です。numpy 配列または配列のリストの場合、想定される形状は `(B, H, W, C)` または `(H, W, C)` です。 mask_image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、または `list[np.ndarray]`) : `image` をマスクするための `Image`、numpy 配列、またはテンソル。マスク内の白いピクセルは再描画され、黒いピクセルは保持されます。`mask_image` が PIL イメージの場合、使用の前に単一チャネル(輝度)に変換されます。numpy 配列または PyTorch テンソルの場合は、3 チャネルではなく 1 つの色チャネル(L)を含む必要があります。そのため、PyTorch テンソルの想定される形状は `(B, 1, H, W)`、`(B, H, W)`、`(1, H, W)`、`(H, W)` となります。一方、numpy 配列の場合は `(B, H, W, 1)`、`(B, H, W)`、`(H, W, 1)`、または `(H, W)` となります。 masked_image_latents (`torch.Tensor`、`list[torch.Tensor]`) : VAEによって生成された`image`をマスクするための画像バッチを表す`Tensor`。指定されない場合、マスク用の潜変数テンソルは`mask_image`によって生成されます。 height (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像のピクセル単位の縦幅。最適な結果を得るため、デフォルトでは 1024 に設定されています。 width (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像の幅(ピクセル単位)。最適な結果を得るため、デフォルトでは 1024 に設定されています。 strength (`float`、*任意*、デフォルト値は 1.0) : 参照となる `image` を変換する度合いを示します。0 から 1 の間の値である必要があります。`image` が起点として使用され、`strength` の値が大きいほど、より多くのノイズが追加されます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。`strength` が 1 の場合、追加されるノイズは最大となり、`num_inference_steps` で指定された全イテレーション数にわたってデノイジングプロセスが実行されます。値が 1 である場合、`image` は実質的に無視されます。 num_inference_steps (`int`、*任意*、デフォルト値は 50) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。 sigmas (`list[float]`, *任意*) : `set_timesteps` メソッドで `sigmas` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムシグマ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。 guidance_scale (`float`、*任意*、デフォルト値は 30.0) : [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)で定義されているガイダンススケールです。`guidance_scale` は、[Imagen Paper](https://huggingface.co/papers/2205.11487)の式 2 の `w` として定義されています。`guidance_scale > 1` を設定することでガイダンススケールが有効になります。ガイダンススケールを高くすると、`prompt` のテキストと密接に関連する画像の生成が促されますが、通常は画像の品質が低下する傾向があります。 num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。 generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : 生成を決定論的にするための [torch ジェネレーター](https://pytorch.org/docs/stable/generated/torch.Generator.html) 1 つまたはそのリスト。 latents (`torch.FloatTensor`, *任意*) : 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数(latents)。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム`generator`を使用してサンプリングを行い、潜在変数テンソルが生成されます。 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 output_type (`str`、*任意*、デフォルトは `"pil"`) : 生成画像の出力形式。[PIL](https://pillow.readthedocs.io/en/stable/)(`PIL.Image.Image`)または `np.array` から選択します。 return_dict (`bool`、*任意*、デフォルトは`True`) : 通常のタプルではなく`~pipelines.flux.FluxPipelineOutput`を返すかどうか。 joint_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。 callback_on_step_end (`Callable`、*任意*) : 推論中の各デノイジングステップの終了時に呼び出される関数です。この関数は、以下の引数とともに呼び出されます: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。 `callback_kwargs` には、`callback_on_step_end_tensor_inputs` で指定されたすべてのテンソルのリストが含まれます。 callback_on_step_end_tensor_inputs (`list`, *任意*) : `callback_on_step_end` 関数へのテンソル入力のリストです。リストで指定されたテンソルは、`callback_kwargs` 引数として渡されます。パイプラインクラスの `._callback_tensor_inputs` 属性に列挙された変数のみを、リストに含めることができます。 max_sequence_length (`int`、デフォルトは 512) : `prompt` に使用する最大シーケンス長。 **戻り値:** `~pipelines.flux.FluxPipelineOutput` または `tuple` `return_dict` が True の場合は `~pipelines.flux.FluxPipelineOutput`、それ以外の場合は `tuple` を返します。tuple を返す場合、最初の要素は生成された画像のリストです。 生成用のパイプラインを呼び出したときに実行される関数。 例: ```py >>> import torch >>> from diffusers import FluxFillPipeline >>> from diffusers.utils import load_image >>> image = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/cup.png") >>> mask = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/cup_mask.png") >>> pipe = FluxFillPipeline.from_pretrained("black-forest-labs/FLUX.1-Fill-dev", torch_dtype=torch.bfloat16) >>> pipe.enable_model_cpu_offload() # save some VRAM by offloading the model to CPU >>> image = pipe( ... prompt="a white paper cup", ... image=image, ... mask_image=mask, ... height=1632, ... width=1232, ... guidance_scale=30, ... num_inference_steps=50, ... max_sequence_length=512, ... generator=torch.Generator("cpu").manual_seed(0), ... ).images[0] >>> image.save("flux_fill.png") ``` #### encode_prompt[[diffusers.FluxFillPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], prompt_2: str | list[str] | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, max_sequence_length: int = 512, lora_scale: float | None = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_fill.py#L421) **パラメータ:** prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。未定義の場合、すべての text-encoder で `prompt` が使用されます。 device : (`torch.device`): torch デバイス num_images_per_prompt (`int`) : プロンプトごとに生成すべき画像の数 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 lora_scale (`float`、*任意*) : LoRAレイヤーが読み込まれている場合、テキストエンコーダーのすべてのLoRAレイヤーに適用されるLoRAスケールです。 ## FluxKontextPipeline[[diffusers.FluxKontextPipeline]] #### diffusers.FluxKontextPipeline[[diffusers.FluxKontextPipeline]] ```python diffusers.FluxKontextPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_kontext.py#L190) **パラメータ:** transformer ([FluxTransformer2DModel](/docs/diffusers/main/ja/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : エンコードされた画像潜在変数をノイズ除去するための条件付き Transformer (MMDiT) アーキテクチャ。 scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。 vae ([AutoencoderKL](/docs/diffusers/main/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ(VAE)モデル。 text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)、具体的には [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) バリアントです。 text_encoder_2 (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)、具体的には [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) バリアントです。 tokenizer (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) の Tokenizer。 tokenizer_2 (`T5TokenizerFast`) : クラス [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) の2番目の Tokenizer。 画像から画像への変換およびテキストから画像への生成を行うFlux Kontextパイプライン。 Reference: https://bfl.ai/announcements/flux-1-kontext-dev #### __call__[[diffusers.FluxKontextPipeline.__call__]] ```python __call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, negative_prompt: str | list[str] = None, negative_prompt_2: str | list[str] | None = None, true_cfg_scale: float = 1.0, height: int | None = None, width: int | None = None, num_inference_steps: int = 28, sigmas: list[float] | None = None, guidance_scale: float = 3.5, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, negative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, negative_ip_adapter_image_embeds: list[torch.Tensor] | None = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512, max_area: int = 1048576, _auto_resize: bool = True) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_kontext.py#L695) **パラメータ:** image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、または `list[np.ndarray]`) : `Image`、numpy 配列、またはテンソル。開始点として使用される画像バッチを表します。numpy 配列および PyTorch テンソルの場合、想定される値の範囲は `[0, 1]` です。テンソルまたはテンソルのリストの場合、想定される形状は `(B, C, H, W)` または `(C, H, W)` です。numpy 配列または配列のリストの場合、想定される形状は `(B, H, W, C)` または `(H, W, C)` です。`image` として画像の潜在変数(latents)を受け取ることもできますが、潜在変数を直接渡す場合は、再度エンコードされません。 prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。 prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。定義されていない場合、代わりに `prompt` が使用されます。 negative_prompt (`str` または `list[str]`、*省略可能*) : 画像生成をガイドしないプロンプトです。未定義の場合、代わりに `negative_prompt_embeds` を渡す必要があります。ガイダンスを使用していない場合は無視されます(`true_cfg_scale` が `1` 以下の場合に無視されます)。 negative_prompt_2 (`str` または `list[str]`、*任意*) : 画像生成を誘導しないプロンプト、またはプロンプトのリストです。`tokenizer_2` および `text_encoder_2` に送信されます。定義されていない場合、すべてのテキストエンコーダーで `negative_prompt` が使用されます。 true_cfg_scale (`float`、*任意*、デフォルト値は 1.0) : 1.0 より大きく、かつ `negative_prompt` が指定されている場合、true classifier-free guidance を有効にします。 height (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像のピクセル単位の縦幅。最適な結果を得るため、デフォルトでは 1024 に設定されています。 width (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像の幅(ピクセル単位)。最適な結果を得るため、デフォルトでは 1024 に設定されています。 num_inference_steps (`int`、*任意*、デフォルト値は 50) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。 sigmas (`list[float]`, *任意*) : `set_timesteps` メソッドで `sigmas` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムシグマ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。 guidance_scale (`float`、*任意*、デフォルト値は 3.5) : `guidance_scale` > 1 を設定することで、埋め込み型ガイダンススケールが有効になります。`guidance_scale` の値を高くすると、プロンプトに沿った画像の生成が促されますが、画像の品質が低下する可能性があります。ガイダンス蒸留モデルは、`guidance_scale` > 1 の場合に、真のクラスファイアフリーガイダンスを近似します。詳細については、[論文](https://huggingface.co/papers/2210.03142)を参照してください。 num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。 generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : 生成を決定論的にするための [torch ジェネレーター](https://pytorch.org/docs/stable/generated/torch.Generator.html) 1 つまたはそのリスト。 latents (`torch.FloatTensor`, *任意*) : 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数(latents)。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム`generator`を使用してサンプリングを行い、潜在変数テンソルが生成されます。 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 ip_adapter_image : (`PipelineImageInput`、*任意*): IP Adapter で使用する任意の画像入力。 ip_adapter_image_embeds (`list[torch.Tensor]`、*省略可*) : IP-Adapter用の事前生成された画像埋め込み。IP-Adapterの数と同じ長さのリストである必要があります。各要素は、`(batch_size, num_images, emb_dim)` の形状を持つテンソルである必要があります。指定されない場合、`ip_adapter_image` 入力引数から埋め込みが計算されます。 negative_ip_adapter_image : (`PipelineImageInput`、*任意*): IP Adapter で使用する任意の画像入力。 negative_ip_adapter_image_embeds (`list[torch.Tensor]`、*省略可*) : IP-Adapter用の事前生成された画像埋め込み。IP-Adapterの数と同じ長さのリストである必要があります。各要素は、`(batch_size, num_images, emb_dim)` の形状を持つテンソルである必要があります。指定されない場合、`ip_adapter_image` 入力引数から埋め込みが計算されます。 negative_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたネガティブなテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`negative_prompt` 入力引数から negative_prompt_embeds が生成されます。 negative_pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたネガティブなプールのテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`negative_prompt` 入力引数からプールの negative_prompt_embeds が生成されます。 output_type (`str`、*任意*、デフォルトは `"pil"`) : 生成画像の出力形式。[PIL](https://pillow.readthedocs.io/en/stable/)(`PIL.Image.Image`)または `np.array` から選択します。 return_dict (`bool`、*任意*、デフォルトは`True`) : 通常のタプルではなく`~pipelines.flux.FluxPipelineOutput`を返すかどうか。 joint_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。 callback_on_step_end (`Callable`、*任意*) : 推論中の各デノイジングステップの終了時に呼び出される関数です。この関数は、以下の引数とともに呼び出されます: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。 `callback_kwargs` には、`callback_on_step_end_tensor_inputs` で指定されたすべてのテンソルのリストが含まれます。 callback_on_step_end_tensor_inputs (`list`, *任意*) : `callback_on_step_end` 関数へのテンソル入力のリストです。リストで指定されたテンソルは、`callback_kwargs` 引数として渡されます。パイプラインクラスの `._callback_tensor_inputs` 属性に列挙された変数のみを、リストに含めることができます。 max_sequence_length (`int`、デフォルトは 512) : `prompt` に使用する最大シーケンス長。 max_area (`int`、デフォルトは`1024 ** 2`) : 生成される画像のピクセル単位の最大面積です。アスペクト比を維持したまま、この面積に収まるよう高さおよび幅が調整されます。 _auto_resize (`bool`, *任意*, デフォルトは `True`) : 入力画像を推奨解像度に自動的にリサイズするかどうかを指定します。 **戻り値:** `~pipelines.flux.FluxPipelineOutput` または `tuple` `return_dict` が True の場合は `~pipelines.flux.FluxPipelineOutput`、それ以外の場合は `tuple` を返します。tuple を返す場合、最初の要素は生成された画像のリストです。 生成用のパイプラインを呼び出したときに実行される関数。 例: ```py >>> import torch >>> from diffusers import FluxKontextPipeline >>> from diffusers.utils import load_image >>> pipe = FluxKontextPipeline.from_pretrained( ... "black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16 ... ) >>> pipe.to("cuda") >>> image = load_image( ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/yarn-art-pikachu.png" ... ).convert("RGB") >>> prompt = "Make Pikachu hold a sign that says 'Black Forest Labs is awesome', yarn art style, detailed, vibrant colors" >>> image = pipe( ... image=image, ... prompt=prompt, ... guidance_scale=2.5, ... generator=torch.Generator().manual_seed(42), ... ).images[0] >>> image.save("output.png") ``` #### encode_prompt[[diffusers.FluxKontextPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], prompt_2: str | list[str] | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, max_sequence_length: int = 512, lora_scale: float | None = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_kontext.py#L360) **パラメータ:** prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。未定義の場合、すべての text-encoder で `prompt` が使用されます。 device : (`torch.device`): torch デバイス num_images_per_prompt (`int`) : プロンプトごとに生成すべき画像の数 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 lora_scale (`float`、*任意*) : LoRAレイヤーが読み込まれている場合、テキストエンコーダーのすべてのLoRAレイヤーに適用されるLoRAスケールです。 ## FluxKontextInpaintPipeline[[diffusers.FluxKontextInpaintPipeline]] #### diffusers.FluxKontextInpaintPipeline[[diffusers.FluxKontextInpaintPipeline]] ```python diffusers.FluxKontextInpaintPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_kontext_inpaint.py#L214) **パラメータ:** transformer ([FluxTransformer2DModel](/docs/diffusers/main/ja/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : エンコードされた画像潜在変数をノイズ除去するための条件付き Transformer (MMDiT) アーキテクチャ。 scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。 vae ([AutoencoderKL](/docs/diffusers/main/ja/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 画像を潜在表現にエンコードし、潜在表現からデコードするための変分オートエンコーダ(VAE)モデル。 text_encoder (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)、具体的には [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) バリアントです。 text_encoder_2 (`T5EncoderModel`) : [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)、具体的には [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) バリアントです。 tokenizer (`CLIPTokenizer`) : クラス [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) の Tokenizer。 tokenizer_2 (`T5TokenizerFast`) : クラス [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) の2番目の Tokenizer。 テキストから画像を生成するための Flux Kontext パイプライン。 参考: https://blackforestlabs.ai/announcing-black-forest-labs/ #### __call__[[diffusers.FluxKontextInpaintPipeline.__call__]] ```python __call__(image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, image_reference: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, negative_prompt: str | list[str] = None, negative_prompt_2: str | list[str] | None = None, true_cfg_scale: float = 1.0, height: int | None = None, width: int | None = None, strength: float = 1.0, padding_mask_crop: int | None = None, num_inference_steps: int = 28, sigmas: list[float] | None = None, guidance_scale: float = 3.5, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, negative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, negative_ip_adapter_image_embeds: list[torch.Tensor] | None = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512, max_area: int = 1048576, _auto_resize: bool = True) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_kontext_inpaint.py#L884) **パラメータ:** image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、または `list[np.ndarray]`) : `Image`、numpy 配列、またはテンソル。インペイントする画像のバッチを表します(`mask_image` でマスクアウトする部分と、`prompt` および `image_reference` に従って再描画する部分)。numpy 配列と PyTorch テンソルの両方において、期待される値の範囲は `[0, 1]` です。テンソルまたはテンソルのリストの場合、期待される形状は `(B, C, H, W)` または `(C, H, W)` です。numpy 配列または配列のリストの場合、期待される形状は `(B, H, W, C)` または `(H, W, C)` です。`image` として画像の潜在変数(latents)も受け取れますが、潜在変数を直接渡す場合は、再度エンコードされません。 image_reference (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、または `list[np.ndarray]`) : マスク領域の開始点として使用される画像バッチを表す `Image`、NumPy 配列、またはテンソル。NumPy 配列および PyTorch テンソルの両方において、期待される値の範囲は `[0, 1]` です。テンソルまたはテンソルのリストの場合、期待される形状は `(B, C, H, W)` または `(C, H, W)` です。NumPy 配列または配列のリストの場合、期待される形状は `(B, H, W, C)` または `(H, W, C)` です。また、`image` として画像の潜在変数(latents)を受け取ることができますが、潜在変数を直接渡す場合は、再度エンコードされません。 mask_image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、または `list[np.ndarray]`) : `image` をマスクするための `Image`、numpy 配列、またはテンソル。マスク内の白いピクセルは再描画され、黒いピクセルは保持されます。`mask_image` が PIL イメージの場合、使用の前に単一チャネル(輝度)に変換されます。numpy 配列または PyTorch テンソルの場合は、3 チャネルではなく 1 つの色チャネル(L)を含む必要があります。そのため、PyTorch テンソルの想定される形状は `(B, 1, H, W)`、`(B, H, W)`、`(1, H, W)`、`(H, W)` となります。一方、numpy 配列の場合は `(B, H, W, 1)`、`(B, H, W)`、`(H, W, 1)`、または `(H, W)` となります。 prompt (`str` または `list[str]`、*省略可*) : 画像生成をガイドするためのプロンプトです。未定義の場合、代わりに `prompt_embeds` を渡す必要があります。 prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。定義されていない場合、代わりに `prompt` が使用されます。 negative_prompt (`str` または `list[str]`、*省略可能*) : 画像生成をガイドしないプロンプトです。未定義の場合、代わりに `negative_prompt_embeds` を渡す必要があります。ガイダンスを使用していない場合は無視されます(`true_cfg_scale` が `1` 以下の場合に無視されます)。 negative_prompt_2 (`str` または `list[str]`、*任意*) : 画像生成を誘導しないプロンプト、またはプロンプトのリストです。`tokenizer_2` および `text_encoder_2` に送信されます。定義されていない場合、すべてのテキストエンコーダーで `negative_prompt` が使用されます。 true_cfg_scale (`float`、*任意*、デフォルト値は 1.0) : `true_cfg_scale` > 1 かつ `negative_prompt` が指定されている場合、True classifier-free guidance(guidance scale)が有効になります。 height (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像のピクセル単位の縦幅。最適な結果を得るため、デフォルトでは 1024 に設定されています。 width (`int`、*任意*、デフォルトは self.unet.config.sample_size * self.vae_scale_factor) : 生成される画像の幅(ピクセル単位)。最適な結果を得るため、デフォルトでは 1024 に設定されています。 strength (`float`、*任意*、デフォルト値は 1.0) : 参照となる `image` を変換する度合いを示します。0 から 1 の間の値である必要があります。`image` が起点として使用され、`strength` の値が大きいほど、より多くのノイズが追加されます。デノイジングのステップ数は、最初に追加されるノイズの量に依存します。`strength` が 1 の場合、追加されるノイズは最大となり、`num_inference_steps` で指定された全イテレーション数にわたってデノイジングプロセスが実行されます。値が 1 である場合、`image` は実質的に無視されます。 padding_mask_crop (`int`, *任意*、デフォルトは `None`) : 画像とマスクに適用するクロップの余白サイズ。`None` の場合、画像および mask_image にはクロップが適用されません。`padding_mask_crop` が `None` でない場合、まず画像と同じアスペクト比を持ち、すべてのマスク領域を含む長方形の領域を特定し、その後 `padding_mask_crop` に基づいてその領域を拡大します。その後、インペインティングのために元の画像サイズにリサイズする前に、拡大された領域に基づいて画像と mask_image がクロップされます。これは、マスク領域が小さく、画像が大きく、背景などインペインティングに関連しない情報が含まれている場合に有用です。 num_inference_steps (`int`、*任意*、デフォルト値は 50) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常はより高品質な画像が得られます。 sigmas (`list[float]`, *任意*) : `set_timesteps` メソッドで `sigmas` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムシグマ。`num_inference_steps` が渡された場合のデフォルトの動作が使用されます。 guidance_scale (`float`、*任意*、デフォルト値は 3.5) : `guidance_scale` > 1 を設定することで、埋め込み型ガイダンススケールが有効になります。`guidance_scale` の値を高くすると、`prompt` により一貫性のある画像を生成するようモデルを促しますが、その代わりとして画像の品質が低下する可能性があります。ガイダンス蒸留モデルは、`guidance_scale` > 1 の場合に、真のクラスファイアフリーガイダンスを近似します。詳細については、[論文](https://huggingface.co/papers/2210.03142)を参照してください。 num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。 generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : 生成を決定論的にするための [torch ジェネレーター](https://pytorch.org/docs/stable/generated/torch.Generator.html) 1 つまたはそのリスト。 latents (`torch.FloatTensor`, *任意*) : 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数(latents)。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム`generator`を使用してサンプリングを行い、潜在変数テンソルが生成されます。 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 ip_adapter_image : (`PipelineImageInput`、*任意*): IP Adapter で使用する任意の画像入力。 ip_adapter_image_embeds (`list[torch.Tensor]`、*省略可*) : IP-Adapter用の事前生成された画像埋め込み。IP-Adapterの数と同じ長さのリストである必要があります。各要素は、`(batch_size, num_images, emb_dim)` の形状を持つテンソルである必要があります。指定されない場合、`ip_adapter_image` 入力引数から埋め込みが計算されます。 negative_ip_adapter_image : (`PipelineImageInput`、*任意*): IP Adapter で使用する任意の画像入力。 negative_ip_adapter_image_embeds (`list[torch.Tensor]`、*省略可*) : IP-Adapter用の事前生成された画像埋め込み。IP-Adapterの数と同じ長さのリストである必要があります。各要素は、`(batch_size, num_images, emb_dim)` の形状を持つテンソルである必要があります。指定されない場合、`ip_adapter_image` 入力引数から埋め込みが計算されます。 negative_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたネガティブなテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`negative_prompt` 入力引数から negative_prompt_embeds が生成されます。 negative_pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたネガティブなプールのテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`negative_prompt` 入力引数からプールの negative_prompt_embeds が生成されます。 output_type (`str`、*任意*、デフォルトは `"pil"`) : 生成画像の出力形式。[PIL](https://pillow.readthedocs.io/en/stable/)(`PIL.Image.Image`)または `np.array` から選択します。 return_dict (`bool`、*任意*、デフォルトは`True`) : 通常のタプルではなく`~pipelines.flux.FluxPipelineOutput`を返すかどうか。 joint_attention_kwargs (`dict`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。 callback_on_step_end (`Callable`、*任意*) : 推論中の各デノイジングステップの終了時に呼び出される関数です。この関数は、以下の引数とともに呼び出されます: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。 `callback_kwargs` には、`callback_on_step_end_tensor_inputs` で指定されたすべてのテンソルのリストが含まれます。 callback_on_step_end_tensor_inputs (`list`, *任意*) : `callback_on_step_end` 関数へのテンソル入力のリストです。リストで指定されたテンソルは、`callback_kwargs` 引数として渡されます。パイプラインクラスの `._callback_tensor_inputs` 属性に列挙された変数のみを、リストに含めることができます。 max_sequence_length (`int`、デフォルトは 512) : `prompt` に使用する最大シーケンス長。 max_area (`int`、デフォルトは`1024 ** 2`) : 生成される画像のピクセル単位の最大面積です。アスペクト比を維持したまま、この面積に収まるよう高さおよび幅が調整されます。 _auto_resize (`bool`, *任意*, デフォルトは `True`) : 入力画像を推奨解像度に自動的にリサイズするかどうかを指定します。 **戻り値:** `~pipelines.flux.FluxPipelineOutput` または `tuple` `return_dict` が True の場合は `~pipelines.flux.FluxPipelineOutput`、それ以外の場合は `tuple` を返します。tuple を返す場合、最初の要素は生成された画像のリストです。 生成用のパイプラインを呼び出したときに実行される関数。 例: # テキストのみでインペインティング ```py >>> import torch >>> from diffusers import FluxKontextInpaintPipeline >>> from diffusers.utils import load_image >>> prompt = "Change the yellow dinosaur to green one" >>> img_url = ( ... "https://github.com/ZenAI-Vietnam/Flux-Kontext-pipelines/blob/main/assets/dinosaur_input.jpeg?raw=true" ... ) >>> mask_url = ( ... "https://github.com/ZenAI-Vietnam/Flux-Kontext-pipelines/blob/main/assets/dinosaur_mask.png?raw=true" ... ) >>> source = load_image(img_url) >>> mask = load_image(mask_url) >>> pipe = FluxKontextInpaintPipeline.from_pretrained( ... "black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16 ... ) >>> pipe.to("cuda") >>> image = pipe(prompt=prompt, image=source, mask_image=mask, strength=1.0).images[0] >>> image.save("kontext_inpainting_normal.png") ``` # 画像条件付きインペインティング ```py >>> import torch >>> from diffusers import FluxKontextInpaintPipeline >>> from diffusers.utils import load_image >>> pipe = FluxKontextInpaintPipeline.from_pretrained( ... "black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16 ... ) >>> pipe.to("cuda") >>> prompt = "Replace this ball" >>> img_url = "https://images.pexels.com/photos/39362/the-ball-stadion-football-the-pitch-39362.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" >>> mask_url = ( ... "https://github.com/ZenAI-Vietnam/Flux-Kontext-pipelines/blob/main/assets/ball_mask.png?raw=true" ... ) >>> image_reference_url = ( ... "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTah3x6OL_ECMBaZ5ZlJJhNsyC-OSMLWAI-xw&s" ... ) >>> source = load_image(img_url) >>> mask = load_image(mask_url) >>> image_reference = load_image(image_reference_url) >>> mask = pipe.mask_processor.blur(mask, blur_factor=12) >>> image = pipe( ... prompt=prompt, image=source, mask_image=mask, image_reference=image_reference, strength=1.0 ... ).images[0] >>> image.save("kontext_inpainting_ref.png") ``` #### encode_prompt[[diffusers.FluxKontextInpaintPipeline.encode_prompt]] ```python encode_prompt(prompt: str | list[str], prompt_2: str | list[str] | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, max_sequence_length: int = 512, lora_scale: float | None = None) ``` [ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/flux/pipeline_flux_kontext_inpaint.py#L393) **パラメータ:** prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。未定義の場合、すべての text-encoder で `prompt` が使用されます。 device : (`torch.device`): torch デバイス num_images_per_prompt (`int`) : プロンプトごとに生成すべき画像の数 prompt_embeds (`torch.FloatTensor`、*任意*) : 事前に生成されたテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを簡単に実行できます。指定されない場合、`prompt` 入力引数からテキスト埋め込みが生成されます。 pooled_prompt_embeds (`torch.FloatTensor`, *任意*) : 事前に生成されたプーリング済みテキスト埋め込み。テキスト入力の調整、*例えば*プロンプトの重み付けなどを容易に行うために使用できます。指定されない場合、`prompt` 入力引数からプーリング済みテキスト埋め込みが生成されます。 lora_scale (`float`、*任意*) : LoRAレイヤーが読み込まれている場合、テキストエンコーダーのすべてのLoRAレイヤーに適用されるLoRAスケールです。
# Flux
Flux は、拡散トランスフォーマーに基づくテキストから画像を生成するモデルのシリーズです。Flux の詳細については、Flux の開発元である Black Forest Labs による元の[ブログ記事](https://blackforestlabs.ai/announcing-black-forest-labs/)をご覧ください。
Fluxの元のモデルチェックポイントは[こちら](https://huggingface.co/black-forest-labs)で確認できます。元の推論コードは[こちら](https://github.com/black-forest-labs/flux)で確認できます。
> [!TIP]
> Flux は、コンシューマー向けハードウェアで実行する場合、コストがかなり高くなる可能性があります。ただし、一連の最適化を行うことで、より高速かつメモリ効率の良い実行が可能です。詳細については、[このセクション](https://huggingface.co/blog/sd3#memory-optimizations-for-sd3)を参照してください。また、Flux は量子化によってメモリ効率を向上させることができますが、推論レイテンシとのトレードオフが発生します。詳細については、[このブログ記事](https://huggingface.co/blog/quanto-diffusers)を参照してください。包括的なリソースのリストについては、[この gist](https://gist.github.com/sayakpaul/b664605caf0aa3bf8585ab109dd5ac9c)をご覧ください。
>
> [Caching](../../optimization/cache) は、中間出力を保存して再利用することで、推論の高速化にも貢献します。
Fluxには、以下のバリエーションがあります:
| モデルタイプ | モデルID |
|:----------:|:--------:|
| タイムステップ蒸留 | [`black-forest-labs/FLUX.1-schnell`](https://huggingface.co/black-forest-labs/FLUX.1-schnell) |
| ガイダンス蒸留 | [`black-forest-labs/FLUX.1-dev`](https://huggingface.co/black-forest-labs/FLUX.1-dev) |
| Fill Inpainting/Outpainting(ガイダンス蒸留) | [`black-forest-labs/FLUX.1-Fill-dev`](https://huggingface.co/black-forest-labs/FLUX.1-Fill-dev) |
| Canny Control (Guidance-distilled) | [`black-forest-labs/FLUX.1-Canny-dev`](https://huggingface.co/black-forest-labs/FLUX.1-Canny-dev) |
| 深度制御(ガイダンス蒸留) | [`black-forest-labs/FLUX.1-Depth-dev`](https://huggingface.co/black-forest-labs/FLUX.1-Depth-dev) |
| Canny Control (LoRA) | [`black-forest-labs/FLUX.1-Canny-dev-lora`](https://huggingface.co/black-forest-labs/FLUX.1-Canny-dev-lora) |
| 深度制御 (LoRA) | [`black-forest-labs/FLUX.1-Depth-dev-lora`](https://huggingface.co/black-forest-labs/FLUX.1-Depth-dev-lora) |
| Redux (Adapter) | [`black-forest-labs/FLUX.1-Redux-dev`](https://huggingface.co/black-forest-labs/FLUX.1-Redux-dev) |
| コンテキスト | [`black-forest-labs/FLUX.1-kontext`](https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev) |
すべてのチェックポイントには異なる用途があり、以下に詳細を説明します。
### タイムステップ蒸留
* `max_sequence_length`は256を超えることはできません。
* `guidance_scale` は 0 である必要があります。
* これはタイムステップ蒸留モデルであるため、サンプリングステップ数を減らすことで恩恵を受けます。
```python
import torch
from diffusers import FluxPipeline
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", dtype=torch.bfloat16)
pipe.enable_model_cpu_offload()
prompt = "A cat holding a sign that says hello world"
out = pipe(
prompt=prompt,
guidance_scale=0.,
height=768,
width=1360,
num_inference_steps=4,
max_sequence_length=256,
).images[0]
out.save("image.png")
```
### ガイダンス蒸留
* guidance-distilled バリアントは、高品質な生成に約50回のサンプリングステップを必要とします。
* `max_sequence_length`に関する制限はありません。
```python
import torch
from diffusers import FluxPipeline
pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", dtype=torch.bfloat16)
pipe.enable_model_cpu_offload()
prompt = "a tiny astronaut hatching from an egg on the moon"
out = pipe(
prompt=prompt,
guidance_scale=3.5,
height=768,
width=1360,
num_inference_steps=50,
).images[0]
out.save("image.png")
```
### インペインティング/アウトペインティングの埋め込み
* Flux Fill パイプラインは、通常のインペインティングパイプラインとは異なり、`strength` を入力として必要としません。
* インペインティングとアウトペインティングの両方をサポートしています。
```python
import torch
from diffusers import FluxFillPipeline
from diffusers.utils import load_image
image = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/cup.png")
mask = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/cup_mask.png")
repo_id = "black-forest-labs/FLUX.1-Fill-dev"
pipe = FluxFillPipeline.from_pretrained(repo_id, dtype=torch.bfloat16).to("cuda") # or "mps", "xpu", "cpu"
image = pipe(
prompt="a white paper cup",
image=image,
mask_image=mask,
height=1632,
width=1232,

Xet Storage Details

Size:
192 kB
·
Xet hash:
a164b8eed7d22da8ee14e678703cd864093b06ec2f7cc87939655d618a1573a0

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.