# Ideogram 4

Ideogram 4 は、マルチモーダルなテキストエンコーダーと非対称な classifier-free guidance スキームを用いる flow-matching 型のテキストから画像生成を行うモデルです。専用の `unconditional_transformer` がテキスト特徴をゼロにしたネガティブブランチを生成し、メインの `transformer` がパックされたテキストと画像のシーケンス全体を消費します。

パイプラインのデフォルト設定は最高品質を推奨する設定であり、単純な`pipe(prompt)`呼び出しでも、そのまま最高品質の結果が得られます。具体的には、logit-normalスケジュール（`mu=0.0`、`std=1.5`）で48ステップのflow-matchingを実行し、主要ステップではclassifier-free guidanceを7.0に固定し、最後の3ステップの「仕上げ」では3.0に下げます。

推論時の主要な設定項目は、パイプライン呼び出しを通じて公開されています:

- `num_inference_steps`、`mu`、`std` は、解像度認識型 logit-normal flow-matching スケジュールを制御します。
- `guidance_scale`（またはステップごとの完全な`guidance_schedule`）は、条件付きと条件なしの速度をブレンドします。

## テキストから画像へ

```python
import torch
from diffusers import Ideogram4Pipeline

pipe = Ideogram4Pipeline.from_pretrained("ideogram-ai/ideogram-v4", dtype=torch.bfloat16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

prompt = "A photo of a cat holding a sign that says hello world"
# The defaults are the recommended settings for best quality.
image = pipe(prompt, height=1024, width=1024, generator=torch.Generator("cuda").manual_seed(0)).images[0]
image.save("ideogram4.png")
```

## プロンプトのアップサンプリング

Ideogram 4 は、自由形式のプロンプトではなく構造化された JSON キャプションで学習されているため、生成前に短いプロンプトをそのネイティブなスキーマに展開するのが最適です。キャプションを生成する方法は2つあります。

### Remote (Ideogram API)

最適な結果を得るには、Ideogram のホスティングされている magic-prompt API を使用してプロンプトを拡張し、返されたキャプションをそのままパイプラインに渡します（キーは [developer.ideogram.ai](https://developer.ideogram.ai/) で取得できます）：

```python
import json
import requests
import torch
from diffusers import Ideogram4Pipeline

pipe = Ideogram4Pipeline.from_pretrained("ideogram-ai/ideogram-4-nf4", dtype=torch.bfloat16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

# Expand the prompt into a structured JSON caption with Ideogram's hosted magic-prompt API.
response = requests.post(
    "https://api.ideogram.ai/v1/ideogram-v4/magic-prompt",
    headers={"Api-Key": "your_ideogram_api_key"},
    json={"text_prompt": "A photo of a cat holding a sign that says hello world", "aspect_ratio": "1x1"},
).json()
caption = json.dumps(response["json_prompt"])

# The caption is already upsampled, so pass it directly (no prompt_upsampling).
image = pipe(caption, height=1024, width=1024, generator=torch.Generator("cuda").manual_seed(0)).images[0]
image.save("ideogram4_upsampled.png")
```

### Local （オンデバイス）

完全にローカルなパイプラインを実現するには、小型の [Ideogram4PromptEnhancerHead](/docs/diffusers/main/ja/api/pipelines/ideogram4#diffusers.Ideogram4PromptEnhancerHead)（Qwen3-VL LM head）を任意の `prompt_enhancer_head` コンポーネントとして読み込み、`prompt_upsampling=True` を渡します。この head は共有の `text_encoder` に graft されるため、2 つ目の text encoder は読み込まれません。スキーマ制約付きキャプションには `outlines` のインストールが必要です（nf4 チェックポイントには `bitsandbytes` も必要です）：

```python
import torch
from diffusers import Ideogram4Pipeline, Ideogram4PromptEnhancerHead

prompt_enhancer_head = Ideogram4PromptEnhancerHead.from_pretrained(
    "diffusers/qwen3-vl-8b-instruct-lm-head", dtype=torch.bfloat16
)
pipe = Ideogram4Pipeline.from_pretrained(
    "ideogram-ai/ideogram-4-nf4", prompt_enhancer_head=prompt_enhancer_head, dtype=torch.bfloat16
)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

prompt = "A photo of a cat holding a sign that says hello world"
image = pipe(
    prompt,
    height=1024,
    width=1024,
    prompt_upsampling=True,
    generator=torch.Generator("cuda").manual_seed(0),
).images[0]
image.save("ideogram4_upsampled.png")
```

## Ideogram4Pipeline[[diffusers.Ideogram4Pipeline]]

#### diffusers.Ideogram4Pipeline[[diffusers.Ideogram4Pipeline]]

```python
diffusers.Ideogram4Pipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKLFlux2, text_encoder: PreTrainedModel, tokenizer: AutoTokenizer, transformer: Ideogram4Transformer2DModel, unconditional_transformer: Ideogram4Transformer2DModel, prompt_enhancer_head: diffusers.pipelines.ideogram4.prompt_enhancer.Ideogram4PromptEnhancerHead | None = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ideogram4/pipeline_ideogram4.py#L141)

**パラメータ:**

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : フローマッチングスケジューラ。パイプラインは、デフォルトのシグマスケジュールを、解像度に応じたロジットノーマルスケジュールで上書きします。

vae (`AutoencoderKLFlux2`) : 潜在変数から画像へデコードするために使用される変分オートエンコーダーです。

text_encoder (`PreTrainedModel`) : マルチモーダルテキストエンコーダーです。このパイプラインは、固定された中間デコーダー層のセットから隠れ状態を消費します（`QWEN3_VL_ACTIVATION_LAYERS`を参照）。

tokenizer (`AutoTokenizer`) : `text_encoder` とペアになる Tokenizer。

transformer ([Ideogram4Transformer2DModel](/docs/diffusers/main/ja/api/models/ideogram4_transformer2d#diffusers.Ideogram4Transformer2DModel)) : 条件付きフローマッチングトランスフォーマー。

unconditional_transformer ([Ideogram4Transformer2DModel](/docs/diffusers/main/ja/api/models/ideogram4_transformer2d#diffusers.Ideogram4Transformer2DModel)) : 無条件（非対称 CFG）フローマッチング・トランスフォーマー。

Ideogram4用のテキストから画像へのパイプライン。

Ideogram4は、非対称なclassifier-free guidanceで訓練されたflow-matchingモデルです。`transformer`がテキスト条件付きの特徴量と画像の潜在変数を同時に処理する一方、別個の`unconditional_transformer`はゼロに設定されたテキスト特徴量でノイズ除去を行います。2つの速度予測は、各ステップで線形にブレンドされます。

#### __call__[[diffusers.Ideogram4Pipeline.__call__]]

```python
__call__(prompt: str | list[str] | None = None, height: int = 2048, width: int = 2048, num_inference_steps: int = 48, guidance_scale: float | None = None, guidance_schedule: typing.Union[list[float], torch.Tensor, NoneType] = (7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 3.0, 3.0, 3.0), mu: float = 0.0, std: float = 1.5, prompt_upsampling: bool = False, prompt_upsampling_temperature: float = 1.0, max_sequence_length: int = 2048, num_images_per_prompt: int = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, output_type: str = 'pil', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[ForwardRef('Ideogram4Pipeline'), int, int, dict[str, typing.Any]], dict[str, typing.Any]]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'])
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ideogram4/pipeline_ideogram4.py#L481)

**パラメータ:**

prompt (`str` または `list[str]`) : 画像生成をガイドするためのプロンプト。

height (`int`、*任意*、デフォルトは 2048) : 出力画像の高さ（ピクセル単位）。`vae_scale_factor * patch_size` の倍数である必要があります。

width (`int`、*任意*、デフォルトは 2048) : 出力画像の幅（ピクセル単位）。`vae_scale_factor * patch_size` の倍数である必要があります。

num_inference_steps (`int`、*optional*、デフォルトは 48) : flow-matching のステップ数です。デフォルト値は、最高品質を得るために推奨される設定です。

guidance_scale (`float`, *任意*) : 各ステップで適用される定数の classifier-free guidance スケール。条件付きと条件なしの速度予測は `v = guidance_scale * v_pos + (1 - guidance_scale) * v_neg` としてブレンドされます。`guidance_schedule` とは排他です（両方を設定すると例外が発生します）。デフォルトは `None` です。

guidance_schedule (`list[float]` または `torch.Tensor`、*任意*) : ステップごとのガイダンススケジュール。長さは `num_inference_steps` でなければなりません。最初の要素は最初のステップ（最大のノイズレベル）に対応します。`guidance_scale` とは排他であり、どちらか一方のみを設定する必要があります。デフォルトでは推奨されるスケジュール（メインステップで 7.0、最後の 3 ステップの「仕上げ」で 3.0 に低下）が使用されます。一定のスケールを使用する場合は、`guidance_scale` を渡し、`guidance_schedule=None` を指定してください。

mu (`float`、*任意*、デフォルト値は 0.0) : logit-normal flow-matching スケジュールのベース平均値です。スケジュールの平均値は、512x512 に対する解像度比の対数の半分だけシフトされます。

std (`float`、*任意*、デフォルトは 1.5) : logit-normal flow-matching スケジュールの標準偏差。

prompt_upsampling (`bool`、*任意*、デフォルトは`False`) : `True`の場合、エンコードの前に`prompt`を[upsample_prompt()](/docs/diffusers/main/ja/api/pipelines/ideogram4#diffusers.Ideogram4Pipeline.upsample_prompt)を通じてIdeogram4のネイティブな構造化JSONキャプションに書き換えます。オプションの`prompt_enhancer_head`コンポーネントが必要です。スキーマ制約付きのキャプションには`outlines`をインストールしてください。`generator`は再利用され、アップサンプリングの再現性を確保します。

prompt_upsampling_temperature (`float`、*任意*、デフォルト値は 1.0) : `prompt_upsampling=True` の場合のプロンプトアップサンプリングにおけるサンプリング温度。

max_sequence_length (`int`、*任意*、デフォルトは 2048) : プロンプトごとのテキストトークンの最大数。

num_images_per_prompt (`int`、*任意*、デフォルトは 1) : プロンプトごとに生成する画像の数。

generator (`torch.Generator` または `list[torch.Generator]`、*任意*) : サンプリングを決定論的に行うために使用するジェネレーター。

latents (`torch.Tensor`, *任意*) : 形状が `(batch_size, num_image_tokens, latent_dim)` の事前生成されたノイズ。

output_type (`str`、*任意*、デフォルトは`"pil"`) : `"pil"`、`"np"`、`"pt"`、`"latent"`のいずれか。

return_dict (`bool`, *任意*, デフォルトは `True`) : [Ideogram4PipelineOutput](/docs/diffusers/main/ja/api/pipelines/ideogram4#diffusers.pipelines.ideogram4.Ideogram4PipelineOutput) を返すかどうかを指定します。

attention_kwargs (`dict`, *任意*) : 各 transformer の attention processor に渡される kwargs 辞書です。PEFT バックエンドが有効な場合、`"scale"` エントリによって読み込まれた LoRA 重みがスケーリングされます（例: `{"scale": 0.7}`）。

callback_on_step_end (`Callable`、*任意*) : すべてのデノイジングステップの終了時に呼び出されるコールバック。

callback_on_step_end_tensor_inputs (`list[str]`、*任意*) : `callback_kwargs` 経由でコールバックに公開するテンソルの名前。

**戻り値:**

[Ideogram4PipelineOutput](/docs/diffusers/main/ja/api/pipelines/ideogram4#diffusers.pipelines.ideogram4.Ideogram4PipelineOutput) または `tuple`。

テキストから画像を生成します。

例:
```py
>>> import torch
>>> from diffusers import Ideogram4Pipeline

>>> pipe = Ideogram4Pipeline.from_pretrained("ideogram-ai/ideogram-v4", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")

>>> prompt = "A photo of a cat holding a sign that says hello world"
>>> # The defaults are the recommended settings for best quality.
>>> image = pipe(prompt, height=2048, width=2048, generator=torch.Generator("cuda").manual_seed(0)).images[0]
>>> image.save("ideogram4.png")
```

#### encode_prompt[[diffusers.Ideogram4Pipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], grid_h: int, grid_w: int, max_sequence_length: int, device: device)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ideogram4/pipeline_ideogram4.py#L335)

パックされたテキスト+画像シーケンスの条件付けを準備します（プロンプトごとに1エントリ）。

フラットなタプル`(prompt_embeds, position_ids, segment_ids, indicator)`を返します。無条件ブランチにはテキストが含まれないため、パイプラインはネガティブプロンプトをエンコードするのではなく、（ゼロ初期化された）入力を直接構築します。

#### upsample_prompt[[diffusers.Ideogram4Pipeline.upsample_prompt]]

```python
upsample_prompt(prompt: str | list[str], height: int = 2048, width: int = 2048, temperature: float = 1.0, max_new_tokens: int = 1024, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, device: typing.Optional[torch.device] = None)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ideogram4/pipeline_ideogram4.py#L204)

各プロンプトを、Ideogram4のネイティブな構造化JSONキャプションに書き換えます。

任意の `prompt_enhancer_head` コンポーネントが必要です。これは共有の `text_encoder` 本体に接合され、生成型にします。`outlines` がインストールされている場合はスキーマ制約付きで生成され、そうでない場合は制約なしで実行されます。サンプリングを再現可能にするには、`generator`（`__call__` が受け入れるものと同じ）を渡してください。

## Ideogram4PromptEnhancerHead[[diffusers.Ideogram4PromptEnhancerHead]]

#### diffusers.Ideogram4PromptEnhancerHead[[diffusers.Ideogram4PromptEnhancerHead]]

```python
diffusers.Ideogram4PromptEnhancerHead(hidden_size: int = 4096, vocab_size: int = 151936)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ideogram4/prompt_enhancer.py#L42)

プロンプトのアップサンプリングのために、ヘッドレスのQwen3-VL `text_encoder`を生成型にするLMヘッド。

任意のパイプラインコンポーネント（`prompt_enhancer_head`）：その重みは、パイプライン内でのダウンロードではなく、通常の`from_pretrained`（独自の小さなリポジトリ、またはモデルリポジトリにバンドルされたもの）によって読み込まれます。アップサンプリング時に、パイプラインはこれを共有の`text_encoder`本体と組み合わせて、生成モデルを形成します。

## Ideogram4PipelineOutput[[diffusers.pipelines.ideogram4.Ideogram4PipelineOutput]]

#### diffusers.pipelines.ideogram4.Ideogram4PipelineOutput[[diffusers.pipelines.ideogram4.Ideogram4PipelineOutput]]

```python
diffusers.pipelines.ideogram4.Ideogram4PipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray)
```

[ソース](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/ideogram4/pipeline_output.py#L24)

**パラメータ:**

images (`list[PIL.Image.Image]` または `np.ndarray`) : 長さ `batch_size` のノイズ除去済み PIL 画像のリスト、または形状 `(batch_size, height, width, num_channels)` の numpy 配列。

Ideogram 4 パイプライン用の出力クラスです。

