Instructions to use diffusers-modular/krea2-edit with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use diffusers-modular/krea2-edit with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline from diffusers.utils import load_image # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("diffusers-modular/krea2-edit", torch_dtype=torch.bfloat16, device_map="cuda") prompt = "Turn this cat into a dog" input_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cat.png") image = pipe(image=input_image, prompt=prompt).images[0] - Notebooks
- Google Colab
- Kaggle
| # Copyright 2026 Krea AI and The HuggingFace Team. All rights reserved. | |
| # | |
| # Licensed under the Apache License, Version 2.0 (the "License"); | |
| # you may not use this file except in compliance with the License. | |
| # You may obtain a copy of the License at | |
| # | |
| # http://www.apache.org/licenses/LICENSE-2.0 | |
| # | |
| # Unless required by applicable law or agreed to in writing, software | |
| # distributed under the License is distributed on an "AS IS" BASIS, | |
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| # See the License for the specific language governing permissions and | |
| # limitations under the License. | |
| import inspect | |
| import numpy as np | |
| import torch | |
| from diffusers.schedulers import FlowMatchEulerDiscreteScheduler | |
| from diffusers.utils.torch_utils import randn_tensor | |
| from diffusers.modular_pipelines.modular_pipeline import ModularPipelineBlocks, PipelineState | |
| from diffusers.modular_pipelines.modular_pipeline_utils import ComponentSpec, InputParam, OutputParam | |
| from .modular_pipeline import Krea2ModularPipeline, Krea2Pachifier | |
| # Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift | |
| def calculate_shift( | |
| image_seq_len, | |
| base_seq_len: int = 256, | |
| max_seq_len: int = 4096, | |
| base_shift: float = 0.5, | |
| max_shift: float = 1.15, | |
| ): | |
| m = (max_shift - base_shift) / (max_seq_len - base_seq_len) | |
| b = base_shift - m * base_seq_len | |
| mu = image_seq_len * m + b | |
| return mu | |
| # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps | |
| def retrieve_timesteps( | |
| scheduler, | |
| num_inference_steps: int | None = None, | |
| device: str | torch.device | None = None, | |
| timesteps: list[int] | None = None, | |
| sigmas: list[float] | None = None, | |
| **kwargs, | |
| ): | |
| r""" | |
| Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles | |
| custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`. | |
| Args: | |
| scheduler (`SchedulerMixin`): | |
| The scheduler to get timesteps from. | |
| num_inference_steps (`int`): | |
| The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps` | |
| must be `None`. | |
| device (`str` or `torch.device`, *optional*): | |
| The device to which the timesteps should be moved to. If `None`, the timesteps are not moved. | |
| timesteps (`list[int]`, *optional*): | |
| Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed, | |
| `num_inference_steps` and `sigmas` must be `None`. | |
| sigmas (`list[float]`, *optional*): | |
| Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed, | |
| `num_inference_steps` and `timesteps` must be `None`. | |
| Returns: | |
| `tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the | |
| second element is the number of inference steps. | |
| """ | |
| if timesteps is not None and sigmas is not None: | |
| raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values") | |
| if timesteps is not None: | |
| accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys()) | |
| if not accepts_timesteps: | |
| raise ValueError( | |
| f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom" | |
| f" timestep schedules. Please check whether you are using the correct scheduler." | |
| ) | |
| scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs) | |
| timesteps = scheduler.timesteps | |
| num_inference_steps = len(timesteps) | |
| elif sigmas is not None: | |
| accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys()) | |
| if not accept_sigmas: | |
| raise ValueError( | |
| f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom" | |
| f" sigmas schedules. Please check whether you are using the correct scheduler." | |
| ) | |
| scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs) | |
| timesteps = scheduler.timesteps | |
| num_inference_steps = len(timesteps) | |
| else: | |
| scheduler.set_timesteps(num_inference_steps, device=device, **kwargs) | |
| timesteps = scheduler.timesteps | |
| return timesteps, num_inference_steps | |
| # Copied from diffusers.modular_pipelines.qwenimage.before_denoise.get_timesteps | |
| def get_timesteps(scheduler, num_inference_steps, strength): | |
| # get the original timestep using init_timestep | |
| init_timestep = min(num_inference_steps * strength, num_inference_steps) | |
| t_start = int(max(num_inference_steps - init_timestep, 0)) | |
| timesteps = scheduler.timesteps[t_start * scheduler.order :] | |
| if hasattr(scheduler, "set_begin_index"): | |
| scheduler.set_begin_index(t_start * scheduler.order) | |
| return timesteps, num_inference_steps - t_start | |
| # ==================== | |
| # 1. PREPARE LATENTS | |
| # ==================== | |
| class Krea2PrepareLatentsStep(ModularPipelineBlocks): | |
| model_name = "krea2" | |
| def description(self) -> str: | |
| return "Prepare initial random noise for the generation process" | |
| def expected_components(self) -> list[ComponentSpec]: | |
| return [ | |
| ComponentSpec("pachifier", Krea2Pachifier, default_creation_method="from_config"), | |
| ] | |
| def inputs(self) -> list[InputParam]: | |
| return [ | |
| InputParam.template("latents"), | |
| InputParam.template("height"), | |
| InputParam.template("width"), | |
| InputParam.template("num_images_per_prompt"), | |
| InputParam.template("generator"), | |
| InputParam.template("batch_size"), | |
| InputParam.template("dtype"), | |
| ] | |
| def intermediate_outputs(self) -> list[OutputParam]: | |
| return [ | |
| OutputParam(name="height", type_hint=int, description="if not set, updated to default value"), | |
| OutputParam(name="width", type_hint=int, description="if not set, updated to default value"), | |
| OutputParam( | |
| name="latents", | |
| type_hint=torch.Tensor, | |
| description="The initial latents to use for the denoising process", | |
| ), | |
| ] | |
| def check_inputs(height, width, vae_scale_factor): | |
| if height is not None and height % (vae_scale_factor * 2) != 0: | |
| raise ValueError(f"Height must be divisible by {vae_scale_factor * 2} but is {height}") | |
| if width is not None and width % (vae_scale_factor * 2) != 0: | |
| raise ValueError(f"Width must be divisible by {vae_scale_factor * 2} but is {width}") | |
| def __call__(self, components: Krea2ModularPipeline, state: PipelineState) -> PipelineState: | |
| block_state = self.get_block_state(state) | |
| self.check_inputs( | |
| height=block_state.height, | |
| width=block_state.width, | |
| vae_scale_factor=components.vae_scale_factor, | |
| ) | |
| device = components._execution_device | |
| batch_size = block_state.batch_size * block_state.num_images_per_prompt | |
| # we can update the height and width here since it's used to generate the initial | |
| block_state.height = block_state.height or components.default_height | |
| block_state.width = block_state.width or components.default_width | |
| # VAE applies 8x compression on images but we must also account for packing which requires | |
| # latent height and width to be divisible by 2. | |
| latent_height = 2 * (int(block_state.height) // (components.vae_scale_factor * 2)) | |
| latent_width = 2 * (int(block_state.width) // (components.vae_scale_factor * 2)) | |
| shape = (batch_size, components.num_channels_latents, 1, latent_height, latent_width) | |
| if isinstance(block_state.generator, list) and len(block_state.generator) != batch_size: | |
| raise ValueError( | |
| f"You have passed a list of generators of length {len(block_state.generator)}, but requested an effective batch" | |
| f" size of {batch_size}. Make sure the batch size matches the length of the generators." | |
| ) | |
| if block_state.latents is None: | |
| block_state.latents = randn_tensor( | |
| shape, generator=block_state.generator, device=device, dtype=block_state.dtype | |
| ) | |
| block_state.latents = components.pachifier.pack_latents(block_state.latents) | |
| self.set_block_state(state, block_state) | |
| return components, state | |
| class Krea2PrepareLatentsWithStrengthStep(ModularPipelineBlocks): | |
| model_name = "krea2" | |
| def description(self) -> str: | |
| return "Step that adds noise to image latents for image-to-image/inpainting. Should be run after set_timesteps, prepare_latents. Both noise and image latents should already be patchified." | |
| def expected_components(self) -> list[ComponentSpec]: | |
| return [ | |
| ComponentSpec("scheduler", FlowMatchEulerDiscreteScheduler), | |
| ] | |
| def inputs(self) -> list[InputParam]: | |
| return [ | |
| InputParam( | |
| name="latents", | |
| required=True, | |
| type_hint=torch.Tensor, | |
| description="The initial random noised, can be generated in prepare latent step.", | |
| ), | |
| InputParam.template("image_latents", note="Can be generated from vae encoder and updated in input step."), | |
| InputParam( | |
| name="timesteps", | |
| required=True, | |
| type_hint=torch.Tensor, | |
| description="The timesteps to use for the denoising process. Can be generated in set_timesteps step.", | |
| ), | |
| ] | |
| def intermediate_outputs(self) -> list[OutputParam]: | |
| return [ | |
| OutputParam( | |
| name="initial_noise", | |
| type_hint=torch.Tensor, | |
| description="The initial random noised used for inpainting denoising.", | |
| ), | |
| OutputParam( | |
| name="latents", | |
| type_hint=torch.Tensor, | |
| description="The scaled noisy latents to use for inpainting/image-to-image denoising.", | |
| ), | |
| ] | |
| def check_inputs(image_latents, latents): | |
| if image_latents.shape[0] != latents.shape[0]: | |
| raise ValueError( | |
| f"`image_latents` must have have same batch size as `latents`, but got {image_latents.shape[0]} and {latents.shape[0]}" | |
| ) | |
| if image_latents.ndim != 3: | |
| raise ValueError(f"`image_latents` must have 3 dimensions (patchified), but got {image_latents.ndim}") | |
| def __call__(self, components: Krea2ModularPipeline, state: PipelineState) -> PipelineState: | |
| block_state = self.get_block_state(state) | |
| self.check_inputs( | |
| image_latents=block_state.image_latents, | |
| latents=block_state.latents, | |
| ) | |
| # prepare latent timestep | |
| latent_timestep = block_state.timesteps[:1].repeat(block_state.latents.shape[0]) | |
| # make copy of initial_noise | |
| block_state.initial_noise = block_state.latents | |
| # scale noise | |
| block_state.latents = components.scheduler.scale_noise( | |
| block_state.image_latents, latent_timestep, block_state.latents | |
| ) | |
| self.set_block_state(state, block_state) | |
| return components, state | |
| class Krea2CreateMaskLatentsStep(ModularPipelineBlocks): | |
| model_name = "krea2" | |
| def description(self) -> str: | |
| return "Step that creates mask latents from preprocessed mask_image by interpolating to latent space." | |
| def expected_components(self) -> list[ComponentSpec]: | |
| return [ | |
| ComponentSpec("pachifier", Krea2Pachifier, default_creation_method="from_config"), | |
| ] | |
| def inputs(self) -> list[InputParam]: | |
| return [ | |
| InputParam( | |
| name="processed_mask_image", | |
| required=True, | |
| type_hint=torch.Tensor, | |
| description="The processed mask to use for the inpainting process.", | |
| ), | |
| InputParam.template("height", required=True), | |
| InputParam.template("width", required=True), | |
| InputParam.template("dtype"), | |
| ] | |
| def intermediate_outputs(self) -> list[OutputParam]: | |
| return [ | |
| OutputParam( | |
| name="mask", type_hint=torch.Tensor, description="The mask to use for the inpainting process." | |
| ), | |
| ] | |
| def __call__(self, components: Krea2ModularPipeline, state: PipelineState) -> PipelineState: | |
| block_state = self.get_block_state(state) | |
| device = components._execution_device | |
| # VAE applies 8x compression on images but we must also account for packing which requires | |
| # latent height and width to be divisible by 2. | |
| height_latents = 2 * (int(block_state.height) // (components.vae_scale_factor * 2)) | |
| width_latents = 2 * (int(block_state.width) // (components.vae_scale_factor * 2)) | |
| block_state.mask = torch.nn.functional.interpolate( | |
| block_state.processed_mask_image, | |
| size=(height_latents, width_latents), | |
| ) | |
| block_state.mask = block_state.mask.unsqueeze(2) | |
| block_state.mask = block_state.mask.repeat(1, components.num_channels_latents, 1, 1, 1) | |
| block_state.mask = block_state.mask.to(device=device, dtype=block_state.dtype) | |
| block_state.mask = components.pachifier.pack_latents(block_state.mask) | |
| self.set_block_state(state, block_state) | |
| return components, state | |
| # ==================== | |
| # 2. SET TIMESTEPS | |
| # ==================== | |
| class Krea2SetTimestepsStep(ModularPipelineBlocks): | |
| model_name = "krea2" | |
| def description(self) -> str: | |
| return "Step that sets the scheduler's timesteps for text-to-image generation. Should be run after prepare latents step." | |
| def expected_components(self) -> list[ComponentSpec]: | |
| return [ | |
| ComponentSpec("scheduler", FlowMatchEulerDiscreteScheduler), | |
| ] | |
| def inputs(self) -> list[InputParam]: | |
| return [ | |
| InputParam.template("num_inference_steps", default=28), | |
| InputParam.template("sigmas"), | |
| InputParam( | |
| name="mu", | |
| type_hint=float, | |
| description="Fixed timestep shift for the scheduler. Pass `1.15` for the few-step distilled (TDM/turbo) checkpoint; if not provided, computed from the image sequence length (base checkpoint behavior).", | |
| ), | |
| InputParam( | |
| name="latents", | |
| required=True, | |
| type_hint=torch.Tensor, | |
| description="The initial random noised latents for the denoising process. Can be generated in prepare latents step.", | |
| ), | |
| ] | |
| def intermediate_outputs(self) -> list[OutputParam]: | |
| return [ | |
| OutputParam( | |
| name="timesteps", type_hint=torch.Tensor, description="The timesteps to use for the denoising process" | |
| ), | |
| ] | |
| def __call__(self, components: Krea2ModularPipeline, state: PipelineState) -> PipelineState: | |
| block_state = self.get_block_state(state) | |
| device = components._execution_device | |
| sigmas = ( | |
| np.linspace(1.0, 1 / block_state.num_inference_steps, block_state.num_inference_steps) | |
| if block_state.sigmas is None | |
| else block_state.sigmas | |
| ) | |
| mu = block_state.mu | |
| if mu is None: | |
| mu = calculate_shift( | |
| image_seq_len=block_state.latents.shape[1], | |
| base_seq_len=components.scheduler.config.get("base_image_seq_len", 256), | |
| max_seq_len=components.scheduler.config.get("max_image_seq_len", 6400), | |
| base_shift=components.scheduler.config.get("base_shift", 0.5), | |
| max_shift=components.scheduler.config.get("max_shift", 1.15), | |
| ) | |
| block_state.timesteps, block_state.num_inference_steps = retrieve_timesteps( | |
| scheduler=components.scheduler, | |
| num_inference_steps=block_state.num_inference_steps, | |
| device=device, | |
| sigmas=sigmas, | |
| mu=mu, | |
| ) | |
| components.scheduler.set_begin_index(0) | |
| self.set_block_state(state, block_state) | |
| return components, state | |
| class Krea2SetTimestepsWithStrengthStep(ModularPipelineBlocks): | |
| model_name = "krea2" | |
| def description(self) -> str: | |
| return "Step that sets the scheduler's timesteps for image-to-image generation, and inpainting. Should be run after prepare latents step." | |
| def expected_components(self) -> list[ComponentSpec]: | |
| return [ | |
| ComponentSpec("scheduler", FlowMatchEulerDiscreteScheduler), | |
| ] | |
| def inputs(self) -> list[InputParam]: | |
| return [ | |
| InputParam.template("num_inference_steps", default=28), | |
| InputParam.template("sigmas"), | |
| InputParam( | |
| name="mu", | |
| type_hint=float, | |
| description="Fixed timestep shift for the scheduler. Pass `1.15` for the few-step distilled (TDM/turbo) checkpoint; if not provided, computed from the image sequence length (base checkpoint behavior).", | |
| ), | |
| InputParam( | |
| "latents", | |
| required=True, | |
| type_hint=torch.Tensor, | |
| description="The latents to use for the denoising process. Can be generated in prepare latents step.", | |
| ), | |
| InputParam.template("strength"), | |
| ] | |
| def intermediate_outputs(self) -> list[OutputParam]: | |
| return [ | |
| OutputParam( | |
| name="timesteps", | |
| type_hint=torch.Tensor, | |
| description="The timesteps to use for the denoising process.", | |
| ), | |
| OutputParam( | |
| name="num_inference_steps", | |
| type_hint=int, | |
| description="The number of denoising steps to perform at inference time. Updated based on strength.", | |
| ), | |
| ] | |
| def __call__(self, components: Krea2ModularPipeline, state: PipelineState) -> PipelineState: | |
| block_state = self.get_block_state(state) | |
| device = components._execution_device | |
| sigmas = ( | |
| np.linspace(1.0, 1 / block_state.num_inference_steps, block_state.num_inference_steps) | |
| if block_state.sigmas is None | |
| else block_state.sigmas | |
| ) | |
| mu = block_state.mu | |
| if mu is None: | |
| mu = calculate_shift( | |
| image_seq_len=block_state.latents.shape[1], | |
| base_seq_len=components.scheduler.config.get("base_image_seq_len", 256), | |
| max_seq_len=components.scheduler.config.get("max_image_seq_len", 6400), | |
| base_shift=components.scheduler.config.get("base_shift", 0.5), | |
| max_shift=components.scheduler.config.get("max_shift", 1.15), | |
| ) | |
| block_state.timesteps, block_state.num_inference_steps = retrieve_timesteps( | |
| scheduler=components.scheduler, | |
| num_inference_steps=block_state.num_inference_steps, | |
| device=device, | |
| sigmas=sigmas, | |
| mu=mu, | |
| ) | |
| block_state.timesteps, block_state.num_inference_steps = get_timesteps( | |
| scheduler=components.scheduler, | |
| num_inference_steps=block_state.num_inference_steps, | |
| strength=block_state.strength, | |
| ) | |
| self.set_block_state(state, block_state) | |
| return components, state | |
| # ==================== | |
| # 3. OTHER INPUTS FOR DENOISER | |
| # ==================== | |
| ## RoPE inputs for denoiser | |
| class Krea2RoPEInputsStep(ModularPipelineBlocks): | |
| model_name = "krea2" | |
| def description(self) -> str: | |
| return ( | |
| "Step that prepares the rotary position ids for the denoising process. Text tokens sit at the origin, " | |
| "image tokens carry their `(0, h, w)` latent-grid coordinates. Should be placed after prepare_latents step." | |
| ) | |
| def expected_components(self) -> list[ComponentSpec]: | |
| return [ | |
| ComponentSpec("pachifier", Krea2Pachifier, default_creation_method="from_config"), | |
| ] | |
| def inputs(self) -> list[InputParam]: | |
| return [ | |
| InputParam.template("height", required=True), | |
| InputParam.template("width", required=True), | |
| InputParam.template("prompt_embeds_mask"), | |
| ] | |
| def intermediate_outputs(self) -> list[OutputParam]: | |
| return [ | |
| OutputParam( | |
| name="position_ids", | |
| kwargs_type="denoiser_input_fields", | |
| type_hint=torch.Tensor, | |
| description="The rotary coordinates of shape (text_seq_len + grid_height * grid_width, 3) for the combined text-image sequence.", | |
| ), | |
| ] | |
| def __call__(self, components: Krea2ModularPipeline, state: PipelineState) -> PipelineState: | |
| block_state = self.get_block_state(state) | |
| device = components._execution_device | |
| patch_size = components.pachifier.config.patch_size | |
| text_seq_len = block_state.prompt_embeds_mask.shape[1] | |
| grid_height = block_state.height // (components.vae_scale_factor * patch_size) | |
| grid_width = block_state.width // (components.vae_scale_factor * patch_size) | |
| text_ids = torch.zeros(text_seq_len, 3, device=device) | |
| image_ids = torch.zeros(grid_height, grid_width, 3, device=device) | |
| image_ids[..., 1] = torch.arange(grid_height, device=device)[:, None] | |
| image_ids[..., 2] = torch.arange(grid_width, device=device)[None, :] | |
| image_ids = image_ids.reshape(grid_height * grid_width, 3) | |
| block_state.position_ids = torch.cat([text_ids, image_ids], dim=0) | |
| self.set_block_state(state, block_state) | |
| return components, state | |
| class Krea2EditRoPEInputsStep(ModularPipelineBlocks): | |
| model_name = "krea2" | |
| def description(self) -> str: | |
| return ( | |
| "Step that prepares the rotary position ids for the edit task: the `[text, image]` coordinates followed " | |
| "by the reference tokens' coordinates (each reference on its own frame axis). Should be placed after " | |
| "prepare_latents and the reference latents step." | |
| ) | |
| def expected_components(self) -> list[ComponentSpec]: | |
| return [ | |
| ComponentSpec("pachifier", Krea2Pachifier, default_creation_method="from_config"), | |
| ] | |
| def inputs(self) -> list[InputParam]: | |
| return [ | |
| InputParam.template("height", required=True), | |
| InputParam.template("width", required=True), | |
| InputParam.template("prompt_embeds_mask"), | |
| InputParam( | |
| "reference_position_ids", | |
| required=True, | |
| type_hint=torch.Tensor, | |
| description="Rotary coordinates for the reference tokens. Can be generated in the reference latents step.", | |
| ), | |
| ] | |
| def intermediate_outputs(self) -> list[OutputParam]: | |
| return [ | |
| OutputParam( | |
| name="position_ids", | |
| kwargs_type="denoiser_input_fields", | |
| type_hint=torch.Tensor, | |
| description="The rotary coordinates of shape (text_seq_len + grid_height * grid_width + ref_seq_len, 3) " | |
| "for the combined text-image-reference sequence.", | |
| ), | |
| ] | |
| def __call__(self, components: Krea2ModularPipeline, state: PipelineState) -> PipelineState: | |
| block_state = self.get_block_state(state) | |
| device = components._execution_device | |
| patch_size = components.pachifier.config.patch_size | |
| text_seq_len = block_state.prompt_embeds_mask.shape[1] | |
| grid_height = block_state.height // (components.vae_scale_factor * patch_size) | |
| grid_width = block_state.width // (components.vae_scale_factor * patch_size) | |
| text_ids = torch.zeros(text_seq_len, 3, device=device) | |
| image_ids = torch.zeros(grid_height, grid_width, 3, device=device) | |
| image_ids[..., 1] = torch.arange(grid_height, device=device)[:, None] | |
| image_ids[..., 2] = torch.arange(grid_width, device=device)[None, :] | |
| image_ids = image_ids.reshape(grid_height * grid_width, 3) | |
| block_state.position_ids = torch.cat([text_ids, image_ids, block_state.reference_position_ids], dim=0) | |
| self.set_block_state(state, block_state) | |
| return components, state | |