How to run with BNB 4bit or 8bit quantization?
I tryed to modify your example code to run this model on lowvram card by BNB 4bit or 8bit quantization config.
While use bnb 4bit config like below:
qnt_config = BitsAndBytesConfig(load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16,
bnb_4bit_use_double_quant=True)
First time this issue occured while pixel_values = pixel_values.to(torch.bfloat16).unsqueeze(0)
RuntimeError: Input type (CUDABFloat16Type) and weight type (torch.cuda.HalfTensor) should be the same
Then I changed it to pixel_values = pixel_values.to(llm_dtype).unsqueeze(0)(llm_dtype is llava models weight load dtype)
RuntimeError: self and mat2 must have the same dtype, but got Half and Byte
these error should be caused by image input dtype.
Any idea to make it works?
Keep pixel_values = pixel_values.to(torch.bfloat16).unsqueeze(0), but maybe try changing bnb_4bit_compute_dtype=torch.float16 to bnb_4bit_compute_dtype=torch.bfloat16?
Keep
pixel_values = pixel_values.to(torch.bfloat16).unsqueeze(0), but maybe try changingbnb_4bit_compute_dtype=torch.float16tobnb_4bit_compute_dtype=torch.bfloat16?
keep bnb_4bit_compute_dtype=torch.bfloat16 same to pixel_values.to(torch.bfloat16).unsqueeze(0)
will cause this error:
Traceback (most recent call last):
File "/opt/conda/lib/python3.10/site-packages/gradio/queueing.py", line 622, in process_events
response = await route_utils.call_process_api(
File "/opt/conda/lib/python3.10/site-packages/gradio/route_utils.py", line 323, in call_process_api
output = await app.get_blocks().process_api(
File "/opt/conda/lib/python3.10/site-packages/gradio/blocks.py", line 2014, in process_api
result = await self.call_function(
File "/opt/conda/lib/python3.10/site-packages/gradio/blocks.py", line 1567, in call_function
prediction = await anyio.to_thread.run_sync( # type: ignore
File "/opt/conda/lib/python3.10/site-packages/anyio/to_thread.py", line 56, in run_sync
return await get_async_backend().run_sync_in_worker_thread(
File "/opt/conda/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 2177, in run_sync_in_worker_thread
return await future
File "/opt/conda/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 859, in run
result = context.run(func, *args)
File "/opt/conda/lib/python3.10/site-packages/gradio/utils.py", line 846, in wrapper
response = f(*args, **kwargs)
File "/root/private_data/wd-joy-caption-cli/wd_llm_caption/gui.py", line 713, in caption_single_inference
caption_text = get_caption_fn.my_llm.get_caption(
File "/root/private_data/wd-joy-caption-cli/wd_llm_caption/utils/inference.py", line 607, in get_caption
self.llm.generate(input_ids=input_ids, pixel_values=pixel_values,
File "/opt/conda/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context
return func(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/transformers/generation/utils.py", line 2047, in generate
result = self._sample(
File "/opt/conda/lib/python3.10/site-packages/transformers/generation/utils.py", line 3007, in _sample
outputs = self(**model_inputs, return_dict=True)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/accelerate/hooks.py", line 170, in new_forward
output = module._old_forward(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/transformers/models/llava/modeling_llava.py", line 453, in forward
image_outputs = self.vision_tower(pixel_values, output_hidden_states=True)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/accelerate/hooks.py", line 170, in new_forward
output = module._old_forward(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/transformers/models/siglip/modeling_siglip.py", line 1189, in forward
return self.vision_model(
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/accelerate/hooks.py", line 170, in new_forward
output = module._old_forward(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/transformers/models/siglip/modeling_siglip.py", line 1100, in forward
pooler_output = self.head(last_hidden_state) if self.use_head else None
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/accelerate/hooks.py", line 170, in new_forward
output = module._old_forward(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/transformers/models/siglip/modeling_siglip.py", line 1127, in forward
hidden_state = self.attention(probe, hidden_state, hidden_state)[0]
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/accelerate/hooks.py", line 170, in new_forward
output = module._old_forward(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/activation.py", line 1241, in forward
attn_output, attn_output_weights = F.multi_head_attention_forward(
File "/opt/conda/lib/python3.10/site-packages/torch/nn/functional.py", line 5430, in multi_head_attention_forward
attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
RuntimeError: self and mat2 must have the same dtype, but got BFloat16 and Byte
if use bnb 8bit config:
qnt_config = BitsAndBytesConfig(load_in_8bit=True,
llm_int8_enable_fp32_cpu_offload=True)
will cause this error:
/opt/conda/lib/python3.10/site-packages/bitsandbytes/autograd/_functions.py:324: UserWarning: MatMul8bitLt: inputs will be cast from torch.bfloat16 to float16 during quantization
warnings.warn(f"MatMul8bitLt: inputs will be cast from {A.dtype} to float16 during quantization")
Traceback (most recent call last):
File "/opt/conda/lib/python3.10/site-packages/gradio/queueing.py", line 622, in process_events
response = await route_utils.call_process_api(
File "/opt/conda/lib/python3.10/site-packages/gradio/route_utils.py", line 323, in call_process_api
output = await app.get_blocks().process_api(
File "/opt/conda/lib/python3.10/site-packages/gradio/blocks.py", line 2014, in process_api
result = await self.call_function(
File "/opt/conda/lib/python3.10/site-packages/gradio/blocks.py", line 1567, in call_function
prediction = await anyio.to_thread.run_sync( # type: ignore
File "/opt/conda/lib/python3.10/site-packages/anyio/to_thread.py", line 56, in run_sync
return await get_async_backend().run_sync_in_worker_thread(
File "/opt/conda/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 2177, in run_sync_in_worker_thread
return await future
File "/opt/conda/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 859, in run
result = context.run(func, *args)
File "/opt/conda/lib/python3.10/site-packages/gradio/utils.py", line 846, in wrapper
response = f(*args, **kwargs)
File "/root/private_data/wd-joy-caption-cli/wd_llm_caption/gui.py", line 713, in caption_single_inference
caption_text = get_caption_fn.my_llm.get_caption(
File "/root/private_data/wd-joy-caption-cli/wd_llm_caption/utils/inference.py", line 607, in get_caption
self.llm.generate(input_ids=input_ids, pixel_values=pixel_values,
File "/opt/conda/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context
return func(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/transformers/generation/utils.py", line 2047, in generate
result = self._sample(
File "/opt/conda/lib/python3.10/site-packages/transformers/generation/utils.py", line 3007, in _sample
outputs = self(**model_inputs, return_dict=True)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/accelerate/hooks.py", line 170, in new_forward
output = module._old_forward(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/transformers/models/llava/modeling_llava.py", line 453, in forward
image_outputs = self.vision_tower(pixel_values, output_hidden_states=True)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/accelerate/hooks.py", line 170, in new_forward
output = module._old_forward(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/transformers/models/siglip/modeling_siglip.py", line 1189, in forward
return self.vision_model(
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/accelerate/hooks.py", line 170, in new_forward
output = module._old_forward(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/transformers/models/siglip/modeling_siglip.py", line 1100, in forward
pooler_output = self.head(last_hidden_state) if self.use_head else None
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/accelerate/hooks.py", line 170, in new_forward
output = module._old_forward(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/transformers/models/siglip/modeling_siglip.py", line 1127, in forward
hidden_state = self.attention(probe, hidden_state, hidden_state)[0]
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
return forward_call(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/accelerate/hooks.py", line 170, in new_forward
output = module._old_forward(*args, **kwargs)
File "/opt/conda/lib/python3.10/site-packages/torch/nn/modules/activation.py", line 1241, in forward
attn_output, attn_output_weights = F.multi_head_attention_forward(
File "/opt/conda/lib/python3.10/site-packages/torch/nn/functional.py", line 5430, in multi_head_attention_forward
attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
RuntimeError: self and mat2 must have the same dtype, but got BFloat16 and Char
Looks like this is a bug in transformers. I've submitted a bug report and pull request to get it fixed: https://github.com/huggingface/transformers/issues/34294
We'll have to wait for that to get fixed and a new version of transformers released to have a clean fix here.
Thanks for your help, let's wait hf response.
Interested as well, could never run NF4 and original model is wayy to slow on my setup :-(
@fpgaminer some news ? I've read the reply from the transformer github and tried their solution but it didn't change anything
https://github.com/bitsandbytes-foundation/bitsandbytes/issues/963 seems to be related. I tried with the current transformers github as of today. It looks like in modeling_siglip.py self.attention.out_proj.weight has a uint8 type after 4-bit quantization, and the multihead attention calculation fails with the same error. I don't know enough about quantization to know whether this is correct behavior.
I haven't had a chance to take a fresh look at this, but getting quantized models running is still on my TODO list. Just so you know I haven't forgotten!
https://github.com/huggingface/transformers/issues/34294#issuecomment-2428261683
Following this post, I tried casting the inputs to bnb_4bit_compute_dtype and it made progress a little, but it ended up crashing with the following. However, it seems that the error with torch's linear function was avoided.
The model is converted to NF4 when loaded.
This is almost same to fireicewolf's attempt, but I tried casting inputs instead of pixel_values. I don't think this is correct...
If you carefully cast the input data in the model code, you may be able to avoid it...
I want the library to do something about it...
# Generate the captions
generate_ids = llava_model.generate( # NF4 model
input_ids=input_ids.to(torch.bfloat16), # cast inputs to the bnb_4bit_compute_dtype
with casting
\lib\site-packages\torch\nn\functional.py", line 2267, in embedding
return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)
RuntimeError: Expected tensor for argument #1 'indices' to have one of the following scalar types: Long, Int; but got CUDABFloat16Type instead (while checking arguments for embedding)
without casting
\lib\site-packages\torch\nn\functional.py", line 5533, in multi_head_attention_forward
attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
RuntimeError: mat1 and mat2 shapes cannot be multiplied (1x1152 and 1x331776)
Hi all,
any update on this? I am facing the same issue too. My model is LLaVa with a siglip vision tower instead of Clip (hf hub model giobin/llava15_siglip_random_adapter).
RuntimeError: self and mat2 must have the same dtype, but got BFloat16 and Byte
There's been no progress with bitsandbytes...😭 https://discuss.huggingface.co/t/valueerror-supplied-state-dict-for-layers-does-not-contain-bitsandbytes-and-possibly-other-quantized-stats-when-load-saved-quantized-model/110808/ There may be ways to try quantization other than bitsandbytes, such as GGUF or GPTQ. It's inconvenient that on-the-fly quantization isn't possible. https://huggingface.co/OPEA/llama-joycaption-alpha-two-hf-llava-int4-sym-inc
My knowledge regarding model structure and quantization is admittedly pretty limited, but I assume it isn't as simple a matter as simply running the model through llama-cpp's llama-quantize.exe so as to quantize it in GGUF format, right? I'd really like to run this version locally, since I have multiple folders and images I want to try it on, so if any other format besides nf4 is more feasible, I'm willing to try it (and fail, but yeah).
I spent some time looking into this and I believe I found the issue for the Mat1/Mat2 shape issue, which was the last blocker for me preventing dynamic 4bit quantization from working.
From what I can tell, the issue is that bitsandbytes is converting SigLIP's head's attention's out_proj to a nn.Linear4bit from a nn.NonDynamicallyQuantizableLinear, as if it were a plain nn.Linear. This sounds wrong, and restoring it back to a plain nn.Linear (as nn.NonDynamicallyQuantizableLinear is private) allows the generation to run without error.
Here is my fix against the example script: https://gist.github.com/maedtb/ee16101ca80638011c975ed0c0d78497
Example output in 4bit mode:
This is a digital anime-style drawing featuring four characters. The central figure is a blue-haired girl with large blue eyes, wearing a teal jacket over a red shirt and blue pants, striking a playful pose. Above her, a red-haired boy with a black hair clip looks down. To the right, a blonde boy in a blue shirt and green pants sleeps, mouth open, with a speech bubble saying "Zzz." Below, a small yellow-haired boy with big eyes and a blue shirt smiles widely. The background is a vibrant pink with white bubbles.
Example output in standard 16bit mode with the same seed/image:
This digital anime-style drawing features four characters in a playful, vibrant setting. The central figure is a blue-haired girl with large eyes and a teal jacket, looking surprised. Behind her, a red-haired boy with a mischievous grin rides her shoulders. Below, a blonde boy with spiky hair, wearing a blue shirt, and a sleeping boy with light brown hair, wearing a white shirt, are positioned. The background is white with pink bubbles, creating a whimsical atmosphere.
4bit mode runs with just over 8GB of vram usage for me / my example image, while 16bit mode runs with just under 17GB of vram usage with the same image/caption/seed.
Here is my fix against the example script: https://gist.github.com/maedtb/ee16101ca80638011c975ed0c0d78497
Nice, thanks for this, will try it when I'm home. Mostly out of curiosity, have you tried this with the latest VQA model?
Nice, thanks for this, will try it when I'm home. Mostly out of curiosity, have you tried this with the latest VQA model?
This change works on the one "Joy Caption Alpha Two, VQA Test One" model uploaded on HuggingFace, yes.
Here is my fix against the example script: https://gist.github.com/maedtb/ee16101ca80638011c975ed0c0d78497
Great! Even if the weights were quantized and saved, or double-quantized, this worked perfectly. https://huggingface.co/John6666/llama-joycaption-alpha-two-hf-llava-nf4/blob/main/scripts/batch-caption.py
FYI I still have this on my to-do list to get sorted out in the official code; just been busy working on the dataset and model.
FYI I still have this on my to-do list to get sorted out in the official code; just been busy working on the dataset and model.
No problem, can't wait to see the model's next iteration :D
Sorry for the late reply.
Looking at this again, it seems like the previous bug in transformers was fixed, but now there's a new bug later in Siglip's stack.
I can't be arsed to hunt down the new bug. However, you can just skip quantizing the vision tower:
qnt_config = BitsAndBytesConfig(load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16,
bnb_4bit_use_double_quant=True,
llm_int8_skip_modules=["vision_tower", "multi_modal_projector"],
)
# Load JoyCaption
# bfloat16 is the native dtype of the LLM used in JoyCaption (Llama 3.1)
# device_map=0 loads the model into the first GPU
processor = AutoProcessor.from_pretrained(MODEL_NAME)
llava_model = LlavaForConditionalGeneration.from_pretrained(MODEL_NAME, device_map=0, quantization_config=qnt_config, torch_dtype="auto")
llava_model.eval()
You can verify that everything went correctly by printing out the model and checking that all layers under vision_tower are still Linear, whereas the ones under language_model are now Linear4bit.
That seems to run without issue for me (transformers==4.51.0.dev0).
hey ... works so long ;)
usual nf4 is lower quality ... some one has made an fp8 model (usual in all cases better) https://huggingface.co/NeoChen1024/llama-joycaption-beta-one-hf-llava-FP8-Dynamic/tree/main
should be work, but simple replace dont work, you can configure? If necessary, I can test... if its only some code lines and install a lib.