transformers - ✅(Solved) Fix [Gemma4] torch.finfo() TypeError on uint8 weights in audio modules during 4-bit (NF4) inference [1 pull requests, 1 comments, 2 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
huggingface/transformers#45672Fetched 2026-04-29 06:11:28
View on GitHub
Comments
1
Participants
2
Timeline
5
Reactions
0
Timeline (top)
cross-referenced ×2commented ×1mentioned ×1subscribed ×1

Error Message

TypeError: torch.finfo() requires a floating point input type. Use torch.iinfo to handle 'torch.uint8'

Root Cause

Gemma4AudioFeedForward, Gemma4AudioLightConv1d, and Gemma4AudioLayer perform gradient clipping via:

weight.data.clamp_(-torch.finfo(weight.dtype).max, torch.finfo(weight.dtype).max)

When loaded with 4-bit quantization, weight.dtype is torch.uint8 (bitsandbytes internal storage format). torch.finfo() does not accept integer types → crash.

Fix Action

Fixed

PR fix notes

PR #45683: Exclude audio modules from conversion process

Description (problem / solution / changelog)

Add logic to exclude audio modules from conversion to prevent uint8 crash in multimodal models.

As discussed in the issue, this prevents the torch.finfo() TypeError on uint8 weights during 4-bit inference for multimodal models like Gemma 4, and preserves audio encoder fidelity.

What does this PR do?

<!-- Congratulations! You've made it this far! You're not quite done yet though. Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution. Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change. Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost. --> <!-- Remove if not applicable -->

Fixes #45672, Fixes #45674

Code Agent Policy

The Transformers repo is currently being overwhelmed by a large number of PRs and issue comments written by code agents. We are currently bottlenecked by our ability to review and respond to them. As a result, we ask that new users do not submit pure code agent PRs at this time. You may use code agents in drafting or to help you diagnose issues. We'd also ask autonomous "OpenClaw"-like agents not to open any PRs or issues for the moment.

PRs that appear to be fully agent-written will probably be closed without review, and we may block users who do this repeatedly or maliciously.

This is a rapidly-evolving situation that's causing significant shockwaves in the open-source community. As a result, this policy is likely to be updated regularly in the near future. For more information, please read CONTRIBUTING.md.

  • I confirm that this is not a pure code agent PR.

Before submitting

  • This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
  • Did you read the contributor guideline, Pull Request section?
  • Was this discussed/approved via a Github issue or the forum? Please add a link to it if that's the case.
  • Did you make sure to update the documentation with your changes? Here are the documentation guidelines, and here are tips on formatting docstrings.
  • Did you write any new necessary tests?

Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag members/contributors who may be interested in your PR.

<!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @ If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**. Please tag fewer than 3 people. Models: - text models: @ArthurZucker @Cyrilvallez - vision models: @yonigozlan @molbap - audio models: @eustlb @ebezzam @vasqu - multimodal models: @zucchini-nlp - graph models: @clefourrier Library: - generate: @zucchini-nlp (visual-language models) or @gante (all others) - continuous batching: @remi-or @ArthurZucker @McPatate - pipelines: @Rocketknight1 - tokenizers: @ArthurZucker and @itazap - trainer: @SunMarc - attention: @vasqu @ArthurZucker @CyrilVallez - model loading (from pretrained, etc): @CyrilVallez - distributed: @3outeille @ArthurZucker - CIs: @ydshieh Integrations: - ray/raytune: @richardliaw, @amogkam - Big Model Inference: @SunMarc - quantization: @SunMarc - kernels: @drbh - peft: @BenjaminBossan @githubnemo Devices/Backends: - AMD ROCm: @ivarflakstad - Intel XPU: @IlyasMoutawwakil - Ascend NPU: @ivarflakstad Documentation: @stevhliu Research projects are not maintained and should be taken as is. -->

Changed files

  • src/transformers/quantizers/base.py (modified, +6/-0)

Code Example

TypeError: torch.finfo() requires a floating point input type.
Use torch.iinfo to handle 'torch.uint8'

---

weight.data.clamp_(-torch.finfo(weight.dtype).max, torch.finfo(weight.dtype).max)

---

import torch
from transformers import AutoModelForImageTextToText, AutoProcessor, BitsAndBytesConfig

bnb_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16)
model = AutoModelForImageTextToText.from_pretrained(
    "google/gemma-4-e2b-it",
    quantization_config=bnb_config,
    device_map="auto",
)
processor = AutoProcessor.from_pretrained("google/gemma-4-e2b-it")

messages = [{"role": "user", "content": [
    {"type": "audio", "audio": "path/to/any.wav"},
    {"type": "text", "text": "Transcribe."},
]}]
inputs = processor.apply_chat_template(
    messages, tokenize=True, add_generation_prompt=True,
    return_dict=True, return_tensors="pt"
).to(model.device, dtype=torch.bfloat16)

model.generate(**inputs, max_new_tokens=50)  # ← crashes here

---

def _safe_finfo_max(dtype: torch.dtype) -> float:
    """Falls back to bfloat16 for non-float dtypes (e.g. uint8 from bitsandbytes 4-bit)."""
    if dtype.is_floating_point:
        return torch.finfo(dtype).max
    return torch.finfo(torch.bfloat16).max

---

# Before
weight.data.clamp_(-torch.finfo(weight.dtype).max, torch.finfo(weight.dtype).max)

# After
weight.data.clamp_(-_safe_finfo_max(weight.dtype), _safe_finfo_max(weight.dtype))
RAW_BUFFERClick to expand / collapse

Environment

  • transformers: 5.5.4
  • bitsandbytes: 0.49.2
  • torch: 2.11.0+cu126
  • CUDA: 12.6
  • OS: Windows 11
  • GPU: NVIDIA RTX 3090

Bug Description

When running google/gemma-4-e2b-it with BitsAndBytesConfig(load_in_4bit=True), the forward pass crashes immediately with:

TypeError: torch.finfo() requires a floating point input type.
Use torch.iinfo to handle 'torch.uint8'

Root Cause

Gemma4AudioFeedForward, Gemma4AudioLightConv1d, and Gemma4AudioLayer perform gradient clipping via:

weight.data.clamp_(-torch.finfo(weight.dtype).max, torch.finfo(weight.dtype).max)

When loaded with 4-bit quantization, weight.dtype is torch.uint8 (bitsandbytes internal storage format). torch.finfo() does not accept integer types → crash.

Minimal Reproducible Example

import torch
from transformers import AutoModelForImageTextToText, AutoProcessor, BitsAndBytesConfig

bnb_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16)
model = AutoModelForImageTextToText.from_pretrained(
    "google/gemma-4-e2b-it",
    quantization_config=bnb_config,
    device_map="auto",
)
processor = AutoProcessor.from_pretrained("google/gemma-4-e2b-it")

messages = [{"role": "user", "content": [
    {"type": "audio", "audio": "path/to/any.wav"},
    {"type": "text", "text": "Transcribe."},
]}]
inputs = processor.apply_chat_template(
    messages, tokenize=True, add_generation_prompt=True,
    return_dict=True, return_tensors="pt"
).to(model.device, dtype=torch.bfloat16)

model.generate(**inputs, max_new_tokens=50)  # ← crashes here

Proposed Fix

Add a helper in modeling_gemma4.py:

def _safe_finfo_max(dtype: torch.dtype) -> float:
    """Falls back to bfloat16 for non-float dtypes (e.g. uint8 from bitsandbytes 4-bit)."""
    if dtype.is_floating_point:
        return torch.finfo(dtype).max
    return torch.finfo(torch.bfloat16).max

Replace in Gemma4AudioFeedForward.forward(), Gemma4AudioLightConv1d.forward(), and Gemma4AudioLayer.forward():

# Before
weight.data.clamp_(-torch.finfo(weight.dtype).max, torch.finfo(weight.dtype).max)

# After
weight.data.clamp_(-_safe_finfo_max(weight.dtype), _safe_finfo_max(weight.dtype))

extent analysis

TL;DR

Replace the torch.finfo(weight.dtype).max calls with a helper function _safe_finfo_max to handle non-float dtypes.

Guidance

  • Identify the locations where torch.finfo(weight.dtype).max is used in the code, specifically in Gemma4AudioFeedForward, Gemma4AudioLightConv1d, and Gemma4AudioLayer.
  • Replace these calls with the proposed _safe_finfo_max helper function to ensure compatibility with non-float dtypes like torch.uint8.
  • Verify that the forward pass no longer crashes with the TypeError after applying the fix.
  • Consider adding additional error handling or type checks to prevent similar issues in the future.

Example

def _safe_finfo_max(dtype: torch.dtype) -> float:
    """Falls back to bfloat16 for non-float dtypes (e.g. uint8 from bitsandbytes 4-bit)."""
    if dtype.is_floating_point:
        return torch.finfo(dtype).max
    return torch.finfo(torch.bfloat16).max

# Replace in forward() methods:
weight.data.clamp_(-_safe_finfo_max(weight.dtype), _safe_finfo_max(weight.dtype))

Notes

This fix assumes that the issue is solely caused by the torch.finfo() call with non-float dtypes. If other issues arise, further investigation may be necessary.

Recommendation

Apply the proposed workaround by replacing the torch.finfo(weight.dtype).max calls with the _safe_finfo_max helper function, as it provides a safe and compatible solution for handling non-float dtypes.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING

transformers - ✅(Solved) Fix [Gemma4] torch.finfo() TypeError on uint8 weights in audio modules during 4-bit (NF4) inference [1 pull requests, 1 comments, 2 participants]