Skip to content

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.

28.0 KB
Raw Blame
import math
from contextlib import ExitStack
from typing import Any, Callable, Optional, Tuple

import torch
import torchvision.transforms as tv_transforms
from diffusers.models.transformers.transformer_sd3 import SD3Transformer2DModel
from torchvision.transforms.functional import resize as tv_resize
from tqdm import tqdm

from invokeai.app.invocations.baseinvocation import BaseInvocation, invocation
from invokeai.app.invocations.constants import LATENT_SCALE_FACTOR
from invokeai.app.invocations.fields import (
    DenoiseMaskField,
    FieldDescriptions,
    Input,
    InputField,
    LatentsField,
    MetadataField,
    SD3ConditioningField,
    WithMetadata,
)
from invokeai.app.invocations.latent_noise import validate_noise_tensor_shape
from invokeai.app.invocations.metadata import (
    LatentsMetaOutput,
    build_denoise_metadata,
    serialize_lora_metadata,
)
from invokeai.app.invocations.model import TransformerField
from invokeai.app.invocations.text_encoder.sd3_text_encoder import SD3_T5_MAX_SEQ_LEN
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.flux.sampling_utils import clip_timestep_schedule_fractional
from invokeai.backend.model_manager.taxonomy import BaseModelType, SD3VariantType
from invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpec
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
from invokeai.backend.patches.layers.loha_layer import LoHALayer
from invokeai.backend.patches.layers.lokr_layer import LoKRLayer
from invokeai.backend.patches.layers.lora_layer import LoRALayer
from invokeai.backend.patches.lora_conversions.sd3_lora_constants import (
    SD3_LORA_TRANSFORMER_PREFIX,
    layer_delta_shape,
    sd3_variant_from_width,
)
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patching
from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtension
from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import SD3ConditioningInfo
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.fp8 import FP8_STORAGE_DTYPES

# How the sizes read in a message; the UI uses the same names.
_SD3_SIZES = {SD3VariantType.Medium: "SD 3 / 3.5 Medium", SD3VariantType.Large: "SD 3.5 Large"}

# What one sidecar-patched layer holds while it computes its residual -- a second copy of the layer's output, or for a
# LoKR/LoHA layer its full weight delta. Same margin as LTX-2 and ERNIE-Image.
_SIDECAR_TRANSIENT_BYTES = 1024**3


def _is_conv_factorization(layer: LoKRLayer | LoHALayer) -> bool:
    tensors = [v for v in vars(layer).values() if isinstance(v, torch.Tensor)]
    has_core = getattr(layer, "t1", None) is not None or getattr(layer, "t2", None) is not None
    return has_core or any(t.ndim > 2 for t in tensors)


def _squeezed_kernel(t: torch.Tensor) -> torch.Tensor | None:
    """A factor with only 1x1 kernel dimensions as the 2-D matrix it is, a plain factor as itself, else ``None``."""
    if t.ndim <= 2:
        return t
    return t.reshape(t.shape[0], t.shape[1]) if all(d == 1 for d in t.shape[2:]) else None


def _delta_fits(layer: BaseLayerPatch, weight: torch.Tensor) -> bool:
    """Whether the layer's weight delta can be applied to `weight`.

    Low-rank layers are compared by their factors' dimensions. A LoKR or LoHA delta is not built here (that costs a
    CPU matmul per layer on every run): its shape follows from its factors' shapes, and a low-rank pair's inner
    dimensions must agree. On a Linear target the delta must have exactly the weight's shape -- the patcher would
    reshape transposed factors with the same element count into a wrong delta without complaint. Factors with 1x1
    kernel dimensions count as the matrices they are; a real kernel or a Tucker core does not fit a Linear. On a
    convolution kernel (`pos_embed.proj`) 2-D factors over the folded kernel are decided by element count, and a
    factorization with kernel dimensions or a Tucker core is not checked. A LoHA's two factor pairs must give the
    same delta shape.
    """
    if isinstance(layer, LoRALayer):
        return layer.up.shape[0] == weight.shape[0] and layer.down.shape[1] == weight.shape[1]
    if not isinstance(layer, (LoKRLayer, LoHALayer)):
        return True
    is_conv = weight.ndim > 2
    if is_conv and _is_conv_factorization(layer):
        return True  # `pos_embed.proj`'s kernel: a factor with kernel dims or a Tucker core; no shape rule here
    if getattr(layer, "t1", None) is not None or getattr(layer, "t2", None) is not None:
        return False
    if isinstance(layer, LoKRLayer):
        names = ("w1", "w1_a", "w1_b", "w2", "w2_a", "w2_b")
        prefix = "lokr_"
    else:
        names = ("w1_a", "w1_b", "w2_a", "w2_b")
        prefix = "hada_"
    factors = {n: getattr(layer, n) for n in names if getattr(layer, n) is not None}
    squeezed = {n: _squeezed_kernel(t) for n, t in factors.items()}
    if any(t is None for t in squeezed.values()):
        return False
    for first in ("w1", "w2"):
        a, b = squeezed.get(f"{first}_a"), squeezed.get(f"{first}_b")
        if a is not None and b is not None and (a.ndim < 2 or b.ndim < 2 or a.shape[1] != b.shape[0]):
            return False
    values = {f"{prefix}{n}": t for n, t in squeezed.items()}
    if isinstance(layer, LoHALayer):
        w1, w2 = squeezed["w1_a"], squeezed["w2_a"]
        if (w2.shape[0], squeezed["w2_b"].shape[1]) != (w1.shape[0], squeezed["w1_b"].shape[1]):
            return False
    shape = layer_delta_shape(values)
    if shape is None:
        return True
    return shape[0] * shape[1] == weight.numel() if is_conv else shape == tuple(weight.shape)


@invocation(
    "sd3_denoise",
    title="Denoise - SD3",
    tags=["image", "sd3"],
    category="latents",
    version="1.4.0",
)
class SD3DenoiseInvocation(BaseInvocation, WithMetadata):
    """Run denoising process with a SD3 model."""

    # If latents is provided, this means we are doing image-to-image.
    latents: Optional[LatentsField] = InputField(
        default=None, description=FieldDescriptions.latents, input=Input.Connection
    )
    noise: Optional[LatentsField] = InputField(
        default=None, description=FieldDescriptions.noise, input=Input.Connection
    )
    # denoise_mask is used for image-to-image inpainting. Only the masked region is modified.
    denoise_mask: Optional[DenoiseMaskField] = InputField(
        default=None, description=FieldDescriptions.denoise_mask, input=Input.Connection
    )
    denoising_start: float = InputField(default=0.0, ge=0, le=1, description=FieldDescriptions.denoising_start)
    denoising_end: float = InputField(default=1.0, ge=0, le=1, description=FieldDescriptions.denoising_end)
    transformer: TransformerField = InputField(
        description=FieldDescriptions.sd3_model, input=Input.Connection, title="Transformer"
    )
    positive_conditioning: SD3ConditioningField = InputField(
        description=FieldDescriptions.positive_cond, input=Input.Connection
    )
    negative_conditioning: SD3ConditioningField = InputField(
        description=FieldDescriptions.negative_cond, input=Input.Connection
    )
    cfg_scale: float | list[float] = InputField(default=3.5, description=FieldDescriptions.cfg_scale, title="CFG Scale")
    width: int = InputField(default=1024, multiple_of=16, description="Width of the generated image.")
    height: int = InputField(default=1024, multiple_of=16, description="Height of the generated image.")
    steps: int = InputField(default=10, gt=0, description=FieldDescriptions.steps)
    seed: int = InputField(default=0, description="Randomness seed for reproducibility.")

    def _build_metadata(self) -> MetadataField:
        updates: dict[str, Any] = {
            "generation_mode": (
                "sd3_inpaint"
                if getattr(self, "denoise_mask", None) is not None
                else ("sd3_img2img" if getattr(self, "latents", None) is not None else "sd3_txt2img")
            ),
            "width": self.width,
            "height": self.height,
            "steps": self.steps,
            "cfg_scale": self.cfg_scale,
            "denoising_start": self.denoising_start,
            "denoising_end": self.denoising_end,
            "model": self.transformer.transformer,
        }
        updates["loras"] = serialize_lora_metadata(getattr(self.transformer, "loras", None))

        if (
            self.noise is not None
            and self.noise.seed is not None
            and (self.latents is None or getattr(self, "add_noise", True))
        ):
            updates["seed"] = self.noise.seed
        elif self.seed is not None:
            updates["seed"] = self.seed
        elif self.latents and self.latents.seed is not None:
            updates["seed"] = self.latents.seed

        return build_denoise_metadata(getattr(self, "metadata", None), updates)

    @torch.no_grad()
    def invoke(self, context: InvocationContext) -> LatentsMetaOutput:
        latents = self._run_diffusion(context)
        latents = latents.detach().to("cpu")

        name = context.tensors.save(tensor=latents)
        return LatentsMetaOutput.build(
            latents_name=name,
            latents=latents,
            seed=None,
            metadata=self._build_metadata(),
            width=self.width,
            height=self.height,
        )

    def _prep_inpaint_mask(self, context: InvocationContext, latents: torch.Tensor) -> torch.Tensor | None:
        """Prepare the inpaint mask.
        - Loads the mask
        - Resizes if necessary
        - Casts to same device/dtype as latents

        Args:
            context (InvocationContext): The invocation context, for loading the inpaint mask.
            latents (torch.Tensor): A latent image tensor. Used to determine the target shape, device, and dtype for the
                inpaint mask.

        Returns:
            torch.Tensor | None: Inpaint mask. Values of 0.0 represent the regions to be fully denoised, and 1.0
                represent the regions to be preserved.
        """
        if self.denoise_mask is None:
            return None
        mask = context.tensors.load(self.denoise_mask.mask_name)

        # The input denoise_mask contains values in [0, 1], where 0.0 represents the regions to be fully denoised, and
        # 1.0 represents the regions to be preserved.
        # We invert the mask so that the regions to be preserved are 0.0 and the regions to be denoised are 1.0.
        mask = 1.0 - mask

        _, _, latent_height, latent_width = latents.shape
        mask = tv_resize(
            img=mask,
            size=[latent_height, latent_width],
            interpolation=tv_transforms.InterpolationMode.BILINEAR,
            antialias=False,
        )

        mask = mask.to(device=latents.device, dtype=latents.dtype)
        return mask

    def _load_text_conditioning(
        self,
        context: InvocationContext,
        conditioning_name: str,
        joint_attention_dim: int,
        dtype: torch.dtype,
        device: torch.device,
    ) -> Tuple[torch.Tensor, torch.Tensor]:
        # Load the conditioning data.
        cond_data = context.conditioning.load(conditioning_name)
        assert len(cond_data.conditionings) == 1
        sd3_conditioning = cond_data.conditionings[0]
        assert isinstance(sd3_conditioning, SD3ConditioningInfo)
        sd3_conditioning = sd3_conditioning.to(dtype=dtype, device=device)

        t5_embeds = sd3_conditioning.t5_embeds
        if t5_embeds is None:
            t5_embeds = torch.zeros(
                (1, SD3_T5_MAX_SEQ_LEN, joint_attention_dim),
                device=device,
                dtype=dtype,
            )

        clip_prompt_embeds = torch.cat([sd3_conditioning.clip_l_embeds, sd3_conditioning.clip_g_embeds], dim=-1)
        clip_prompt_embeds = torch.nn.functional.pad(
            clip_prompt_embeds, (0, t5_embeds.shape[-1] - clip_prompt_embeds.shape[-1])
        )

        prompt_embeds = torch.cat([clip_prompt_embeds, t5_embeds], dim=-2)
        pooled_prompt_embeds = torch.cat(
            [sd3_conditioning.clip_l_pooled_embeds, sd3_conditioning.clip_g_pooled_embeds], dim=-1
        )

        return prompt_embeds, pooled_prompt_embeds

    def _get_noise(
        self,
        num_samples: int,
        num_channels_latents: int,
        height: int,
        width: int,
        dtype: torch.dtype,
        device: torch.device,
        seed: int,
    ) -> torch.Tensor:
        # We always generate noise on the same device and dtype then cast to ensure consistency across devices/dtypes.
        rand_device = "cpu"
        rand_dtype = TorchDevice.choose_noise_dtype(torch.float16)

        return torch.randn(
            num_samples,
            num_channels_latents,
            int(height) // LATENT_SCALE_FACTOR,
            int(width) // LATENT_SCALE_FACTOR,
            device=rand_device,
            dtype=rand_dtype,
            generator=torch.Generator(device=rand_device).manual_seed(seed),
        ).to(device=device, dtype=dtype)

    def _prepare_cfg_scale(self, num_timesteps: int) -> list[float]:
        """Prepare the CFG scale list.

        Args:
            num_timesteps (int): The number of timesteps in the scheduler. Could be different from num_steps depending
            on the scheduler used (e.g. higher order schedulers).

        Returns:
            list[float]: _description_
        """
        if isinstance(self.cfg_scale, float):
            cfg_scale = [self.cfg_scale] * num_timesteps
        elif isinstance(self.cfg_scale, list):
            assert len(self.cfg_scale) == num_timesteps
            cfg_scale = self.cfg_scale
        else:
            raise ValueError(f"Invalid CFG scale type: {type(self.cfg_scale)}")

        return cfg_scale

    def _run_diffusion(
        self,
        context: InvocationContext,
    ):
        inference_dtype = TorchDevice.choose_torch_dtype()
        device = TorchDevice.choose_torch_device()

        transformer_info = context.models.load(self.transformer.transformer)

        # Load/process the conditioning data.
        cfg_scales = [self.cfg_scale] if isinstance(self.cfg_scale, float) else self.cfg_scale
        any_cfg = self.negative_conditioning is not None and any(not math.isclose(s, 1.0) for s in cfg_scales)
        pos_prompt_embeds, pos_pooled_prompt_embeds = self._load_text_conditioning(
            context=context,
            conditioning_name=self.positive_conditioning.conditioning_name,
            joint_attention_dim=transformer_info.model.config.joint_attention_dim,
            dtype=inference_dtype,
            device=device,
        )
        if any_cfg:
            neg_prompt_embeds, neg_pooled_prompt_embeds = self._load_text_conditioning(
                context=context,
                conditioning_name=self.negative_conditioning.conditioning_name,
                joint_attention_dim=transformer_info.model.config.joint_attention_dim,
                dtype=inference_dtype,
                device=device,
            )
            # TODO(ryand): Support both sequential and batched CFG inference.
            prompt_embeds = torch.cat([neg_prompt_embeds, pos_prompt_embeds], dim=0)
            pooled_prompt_embeds = torch.cat([neg_pooled_prompt_embeds, pos_pooled_prompt_embeds], dim=0)
        else:
            prompt_embeds = pos_prompt_embeds
            pooled_prompt_embeds = pos_pooled_prompt_embeds

        # Prepare the timestep schedule.
        # We add an extra step to the end to account for the final timestep of 0.0.
        timesteps: list[float] = torch.linspace(1, 0, self.steps + 1).tolist()
        # Clip the timesteps schedule based on denoising_start and denoising_end.
        timesteps = clip_timestep_schedule_fractional(timesteps, self.denoising_start, self.denoising_end)
        total_steps = len(timesteps) - 1

        # Prepare the CFG scale list.
        cfg_scale = self._prepare_cfg_scale(total_steps)

        # Load the input latents, if provided.
        init_latents = context.tensors.load(self.latents.latents_name) if self.latents else None
        if init_latents is not None:
            init_latents = init_latents.to(device=device, dtype=inference_dtype)

        # Generate initial latent noise.
        num_channels_latents = transformer_info.model.config.in_channels
        assert isinstance(num_channels_latents, int)
        noise = self._prepare_noise_tensor(context, num_channels_latents, inference_dtype, device)

        # Prepare input latent image.
        if init_latents is not None:
            # Noise the init_latents by the appropriate amount for the first timestep.
            t_0 = timesteps[0]
            latents = t_0 * noise + (1.0 - t_0) * init_latents
        else:
            # init_latents are not provided, so we are not doing image-to-image (i.e. we are starting from pure noise).
            if self.denoising_start > 1e-5:
                raise ValueError("denoising_start should be 0 when initial latents are not provided.")
            latents = noise

        # If len(timesteps) == 1, then short-circuit. We are just noising the input latents, but not taking any
        # denoising steps.
        if len(timesteps) <= 1:
            return latents

        # Prepare inpaint extension.
        inpaint_mask = self._prep_inpaint_mask(context, latents)
        inpaint_extension: RectifiedFlowInpaintExtension | None = None
        if inpaint_mask is not None:
            assert init_latents is not None
            inpaint_extension = RectifiedFlowInpaintExtension(
                init_latents=init_latents,
                inpaint_mask=inpaint_mask,
                noise=noise,
            )

        step_callback = self._build_step_callback(context)

        # Loaded before the lock, so a LoRA that does not fit fails before the transformer moves, and the
        # reservation below can be sized from the patches.
        lora_patch_specs = self._materialize_lora_patches(context)
        self._raise_unless_loras_fit(context, transformer_info.model, lora_patch_specs)
        # A GGUF build's packed weights cannot be written to, so its LoRAs always go on the sidecar.
        force_sidecar = bool(lora_patch_specs) and requires_sidecar_patching(
            transformer_info.model, context.models.get_config(self.transformer.transformer).format
        )
        # The patcher also picks the sidecar on its own for fp8 weights (FP8 Storage), which cannot be added to.
        lora_on_device = force_sidecar or (
            bool(lora_patch_specs) and any(p.dtype in FP8_STORAGE_DTYPES for p in transformer_info.model.parameters())
        )
        # A GGUF build dequantizes each Linear per forward, a transient its resident size does not cover; zero for a
        # Diffusers build.
        dequant_bytes = peak_dequant_transient_bytes(transformer_info.model, inference_dtype)
        # This node has no activation estimate, so the cache floors its request at `device_working_mem_gb`, which then
        # stands in for the activations; without sidecar patches the dequantization copy is the whole request. Sidecar
        # patches stay on the device for the whole run, so they come on top of that floor rather than out of it,
        # with one layer's transients. For plain LoRA layers those follow each other: the base forward frees its
        # dequantized weight before `linear_lora_forward` runs, so the larger one is reserved. Any other patch (LoKR,
        # LoHA, a full layer) goes through `_aggregate_patch_parameters`, which dequantizes the weight again and holds
        # it beside the full delta it builds, so both are reserved. Patches merged into the weights leave nothing
        # resident.
        working_mem_bytes: Optional[int] = dequant_bytes or None
        if lora_on_device:
            floor = int(context.config.get().device_working_mem_gb * 2**30)
            lora_bytes = sum(spec[0].calc_size() for spec in lora_patch_specs)
            aggregates_with_weight = any(
                not isinstance(layer, LoRALayer)
                for spec in lora_patch_specs
                for key, layer in spec[0].layers.items()
                if key.startswith(SD3_LORA_TRANSFORMER_PREFIX)
            )
            transient = (
                _SIDECAR_TRANSIENT_BYTES + dequant_bytes
                if aggregates_with_weight
                else max(_SIDECAR_TRANSIENT_BYTES, dequant_bytes)
            )
            working_mem_bytes = floor + lora_bytes + transient

        with ExitStack() as exit_stack:
            (cached_weights, transformer) = exit_stack.enter_context(
                transformer_info.model_on_device(working_mem_bytes=working_mem_bytes)
            )
            assert isinstance(transformer, SD3Transformer2DModel)
            if lora_patch_specs:
                exit_stack.enter_context(
                    LayerPatcher.apply_smart_model_patches(
                        model=transformer,
                        patches=lora_patch_specs,
                        prefix=SD3_LORA_TRANSFORMER_PREFIX,
                        dtype=inference_dtype,
                        cached_weights=cached_weights,
                        force_sidecar_patching=force_sidecar,
                    )
                )

            # Inside the lock: a Tiny AutoEncoder preview loads its TAE only if it fits next to the locked model.
            step_callback(
                PipelineIntermediateState(
                    step=0,
                    order=1,
                    total_steps=total_steps,
                    timestep=int(timesteps[0]),
                    latents=latents,
                ),
            )

            # 6. Denoising loop
            for step_idx, (t_curr, t_prev) in tqdm(
                list(enumerate(zip(timesteps[:-1], timesteps[1:], strict=True))),
                desc=f"Denoising{TorchDevice.get_session_device_label()}",
            ):
                do_classifier_free_guidance = any_cfg and not math.isclose(cfg_scale[step_idx], 1.0)
                # Expand the latents if we are doing CFG.
                latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
                # Expand the timestep to match the latent model input.
                # Multiply by 1000 to match the default FlowMatchEulerDiscreteScheduler num_train_timesteps.
                timestep = torch.tensor([t_curr * 1000], device=device).expand(latent_model_input.shape[0])

                noise_pred = transformer(
                    hidden_states=latent_model_input,
                    timestep=timestep,
                    encoder_hidden_states=prompt_embeds if do_classifier_free_guidance else pos_prompt_embeds,
                    pooled_projections=(
                        pooled_prompt_embeds if do_classifier_free_guidance else pos_pooled_prompt_embeds
                    ),
                    joint_attention_kwargs=None,
                    return_dict=False,
                )[0]

                # Apply CFG.
                if do_classifier_free_guidance:
                    noise_pred_uncond, noise_pred_cond = noise_pred.chunk(2)
                    noise_pred = noise_pred_uncond + cfg_scale[step_idx] * (noise_pred_cond - noise_pred_uncond)

                # Compute the previous noisy sample x_t -> x_t-1.
                latents_dtype = latents.dtype
                latents = latents.to(dtype=torch.float32)
                latents = latents + (t_prev - t_curr) * noise_pred
                latents = latents.to(dtype=latents_dtype)

                if inpaint_extension is not None:
                    latents = inpaint_extension.merge_intermediate_latents_with_init_latents(latents, t_prev)

                step_callback(
                    PipelineIntermediateState(
                        step=step_idx + 1,
                        order=1,
                        total_steps=total_steps,
                        timestep=int(t_curr),
                        latents=latents,
                    ),
                )

        return latents

    def _materialize_lora_patches(self, context: InvocationContext) -> list[PatchSpec]:
        """Load every LoRA on the transformer field into (patch, weight, cache-pin) specs."""
        patch_specs: list[PatchSpec] = []
        for lora in self.transformer.loras:
            lora_info = context.models.load(lora.lora)
            if not isinstance(lora_info.model, ModelPatchRaw):
                raise TypeError(
                    f"Expected ModelPatchRaw for LoRA '{lora.lora.key}', got {type(lora_info.model).__name__}."
                )
            patch_specs.append((lora_info.model, lora.weight, lora_info.model_in_ram()))
        return patch_specs

    def _raise_unless_loras_fit(
        self, context: InvocationContext, transformer: SD3Transformer2DModel, patch_specs: list[PatchSpec]
    ) -> None:
        """Refuse a LoRA trained for another SD 3 size, or for modules this model does not have.

        Medium and Large name the same modules at different widths, so the patcher would only log and skip every
        layer; and a LoRA for SD 3.5 Medium's dual attention (`attn2`) targets modules SD 3 Medium lacks.
        """
        if not patch_specs:
            return
        width = int(transformer.config.num_attention_heads) * int(transformer.config.attention_head_dim)
        model_variant = sd3_variant_from_width(width)
        for lora, spec in zip(self.transformer.loras, patch_specs, strict=True):
            name = lora.lora.name or lora.lora.key
            lora_variant = getattr(context.models.get_config(lora.lora), "variant", None)
            if lora_variant is not None and model_variant is not None and lora_variant is not model_variant:
                # A hand-built workflow can route another base's LoRA here, with a variant SD 3 has no name for.
                trained_for = _SD3_SIZES.get(lora_variant, getattr(lora_variant, "value", lora_variant))
                raise ValueError(
                    f"LoRA '{name}' was trained for {trained_for} and does not fit this "
                    f"{_SD3_SIZES[model_variant]} model."
                )
            for key, layer in spec[0].layers.items():
                if not key.startswith(SD3_LORA_TRANSFORMER_PREFIX):
                    continue
                path = key.removeprefix(SD3_LORA_TRANSFORMER_PREFIX)
                try:
                    module = transformer.get_submodule(path)
                except AttributeError:
                    hint = " (it was trained for SD 3.5 Medium's dual attention)" if ".attn2." in path else ""
                    raise ValueError(f"LoRA '{name}' patches `{path}`, which this SD 3 model does not have{hint}.")
                if not _delta_fits(layer, module.weight):
                    other_size = (
                        " It was trained for another SD 3 size."
                        if lora_variant is None or lora_variant is not model_variant
                        else " It was trained for a different SD 3 checkpoint layout."
                    )
                    raise ValueError(
                        f"LoRA '{name}' does not fit this SD 3 model: `{path}` is {tuple(module.weight.shape)} here."
                        + other_size
                    )

    def _prepare_noise_tensor(
        self, context: InvocationContext, num_channels_latents: int, inference_dtype: torch.dtype, device: torch.device
    ) -> torch.Tensor:
        if self.noise is not None:
            noise = context.tensors.load(self.noise.latents_name).to(device=device, dtype=inference_dtype)
            validate_noise_tensor_shape(noise, "SD3", self.width, self.height)
            return noise

        return self._get_noise(
            num_samples=1,
            num_channels_latents=num_channels_latents,
            height=self.height,
            width=self.width,
            dtype=inference_dtype,
            device=device,
            seed=self.seed,
        )

    def _build_step_callback(self, context: InvocationContext) -> Callable[[PipelineIntermediateState], None]:
        def step_callback(state: PipelineIntermediateState) -> None:
            context.util.sd_step_callback(state, BaseModelType.StableDiffusion3)

        return step_callback