# P-H3-Image

P-H3-Image adalah model gambar dari Pruna AI yang berbasis pada [MiniMax-H3](./minimax_h3), untuk generasi gambar dari teks dan pengeditan gambar berbasis instruksi. Anda dapat menemukan checkpoint di [PrunaAI/P-H3-Image](https://huggingface.co/PrunaAI/P-H3-Image).

```py
import torch
from diffusers import ComponentsManager, ModularPipeline

manager = ComponentsManager()
manager.enable_auto_cpu_offload(device="cuda")  # or "mps", "xpu"

pipe = ModularPipeline.from_pretrained("PrunaAI/P-H3-Image", components_manager=manager)
pipe.load_components(dtype=torch.bfloat16)

prompt = (
    "A German Expressionist oil painting of a Berlin street at night in the manner of Ernst Ludwig Kirchner, "
    "with gaunt figures hurrying past a glowing gas lamp."
)
image = pipe(prompt=prompt, height=3360, width=2496, generator=torch.Generator().manual_seed(3), output="images")[0]
edited = pipe(prompt="let it snow on the street", image=image, output="images")[0]
```

Setiap permintaan melewati [prompt upsampler](#prompt-upsampling) terlebih dahulu. Dengan setiap komponen di akselerator, pipeline membutuhkan sekitar 101 GB dalam bfloat16 pada 8 megapiksel, sehingga contoh menggunakan auto offloading: [ComponentsManager](/docs/diffusers/main/id/api/modular_diffusers/pipeline_components#diffusers.ComponentsManager) memindahkan setiap komponen ke akselerator ketika sebuah blok membutuhkannya, dan pipeline berjalan di GPU 80 GB.

## Komponen

| Komponen | Kelas |
|---|---|
| `transformer` | [MiniMaxH3Transformer3DModel](/docs/diffusers/main/id/api/models/minimax_h3_transformer3d#diffusers.MiniMaxH3Transformer3DModel) |
| `text_encoder` | `Qwen3VLForConditionalGeneration` (Qwen3-VL-4B) |
| `text_connector` | [PH3ImageTextConnector](/docs/diffusers/main/id/api/pipelines/p_h3_image#diffusers.PH3ImageTextConnector) |
| `vae` | [AutoencoderKLPH3Image](/docs/diffusers/main/id/api/models/autoencoderkl_p_h3_image#diffusers.AutoencoderKLPH3Image) |
| `tokenizer`, `processor` | Tokenizer dari text encoder, dan `Qwen3VLProcessor` dengan image processor MiniMax-H3 |
| `scheduler`, `audio_scheduler` | [MiniMaxH3Scheduler](/docs/diffusers/main/id/api/schedulers/minimax_h3#diffusers.MiniMaxH3Scheduler) |
| `prompt_upsampler`, `prompt_upsampler_processor` | `Qwen3_5ForConditionalGeneration` (berdasarkan Qwen3.5-9B) dan prosesor-nya |

## Alur Kerja

Alur kerja dipilih pada input `image`:

- **`text2image`** menghasilkan gambar dari `prompt`. Nilai default untuk `height` dan `width` adalah 2912, dan dibulatkan ke kelipatan 32. Model ini bekerja paling baik pada resolusi 8 megapiksel, misalnya 2912x2912, 3872x2176, atau 2176x3872.
- **`image_conditioned`** mengedit `image` berdasarkan instruksi dalam `prompt`, dan bekerja paling baik pada resolusi 4 atau 8 megapiksel. Gambar dikodekan pada sekitar `vision_pixels` (satu megapiksel) untuk text encoder dan pada ukuran aslinya untuk VAE, dengan skala diperbesar hingga `reference_min_pixels` (satu megapiksel) atau diperkecil hingga `reference_max_pixels` (delapan megapiksel) jika berada di luar rentang tersebut. Tanpa `height` dan `width`, hasil edit dihasilkan pada ukuran gambar pertama, yang akan diperbesar hingga `canvas_min_pixels` (empat megapiksel) jika ukurannya lebih kecil. Nilai `height` dan `width` yang diberikan, dibulatkan ke kelipatan 32, mengubah kanvas tetapi tidak mengubah gambar. `image` juga dapat berupa daftar hingga 8 gambar: gambar pertama yang diedit dan sisanya sebagai referensi, seperti `<Picture 2>`, `<Picture 3>`, dan seterusnya.

## Upsampling prompt

P-H3-Image dirancang untuk merender prompt lengkap, bukan permintaan singkat, sehingga pipeline menjalankan prompt upsampler terlebih dahulu pada setiap permintaan. Model ini memikirkan permintaan tersebut lalu menulis prompt: prompt teks-ke-gambar yang detail untuk rasio aspek `height` dan `width`, atau, saat mengedit, ringkasan tentang apa yang harus dipertahankan dan apa yang harus diubah pada gambar. Prompt yang ditulisnya dikembalikan sebagai output `prompt`.

```py
out = pipe(prompt=prompt, height=3360, width=2496, output=["images", "prompt"])
print(out["prompt"])
```

`max_new_tokens` membatasi total token untuk penalaran dan prompt, yaitu 1024 token untuk teks-ke-gambar dan 1536 untuk edit secara default. Jika upsampler tidak mengembalikan prompt yang dapat digunakan, pipeline akan melempar error alih-alih merendernya.

Untuk merender `prompt` sesuai yang diberikan, ambil langkah dari blok. Blok yang diambil juga berjalan secara mandiri, misalnya untuk menampilkan prompt kepada pengguna sebelum merendernya:

```py
manager = ComponentsManager()
manager.enable_auto_cpu_offload(device="cuda")

blocks = ModularPipeline.from_pretrained("PrunaAI/P-H3-Image").blocks
upsampler_block = blocks.sub_blocks.pop("prompt_upsampler")

upsampler = upsampler_block.init_pipeline("PrunaAI/P-H3-Image", components_manager=manager)
upsampler.load_components(dtype=torch.bfloat16)
upsampled = upsampler(prompt=prompt, height=3360, width=2496, output="prompt")

pipe = blocks.init_pipeline("PrunaAI/P-H3-Image", components_manager=manager)
pipe.load_components(dtype=torch.bfloat16)
image = pipe(prompt=upsampled, height=3360, width=2496, output="images")[0]
```

Tanpa langkah tersebut, prompt edit dalam bentuk apa pun yang ditulis oleh upsampler, ringkasan enam bagian atau paragraf yang dimulai dengan `Edit <Picture 1>.`, akan dienkod sesuai dengan yang tertulis; instruksi lain akan diberi awalan tersebut.

## Sampling

- 8 langkah dijalankan di atas `sample_sigmas` checkpoint. Luluskan `sigmas` untuk menggunakan grid lain.
- Model ini telah melalui distilasi panduan, sehingga tidak ada `negative_prompt` atau `guidance_scale`.

## PH3ImageModularPipeline[[diffusers.PH3ImageModularPipeline]]

#### diffusers.PH3ImageModularPipeline[[diffusers.PH3ImageModularPipeline]]

```python
diffusers.PH3ImageModularPipeline(blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = None, pretrained_model_name_or_path: str | os.PathLike | None = None, components_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = None, collection: str | None = None, workflow: str | None = None, modular_config_dict: dict[str, typing.Any] | None = None, config_dict: dict[str, typing.Any] | None = None, **kwargs)
```

[Sumber](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/p_h3_image/modular_pipeline.py#L22)

A ModularPipeline untuk P-H3-Image, sebuah model gambar berbasis MiniMax-H3, untuk teks-ke-gambar (`text2image`) dan pengeditan berbasis instruksi (`image_conditioned`).

Gambar tersebut adalah satu frame laten, yang dinoise dalam satu urutan terpadu dengan dua laten audio yang dibuang.

```py
import torch
from diffusers import ComponentsManager, ModularPipeline

manager = ComponentsManager()
manager.enable_auto_cpu_offload(device="cuda")

pipe = ModularPipeline.from_pretrained("PrunaAI/P-H3-Image", components_manager=manager)
pipe.load_components(dtype=torch.bfloat16)
prompt = (
    "A German Expressionist oil painting of a Berlin street at night in the manner of Ernst Ludwig Kirchner, "
    "with gaunt figures hurrying past a glowing gas lamp."
)
image = pipe(prompt=prompt, height=3360, width=2496, output="images")[0]
```

## PH3ImageBlocks[[diffusers.PH3ImageBlocks]]

#### diffusers.PH3ImageBlocks[[diffusers.PH3ImageBlocks]]

```python
diffusers.PH3ImageBlocks()
```

[Sumber](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/p_h3_image/modular_blocks_p_h3_image.py#L376)

Blok pipeline modular untuk P-H3-Image: `text2image`, dan pengeditan berbasis instruksi (`image_conditioned`) ketika `image` diteruskan. `prompt` melewati prompt upsampler terlebih dahulu; hapus langkah `prompt_upsampler` untuk merendernya sesuai yang diberikan.

Alur kerja yang didukung:
- `text2image`: membutuhkan `prompt`
- `image_conditioned`: membutuhkan `prompt`, `image`

Komponen: image_processor (`VaeImageProcessor`) prompt_upsampler (`Qwen3_5ForConditionalGeneration`): Prompt upsampler. prompt_upsampler_processor (`AutoProcessor`): Prosesornya. text_encoder (`Qwen3VLForConditionalGeneration`) text_connector (`PH3ImageTextConnector`) tokenizer (`Qwen2Tokenizer`) processor (`Qwen3VLProcessor`) vae (`AutoencoderKLPH3Image`) scheduler (`MiniMaxH3Scheduler`) audio_scheduler (`MiniMaxH3Scheduler`) transformer (`MiniMaxH3Transformer3DModel`)

Konfigurasi: reference_min_pixels (default: 1048576) reference_max_pixels (default: 8388608) canvas_min_pixels (default:
4194304) vision_pixels (default: 1000000) sample_sigmas (default: [1.0, 0.984753, 0.967905, 0.951688,
0.925372, 0.881923, 0.810083, 0.528718, 0.0]): Grid sampling checkpoint, digunakan ketika `sigmas` tidak diteruskan.

Inputs: image (`Image | list`, *optional*): The image to edit, or a list of at most 8 images: the first is edited, the others are references. height (`int`, *optional*): Height of the generated image in pixels, rounded to a multiple of 32. Defaults to 2912 for `text2image`, which works best at 8 megapixels. An edit defaults to the first image's size, at least `canvas_min_pixels`, and works best at 4 or 8 megapixels. width (`int`, *optional*): Width of the generated image in pixels, rounded to a multiple of 32. Defaults to 2912 for `text2image`, which works best at 8 megapixels. An edit defaults to the first image's size, at least `canvas_min_pixels`, and works best at 4 or 8 megapixels. prompt (`str`): The prompt, or the edit instruction when `image` is passed. A single string. max_new_tokens (`int`, *optional*, defaults to 1536 or 1024, depending on the workflow): The most tokens the upsampler may generate, its reasoning included. vision_images (`list`, *optional*): The images of the edit resized for the text encoder, the image to edit first. reference_images (`list`, *optional*): The images of the edit resized for the VAE, the image to edit first. condition_latents (`list`, *optional*): The conditioning latents of the images of the edit. Their shapes give the geometry of the reference blocks. generator (`Generator`, *optional*): The generator of the request. The conditioning noise is drawn from it first, one draw per condition, before the noise of the generated rows. latents (`Tensor`): Pre-generated image noise of shape `(1, latent_channels, 1, latent_height, latent_width)`, used instead of the draw. sigmas (`list`, *optional*): A custom sampling grid, strictly decreasing and ending at 0. Defaults to the checkpoint's `sample_sigmas`. **denoiser_input_fields (`None`, *optional*): The structural description of the packed sequence the transformer reads by name: `token_tags`, `position_ids` and the three row-index tensors. attention_kwargs (`dict`, *optional*): Additional kwargs for attention processors. output_type (`str`, *optional*, defaults to pil): Output format: 'pil', 'np', 'pt'.

Output: gambar (`list`): Gambar yang dihasilkan.

## PH3ImageTextConnector[[diffusers.PH3ImageTextConnector]]

#### diffusers.PH3ImageTextConnector[[diffusers.PH3ImageTextConnector]]

```python
diffusers.PH3ImageTextConnector(hidden_state_indices: tuple[int, ...] = (13, 19, 25, 31, 36), text_hidden_size: int = 2560, out_channels: int = 5120)
```

[Sumber](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/condition_embedders/condition_embedder_p_h3_image.py#L22)

**Parameter:**

hidden_state_indices (`tuple[int, ...]`, defaultnya `(13, 19, 25, 31, 36)`) : Entri mana dari `hidden_states` text encoder yang dibaca, sesuai penomoran `output_hidden_states` (`0` adalah output embedding, `i` adalah output dari decoder layer `i`, dan yang terakhir adalah hidden state final yang telah dinormalisasi).

text_hidden_size (`int`, defaultnya `2560`) : Ukuran tersembunyi dari pengkode teks.

out_channels (`int`, defaultnya `5120`) : Jumlah channel dari transformer MiniMax-H3 yang dibaca untuk conditioning.

Memetakan hidden states dari encoder teks Qwen3-VL milik P-H3-Image ke kondisi teks yang dibaca oleh transformer-nya.

Hidden states yang terdaftar dalam `hidden_state_indices` digabungkan, distandardisasi, diproyeksikan secara linear, dan didestandardisasi. Token pertama adalah attention sink dengan kondisioning yang sama untuk setiap prompt, sehingga diganti dengan `sink_embedding`.

#### forward[[diffusers.PH3ImageTextConnector.forward]]

```python
forward(hidden_states: tuple[torch.Tensor, ...])
```

[Sumber](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/condition_embedders/condition_embedder_p_h3_image.py#L61)

**Parameter:**

hidden_states (`tuple[torch.Tensor, ...]`) : State tersembunyi dari pengkode teks, sebagaimana dikembalikan oleh `output_hidden_states=True`: satu tensor dengan bentuk `(batch_size, num_tokens, text_hidden_size)` per entri.

**Mengembalikan:** `torch.Tensor`

kondisi, dengan bentuk `(batch_size, num_tokens, out_channels)`, dalam dtype dari parameter konektor.

