From 05d1de8395e4ec792683b94999d978411a35f406 Mon Sep 17 00:00:00 2001 From: JingyaHuang Date: Wed, 11 Nov 2026 23:45:23 +0000 Subject: [PATCH 1/5] poc: prepare FLUX.2 Klein for Neuron serving through Diffusers, vllm-omni --- docs/source/en/optimization/neuron.md | 31 +++++++++++++ .../pipelines/flux2/pipeline_flux2_klein.py | 46 +++++++++++-------- ...test_pipeline_flux2_klein_prompt_embeds.py | 44 ++++++++++++++++++ 3 files changed, 101 insertions(+), 20 deletions(-) create mode 100644 tests/pipelines/flux2/test_pipeline_flux2_klein_prompt_embeds.py diff --git a/docs/source/en/optimization/neuron.md b/docs/source/en/optimization/neuron.md index fb0f9ac25077..88680a610b66 100644 --- a/docs/source/en/optimization/neuron.md +++ b/docs/source/en/optimization/neuron.md @@ -115,3 +115,34 @@ Launch one process per NeuronCore. Set `--nproc_per_node` to the number of Neuro ```bash torchrun --nproc_per_node=8 tensor_parallel_neuron.py ``` + + +## Native FLUX.2 Klein serving proof of concept + +The `examples/inference/flux2_klein_neuron.py` example provides a standalone +single-device BF16 baseline for `black-forest-labs/FLUX.2-klein-4B` using the native +`torch_neuronx` device backend. This is separate from the Optimum Neuron export +workflow above. It uses CPU random generators and optionally compiles the +transformer while leaving the text encoder and VAE eager. + +```bash +NEURON_RT_VISIBLE_CORES=0 \ +TORCH_NEURONX_NEFF_CACHE_DIR=/tmp/flux2-klein-neff-cache \ +python examples/inference/flux2_klein_neuron.py \ + --compile-transformer --height 256 --width 256 --runs 2 +``` + +Use a free Neuron core and a compatible native Neuron SDK. The initial resolution +is deliberately small; larger resolutions and tensor parallelism are outside +this proof of concept. The first request includes compilation; subsequent +requests recreate the same CPU generator to help compare outputs. + +For serving, the experimental `add-diffusers-support` branch of +`vllm-omni-neuron` wraps the same pipeline with vLLM-Omni's Diffusers adapter. +Diffusers owns model execution; the plugin owns worker initialization, placement, +and compilation policy. The pinned serving runtime compiles the text encoder, +transformer, VAE decoder, scheduler step, and tensor preparation regions; this +compilation policy differs from the standalone baseline. See that branch's `examples/diffusers/README.md` for +offline and HTTP smoke tests. The real 4B checkpoint has completed offline Omni +generation on Trainium2 at 256×256, four steps, BF16, and TP=1. HTTP serving and +larger shapes remain unvalidated; this is not production support. diff --git a/src/diffusers/pipelines/flux2/pipeline_flux2_klein.py b/src/diffusers/pipelines/flux2/pipeline_flux2_klein.py index 50fd51e283f6..c86f80857918 100644 --- a/src/diffusers/pipelines/flux2/pipeline_flux2_klein.py +++ b/src/diffusers/pipelines/flux2/pipeline_flux2_klein.py @@ -253,14 +253,10 @@ def _get_qwen3_prompt_embeds( use_cache=False, ) - # Only use outputs from intermediate layers and stack them - out = torch.stack([output.hidden_states[k] for k in hidden_states_layers], dim=1) - out = out.to(dtype=dtype, device=device) - - batch_size, num_channels, seq_len, hidden_dim = out.shape - prompt_embeds = out.permute(0, 2, 1, 3).reshape(batch_size, seq_len, num_channels * hidden_dim) - - return prompt_embeds + # Concatenating the selected layers preserves their feature order without + # a non-contiguous intermediate from stack -> permute -> reshape. + prompt_embeds = torch.cat([output.hidden_states[k] for k in hidden_states_layers], dim=-1) + return prompt_embeds.to(dtype=dtype, device=device) @staticmethod # Copied from diffusers.pipelines.flux2.pipeline_flux2.Flux2Pipeline._prepare_text_ids @@ -426,6 +422,26 @@ def _unpack_latents_with_ids( return torch.stack(x_list, dim=0) + @staticmethod + def _prepare_timestep(timestep: torch.Tensor, latents: torch.Tensor) -> torch.Tensor: + """Tensor-only timestep preparation, suitable for regional compilation.""" + return timestep.expand(latents.shape[0]).to(latents.dtype) + + def _prepare_vae_latents(self, latents, latent_ids, height, width): + """Unpack and denormalize latents before VAE decode.""" + # Pass pre-computed latent height/width to avoid DtoH sync from torch.max().item() + latent_height = 2 * (int(height) // (self.vae_scale_factor * 2)) + latent_width = 2 * (int(width) // (self.vae_scale_factor * 2)) + latents = self._unpack_latents_with_ids(latents, latent_ids, latent_height // 2, latent_width // 2) + + latents_bn_mean = self.vae.bn.running_mean.view(1, -1, 1, 1).to(latents.device, latents.dtype) + latents_bn_std = torch.sqrt(self.vae.bn.running_var.view(1, -1, 1, 1) + self.vae.config.batch_norm_eps).to( + latents.device, latents.dtype + ) + latents = latents * latents_bn_std + latents_bn_mean + latents = self._unpatchify_latents(latents) + return latents + def encode_prompt( self, prompt: str | list[str], @@ -838,7 +854,7 @@ def __call__( self._current_timestep = t # broadcast to batch dimension in a way that's compatible with ONNX/Core ML - timestep = t.expand(latents.shape[0]).to(latents.dtype) + timestep = self._prepare_timestep(t, latents) latent_model_input = latents.to(self.transformer.dtype) latent_image_ids = latent_ids @@ -903,17 +919,7 @@ def __call__( self._current_timestep = None - # Pass pre-computed latent height/width to avoid DtoH sync from torch.max().item() - latent_height = 2 * (int(height) // (self.vae_scale_factor * 2)) - latent_width = 2 * (int(width) // (self.vae_scale_factor * 2)) - latents = self._unpack_latents_with_ids(latents, latent_ids, latent_height // 2, latent_width // 2) - - latents_bn_mean = self.vae.bn.running_mean.view(1, -1, 1, 1).to(latents.device, latents.dtype) - latents_bn_std = torch.sqrt(self.vae.bn.running_var.view(1, -1, 1, 1) + self.vae.config.batch_norm_eps).to( - latents.device, latents.dtype - ) - latents = latents * latents_bn_std + latents_bn_mean - latents = self._unpatchify_latents(latents) + latents = self._prepare_vae_latents(latents, latent_ids, height, width) if output_type == "latent": image = latents else: diff --git a/tests/pipelines/flux2/test_pipeline_flux2_klein_prompt_embeds.py b/tests/pipelines/flux2/test_pipeline_flux2_klein_prompt_embeds.py new file mode 100644 index 000000000000..389a6e68412c --- /dev/null +++ b/tests/pipelines/flux2/test_pipeline_flux2_klein_prompt_embeds.py @@ -0,0 +1,44 @@ +"""Regression coverage for Klein prompt feature ordering across hidden layers.""" + +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest +import torch + +from diffusers import Flux2KleinPipeline + + +@pytest.mark.parametrize("batch_size", [1, 2]) +@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16]) +def test_prompt_hidden_layer_feature_order(batch_size, dtype): + class Encoder(torch.nn.Module): + device = torch.device("cpu") + + def __init__(self): + super().__init__() + self.dtype = dtype + self.hidden_states = tuple(torch.randn(batch_size, 4, 8) for _ in range(4)) + + def forward(self, **kwargs): + return SimpleNamespace(hidden_states=self.hidden_states) + + encoder = Encoder() + tokenizer = MagicMock( + return_value={ + "input_ids": torch.ones(1, 4, dtype=torch.long), + "attention_mask": torch.ones(1, 4, dtype=torch.long), + } + ) + layers = (3, 1, 2) + actual = Flux2KleinPipeline._get_qwen3_prompt_embeds( + encoder, + tokenizer, + ["prompt"] * batch_size, + max_sequence_length=4, + hidden_states_layers=layers, + ) + expected = torch.stack([encoder.hidden_states[k] for k in layers], dim=1) + expected = expected.to(dtype).permute(0, 2, 1, 3).reshape(batch_size, 4, 24) + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + assert actual.is_contiguous() From e412d838c83a70b5068de13fa2346bd9547c15a4 Mon Sep 17 00:00:00 2001 From: JingyaHuang Date: Wed, 11 Nov 2026 23:56:30 +0000 Subject: [PATCH 2/5] doc: modify doc --- docs/source/en/optimization/neuron.md | 34 ++++++++------------------- 1 file changed, 10 insertions(+), 24 deletions(-) diff --git a/docs/source/en/optimization/neuron.md b/docs/source/en/optimization/neuron.md index 88680a610b66..b8d4b8a0c246 100644 --- a/docs/source/en/optimization/neuron.md +++ b/docs/source/en/optimization/neuron.md @@ -119,30 +119,16 @@ torchrun --nproc_per_node=8 tensor_parallel_neuron.py ## Native FLUX.2 Klein serving proof of concept -The `examples/inference/flux2_klein_neuron.py` example provides a standalone -single-device BF16 baseline for `black-forest-labs/FLUX.2-klein-4B` using the native -`torch_neuronx` device backend. This is separate from the Optimum Neuron export -workflow above. It uses CPU random generators and optionally compiles the -transformer while leaving the text encoder and VAE eager. +The experimental `add-diffusers-support` branch of `vllm-omni-neuron` wraps +`Flux2KleinPipeline` with vLLM-Omni's Diffusers adapter for single-device BF16 +inference. This is separate from the Optimum Neuron export workflow above. -```bash -NEURON_RT_VISIBLE_CORES=0 \ -TORCH_NEURONX_NEFF_CACHE_DIR=/tmp/flux2-klein-neff-cache \ -python examples/inference/flux2_klein_neuron.py \ - --compile-transformer --height 256 --width 256 --runs 2 -``` - -Use a free Neuron core and a compatible native Neuron SDK. The initial resolution -is deliberately small; larger resolutions and tensor parallelism are outside -this proof of concept. The first request includes compilation; subsequent -requests recreate the same CPU generator to help compare outputs. - -For serving, the experimental `add-diffusers-support` branch of -`vllm-omni-neuron` wraps the same pipeline with vLLM-Omni's Diffusers adapter. Diffusers owns model execution; the plugin owns worker initialization, placement, and compilation policy. The pinned serving runtime compiles the text encoder, -transformer, VAE decoder, scheduler step, and tensor preparation regions; this -compilation policy differs from the standalone baseline. See that branch's `examples/diffusers/README.md` for -offline and HTTP smoke tests. The real 4B checkpoint has completed offline Omni -generation on Trainium2 at 256×256, four steps, BF16, and TP=1. HTTP serving and -larger shapes remain unvalidated; this is not production support. +transformer, VAE decoder, scheduler step, and tensor preparation regions. +See that branch's `examples/diffusers/README.md` for setup and serving examples. + +The real `black-forest-labs/FLUX.2-klein-4B` checkpoint has completed offline Omni +generation on Trainium2 at 256×256, four steps, BF16, and TP=1. HTTP serving, +larger shapes, and tensor parallelism remain unvalidated; this is not production +support. From f4b20edab511b6c2ed63ab92269a2a48088dbd67 Mon Sep 17 00:00:00 2001 From: JingyaHuang Date: Wed, 25 Nov 2026 16:58:26 +0000 Subject: [PATCH 3/5] fix: flashinfer fix+doc update --- docs/source/en/optimization/neuron.md | 9 +++++++++ src/diffusers/quantizers/bfl/utils.py | 6 ++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/docs/source/en/optimization/neuron.md b/docs/source/en/optimization/neuron.md index b8d4b8a0c246..e71befcda2fc 100644 --- a/docs/source/en/optimization/neuron.md +++ b/docs/source/en/optimization/neuron.md @@ -128,6 +128,15 @@ and compilation policy. The pinned serving runtime compiles the text encoder, transformer, VAE decoder, scheduler step, and tensor preparation regions. See that branch's `examples/diffusers/README.md` for setup and serving examples. +Neuron compiles static shapes, so the server only accepts the resolutions you declare up front. +List them in `VLLM_OMNI_NEURON_DIFFUSERS_RESOLUTIONS` (default `256x256`). The server compiles +all of them at startup and rejects any other resolution. The number of inference steps is not +restricted. + +```bash +export VLLM_OMNI_NEURON_DIFFUSERS_RESOLUTIONS=256x256,512x512 +``` + The real `black-forest-labs/FLUX.2-klein-4B` checkpoint has completed offline Omni generation on Trainium2 at 256×256, four steps, BF16, and TP=1. HTTP serving, larger shapes, and tensor parallelism remain unvalidated; this is not production diff --git a/src/diffusers/quantizers/bfl/utils.py b/src/diffusers/quantizers/bfl/utils.py index e75b79c4ee7d..2dd609832b98 100644 --- a/src/diffusers/quantizers/bfl/utils.py +++ b/src/diffusers/quantizers/bfl/utils.py @@ -26,10 +26,6 @@ from accelerate import init_empty_weights from accelerate.hooks import add_hook_to_module, remove_hook_from_module -if is_flashinfer_available(): - import flashinfer - - FP8_MAX = 448.0 E2M1_MAX = 6.0 NVFP4_BLOCK = 16 @@ -217,6 +213,8 @@ def __init__(self, in_features, out_features, bias=True, compute_dtype=None, dev def forward(self, inputs: torch.Tensor) -> torch.Tensor: if inputs.is_cuda and is_flashinfer_available() and torch.cuda.get_device_capability(inputs.device)[0] >= 10: + import flashinfer + x = inputs.reshape(-1, self.in_features).to(torch.bfloat16).contiguous() x_q, x_scale = flashinfer.nvfp4_quantize( x, (1.0 / self.input_scale).reshape(1), sfLayout=flashinfer.SfLayout.layout_128x4, do_shuffle=False From cedef4c18db95b9dbef3bd8c4663e665dce091fe Mon Sep 17 00:00:00 2001 From: JingyaHuang Date: Wed, 25 Nov 2026 18:02:49 +0000 Subject: [PATCH 4/5] doc: describe serving Diffusers pipelines with vllm-omni-neuron --- docs/source/en/optimization/neuron.md | 24 +++++++----------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/docs/source/en/optimization/neuron.md b/docs/source/en/optimization/neuron.md index e71befcda2fc..012942966201 100644 --- a/docs/source/en/optimization/neuron.md +++ b/docs/source/en/optimization/neuron.md @@ -117,27 +117,17 @@ torchrun --nproc_per_node=8 tensor_parallel_neuron.py ``` -## Native FLUX.2 Klein serving proof of concept +## Serving with vLLM-Omni -The experimental `add-diffusers-support` branch of `vllm-omni-neuron` wraps -`Flux2KleinPipeline` with vLLM-Omni's Diffusers adapter for single-device BF16 -inference. This is separate from the Optimum Neuron export workflow above. +[vllm-omni-neuron](https://github.com/aws-neuron/vllm-omni-neuron) serves Diffusers pipelines on Neuron through +vLLM-Omni. Diffusers runs the pipeline, and the plugin handles device placement and compilation. -Diffusers owns model execution; the plugin owns worker initialization, placement, -and compilation policy. The pinned serving runtime compiles the text encoder, -transformer, VAE decoder, scheduler step, and tensor preparation regions. -See that branch's `examples/diffusers/README.md` for setup and serving examples. - -Neuron compiles static shapes, so the server only accepts the resolutions you declare up front. -List them in `VLLM_OMNI_NEURON_DIFFUSERS_RESOLUTIONS` (default `256x256`). The server compiles -all of them at startup and rejects any other resolution. The number of inference steps is not -restricted. +Neuron compiles static shapes, so declare the resolutions to serve up front. The server compiles them at startup and +rejects any other resolution. The number of inference steps isn't restricted. ```bash export VLLM_OMNI_NEURON_DIFFUSERS_RESOLUTIONS=256x256,512x512 +vllm serve --omni --diffusion-load-format diffusers --dtype bfloat16 ``` -The real `black-forest-labs/FLUX.2-klein-4B` checkpoint has completed offline Omni -generation on Trainium2 at 256×256, four steps, BF16, and TP=1. HTTP serving, -larger shapes, and tensor parallelism remain unvalidated; this is not production -support. +See the vllm-omni-neuron repository for installation and supported pipelines. From 817e86c5a5061addf1452123ccc1af6dc86d3c9e Mon Sep 17 00:00:00 2001 From: JingyaHuang Date: Fri, 27 Nov 2026 11:28:19 +0000 Subject: [PATCH 5/5] flux2 klein: add _prepare_timestep to all Klein pipelines Revert the prompt-embeds and VAE-latents workarounds (now handled in vllm-omni-neuron) and keep only a tensor-only timestep helper, shared by Klein, Klein inpaint and Klein KV via # Copied from. --- .../pipelines/flux2/pipeline_flux2_klein.py | 45 ++++++++++--------- .../flux2/pipeline_flux2_klein_inpaint.py | 12 ++++- .../flux2/pipeline_flux2_klein_kv.py | 12 ++++- ...test_pipeline_flux2_klein_prompt_embeds.py | 44 ------------------ 4 files changed, 46 insertions(+), 67 deletions(-) delete mode 100644 tests/pipelines/flux2/test_pipeline_flux2_klein_prompt_embeds.py diff --git a/src/diffusers/pipelines/flux2/pipeline_flux2_klein.py b/src/diffusers/pipelines/flux2/pipeline_flux2_klein.py index ccb6914ae51e..a2bdae0da0ab 100644 --- a/src/diffusers/pipelines/flux2/pipeline_flux2_klein.py +++ b/src/diffusers/pipelines/flux2/pipeline_flux2_klein.py @@ -253,10 +253,14 @@ def _get_qwen3_prompt_embeds( use_cache=False, ) - # Concatenating the selected layers preserves their feature order without - # a non-contiguous intermediate from stack -> permute -> reshape. - prompt_embeds = torch.cat([output.hidden_states[k] for k in hidden_states_layers], dim=-1) - return prompt_embeds.to(dtype=dtype, device=device) + # Only use outputs from intermediate layers and stack them + out = torch.stack([output.hidden_states[k] for k in hidden_states_layers], dim=1) + out = out.to(dtype=dtype, device=device) + + batch_size, num_channels, seq_len, hidden_dim = out.shape + prompt_embeds = out.permute(0, 2, 1, 3).reshape(batch_size, seq_len, num_channels * hidden_dim) + + return prompt_embeds @staticmethod # Copied from diffusers.pipelines.flux2.pipeline_flux2.Flux2Pipeline._prepare_text_ids @@ -424,23 +428,12 @@ def _unpack_latents_with_ids( @staticmethod def _prepare_timestep(timestep: torch.Tensor, latents: torch.Tensor) -> torch.Tensor: - """Tensor-only timestep preparation, suitable for regional compilation.""" - return timestep.expand(latents.shape[0]).to(latents.dtype) - - def _prepare_vae_latents(self, latents, latent_ids, height, width): - """Unpack and denormalize latents before VAE decode.""" - # Pass pre-computed latent height/width to avoid DtoH sync from torch.max().item() - latent_height = 2 * (int(height) // (self.vae_scale_factor * 2)) - latent_width = 2 * (int(width) // (self.vae_scale_factor * 2)) - latents = self._unpack_latents_with_ids(latents, latent_ids, latent_height // 2, latent_width // 2) + """Broadcast the timestep to the batch and cast it to the latents dtype. - latents_bn_mean = self.vae.bn.running_mean.view(1, -1, 1, 1).to(latents.device, latents.dtype) - latents_bn_std = torch.sqrt(self.vae.bn.running_var.view(1, -1, 1, 1) + self.vae.config.batch_norm_eps).to( - latents.device, latents.dtype - ) - latents = latents * latents_bn_std + latents_bn_mean - latents = self._unpatchify_latents(latents) - return latents + Kept as a tensor-only method so backends can compile it as its own region (e.g. libtorch-neuronx-lite, where + running this cast eagerly breaks the denoising loop). + """ + return timestep.expand(latents.shape[0]).to(latents.dtype) def encode_prompt( self, @@ -919,7 +912,17 @@ def __call__( self._current_timestep = None - latents = self._prepare_vae_latents(latents, latent_ids, height, width) + # Pass pre-computed latent height/width to avoid DtoH sync from torch.max().item() + latent_height = 2 * (int(height) // (self.vae_scale_factor * 2)) + latent_width = 2 * (int(width) // (self.vae_scale_factor * 2)) + latents = self._unpack_latents_with_ids(latents, latent_ids, latent_height // 2, latent_width // 2) + + latents_bn_mean = self.vae.bn.running_mean.view(1, -1, 1, 1).to(latents.device, latents.dtype) + latents_bn_std = torch.sqrt(self.vae.bn.running_var.view(1, -1, 1, 1) + self.vae.config.batch_norm_eps).to( + latents.device, latents.dtype + ) + latents = latents * latents_bn_std + latents_bn_mean + latents = self._unpatchify_latents(latents) if output_type == "latent": image = latents else: diff --git a/src/diffusers/pipelines/flux2/pipeline_flux2_klein_inpaint.py b/src/diffusers/pipelines/flux2/pipeline_flux2_klein_inpaint.py index d56dab1678d2..4d08613481f8 100644 --- a/src/diffusers/pipelines/flux2/pipeline_flux2_klein_inpaint.py +++ b/src/diffusers/pipelines/flux2/pipeline_flux2_klein_inpaint.py @@ -504,6 +504,16 @@ def _get_raw_image_size(image: PipelineImageInput) -> tuple[int, int]: raise ValueError(f"Unsupported image type: {type(image)}") + @staticmethod + # Copied from diffusers.pipelines.flux2.pipeline_flux2_klein.Flux2KleinPipeline._prepare_timestep + def _prepare_timestep(timestep: torch.Tensor, latents: torch.Tensor) -> torch.Tensor: + """Broadcast the timestep to the batch and cast it to the latents dtype. + + Kept as a tensor-only method so backends can compile it as its own region (e.g. libtorch-neuronx-lite, where + running this cast eagerly breaks the denoising loop). + """ + return timestep.expand(latents.shape[0]).to(latents.dtype) + # Copied from diffusers.pipelines.flux2.pipeline_flux2_klein.Flux2KleinPipeline.encode_prompt def encode_prompt( self, @@ -1173,7 +1183,7 @@ def __call__( self._current_timestep = t # broadcast to batch dimension in a way that's compatible with ONNX/Core ML - timestep = t.expand(latents.shape[0]).to(latents.dtype) + timestep = self._prepare_timestep(t, latents) latent_model_input = torch.cat([latents, condition_image_latents], dim=1) img_ids = combined_image_ids diff --git a/src/diffusers/pipelines/flux2/pipeline_flux2_klein_kv.py b/src/diffusers/pipelines/flux2/pipeline_flux2_klein_kv.py index 4671ad0ae3fd..90a1167665a2 100644 --- a/src/diffusers/pipelines/flux2/pipeline_flux2_klein_kv.py +++ b/src/diffusers/pipelines/flux2/pipeline_flux2_klein_kv.py @@ -427,6 +427,16 @@ def _unpack_latents_with_ids(x: torch.Tensor, x_ids: torch.Tensor) -> list[torch return torch.stack(x_list, dim=0) + @staticmethod + # Copied from diffusers.pipelines.flux2.pipeline_flux2_klein.Flux2KleinPipeline._prepare_timestep + def _prepare_timestep(timestep: torch.Tensor, latents: torch.Tensor) -> torch.Tensor: + """Broadcast the timestep to the batch and cast it to the latents dtype. + + Kept as a tensor-only method so backends can compile it as its own region (e.g. libtorch-neuronx-lite, where + running this cast eagerly breaks the denoising loop). + """ + return timestep.expand(latents.shape[0]).to(latents.dtype) + def _set_kv_attn_processors(self): """Replace default attention processors with KV-cache-aware variants.""" for block in self.transformer.transformer_blocks: @@ -789,7 +799,7 @@ def __call__( continue self._current_timestep = t - timestep = t.expand(latents.shape[0]).to(latents.dtype) + timestep = self._prepare_timestep(t, latents) if i == 0 and image_latents is not None: # Step 0: include ref tokens, extract KV cache diff --git a/tests/pipelines/flux2/test_pipeline_flux2_klein_prompt_embeds.py b/tests/pipelines/flux2/test_pipeline_flux2_klein_prompt_embeds.py deleted file mode 100644 index 389a6e68412c..000000000000 --- a/tests/pipelines/flux2/test_pipeline_flux2_klein_prompt_embeds.py +++ /dev/null @@ -1,44 +0,0 @@ -"""Regression coverage for Klein prompt feature ordering across hidden layers.""" - -from types import SimpleNamespace -from unittest.mock import MagicMock - -import pytest -import torch - -from diffusers import Flux2KleinPipeline - - -@pytest.mark.parametrize("batch_size", [1, 2]) -@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16]) -def test_prompt_hidden_layer_feature_order(batch_size, dtype): - class Encoder(torch.nn.Module): - device = torch.device("cpu") - - def __init__(self): - super().__init__() - self.dtype = dtype - self.hidden_states = tuple(torch.randn(batch_size, 4, 8) for _ in range(4)) - - def forward(self, **kwargs): - return SimpleNamespace(hidden_states=self.hidden_states) - - encoder = Encoder() - tokenizer = MagicMock( - return_value={ - "input_ids": torch.ones(1, 4, dtype=torch.long), - "attention_mask": torch.ones(1, 4, dtype=torch.long), - } - ) - layers = (3, 1, 2) - actual = Flux2KleinPipeline._get_qwen3_prompt_embeds( - encoder, - tokenizer, - ["prompt"] * batch_size, - max_sequence_length=4, - hidden_states_layers=layers, - ) - expected = torch.stack([encoder.hidden_states[k] for k in layers], dim=1) - expected = expected.to(dtype).permute(0, 2, 1, 3).reshape(batch_size, 4, 24) - torch.testing.assert_close(actual, expected, rtol=0, atol=0) - assert actual.is_contiguous()