Skip to content

Bnb4bit support for MoE models on transformers v5 #4032

Closed

Description

@silentgameshub

I have reviewed code env. Ensured latest unsloth is installed correctly.
Hardware settings:
amd 7b13 for cpu
mem:90gb (vm mem size)
gpu:1x 3090 with modified 48gb vram.
Env:torch2.8with cu128 py312
Belowing is my begining parts of notebook:

from unsloth import FastLanguageModel, is_bfloat16_supported
import torch
max_seq_length = 3001 # Can increase for longer reasoning traces
lora_rank = 64 # Larger rank = smarter, but slower

model, tokenizer = FastLanguageModel.from_pretrained(
model_name = "Bahadir26/Qwen3-30B-A3B-Thinking-2507-bnb-4bit",
max_seq_length = max_seq_length,
load_in_4bit = True, # False for LoRA 16bit
fast_inference = False, # Enable vLLM fast inference
load_in_8bit = False,
max_lora_rank = lora_rank,
#gpu_memory_utilization = 0.5, # Reduce if out of memory
#offload_embedding = True, # Reduces VRAM by 1GB
device_map = {"": 0},
)
#model.config.use_cache = False
#model.base_model.model.model.embed_tokens.weight.requires_grad = False
model = FastLanguageModel.get_peft_model(
model,
r = lora_rank, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
target_modules = [
"q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj",
], # Remove QKVO if out of memory
lora_alpha = 2*lora_rank,
use_gradient_checkpointing = "unsloth", # Enable long context finetuning
random_state = 3407,
)
When removed device_map = {"": 0}, then it said 48gb is oom. Which is impossible.

When we implement device map. It can run the trainer for a minute.but quickly raised fatal error.

When we removed gate up down. it said AttributeError
Traceback (most recent call last)
File ~/miniconda3/lib/python3.12/site-packages/peft/peft_model.py:896, in PeftModel.getattr(self, name)
895 try:
--> 896 return super().getattr(name) # defer to nn.Module's logic
897 except AttributeError:
File ~/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py:1962, in Module.getattr(self, name)
1961 return modules[name]
-> 1962 raise AttributeError(
1963 f"'{type(self).name}' object has no attribute '{name}'"
1964 )
AttributeError: 'PeftModelForCausalLM' object has no attribute 'warnings_issued'
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
File ~/miniconda3/lib/python3.12/site-packages/peft/tuners/tuners_utils.py:1239, in BaseTuner.getattr(self, name)
1238 try:
-> 1239 return super().getattr(name) # defer to nn.Module's logic
1240 except AttributeError:
File ~/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py:1962, in Module.getattr(self, name)
1961 return modules[name]
-> 1962 raise AttributeError(
1963 f"'{type(self).name}' object has no attribute '{name}'"
1964 )
AttributeError: 'LoraModel' object has no attribute 'warnings_issued'
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
Cell In[10], line 1
----> 1 trainer = GRPOTrainer(
2 model = model,
3 processing_class = tokenizer,
4 reward_funcs = [
5 format_reward_func,
6 deepseek_reward_func,
7 # 移除了combined_reward_func
8 ],
9 args = training_args,
10 train_dataset = dataset,
11 )
12 trainer.train()
File ~/miniconda3/lib/python3.12/site-packages/unsloth/trainer.py:314, in _backwards_compatible_trainer..new_init(self, *args, **kwargs)
312 kwargs = trainer_kwargs
313 kwargs["args"] = config
--> 314 original_init(self, *args, **kwargs)
File ~/unsloth_compiled_cache/UnslothGRPOTrainer.py:4029, in UnslothGRPOTrainer.init(self, model, reward_funcs, args, train_dataset, eval_dataset, processing_class, reward_processing_classes, callbacks, peft_config, **kwargs)
4027 if "model" in locals() and hasattr(model, "for_training"):
4028 model.for_training(use_gradient_checkpointing=getattr(args, 'gradient_checkpointing', True))
-> 4029 super().init(
4030 model = model,
4031 reward_funcs = reward_funcs,
4032 args = args,
4033 train_dataset = train_dataset,
4034 eval_dataset = eval_dataset,
4035 processing_class = processing_class,
4036 reward_processing_classes = reward_processing_classes,
4037 callbacks = callbacks,
4038 peft_config = peft_config,**kwargs)
4039 if "model" in locals() and hasattr(model, "for_inference"):
4040 model.for_inference()
File ~/unsloth_compiled_cache/UnslothGRPOTrainer.py:2009, in _UnslothGRPOTrainer.init(self, model, reward_funcs, args, train_dataset, eval_dataset, processing_class, reward_processing_classes, callbacks, optimizers, peft_config)
2001 self._buffered_inputs = None
2003 # The trainer estimates the number of FLOPs [floating-point operations] using the number of elements in the
2004 # input tensor associated with the key "input_ids". However, in GRPO, the sampled data does not include the
2005 # "input_ids" key. Instead, the available keys is "prompt". As a result, the trainer issues the warning:
2006 # "Could not estimate the number of tokens of the input, floating-point operations will not be computed." To
2007 # suppress this warning, we set the "estimate_tokens" key in the model's "warnings_issued" dictionary to True.
2008 # This acts as a flag to indicate that the warning has already been issued.
-> 2009 model.warnings_issued["estimate_tokens"] = True
2011 super().init(
2012 model=model,
2013 args=args,
(...) 2025 compute_loss_func="non-None value to disable scaling",
2026 )
2028 # Reference model
File ~/miniconda3/lib/python3.12/site-packages/peft/peft_model.py:900, in PeftModel.getattr(self, name)
898 if name == "base_model": # see #1892: prevent infinite recursion if class is not initialized
899 raise
--> 900 return getattr(self.base_model, name)
File ~/miniconda3/lib/python3.12/site-packages/peft/tuners/tuners_utils.py:1243, in BaseTuner.getattr(self, name)
1241 if name == "model": # see #1892: prevent infinite recursion if class is not initialized
1242 raise
-> 1243 return getattr(self.model, name)
File ~/miniconda3/lib/python3.12/site-packages/torch/nn/modules/module.py:1962, in Module.getattr(self, name)
1960 if name in modules:
1961 return modules[name]
-> 1962 raise AttributeError(
1963 f"'{type(self).name}' object has no attribute '{name}'"
1964 )
AttributeError: 'Qwen3MoeForCausalLM' object has no attribute 'warnings_issued'

After everything is implemented. We find out the final issue.
** bnb quant transform the weight into a 1d shape,which is impossible to do the matmul.That is why bnb can’t work on all the moes**
important
Datta0 has already told me about this issue,so I'm here to share my insights and a reproduce process. Hope it might help.
Belowing is how to fix the warning issued.It is a easy unsloth bug.

if not hasattr(model, "warnings_issued"):
model.warnings_issued = {}

Activity

  1. Datta0 commented on Feb 12, 2026

    @Datta0
    Contributor

    Hey @silentgameshub the error AttributeError: 'PeftModelForCausalLM' object has no attribute 'warnings_issued' is due to trl. Can you try updating trl? They had that in a couple of versions but removed now from what I see.
    Yeah the quantization support for MoE with transformers v5 is limited unfortunately. We might try exploring that later down the line

  2. silentgameshub commented on Feb 12, 2026

    @silentgameshub
    Author

    Got it. I'm checking the trl version. I‘ve written a new experimental bnb module and I'll share it later.

  3. silentgameshub commented on Feb 12, 2026

    @silentgameshub
    Author

    Package Version


    absl-py 2.3.1
    accelerate 1.12.0
    aiohappyeyeballs 2.6.1
    aiohttp 3.13.3
    aiosignal 1.4.0
    anaconda-anon-usage 0.4.4
    annotated-doc 0.0.4
    annotated-types 0.7.0
    anyio 4.10.0
    archspec 0.2.3
    argon2-cffi 25.1.0
    argon2-cffi-bindings 25.1.0
    arrow 1.3.0
    asttokens 3.0.0
    async-lru 2.0.5
    attrs 25.3.0
    babel 2.17.0
    beautifulsoup4 4.13.4
    bitsandbytes 0.49.1
    bleach 6.2.0
    boltons 23.0.0
    Brotli 1.0.9
    certifi 2024.2.2
    cffi 1.16.0
    charset-normalizer 2.0.4
    click 8.3.1
    comm 0.2.3
    conda 24.4.0
    conda-content-trust 0.2.0
    conda-libmamba-solver 24.1.0
    conda-package-handling 2.2.0
    conda_package_streaming 0.9.0
    contourpy 1.3.3
    cryptography 42.0.5
    cycler 0.12.1
    datasets 4.3.0
    debugpy 1.8.16
    decorator 5.2.1
    defusedxml 0.7.1
    dill 0.4.0
    distro 1.9.0
    executing 2.2.0
    fastjsonschema 2.21.1
    filelock 3.18.0
    fonttools 4.59.0
    fqdn 1.5.1
    frozenlist 1.8.0
    fsspec 2025.7.0
    grpcio 1.74.0
    h11 0.16.0
    hf_transfer 0.1.9
    hf-xet 1.2.0
    httpcore 1.0.9
    httpx 0.28.1
    huggingface_hub 1.4.1
    idna 3.7
    ipykernel 6.30.1
    ipython 9.4.0
    ipython_pygments_lexers 1.1.1
    ipywidgets 8.1.7
    isoduration 20.11.0
    jedi 0.19.2
    Jinja2 3.1.6
    json5 0.12.0
    jsonpatch 1.33
    jsonpointer 2.1
    jsonschema 4.25.0
    jsonschema-specifications 2025.4.1
    jupyter_client 8.6.3
    jupyter_core 5.8.1
    jupyter-events 0.12.0
    jupyter-lsp 2.2.6
    jupyter_server 2.16.0
    jupyter_server_terminals 0.5.3
    jupyterlab 4.4.5
    jupyterlab-language-pack-zh-CN 4.4.post0
    jupyterlab_pygments 0.3.0
    jupyterlab_server 2.27.3
    jupyterlab_widgets 3.0.15
    kiwisolver 1.4.8
    lark 1.2.2
    libmambapy 1.5.8
    Markdown 3.8.2
    markdown-it-py 4.0.0
    MarkupSafe 3.0.2
    matplotlib 3.10.5
    matplotlib-inline 0.1.7
    mdurl 0.1.2
    menuinst 2.0.2
    mistune 3.1.3
    mpmath 1.3.0
    multidict 6.7.1
    multiprocess 0.70.16
    nbclient 0.10.2
    nbconvert 7.16.6
    nbformat 5.10.4
    nest-asyncio 1.6.0
    networkx 3.5
    notebook_shim 0.2.4
    numpy 2.3.2
    nvidia-cublas-cu12 12.8.4.1
    nvidia-cuda-cupti-cu12 12.8.90
    nvidia-cuda-nvrtc-cu12 12.8.93
    nvidia-cuda-runtime-cu12 12.8.90
    nvidia-cudnn-cu12 9.10.2.21
    nvidia-cufft-cu12 11.3.3.83
    nvidia-cufile-cu12 1.13.1.3
    nvidia-curand-cu12 10.3.9.90
    nvidia-cusolver-cu12 11.7.3.90
    nvidia-cusparse-cu12 12.5.8.93
    nvidia-cusparselt-cu12 0.7.1
    nvidia-ml-py 13.590.48
    nvidia-nccl-cu12 2.27.3
    nvidia-nvjitlink-cu12 12.8.93
    nvidia-nvtx-cu12 12.8.90
    overrides 7.7.0
    packaging 23.2
    pandas 3.0.0
    pandocfilters 1.5.1
    parso 0.8.4
    peft 0.18.1
    pexpect 4.9.0
    pillow 11.3.0
    pip 24.0
    platformdirs 4.5.1
    pluggy 1.0.0
    prettytable 3.17.0
    prometheus_client 0.22.1
    prompt_toolkit 3.0.51
    propcache 0.4.1
    protobuf 6.31.1
    psutil 7.0.0
    ptyprocess 0.7.0
    pure_eval 0.2.3
    pyarrow 23.0.0
    pycosat 0.6.6
    pycparser 2.21
    pydantic 2.12.5
    pydantic_core 2.41.5
    pyecharts 2.1.0
    Pygments 2.19.2
    pyparsing 3.2.3
    PySocks 1.7.1
    python-dateutil 2.9.0.post0
    python-json-logger 3.3.0
    PyYAML 6.0.2
    pyzmq 27.0.1
    referencing 0.36.2
    regex 2026.1.15
    requests 2.32.5
    rfc3339-validator 0.1.4
    rfc3986-validator 0.1.1
    rfc3987-syntax 1.1.0
    rich 13.9.4
    rpds-py 0.26.0
    ruamel.yaml 0.17.21
    safetensors 0.7.0
    Send2Trash 1.8.3
    sentencepiece 0.2.1
    setuptools 69.5.1
    shellingham 1.5.4
    simplejson 3.20.2
    six 1.17.0
    sniffio 1.3.1
    soupsieve 2.7
    stack-data 0.6.3
    supervisor 4.2.5
    swanlab 0.7.8
    sympy 1.14.0
    tensorboard 2.20.0
    tensorboard-data-server 0.7.2
    terminado 0.18.1
    tinycss2 1.4.0
    tokenizers 0.22.2
    torch 2.8.0+cu128
    torchvision 0.23.0+cu128
    tornado 6.5.1
    tqdm 4.67.3
    traitlets 5.14.3
    transformers 5.1.0
    triton 3.4.0
    trl 0.22.2
    truststore 0.8.0
    typer-slim 0.21.2
    types-python-dateutil 2.9.0.20250708
    typing_extensions 4.14.1
    typing-inspection 0.4.2
    unsloth 2026.2.1
    unsloth_zoo 2026.2.1
    uri-template 1.3.0
    urllib3 2.1.0
    wcwidth 0.2.13
    webcolors 24.11.1
    webencodings 0.5.1
    websocket-client 1.8.0
    Werkzeug 3.1.3
    wheel 0.43.0
    widgetsnbextension 4.0.14
    wrapt 2.1.1
    xformers 0.0.34
    xxhash 3.6.0
    yarl 1.22.0
    zstandard 0.22.0

  4. Datta0 commented on Feb 12, 2026

    @Datta0
    Contributor

    You might want to try updating trl ?

  5. silentgameshub commented on Feb 12, 2026

    @silentgameshub
    Author

    You might want to try updating trl ?

    Yes, 'warnings_issued' stop happening.

    I'm focusing on how to make sure that bnb generates correct dequant result. Currently, I have investigated bitsandbytes and successfully implemented the BatchLinear4bit module, which is the key component needed to support efficient 4-bit loading of transformers v5 MoE models that use fused nn.Parameter tensors (like Qwen3MoeExperts).
    But unsloth loops(qwen3_moe.forward_native_moe_loop) need changes too. That is very frustrating.

  6. silentgameshub commented on Feb 12, 2026

    @silentgameshub
    Author

    Using older trl won't change the bnb quant result. I need to support my old hyper parameter. So update is useful for 'warnings_issued'.

  7. silentgameshub commented on Feb 12, 2026

    @silentgameshub
    Author

    Unfortunately,it is a transformer problem,very hard to fix.
    Ref:bitsandbytes-foundation/bitsandbytes#1849
    huggingface/transformers#43472
    huggingface/transformers#43284
    Though I implemented BatchLinear4bit,transformers is another huge problem.
    I'll release the modified bnb module later. Really sad about that.

  8. Datta0 commented on Feb 13, 2026

    @Datta0
    Contributor

    Oh sorry. If you meant the quantization thing, yeah we're working on it.
    I was referring to the warnings_issued which was a trl doing.

  9. added
    WIP
    on Feb 17, 2026
  10. changed the title [-]Qwen3moe(almost all moe models) do not support quant.(1x131072 1d)[/-] [+]Bnb4bit support for MoE models on transformers v5[/+] on Feb 17, 2026
  11. kirawi commented on Mar 3, 2026

    @kirawi

    Oh sorry. If you meant the quantization thing, yeah we're working on it. I was referring to the warnings_issued which was a trl doing.

    Would you expect bnb support for MoEs to be anytime soon?

  12. Datta0 commented on Mar 3, 2026

    @Datta0
    Contributor

    There are a few things. But I see a community PR https://github.com/unslothai/unsloth-zoo/pull/527/changes so depends how fast this gets resolved ig

  13. kirawi commented on Mar 7, 2026

    @kirawi
  14. danielhanchen commented on Jun 18, 2026

    @danielhanchen
    Member

    This should be supported now - sorry on the delay - please update with uv pip install --upgrade unsloth unsloth_zoo --force-reinstall --no-cache-dir - if it's not supported yet, it'll be in the next pip / PyPI release - if it's still not working after that, please open another issue - appreciate it again!

  15. pjordanandrsn commented on Jul 2, 2026

    @pjordanandrsn

    Coming to this after the fix landed — two complementary pieces for people finding this thread.

    The in-tree solve covers the core gap this was closed with: verified on unsloth 2026.6.9 /
    unsloth-zoo 2026.6.7 (torch 2.11 — outside the declared <2.11 pin; environment details in the
    linked issues), a real-weights Qwen3-30B-A3B slice quantizes its fused experts to Params4bit,
    matches stock math at bf16-noise level, and expert-LoRA adapters attach and train. Two follow-ups
    from the same verification pass: unslothai/unsloth-zoo#849 and unslothai/unsloth-zoo#850. From working the same problem out
    of tree — pip install experts4bit-qlora
    (https://github.com/pjordanandrsn/experts4bit-qlora):

    Scope, honestly: dequant-path forward — capacity/correctness, not a fused grouped kernel — so it
    composes with the grouped_mm speed work rather than replacing it. Three architectures so far
    (OLMoE / Qwen3-MoE / Gemma-4 text).

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    WIP

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions