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(nodes): blend bfloat16 and float16 latents in Blend Latents (#10286)

Mohammad Hijjawicf979e3c6ada
diff --git a/invokeai/app/invocations/blend_latents.py b/invokeai/app/invocations/blend_latents.py
index aeda33ea97..fe2c2a544a 100644
--- a/invokeai/app/invocations/blend_latents.py
+++ b/invokeai/app/invocations/blend_latents.py
@@ -33,12 +33,15 @@ def slerp(
v2 (np.ndarray): Interpolation vector between v0 and v1
"""
inputs_are_torch = False
+ dtype = None
+ # Interpolate in float32: numpy has no bfloat16, and a float16 norm overflows for a full-size latent.
if not isinstance(v0, np.ndarray):
inputs_are_torch = True
- v0 = v0.detach().cpu().numpy()
+ dtype = v0.dtype
+ v0 = v0.detach().cpu().float().numpy()
if not isinstance(v1, np.ndarray):
inputs_are_torch = True
- v1 = v1.detach().cpu().numpy()
+ v1 = v1.detach().cpu().float().numpy()
dot = np.sum(v0 * v1 / (np.linalg.norm(v0) * np.linalg.norm(v1)))
if np.abs(dot) > DOT_THRESHOLD:
@@ -53,7 +56,7 @@ def slerp(
v2 = s0 * v0 + s1 * v1
if inputs_are_torch:
- v2 = torch.from_numpy(v2).to(device)
+ v2 = torch.from_numpy(v2).to(device=device, dtype=dtype)
return v2
@@ -63,7 +66,7 @@ def slerp(
title="Blend Latents",
tags=["latents", "blend", "mask"],
category="latents",
- version="1.1.0",
+ version="1.1.1",
)
class BlendLatentsInvocation(BaseInvocation):
"""Blend two latents using a given alpha. If a mask is provided, the second latents will be masked before blending.
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index 9fdfce1a30..d08dbc4d5b 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -23347,7 +23347,7 @@
"tags": ["latents", "blend", "mask"],
"title": "Blend Latents",
"type": "object",
- "version": "1.1.0",
+ "version": "1.1.1",
"output": {
"$ref": "#/components/schemas/LatentsOutput"
}
diff --git a/tests/app/invocations/test_blend_latents.py b/tests/app/invocations/test_blend_latents.py
new file mode 100644
index 0000000000..630daca889
--- /dev/null
+++ b/tests/app/invocations/test_blend_latents.py
@@ -0,0 +1,43 @@
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+
+from invokeai.app.invocations.blend_latents import BlendLatentsInvocation
+from invokeai.app.invocations.fields import LatentsField
+
+
+def _blend(latents_a: torch.Tensor, latents_b: torch.Tensor, alpha: float) -> torch.Tensor:
+ context = MagicMock()
+ context.tensors.load.side_effect = {"a": latents_a, "b": latents_b}.__getitem__
+ context.tensors.save.return_value = "blended"
+
+ invocation = BlendLatentsInvocation(
+ latents_a=LatentsField(latents_name="a"), latents_b=LatentsField(latents_name="b"), alpha=alpha
+ )
+ invocation.invoke(context)
+
+ return context.tensors.save.call_args.kwargs["tensor"]
+
+
[email protected]("dtype", [torch.float32, torch.float16, torch.bfloat16])
+def test_blend_latents_halfway_between_orthogonal_latents(dtype: torch.dtype):
+ # Two orthogonal latents of equal norm: halfway along the arc is (a + b) * sin(pi/4) / sin(pi/2).
+ checkerboard = (torch.arange(4 * 8 * 8).reshape(1, 4, 8, 8) % 2).to(torch.float32)
+ latents_a = checkerboard.to(dtype)
+ latents_b = (1 - checkerboard).to(dtype)
+
+ blended = _blend(latents_a, latents_b, alpha=0.5)
+
+ assert blended.dtype == dtype
+ torch.testing.assert_close(blended.float(), torch.full_like(checkerboard, 0.5**0.5), atol=1e-2, rtol=0)
+
+
+def test_blend_latents_keeps_identical_large_half_precision_latents():
+ # A 1024x1024 SD latent has 65,536 values, so its squared norm overflows float16 (max 65,504).
+ latents = torch.full((1, 4, 128, 128), 1.5, dtype=torch.float16)
+
+ blended = _blend(latents, latents.clone(), alpha=0.5)
+
+ assert blended.dtype == torch.float16
+ torch.testing.assert_close(blended, latents)