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): silence the int8 cast notice bitsandbytes 0.50 logs on every matmul

Alexander Eichhorn83bda7fdfb43
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 768f413e0e..826bd4083a 100644
--- a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py
+++ b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py
@@ -395,8 +395,6 @@ class QwenImageTextEncoderInvocation(BaseInvocation):
layers to the CPU, which BnB int8 refuses with "Some modules are dispatched on
the CPU or the disk" (issue #9147).
"""
- import warnings
-
from transformers import BitsAndBytesConfig, Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration
encoder_config = context.models.get_config(self.qwen_vl_encoder.text_encoder)
@@ -414,7 +412,11 @@ 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()
# Load onto this worker's execution device, never `device_map="auto"`: "auto" sizes its plan from whatever
# VRAM is free *right now* and quietly spills to the CPU when the cached models fill the card, and it shards
@@ -464,9 +466,7 @@ class QwenImageTextEncoderInvocation(BaseInvocation):
model_config = Qwen2_5_VLConfig.from_pretrained(str(encoder_path), local_files_only=True)
state_dict = _read_checkpoint(encoder_path)
- with MODEL_LOAD_LOCK.write_lock(), warnings.catch_warnings():
- # BnB int8 internally casts bfloat16→float16; the warning is harmless
- warnings.filterwarnings("ignore", message="MatMul8bitLt.*cast.*float16")
+ with MODEL_LOAD_LOCK.write_lock():
text_encoder = Qwen2_5_VLForConditionalGeneration.from_pretrained(
None if state_dict is not None else str(encoder_path),
config=model_config,
diff --git a/invokeai/backend/quantization/bnb_llm_int8.py b/invokeai/backend/quantization/bnb_llm_int8.py
index 52203800c8..7ac726b8bc 100644
--- a/invokeai/backend/quantization/bnb_llm_int8.py
+++ b/invokeai/backend/quantization/bnb_llm_int8.py
@@ -1,3 +1,4 @@
+import logging
import warnings
import bitsandbytes as bnb
@@ -7,15 +8,32 @@ import torch
# 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
-# bitsandbytes' LLM.int8 matmul kernel only supports fp16 activations. Our compute dtype for the
-# (T5) encoder is bf16, so bitsandbytes casts bf16->fp16 internally and emits this UserWarning on
-# *every* matmul of *every* layer. The cast is correct and intended for LLM.int8, so silence the
-# warning here (once, at import) to avoid flooding the logs on each text-encode.
-warnings.filterwarnings(
- "ignore",
- message=r"MatMul8bitLt: inputs will be cast from .* to float16 during quantization",
- category=UserWarning,
-)
+_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()
# NOTE(ryand): All of the custom state_dict manipulation logic in this file is pretty hacky. This could be made much
diff --git a/tests/backend/quantization/test_bnb_llm_int8.py b/tests/backend/quantization/test_bnb_llm_int8.py
index 481b809d03..a559c961d9 100644
--- a/tests/backend/quantization/test_bnb_llm_int8.py
+++ b/tests/backend/quantization/test_bnb_llm_int8.py
@@ -1,11 +1,16 @@
+import logging
+import warnings
+
import pytest
import torch
try:
- from invokeai.backend.quantization.bnb_llm_int8 import InvokeLinear8bitLt
+ from invokeai.backend.quantization.bnb_llm_int8 import InvokeLinear8bitLt, silence_int8_cast_notice
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."""
@@ -83,3 +88,40 @@ def test_invoke_linear_8bit_lt_state_dict_roundtrip():
# Assert that the inference results are the same.
assert torch.allclose(y, y_quantized_1.to("cpu"), atol=0.05)
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():
+ pytest.skip("CUDA is not available")
+ layer = InvokeLinear8bitLt(input_features=32, output_features=64, has_fp16_weights=False)
+ layer.load_state_dict(torch.nn.Linear(32, 64).state_dict())
+ layer.to("cuda")
+
+ with warnings.catch_warnings(record=True) as caught, caplog.at_level(logging.WARNING):
+ warnings.simplefilter("always")
+ silence_int8_cast_notice()
+ layer(torch.randn(4, 32, dtype=torch.bfloat16, device="cuda"))
+ layer(torch.randn(4, 32, dtype=torch.bfloat16, device="cuda"))
+
+ assert not [w for w in caught if "MatMul8bitLt" in str(w.message)]
+ assert not [r for r in caplog.records if "MatMul8bitLt" in r.getMessage()]