Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
"""Sampling/packing utilities for Krea-2 (Krea2Pipeline) inference.
InvokeAI hand-writes its own denoise loop for Qwen-family models rather than calling the
diffusers pipeline ``__call__``. These helpers replicate the Krea-2 sampling math so the
``Krea2Transformer2DModel`` (loaded from diffusers) can be driven directly.
Reference: ``diffusers/pipelines/krea2/pipeline_krea2.py`` (diffusers main / 0.39.0.dev0).
"""
from typing import List, Sequence
import numpy as np
import torch
# Krea-2 packs latents into 2x2 patches; the VAE (AutoencoderKLQwenImage) is f8.
PATCH_SIZE = 2
VAE_SCALE_FACTOR = 8
# Hidden-state layers tapped from the Qwen3-VL text encoder (model_index.json
# text_encoder_select_layers). Stacked per token into prompt_embeds (B, seq, 12, hidden).
KREA2_SELECT_LAYERS = (2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35)
# Text template constants (diffusers Krea2Pipeline.get_text_hidden_states).
KREA2_MAX_SEQ_LEN = 512
KREA2_START_IDX = 34 # drop the system-prompt prefix tokens
KREA2_NUM_SUFFIX_TOKENS = 5
# The Raw checkpoint's scheduler_config.json, for checkpoints that ship none (see `load_scheduler`). Its shift fit ends
# at 6400 tokens, 1280x1280 of area, and is held there: extrapolated, mu would be 2.2 at 2048x2048, which puts about
# half of 28 steps above sigma 0.9, and 7.4 at 4096x4096, which puts all of them there, so an img2img start would have
# no step near the sigma it asks for. Held, Raw ends at Turbo's fixed mu, which ComfyUI also uses for Krea-2 at every
# size; diffusers' `Krea2Pipeline` extrapolates. The scheduler applies the exponential time shift to the mu it is
# handed, so Raw's mu goes to `set_timesteps` as it is.
KREA2_SCHEDULER_CONFIG = {
"use_dynamic_shifting": True,
"base_shift": 0.5,
"max_shift": 1.15,
"base_image_seq_len": 256,
"max_image_seq_len": 6400,
"num_train_timesteps": 1000,
"time_shift_type": "exponential",
}
# Fixed timestep shift for the distilled (Turbo) checkpoint.
KREA2_DISTILLED_MU = 1.15
def pack_latents(latents: torch.Tensor, batch_size: int, num_channels: int, height: int, width: int) -> torch.Tensor:
"""Pack 4D latents (B, C, H, W) into 2x2-patched 3D (B, H/2*W/2, C*4).
Identical to the Qwen-Image / Krea-2 ``_pack_latents`` (patch_size=2).
"""
p = PATCH_SIZE
latents = latents.view(batch_size, num_channels, height // p, p, width // p, p)
latents = latents.permute(0, 2, 4, 1, 3, 5)
latents = latents.reshape(batch_size, (height // p) * (width // p), num_channels * p * p)
return latents
def unpack_latents(latents: torch.Tensor, height: int, width: int) -> torch.Tensor:
"""Unpack 3D patched latents (B, seq, C*4) back to 4D (B, C, H, W).
``height``/``width`` are in latent space (i.e. pixels // vae_scale_factor).
"""
p = PATCH_SIZE
batch_size, _num_patches, channels = latents.shape
h = p * (height // p)
w = p * (width // p)
latents = latents.view(batch_size, h // p, w // p, channels // (p * p), p, p)
latents = latents.permute(0, 3, 1, 4, 2, 5)
latents = latents.reshape(batch_size, channels // (p * p), h, w)
return latents
def _grid_position_ids(index: int, grid_height: int, grid_width: int, device: torch.device) -> torch.Tensor:
"""(grid_h*grid_w, 3) rotary coordinates (index, h, w) of one latent grid, row-major."""
ids = torch.zeros(grid_height, grid_width, 3, device=device)
ids[..., 0] = index
ids[..., 1] = torch.arange(grid_height, device=device)[:, None]
ids[..., 2] = torch.arange(grid_width, device=device)[None, :]
return ids.reshape(grid_height * grid_width, 3)
def prepare_position_ids(text_seq_len: int, grid_height: int, grid_width: int, device: torch.device) -> torch.Tensor:
"""Build the (text_seq_len + grid_h*grid_w, 3) rotary coordinates.
Text tokens sit at the origin (0, 0, 0); image tokens carry their (0, h, w) latent-grid
coordinates. Matches diffusers ``Krea2Pipeline.prepare_position_ids``.
"""
text_ids = torch.zeros(text_seq_len, 3, device=device)
return torch.cat([text_ids, _grid_position_ids(0, grid_height, grid_width, device)], dim=0)
def prepare_reference_position_ids(reference_grids: Sequence[tuple[int, int]], device: torch.device) -> torch.Tensor:
"""Rotary coordinates of the reference tokens alone: reference ``i`` (1-based) carries ``(i, h, w)`` over its
own ``(grid_h, grid_w)``, starting from 0."""
reference_ids = [
_grid_position_ids(index, ref_height, ref_width, device)
for index, (ref_height, ref_width) in enumerate(reference_grids, start=1)
]
return torch.cat(reference_ids, dim=0) if reference_ids else torch.zeros(0, 3, device=device)
def prepare_position_ids_with_references(
text_seq_len: int,
grid_height: int,
grid_width: int,
reference_grids: Sequence[tuple[int, int]],
device: torch.device,
) -> torch.Tensor:
"""Rotary coordinates for ``[text | target | reference 1 | reference 2 | ...]``.
Text and target are laid out as in ``prepare_position_ids``. Reference ``i`` (1-based) carries
``(i, h, w)`` over its own ``(grid_h, grid_w)``, starting from 0: the first axis is what tells the
transformer the reference tokens apart from the target and from each other. This is the layout the
ai-toolkit edit LoRAs were trained with (ComfyUI's "index_timestep_zero" reference method).
"""
return torch.cat(
[
prepare_position_ids(text_seq_len, grid_height, grid_width, device),
prepare_reference_position_ids(reference_grids, device),
],
dim=0,
)
def build_sigmas(steps: int) -> List[float]:
"""Krea-2 sigma schedule: linspace(1.0, 1/steps, steps)."""
return np.linspace(1.0, 1.0 / steps, steps).tolist()