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(quantization): install the int8 cast notice filter without importing bitsandbytes

Alexander Eichhornf88a7b7c5931
diff --git a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py
index 826bd4083a..93b7340055 100644
--- a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py
+++ b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py
@@ -21,6 +21,7 @@ from invokeai.app.invocations.primitives import QwenImageConditioningOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.model_manager.load.model_cache.model_cache import MB, MODEL_LOAD_LOCK
from invokeai.backend.model_manager.load.model_util import calc_model_size_by_fs
+from invokeai.backend.quantization.bnb_cast_notice import silence_int8_cast_notice
from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes
from invokeai.backend.qwen2_5_vl.qwen2_5_vl_assets import (
load_bundled_qwen2_5_vl_preprocessor_config_dict,
@@ -412,9 +413,6 @@ class QwenImageTextEncoderInvocation(BaseInvocation):
bnb_4bit_quant_type="nf4",
)
else: # int8
- # Imported here: bitsandbytes is not installed on macOS, where the single-file path above still works.
- from invokeai.backend.quantization.bnb_llm_int8 import silence_int8_cast_notice
-
bnb_config = BitsAndBytesConfig(load_in_8bit=True)
silence_int8_cast_notice()
diff --git a/invokeai/backend/quantization/bnb_cast_notice.py b/invokeai/backend/quantization/bnb_cast_notice.py
new file mode 100644
index 0000000000..258e2b24fe
--- /dev/null
+++ b/invokeai/backend/quantization/bnb_cast_notice.py
@@ -0,0 +1,32 @@
+"""Silence bitsandbytes' per-matmul notice that LLM.int8 casts bf16 activations to fp16.
+
+Kept apart from `bnb_llm_int8` so it imports without bitsandbytes, which is not installed on macOS: callers that load
+an int8 model through transformers install the filter before bitsandbytes is ever imported.
+"""
+
+import logging
+import warnings
+
+_INT8_CAST_NOTICE = "MatMul8bitLt: inputs will be cast from"
+
+
+class _DropInt8CastNotice(logging.Filter):
+ def filter(self, record: logging.LogRecord) -> bool:
+ return not record.getMessage().startswith(_INT8_CAST_NOTICE)
+
+
+def silence_int8_cast_notice() -> None:
+ """Silence bitsandbytes' notice that LLM.int8 casts bf16 activations to fp16.
+
+ The int8 matmul kernel only takes fp16 activations, so for our bf16 encoders the cast is correct and intended, but
+ bitsandbytes reports it on *every* matmul of *every* layer: as a UserWarning up to 0.49, through the
+ `bitsandbytes.autograd._functions` logger from 0.50, which `warnings` filters do not reach. Idempotent.
+ """
+ warnings.filterwarnings(
+ "ignore",
+ message=r"MatMul8bitLt: inputs will be cast from .* to float16 during quantization",
+ category=UserWarning,
+ )
+ bnb_logger = logging.getLogger("bitsandbytes.autograd._functions")
+ if not any(isinstance(existing, _DropInt8CastNotice) for existing in bnb_logger.filters):
+ bnb_logger.addFilter(_DropInt8CastNotice())
diff --git a/invokeai/backend/quantization/bnb_llm_int8.py b/invokeai/backend/quantization/bnb_llm_int8.py
index 7ac726b8bc..b3d042e383 100644
--- a/invokeai/backend/quantization/bnb_llm_int8.py
+++ b/invokeai/backend/quantization/bnb_llm_int8.py
@@ -1,38 +1,12 @@
-import logging
-import warnings
-
import bitsandbytes as bnb
import torch
+from invokeai.backend.quantization.bnb_cast_notice import silence_int8_cast_notice
+
# This file contains utils for working with models that use bitsandbytes LLM.int8() quantization.
# The utils in this file are partially inspired by:
# https://github.com/Lightning-AI/pytorch-lightning/blob/1551a16b94f5234a4a78801098f64d0732ef5cb5/src/lightning/fabric/plugins/precision/bitsandbytes.py
-_INT8_CAST_NOTICE = "MatMul8bitLt: inputs will be cast from"
-
-
-class _DropInt8CastNotice(logging.Filter):
- def filter(self, record: logging.LogRecord) -> bool:
- return not record.getMessage().startswith(_INT8_CAST_NOTICE)
-
-
-def silence_int8_cast_notice() -> None:
- """Silence bitsandbytes' notice that LLM.int8 casts bf16 activations to fp16.
-
- The int8 matmul kernel only takes fp16 activations, so for our bf16 encoders the cast is correct and intended, but
- bitsandbytes reports it on *every* matmul of *every* layer: as a UserWarning up to 0.49, through the
- `bitsandbytes.autograd._functions` logger from 0.50, which `warnings` filters do not reach. Idempotent.
- """
- warnings.filterwarnings(
- "ignore",
- message=r"MatMul8bitLt: inputs will be cast from .* to float16 during quantization",
- category=UserWarning,
- )
- bnb_logger = logging.getLogger("bitsandbytes.autograd._functions")
- if not any(isinstance(existing, _DropInt8CastNotice) for existing in bnb_logger.filters):
- bnb_logger.addFilter(_DropInt8CastNotice())
-
-
silence_int8_cast_notice()
diff --git a/tests/backend/quantization/test_bnb_cast_notice.py b/tests/backend/quantization/test_bnb_cast_notice.py
new file mode 100644
index 0000000000..5e664692ba
--- /dev/null
+++ b/tests/backend/quantization/test_bnb_cast_notice.py
@@ -0,0 +1,28 @@
+"""`silence_int8_cast_notice`, which must work without bitsandbytes installed (macOS has none)."""
+
+import logging
+import warnings
+
+import torch
+
+from invokeai.backend.quantization.bnb_cast_notice import silence_int8_cast_notice
+
+_CAST_NOTICE = "MatMul8bitLt: inputs will be cast from torch.bfloat16 to float16 during quantization"
+
+
+def test_int8_cast_notice_is_silenced_as_a_warning_and_as_a_log_record(caplog):
+ """bitsandbytes up to 0.49 warns with `warnings`; from 0.50 it logs. Other notices from either path still show."""
+ bnb_logger = logging.getLogger("bitsandbytes.autograd._functions")
+ with warnings.catch_warnings(record=True) as caught, caplog.at_level(logging.WARNING, logger=bnb_logger.name):
+ warnings.simplefilter("always")
+ silence_int8_cast_notice()
+ silence_int8_cast_notice() # idempotent: one log filter, not two
+
+ warnings.warn(_CAST_NOTICE, UserWarning, stacklevel=1)
+ warnings.warn("an unrelated bitsandbytes warning", UserWarning, stacklevel=1)
+ bnb_logger.warning("MatMul8bitLt: inputs will be cast from %s to float16 during quantization", torch.bfloat16)
+ bnb_logger.warning("an unrelated bitsandbytes log record")
+
+ assert [str(w.message) for w in caught] == ["an unrelated bitsandbytes warning"]
+ assert [r.getMessage() for r in caplog.records] == ["an unrelated bitsandbytes log record"]
+ assert sum(type(f).__name__ == "_DropInt8CastNotice" for f in bnb_logger.filters) == 1
diff --git a/tests/backend/quantization/test_bnb_llm_int8.py b/tests/backend/quantization/test_bnb_llm_int8.py
index a559c961d9..a63db123eb 100644
--- a/tests/backend/quantization/test_bnb_llm_int8.py
+++ b/tests/backend/quantization/test_bnb_llm_int8.py
@@ -4,13 +4,13 @@ import warnings
import pytest
import torch
+from invokeai.backend.quantization.bnb_cast_notice import silence_int8_cast_notice
+
try:
- from invokeai.backend.quantization.bnb_llm_int8 import InvokeLinear8bitLt, silence_int8_cast_notice
+ from invokeai.backend.quantization.bnb_llm_int8 import InvokeLinear8bitLt
except ImportError:
pass
-_CAST_NOTICE = "MatMul8bitLt: inputs will be cast from torch.bfloat16 to float16 during quantization"
-
def test_invoke_linear_8bit_lt_quantization():
"""Test quantization with InvokeLinear8bitLt."""
@@ -90,25 +90,6 @@ def test_invoke_linear_8bit_lt_state_dict_roundtrip():
assert torch.allclose(y_quantized_1, y_quantized_2, atol=1e-5)
-def test_int8_cast_notice_is_silenced_as_a_warning_and_as_a_log_record(caplog):
- """bitsandbytes up to 0.49 warns with `warnings`; from 0.50 it logs. Other notices from either path still show."""
- pytest.importorskip("bitsandbytes")
- bnb_logger = logging.getLogger("bitsandbytes.autograd._functions")
- with warnings.catch_warnings(record=True) as caught, caplog.at_level(logging.WARNING, logger=bnb_logger.name):
- warnings.simplefilter("always")
- silence_int8_cast_notice()
- silence_int8_cast_notice() # idempotent: one log filter, not two
-
- warnings.warn(_CAST_NOTICE, UserWarning, stacklevel=1)
- warnings.warn("an unrelated bitsandbytes warning", UserWarning, stacklevel=1)
- bnb_logger.warning("MatMul8bitLt: inputs will be cast from %s to float16 during quantization", torch.bfloat16)
- bnb_logger.warning("an unrelated bitsandbytes log record")
-
- assert [str(w.message) for w in caught] == ["an unrelated bitsandbytes warning"]
- assert [r.getMessage() for r in caplog.records] == ["an unrelated bitsandbytes log record"]
- assert sum(type(f).__name__ == "_DropInt8CastNotice" for f in bnb_logger.filters) == 1
-
-
def test_a_bf16_int8_matmul_reports_no_cast_notice(caplog):
"""The installed bitsandbytes, not a stand-in: a renamed logger or message would show up here."""
if not torch.cuda.is_available():