Spaces:
Paused
Paused
File size: 23,554 Bytes
cd458ae | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 | # 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 numpy as np
import torch
from ...models.transformers.transformer_krea2 import Krea2Transformer2DModel
from ...schedulers import FlowMatchEulerDiscreteScheduler
from ...utils import logging
from ...utils.torch_utils import randn_tensor
from ..modular_pipeline import ModularPipelineBlocks, PipelineState
from ..modular_pipeline_utils import ComponentSpec, InputParam, OutputParam
from .modular_pipeline import Krea2ModularPipeline
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
# Copied from diffusers.pipelines.krea2.pipeline_krea2.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
# auto_docstring
class Krea2TextInputsStep(ModularPipelineBlocks):
"""
Input step that determines `batch_size`/`dtype` from the per-prompt `prompt_embeds` and replicates the text
conditioning (and the optional negative branch) to `batch_size * num_images_per_prompt`. Place after the text
encoder.
Inputs:
num_images_per_prompt (`int`, *optional*, defaults to 1):
The number of images to generate per prompt.
prompt_embeds (`Tensor`):
Per-prompt stacked text features (B, text_seq_len, num_text_layers, text_hidden_dim).
prompt_embeds_mask (`Tensor`):
Per-prompt boolean text mask (B, text_seq_len).
negative_prompt_embeds (`Tensor`, *optional*):
Per-prompt negative text features.
negative_prompt_embeds_mask (`Tensor`, *optional*):
Per-prompt negative text mask.
Outputs:
batch_size (`int`):
Effective batch size (num prompts * num_images_per_prompt).
dtype (`dtype`):
The dtype of the text features.
prompt_embeds (`Tensor`):
Text features, batch-expanded.
prompt_embeds_mask (`Tensor`):
Text mask, batch-expanded.
negative_prompt_embeds (`Tensor`):
Negative text features, batch-expanded.
negative_prompt_embeds_mask (`Tensor`):
Negative text mask, batch-expanded.
"""
model_name = "krea2"
@property
def description(self) -> str:
return (
"Input step that determines `batch_size`/`dtype` from the per-prompt `prompt_embeds` and replicates the "
"text conditioning (and the optional negative branch) to `batch_size * num_images_per_prompt`. Place after "
"the text encoder."
)
@property
def inputs(self) -> list[InputParam]:
return [
InputParam.template("num_images_per_prompt", default=1),
InputParam(
name="prompt_embeds",
required=True,
type_hint=torch.Tensor,
description="Per-prompt stacked text features (B, text_seq_len, num_text_layers, text_hidden_dim).",
),
InputParam(
name="prompt_embeds_mask",
required=True,
type_hint=torch.Tensor,
description="Per-prompt boolean text mask (B, text_seq_len).",
),
InputParam(
name="negative_prompt_embeds",
type_hint=torch.Tensor,
description="Per-prompt negative text features.",
),
InputParam(
name="negative_prompt_embeds_mask",
type_hint=torch.Tensor,
description="Per-prompt negative text mask.",
),
]
@property
def intermediate_outputs(self) -> list[OutputParam]:
return [
OutputParam(
name="batch_size",
type_hint=int,
description="Effective batch size (num prompts * num_images_per_prompt).",
),
OutputParam(name="dtype", type_hint=torch.dtype, description="The dtype of the text features."),
OutputParam(name="prompt_embeds", type_hint=torch.Tensor, description="Text features, batch-expanded."),
OutputParam(name="prompt_embeds_mask", type_hint=torch.Tensor, description="Text mask, batch-expanded."),
OutputParam(
name="negative_prompt_embeds",
type_hint=torch.Tensor,
description="Negative text features, batch-expanded.",
),
OutputParam(
name="negative_prompt_embeds_mask",
type_hint=torch.Tensor,
description="Negative text mask, batch-expanded.",
),
]
@torch.no_grad()
def __call__(self, components: Krea2ModularPipeline, state: PipelineState) -> PipelineState:
block_state = self.get_block_state(state)
prompt_batch, seq_len, num_layers, dim = block_state.prompt_embeds.shape
n = block_state.num_images_per_prompt
block_state.dtype = block_state.prompt_embeds.dtype
block_state.batch_size = prompt_batch * n
block_state.prompt_embeds = block_state.prompt_embeds.repeat(1, n, 1, 1).view(
prompt_batch * n, seq_len, num_layers, dim
)
block_state.prompt_embeds_mask = block_state.prompt_embeds_mask.repeat(1, n).view(prompt_batch * n, seq_len)
if block_state.negative_prompt_embeds is not None:
block_state.negative_prompt_embeds = block_state.negative_prompt_embeds.repeat(1, n, 1, 1).view(
prompt_batch * n, seq_len, num_layers, dim
)
block_state.negative_prompt_embeds_mask = block_state.negative_prompt_embeds_mask.repeat(1, n).view(
prompt_batch * n, seq_len
)
self.set_block_state(state, block_state)
return components, state
# auto_docstring
class Krea2TurboTextInputsStep(ModularPipelineBlocks):
"""
Input step for the distilled Krea 2 turbo checkpoint that determines `batch_size`/`dtype` from the per-prompt
`prompt_embeds` and replicates the text conditioning to `batch_size * num_images_per_prompt`. The distilled
checkpoint runs without classifier-free guidance, so there is no negative branch. Place after the text encoder.
Inputs:
num_images_per_prompt (`int`, *optional*, defaults to 1):
The number of images to generate per prompt.
prompt_embeds (`Tensor`):
Per-prompt stacked text features (B, text_seq_len, num_text_layers, text_hidden_dim).
prompt_embeds_mask (`Tensor`):
Per-prompt boolean text mask (B, text_seq_len).
Outputs:
batch_size (`int`):
Effective batch size (num prompts * num_images_per_prompt).
dtype (`dtype`):
The dtype of the text features.
prompt_embeds (`Tensor`):
Text features, batch-expanded.
prompt_embeds_mask (`Tensor`):
Text mask, batch-expanded.
"""
model_name = "krea2"
@property
def description(self) -> str:
return (
"Input step for the distilled Krea 2 turbo checkpoint that determines `batch_size`/`dtype` from the "
"per-prompt `prompt_embeds` and replicates the text conditioning to `batch_size * num_images_per_prompt`. "
"The distilled checkpoint runs without classifier-free guidance, so there is no negative branch. Place "
"after the text encoder."
)
@property
def inputs(self) -> list[InputParam]:
return [
InputParam.template("num_images_per_prompt", default=1),
InputParam(
name="prompt_embeds",
required=True,
type_hint=torch.Tensor,
description="Per-prompt stacked text features (B, text_seq_len, num_text_layers, text_hidden_dim).",
),
InputParam(
name="prompt_embeds_mask",
required=True,
type_hint=torch.Tensor,
description="Per-prompt boolean text mask (B, text_seq_len).",
),
]
@property
def intermediate_outputs(self) -> list[OutputParam]:
return [
OutputParam(
name="batch_size",
type_hint=int,
description="Effective batch size (num prompts * num_images_per_prompt).",
),
OutputParam(name="dtype", type_hint=torch.dtype, description="The dtype of the text features."),
OutputParam(name="prompt_embeds", type_hint=torch.Tensor, description="Text features, batch-expanded."),
OutputParam(name="prompt_embeds_mask", type_hint=torch.Tensor, description="Text mask, batch-expanded."),
]
@torch.no_grad()
def __call__(self, components: Krea2ModularPipeline, state: PipelineState) -> PipelineState:
block_state = self.get_block_state(state)
prompt_batch, seq_len, num_layers, dim = block_state.prompt_embeds.shape
n = block_state.num_images_per_prompt
block_state.dtype = block_state.prompt_embeds.dtype
block_state.batch_size = prompt_batch * n
block_state.prompt_embeds = block_state.prompt_embeds.repeat(1, n, 1, 1).view(
prompt_batch * n, seq_len, num_layers, dim
)
block_state.prompt_embeds_mask = block_state.prompt_embeds_mask.repeat(1, n).view(prompt_batch * n, seq_len)
self.set_block_state(state, block_state)
return components, state
# auto_docstring
class Krea2PrepareLatentsStep(ModularPipelineBlocks):
"""
Step that samples the spatial image latents and patch-packs them into (B, image_seq_len, in_channels) for the
denoising loop.
Components:
transformer (`Krea2Transformer2DModel`)
Inputs:
latents (`Tensor`, *optional*):
Pre-generated noisy latents for image generation.
height (`int`, *optional*, defaults to 1024):
The height in pixels of the generated image.
width (`int`, *optional*, defaults to 1024):
The width in pixels of the generated image.
generator (`Generator`, *optional*):
Torch generator for deterministic generation.
batch_size (`int`):
Effective batch size.
dtype (`dtype`):
The working dtype.
Outputs:
latents (`Tensor`):
The initial packed image latents (B, image_seq_len, in_channels).
image_seq_len (`int`):
Number of image tokens (grid_h * grid_w).
"""
model_name = "krea2"
@property
def description(self) -> str:
return (
"Step that samples the spatial image latents and patch-packs them into (B, image_seq_len, in_channels) "
"for the denoising loop."
)
@property
def expected_components(self) -> list[ComponentSpec]:
return [ComponentSpec("transformer", Krea2Transformer2DModel)]
@property
def inputs(self) -> list[InputParam]:
return [
InputParam.template("latents"),
InputParam.template("height", default=1024),
InputParam.template("width", default=1024),
InputParam.template("generator"),
InputParam(name="batch_size", required=True, type_hint=int, description="Effective batch size."),
InputParam(name="dtype", required=True, type_hint=torch.dtype, description="The working dtype."),
]
@property
def intermediate_outputs(self) -> list[OutputParam]:
return [
OutputParam(
name="latents",
type_hint=torch.Tensor,
description="The initial packed image latents (B, image_seq_len, in_channels).",
),
OutputParam(name="image_seq_len", type_hint=int, description="Number of image tokens (grid_h * grid_w)."),
]
@torch.no_grad()
def __call__(self, components: Krea2ModularPipeline, state: PipelineState) -> PipelineState:
block_state = self.get_block_state(state)
device = components._execution_device
p = components.patch_size
num_channels_latents = components.transformer.config.in_channels // (p**2)
multiple = components.vae_scale_factor * components.patch_size
if block_state.height % multiple != 0 or block_state.width % multiple != 0:
rounded_height = ((block_state.height + multiple - 1) // multiple) * multiple
rounded_width = ((block_state.width + multiple - 1) // multiple) * multiple
logger.warning(
f"`height` and `width` must be multiples of {multiple}; rounding up from {block_state.height}x{block_state.width} to"
f" {rounded_height}x{rounded_width}."
)
block_state.height, block_state.width = rounded_height, rounded_width
latent_height = block_state.height // components.vae_scale_factor
latent_width = block_state.width // components.vae_scale_factor
if block_state.latents is not None:
block_state.latents = block_state.latents.to(device=device, dtype=block_state.dtype)
else:
latents = randn_tensor(
(block_state.batch_size, num_channels_latents, latent_height, latent_width),
generator=block_state.generator,
device=device,
dtype=block_state.dtype,
)
latents = latents.view(
block_state.batch_size, num_channels_latents, latent_height // p, p, latent_width // p, p
)
latents = latents.permute(0, 2, 4, 1, 3, 5)
block_state.latents = latents.reshape(
block_state.batch_size, (latent_height // p) * (latent_width // p), num_channels_latents * p * p
)
block_state.image_seq_len = block_state.latents.shape[1]
self.set_block_state(state, block_state)
return components, state
# auto_docstring
class Krea2SetTimestepsStep(ModularPipelineBlocks):
"""
Step that sets the Krea 2 flow-matching schedule on the scheduler: a linear sigma schedule with a resolution-aware
dynamic time shift `mu`.
Components:
scheduler (`FlowMatchEulerDiscreteScheduler`)
Inputs:
num_inference_steps (`int`, *optional*, defaults to 28):
The number of denoising steps.
sigmas (`list`, *optional*):
Custom sigma schedule (defaults to a linear ramp).
image_seq_len (`int`):
Number of image tokens, used to compute the resolution-aware shift.
Outputs:
timesteps (`Tensor`):
The denoising timesteps.
"""
model_name = "krea2"
@property
def description(self) -> str:
return (
"Step that sets the Krea 2 flow-matching schedule on the scheduler: a linear sigma schedule with a "
"resolution-aware dynamic time shift `mu`."
)
@property
def expected_components(self) -> list[ComponentSpec]:
return [ComponentSpec("scheduler", FlowMatchEulerDiscreteScheduler)]
@property
def inputs(self) -> list[InputParam]:
return [
InputParam.template("num_inference_steps", default=28),
InputParam(
name="sigmas", type_hint=list, description="Custom sigma schedule (defaults to a linear ramp)."
),
InputParam(
name="image_seq_len",
required=True,
type_hint=int,
description="Number of image tokens, used to compute the resolution-aware shift.",
),
]
@property
def intermediate_outputs(self) -> list[OutputParam]:
return [OutputParam(name="timesteps", type_hint=torch.Tensor, description="The denoising timesteps.")]
@torch.no_grad()
def __call__(self, components: Krea2ModularPipeline, state: PipelineState) -> PipelineState:
block_state = self.get_block_state(state)
device = components._execution_device
num_inference_steps = block_state.num_inference_steps
sigmas = block_state.sigmas
if sigmas is None:
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
else:
block_state.num_inference_steps = len(sigmas)
config = components.scheduler.config
mu = calculate_shift(
block_state.image_seq_len,
config.get("base_image_seq_len", 256),
config.get("max_image_seq_len", 6400),
config.get("base_shift", 0.5),
config.get("max_shift", 1.15),
)
components.scheduler.set_timesteps(sigmas=sigmas, mu=mu, device=device)
components.scheduler.set_begin_index(0)
block_state.timesteps = components.scheduler.timesteps
self.set_block_state(state, block_state)
return components, state
# auto_docstring
class Krea2TurboSetTimestepsStep(ModularPipelineBlocks):
"""
Step that sets the flow-matching schedule for the distilled Krea 2 turbo checkpoint on the scheduler: a linear
sigma schedule with the fixed time shift `mu=1.15` the checkpoint was distilled with.
Components:
scheduler (`FlowMatchEulerDiscreteScheduler`)
Inputs:
num_inference_steps (`int`, *optional*, defaults to 8):
The number of denoising steps.
sigmas (`list`, *optional*):
Custom sigma schedule (defaults to a linear ramp).
Outputs:
timesteps (`Tensor`):
The denoising timesteps.
"""
model_name = "krea2"
@property
def description(self) -> str:
return (
"Step that sets the flow-matching schedule for the distilled Krea 2 turbo checkpoint on the scheduler: a "
"linear sigma schedule with the fixed time shift `mu=1.15` the checkpoint was distilled with."
)
@property
def expected_components(self) -> list[ComponentSpec]:
return [ComponentSpec("scheduler", FlowMatchEulerDiscreteScheduler)]
@property
def inputs(self) -> list[InputParam]:
return [
InputParam.template("num_inference_steps", default=8),
InputParam(
name="sigmas", type_hint=list, description="Custom sigma schedule (defaults to a linear ramp)."
),
]
@property
def intermediate_outputs(self) -> list[OutputParam]:
return [OutputParam(name="timesteps", type_hint=torch.Tensor, description="The denoising timesteps.")]
@torch.no_grad()
def __call__(self, components: Krea2ModularPipeline, state: PipelineState) -> PipelineState:
block_state = self.get_block_state(state)
device = components._execution_device
num_inference_steps = block_state.num_inference_steps
sigmas = block_state.sigmas
if sigmas is None:
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
else:
block_state.num_inference_steps = len(sigmas)
components.scheduler.set_timesteps(sigmas=sigmas, mu=1.15, device=device)
components.scheduler.set_begin_index(0)
block_state.timesteps = components.scheduler.timesteps
self.set_block_state(state, block_state)
return components, state
# auto_docstring
class Krea2PreparePositionIdsStep(ModularPipelineBlocks):
"""
Step that builds the shared rotary position ids for the combined [text | image] sequence: text at the origin, image
tokens at their (0, h, w) latent-grid coordinates. Place after prepare_latents.
Inputs:
height (`int`, *optional*, defaults to 1024):
The height in pixels of the generated image.
width (`int`, *optional*, defaults to 1024):
The width in pixels of the generated image.
prompt_embeds (`Tensor`):
Batch-expanded text features (only text_seq_len is used).
Outputs:
position_ids (`Tensor`):
Shared rotary coordinates (text_seq_len + grid_h * grid_w, 3).
"""
model_name = "krea2"
@property
def description(self) -> str:
return (
"Step that builds the shared rotary position ids for the combined [text | image] sequence: text at the "
"origin, image tokens at their (0, h, w) latent-grid coordinates. Place after prepare_latents."
)
@property
def inputs(self) -> list[InputParam]:
return [
InputParam.template("height", default=1024),
InputParam.template("width", default=1024),
InputParam(
name="prompt_embeds",
required=True,
type_hint=torch.Tensor,
description="Batch-expanded text features (only text_seq_len is used).",
),
]
@property
def intermediate_outputs(self) -> list[OutputParam]:
return [
OutputParam(
name="position_ids",
type_hint=torch.Tensor,
description="Shared rotary coordinates (text_seq_len + grid_h * grid_w, 3).",
)
]
@staticmethod
# Copied from diffusers.pipelines.krea2.pipeline_krea2.Krea2Pipeline.prepare_position_ids
def prepare_position_ids(text_seq_len: int, grid_height: int, grid_width: int, device: torch.device):
"""Build the `(text_seq_len + grid_height * grid_width, 3)` rotary coordinates for the combined sequence:
text tokens sit at the origin, image tokens carry their `(0, h, w)` latent-grid coordinates."""
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)
return torch.cat([text_ids, image_ids], dim=0)
@torch.no_grad()
def __call__(self, components: Krea2ModularPipeline, state: PipelineState) -> PipelineState:
block_state = self.get_block_state(state)
device = components._execution_device
p = components.patch_size
grid_h = block_state.height // (components.vae_scale_factor * p)
grid_w = block_state.width // (components.vae_scale_factor * p)
text_seq_len = block_state.prompt_embeds.shape[1]
block_state.position_ids = self.prepare_position_ids(text_seq_len, grid_h, grid_w, device)
self.set_block_state(state, block_state)
return components, state
|