Skip to content

Granite nvfp4 underflow fix - #1836

Merged
zcbenz merged 4 commits into
ml-explore:mainfrom
gabe-l-hart:GraniteNVFP4UnderflowFix
Sep 12, 2026
Merged

zcbenz merged 4 commits into
ml-explore:mainfrom
gabe-l-hart:GraniteNVFP4UnderflowFix

Conversation

@gabe-l-hart

@gabe-l-hart gabe-l-hart commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR fixes underflows in the recent IBM Granite 4.2 models (https://huggingface.co/collections/ibm-granite/granite-42-language-models) and existing GraniteMoE models (eg https://huggingface.co/ibm-granite/granite-3.1-3b-a800m-instruct) when quantizing to nvfp4.

Details

I found these issues while adding MLX support to Ollama (ollama/ollama#17972) and verified that they also existed in native mlx-lm. The fix is to protect several key tensors from quantization below 8-bit.

Open Questions

It looks like there's no way to differentiate between target quants when applying the precision guards. In testing, the int4 quants work smoothly without these guards, so it appears to be unique to nvfp4, but it seems to be better to protect here for all sub-8-bit quants. Does this sound like the right choice?

Testing

GraniteForCausalLM (dense)

Baseline NVFP4

$ uv run mlx_lm generate --model ./granite-4.2-3b-mlx-nvfp4-baseline/ --prompt "Tell me a short story"
==========
-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore
==========
Prompt: 20 tokens, 254.589 tokens-per-sec
Generation: 100 tokens, 146.458 tokens-per-sec
Peak memory: 2.177 GB

Branch NVFP4

$ uv run mlx_lm generate --model ./granite-4.2-3b-mlx-nvfp4-branch/ --prompt "Tell me a short story"
==========
Okay, the user asked for a short story. They probably wants something quick and engaging—maybe for a break, or to unwind. I'll keep it under 200 words, vivid but simple, with a gentle twist. No need for complex details; just a warm, memorable moment.

I'll craft a tiny story about a quiet place, a small kindness, ending softly. That should feel satisfying without being long.
</think>
The rain had stopped an hour ago, leaving the streets
==========
Prompt: 20 tokens, 223.821 tokens-per-sec
Generation: 100 tokens, 116.476 tokens-per-sec
Peak memory: 2.856 GB

GraniteMoeForCausalLM (MoE)

NOTE: The existing 3.1 MoE models don't exhibit the underflow errors in baseline, but a private internal model does:

Baseline NVFP4

uv run mlx_lm generate --model ./sample-moe-mlx-nvfp4-baseline/ --prompt "Tell me a short story"
==========

...
<many many newlines>
...
==========
Prompt: 20 tokens, 201.232 tokens-per-sec
Generation: 100 tokens, 136.240 tokens-per-sec
Peak memory: 12.427 GB

Branch NVFP4

uv run mlx_lm generate --model ./sample-moe-mlx-nvfp4-branch/ --prompt "Tell me a short story"
==========
The user wants a short story. I need to come up with a concept, a plot, and a resolution.

**Concept Brainstorming:**
1.  *Sci-Fi:* A robot learning to paint. (A bit cliché, but effective).
2.  *Fantasy:* A wizard's last spell. (Classic, but maybe too generic).
3.  *Mystery:* A detective finds a clue in an old attic. (Good for tension).
==========
Prompt: 20 tokens, 180.196 tokens-per-sec
Generation: 100 tokens, 124.404 tokens-per-sec
Peak memory: 16.126 GB

AI Usage

  • ☑️ I understand it is strictly prohibited to use AI to write PR description
  • AI usage disclosure: This PR was created using Claude Code. All commits were manually authored and reviewed.
git-ai-stats
╔══════════════════════════════════════════════════════════╗
║           GIT AI USAGE ANALYSIS                          ║
╚══════════════════════════════════════════════════════════╝

📊 COMMITS BY AGENT

--- Aggregate ---
Commits                        |      Count
---------------------------------------------
Claude + Sonnet 5              |          2
none                           |          1
---------------------------------------------
TOTAL                          |          3

📊 COMMITS BY USAGE TYPE

--- Aggregate ---
Commits                        |      Count
---------------------------------------------
none                           |          1
draft                          |          0
full                           |          2
---------------------------------------------
TOTAL                          |          3

📈 LINES OF CODE BY AGENT

--- Aggregate ---
Agent                     |    Commits |  Additions |  Deletions
------------------------------------------------------------
Claude + Sonnet 5         |          2 |         70 |          7
none                      |          1 |          6 |          1
------------------------------------------------------------
TOTAL                     |          3 |         76 |          8

📈 LINES OF CODE BY USAGE TYPE

--- Aggregate ---
Usage Type           |    Commits |  Additions |  Deletions
-------------------------------------------------------
none                 |          1 |          6 |          1
draft                |          0 |          0 |          0
full                 |          2 |         70 |          7
-------------------------------------------------------
TOTAL                |          3 |         76 |          8

This protection only seems to be strictly necessary for NVFP4. We've
verified that the existing int4 quant does produce coherent results, but
it's likely that this will also help there.

Branch: GraniteNVFP4UnderflowFix
AI-usage: full (Claude + Sonnet 5)
Signed-off-by: Gabe Goodhart <ghart@us.ibm.com>
These are always protected in Ollama and turn out to be critical here too
for these models.

Branch: GraniteNVFP4UnderflowFix
AI-usage: full (Claude + Sonnet 5)
Signed-off-by: Gabe Goodhart <ghart@us.ibm.com>
Branch: GraniteNVFP4UnderflowFix
AI-usage: none
Signed-off-by: Gabe Goodhart <ghart@us.ibm.com>

@zcbenz zcbenz left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This problem is unique to nvfp4 because the MLX's nvfp4 quantization currently miss global scale, which would be fixe by #1844. I think this change would work for a specific problem for now but we would have to revert it once getting global scale support, so I think we are not going to accept this and will wait for #1844.

@zcbenz zcbenz closed this Sep 9, 2026
@gabe-l-hart

gabe-l-hart commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor Author

@zcbenz Thanks for the review! I tried out the fix on #1844, but it doesn't seem to help for the dense models where we're seeing this issue (granite-4.2-*).

gh pr checkout 1844

uv run mlx_lm convert --model ~/models/ibm-granite/granite-4.2-3b/ --mlx-path ./granite-4.2-3b-mlx-nvfp4-1844 --quantize --q-mode nvfp4
# [INFO] Loading
# [INFO] Using dtype: bfloat16
# [INFO] Quantizing
# [INFO] Quantized model with 4.501 bits per weight.

uv run mlx_lm generate --model ./granite-4.2-3b-mlx-nvfp4-1844/ --prompt "Tell me a short story"
# ==========
# -fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore-fore
# ==========
# Prompt: 20 tokens, 251.845 tokens-per-sec
# Generation: 100 tokens, 147.237 tokens-per-sec
# Peak memory: 2.177 GB

When I try on our internal MoE that was also experiencing this issue, I get a stack trace:

uv run mlx_lm convert --model ~/models/ibm-research/sample-moe --mlx-path ./sample-moe-mlx-nvfp4-1844 --quantize --q-mode nvfp4
# [INFO] Loading
# [INFO] Using dtype: bfloat16
# [INFO] Quantizing
# [INFO] Quantized model with 4.501 bits per weight.

uv run mlx_lm generate --model ./sample-moe-mlx-nvfp4-1844 --prompt "Tell me a short story"
==========
Traceback (most recent call last):
  File "/Users/ghart/Projects/mlx-lm/.venv/bin/mlx_lm", line 10, in <module>
    sys.exit(main())
             ^^^^^^
  File "/Users/ghart/Projects/mlx-lm/mlx_lm/cli.py", line 40, in main
    submodule.main()
  File "/Users/ghart/Projects/mlx-lm/mlx_lm/generate.py", line 2145, in main
    response = generate(
               ^^^^^^^^^
  File "/Users/ghart/Projects/mlx-lm/mlx_lm/generate.py", line 786, in generate
    for response in stream_generate(model, tokenizer, prompt, **kwargs):
  File "/Users/ghart/Projects/mlx-lm/mlx_lm/generate.py", line 723, in stream_generate
    for n, (token, logprobs, from_draft) in enumerate(token_generator):
  File "/Users/ghart/Projects/mlx-lm/mlx_lm/generate.py", line 712, in <genexpr>
    token_generator = (
                      ^
  File "/Users/ghart/Projects/mlx-lm/mlx_lm/generate.py", line 428, in generate_step
    _model_call(
  File "/Users/ghart/Projects/mlx-lm/mlx_lm/generate.py", line 388, in _model_call
    return model(input_tokens, cache=prompt_cache)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/ghart/Projects/mlx-lm/mlx_lm/models/granitemoe.py", line 199, in __call__
    out = self.model(inputs, cache)
          ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/ghart/Projects/mlx-lm/mlx_lm/models/granitemoe.py", line 179, in __call__
    h = layer(h, mask, cache=c)
        ^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/ghart/Projects/mlx-lm/mlx_lm/models/granitemoe.py", line 150, in __call__
    r = self.block_sparse_moe(self.post_attention_layernorm(h))
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/ghart/Projects/mlx-lm/mlx_lm/models/granitemoe.py", line 127, in __call__
    y = self.switch_mlp(x, token_ids)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/ghart/Projects/mlx-lm/mlx_lm/models/switch_layers.py", line 221, in __call__
    x_up = self.up_proj(x, idx, sorted_indices=do_sort)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/ghart/Projects/mlx-lm/mlx_lm/models/switch_layers.py", line 96, in __call__
    x = mx.gather_qmm(
        ^^^^^^^^^^^^^^
TypeError: gather_qmm(): incompatible function arguments. The following argument types are supported:
    1. gather_qmm(x: array, w: array, /, scales: array, biases: array | None = None, lhs_indices: array | None = None, rhs_indices: array | None = None, transpose: bool = True, group_size: int | None = None, bits: int | None = None, mode: str = 'affine', *, sorted_indices: bool = False, stream: StreamOrDevice = None) -> array

Invoked with types: mlx.core.array, mlx.core.array, mlx.core.array, NoneType, kwargs = { rhs_indices: mlx.core.array, transpose: bool, group_size: int, bits: int, mode: str, global_scale: NoneType, sorted_indices: bool }

@gabe-l-hart

Copy link
Copy Markdown
Contributor Author

NOTE: I did do uv pip install -e . -U to ensure I had the latest dependencies before this test.

@nastya236

nastya236 commented Sep 9, 2026 •

Copy link
Copy Markdown
Collaborator

You are facing this issue because mlx release does not include this fix yet. You should pip intall mlx from source.
In your error message there is no global scale as an argument, but there is this argument on main: https://github.com/ml-explore/mlx/blob/24c699ecee2f7c8b2040de8da1c8382c8bcf31c7/mlx/ops.cpp#L5528. Could you test with building from source? Otherwise I can test it, if you provide the command that you are using to reproduce.

@gabe-l-hart

Copy link
Copy Markdown
Contributor Author

@nastya236 @zcbenz Following the suggestion above, I did install mlx from source and while that mitigated the TypeError exception, I'm still seeing the same incorrect generation behavior from both the GraniteForCausalLM (dense) and GraniteMoeForCausalLM (MoE) models that this branch mitigates. I'd like to consider re-opening this PR and reviewing it independently from #1844 which seems to address a different issue. The issue this branch fixes seems to be specific to these Granite models requiring higher precision for these specific layers.

@nastya236

Copy link
Copy Markdown
Collaborator

@gabe-l-hart hmm thanks for the update! of course, thanks for looking into this. please reopen the PR!

@gabe-l-hart

Copy link
Copy Markdown
Contributor Author

@nastya236 It looks like I don't have permission to re-open the PR. Is that something you can do as a Collaborator, or would it require @zcbenz as a Member?

@zcbenz zcbenz reopened this Sep 12, 2026
@zcbenz
zcbenz merged commit 522d756 into ml-explore:main Sep 12, 2026
5 checks passed
@zcbenz

zcbenz commented Sep 12, 2026

Copy link
Copy Markdown
Member

Thanks for testing the global scale PR!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants