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.

fix(lora): sidecar-patch fp8 weights to avoid float8 add crash (#9246)

Lincoln Stein72cee9f75bc6
diff --git a/invokeai/backend/patches/layer_patcher.py b/invokeai/backend/patches/layer_patcher.py
index 8ad3921337..fbfcd04de2 100644
--- a/invokeai/backend/patches/layer_patcher.py
+++ b/invokeai/backend/patches/layer_patcher.py
@@ -121,10 +121,18 @@ class LayerPatcher:
use_sidecar_patching = False
if force_direct_patching and force_sidecar_patching:
raise ValueError("Cannot force both direct and sidecar patching.")
- elif force_direct_patching:
- use_sidecar_patching = False
elif force_sidecar_patching:
use_sidecar_patching = True
+ elif LayerPatcher._is_any_part_of_layer_fp8(module):
+ # FP8 weights (e.g. a model loaded with fp8_storage layerwise casting) cannot be
+ # directly patched: _apply_model_layer_patch does an in-place add on the model weight,
+ # and CUDA has no add kernel for float8 ("ufunc_add_CUDA not implemented for
+ # Float8_e4m3fn"). Sidecar patching dequantizes to the compute dtype before any math,
+ # so it works regardless of the storage dtype. This takes precedence over
+ # force_direct_patching, since direct patching is simply not possible on fp8 weights.
+ use_sidecar_patching = True
+ elif force_direct_patching:
+ use_sidecar_patching = False
elif module.get_num_patches() > 0:
use_sidecar_patching = True
elif LayerPatcher._is_any_part_of_layer_on_cpu(module):
@@ -152,6 +160,14 @@ class LayerPatcher:
def _is_any_part_of_layer_on_cpu(layer: torch.nn.Module) -> bool:
return any(p.device.type == "cpu" for p in layer.parameters())
+ # FP8 storage dtypes. Direct patching does in-place arithmetic on the model weights, which has no
+ # CUDA kernel for these dtypes, so a layer with fp8 weights must be patched via the sidecar wrapper.
+ _FP8_DTYPES = (torch.float8_e4m3fn, torch.float8_e5m2)
+
+ @staticmethod
+ def _is_any_part_of_layer_fp8(layer: torch.nn.Module) -> bool:
+ return any(p.dtype in LayerPatcher._FP8_DTYPES for p in layer.parameters())
+
@staticmethod
@torch.no_grad()
def _apply_model_layer_patch(
diff --git a/tests/app/util/test_step_callback.py b/tests/app/util/test_step_callback.py
index bada75f7ec..3235d4d469 100644
--- a/tests/app/util/test_step_callback.py
+++ b/tests/app/util/test_step_callback.py
@@ -88,7 +88,7 @@ class TestSampleToLowresEstimatedImage:
assert image.size == (2, 2)
# All pixels should be identical (uniform zero input)
- pixels = list(image.get_flattened_data())
+ pixels = [image.getpixel((x, y)) for y in range(image.height) for x in range(image.width)]
assert all(p == pixels[0] for p in pixels)
# With zero input, result = bias, scaled: ((bias + 1) / 2) * 255
diff --git a/tests/backend/patches/test_layer_patcher.py b/tests/backend/patches/test_layer_patcher.py
index 84741fc60a..76712b9219 100644
--- a/tests/backend/patches/test_layer_patcher.py
+++ b/tests/backend/patches/test_layer_patcher.py
@@ -311,3 +311,47 @@ def test_apply_smart_model_patches_force_sidecar_and_direct_patching():
force_sidecar_patching=True,
):
pass
+
+
+def test_apply_smart_model_patches_fp8_weights_force_sidecar():
+ """Regression test: a module whose weights are stored in float8 (e.g. from fp8_storage layerwise
+ casting) must be sidecar-patched, even when direct patching is explicitly requested. Direct patching
+ does an in-place add on the model weight, which has no CUDA add kernel for float8 and raises
+ 'ufunc_add_CUDA not implemented for Float8_e4m3fn'.
+ """
+ linear_in_features = 4
+ linear_out_features = 8
+ lora_rank = 2
+ # Build the model, then cast its weights to fp8 to mimic fp8_storage layerwise casting.
+ model = DummyModuleWithOneLayer(linear_in_features, linear_out_features, device="cpu", dtype=torch.bfloat16)
+ model.linear_layer_1.weight.data = model.linear_layer_1.weight.data.to(torch.float8_e4m3fn)
+ model.linear_layer_1.bias.data = model.linear_layer_1.bias.data.to(torch.float8_e4m3fn)
+ apply_custom_layers_to_model(model)
+
+ assert LayerPatcher._is_any_part_of_layer_fp8(model.linear_layer_1)
+
+ lora_layers = {
+ "linear_layer_1": LoRALayer.from_state_dict_values(
+ values={
+ "lora_down.weight": torch.ones((lora_rank, linear_in_features), device="cpu", dtype=torch.bfloat16),
+ "lora_up.weight": torch.ones((linear_out_features, lora_rank), device="cpu", dtype=torch.bfloat16),
+ },
+ )
+ }
+ lora = ModelPatchRaw(lora_layers)
+
+ # force_direct_patching=True would crash on fp8 weights if it were honored; the fp8 guard must
+ # override it and route to sidecar patching instead.
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(lora, 0.5)],
+ prefix="",
+ dtype=torch.bfloat16,
+ force_direct_patching=True,
+ ):
+ # A sidecar patch was added to the module rather than the weight being modified in place.
+ assert model.linear_layer_1.get_num_patches() == 1
+
+ # After exiting the context, the sidecar patch is cleared.
+ assert model.linear_layer_1.get_num_patches() == 0