transformers: Assert error in convert_llava_onevision_weights_to_hf.py
System Info
transformersversion: 4.46.0- Platform: Linux-5.15.0-97-generic-x86_64-with-glibc2.35
- Python version: 3.12.3
- Huggingface_hub version: 0.26.1
- Safetensors version: 0.4.5
- Accelerate version: 1.0.1
- Accelerate config: not found
- PyTorch version (GPU?): 2.3.0+cu121 (True)
- Tensorflow version (GPU?): not installed (NA)
- Flax version (CPU?/GPU?/TPU?): not installed (NA)
- Jax version: not installed
- JaxLib version: not installed
- Using distributed or parallel set-up in script?: <fill in>
- Using GPU in script?: <fill in>
- GPU type: NVIDIA GeForce RTX 4090
Who can help?
Information
- The official example scripts
- My own modified scripts
Tasks
- An officially supported task in the
examplesfolder (such as GLUE/SQuAD, …) - My own task or dataset (give details below)
Reproduction
I copied convert_llava_onevision_weights_to_hf.py as convert.py, and run:
python convert.py --pytorch_dump_folder_path ./0.5b --model_id lmms-lab/llava-onevision-qwen2-0.5b-ov
python convert.py --pytorch_dump_folder_path ./7b --model_id lmms-lab/llava-onevision-qwen2-7b-ov
Then I encountered an assertion error; it appears that the logits produced by the converted model do not match those specified in the script.
lmms-lab/llava-onevision-qwen2-0.5b-ov output:
$ python convert.py --pytorch_dump_folder_path ./0.5b --model_id lmms-lab/llava-onevision-qwen2-0.5b-ov
{'_name_or_path': '/mnt/bn/vl-research/checkpoints/onevision/llavanext-google_siglip-so400m-patch14-384-Qwen_Qwen2-0.5B-Instruct-mid_to_final_next_3p2m_am9_july21', 'architectures': ['LlavaQwenForCausalLM'], 'attention_dropout': 0.0, 'mm_newline_position': 'one_token', 'bos_token_id': 151643, 'eos_token_id': 151645, 'hidden_act': 'silu', 'hidden_size': 896, 'image_aspect_ratio': 'anyres_max_9', 'image_crop_resolution': None, 'image_grid_pinpoints': [[384, 384], [384, 768], [384, 1152], [384, 1536], [384, 1920], [384, 2304], [768, 384], [768, 768], [768, 1152], [768, 1536], [768, 1920], [768, 2304], [1152, 384], [1152, 768], [1152, 1152], [1152, 1536], [1152, 1920], [1152, 2304], [1536, 384], [1536, 768], [1536, 1152], [1536, 1536], [1536, 1920], [1536, 2304], [1920, 384], [1920, 768], [1920, 1152], [1920, 1536], [1920, 1920], [1920, 2304], [2304, 384], [2304, 768], [2304, 1152], [2304, 1536], [2304, 1920], [2304, 2304]], 'image_split_resolution': None, 'image_token_index': 151646, 'initializer_range': 0.02, 'intermediate_size': 4864, 'max_position_embeddings': 32768, 'max_window_layers': 24, 'mm_hidden_size': 1152, 'mm_patch_merge_type': 'spatial_unpad', 'mm_projector_lr': None, 'mm_projector_type': 'mlp2x_gelu', 'mm_resampler_type': None, 'mm_spatial_pool_mode': 'bilinear', 'mm_tunable_parts': 'mm_vision_tower,mm_mlp_adapter,mm_language_model', 'mm_use_im_patch_token': False, 'mm_use_im_start_end': False, 'mm_vision_select_feature': 'patch', 'mm_vision_select_layer': -2, 'mm_vision_tower': 'google/siglip-so400m-patch14-384', 'mm_vision_tower_lr': 2e-06, 'model_type': 'llava', 'num_attention_heads': 14, 'num_hidden_layers': 24, 'num_key_value_heads': 2, 'pos_skipping_range': 4096, 'rms_norm_eps': 1e-06, 'rope_scaling': None, 'rope_theta': 1000000.0, 'sliding_window': 32768, 'tie_word_embeddings': True, 'tokenizer_model_max_length': 32768, 'tokenizer_padding_side': 'right', 'torch_dtype': 'bfloat16', 'transformers_version': '4.40.0.dev0', 'use_cache': True, 'use_mm_proj': True, 'use_pos_skipping': False, 'use_sliding_window': False, 'vision_tower_pretrained': None, 'vocab_size': 151936}
Fetching 1 files: 100%|█████████████████████████████████████████████| 1/1 [00:00<00:00, 2460.00it/s]
The new embeddings will be initialized from a multivariate normal distribution that has old embeddings' mean and covariance. As described in this article: https://nlp.stanford.edu/~johnhew/vocab-expansion.html. To disable this, use `mean_resizing=False`
The new lm_head weights will be initialized from a multivariate normal distribution that has old embeddings' mean and covariance. As described in this article: https://nlp.stanford.edu/~johnhew/vocab-expansion.html. To disable this, use `mean_resizing=False`
Saving model and processor for lmms-lab/llava-onevision-qwen2-0.5b-ov to ./0.5b
Single forward pass
Shape of logits: torch.Size([1, 6578, 152000])
First values of logits: tensor([[-12.0234, -14.3828, -12.7500],
[ 2.3828, 1.0283, 3.9512],
[ 3.6641, 4.7031, 9.1172]], device='cuda:0')
Traceback (most recent call last):
File "/root/autodl-tmp/convert.py", line 388, in <module>
convert_llava_to_hf(args.model_id, args.pytorch_dump_folder_path, args.push_to_hub)
File "/root/autodl-tmp/convert.py", line 288, in convert_llava_to_hf
assert torch.allclose(outputs.logits[0, :3, :3], expected_slice, atol=1e-4)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Half did not match Float
lmms-lab/llava-onevision-qwen2-7b-ov output:
$ python convert.py --pytorch_dump_folder_path ./7b --model_id lmms-lab/llava-onevision-qwen2-7b-ov
{'_name_or_path': '/mnt/bn/vl-research/checkpoints/onevision/llavanext-google_siglip-so400m-patch14-384-Qwen_Qwen2-7B-Instruct-mid_to_final_next_2p4m_am4', 'architectures': ['LlavaQwenForCausalLM'], 'mm_newline_position': 'one_token', 'attention_dropout': 0.0, 'bos_token_id': 151643, 'eos_token_id': 151645, 'hidden_act': 'silu', 'hidden_size': 3584, 'image_token_index': 151646, 'image_aspect_ratio': 'anyres_max_9', 'image_crop_resolution': None, 'image_grid_pinpoints': [[384, 384], [384, 768], [384, 1152], [384, 1536], [384, 1920], [384, 2304], [768, 384], [768, 768], [768, 1152], [768, 1536], [768, 1920], [768, 2304], [1152, 384], [1152, 768], [1152, 1152], [1152, 1536], [1152, 1920], [1152, 2304], [1536, 384], [1536, 768], [1536, 1152], [1536, 1536], [1536, 1920], [1536, 2304], [1920, 384], [1920, 768], [1920, 1152], [1920, 1536], [1920, 1920], [1920, 2304], [2304, 384], [2304, 768], [2304, 1152], [2304, 1536], [2304, 1920], [2304, 2304]], 'image_split_resolution': None, 'initializer_range': 0.02, 'intermediate_size': 18944, 'max_position_embeddings': 32768, 'max_window_layers': 28, 'mm_hidden_size': 1152, 'mm_patch_merge_type': 'spatial_unpad', 'mm_projector_lr': None, 'mm_projector_type': 'mlp2x_gelu', 'mm_resampler_type': None, 'mm_spatial_pool_mode': 'bilinear', 'mm_tunable_parts': 'mm_vision_tower,mm_mlp_adapter,mm_language_model', 'mm_use_im_patch_token': False, 'mm_use_im_start_end': False, 'mm_vision_select_feature': 'patch', 'mm_vision_select_layer': -2, 'mm_vision_tower': 'google/siglip-so400m-patch14-384', 'mm_vision_tower_lr': 2e-06, 'model_type': 'llava', 'num_attention_heads': 28, 'num_hidden_layers': 28, 'num_key_value_heads': 4, 'pos_skipping_range': 4096, 'rms_norm_eps': 1e-06, 'rope_scaling': None, 'rope_theta': 1000000.0, 'sliding_window': 131072, 'tie_word_embeddings': False, 'tokenizer_model_max_length': 32768, 'tokenizer_padding_side': 'right', 'torch_dtype': 'bfloat16', 'transformers_version': '4.40.0.dev0', 'use_cache': True, 'use_mm_proj': True, 'use_pos_skipping': False, 'use_sliding_window': False, 'vision_tower_pretrained': None, 'vocab_size': 152064}
Fetching 4 files: 100%|██████████████████████████████████████████████| 4/4 [00:00<00:00, 298.81it/s]
The new embeddings will be initialized from a multivariate normal distribution that has old embeddings' mean and covariance. As described in this article: https://nlp.stanford.edu/~johnhew/vocab-expansion.html. To disable this, use `mean_resizing=False`
The new lm_head weights will be initialized from a multivariate normal distribution that has old embeddings' mean and covariance. As described in this article: https://nlp.stanford.edu/~johnhew/vocab-expansion.html. To disable this, use `mean_resizing=False`
Saving model and processor for lmms-lab/llava-onevision-qwen2-7b-ov to ./7b
Loading checkpoint shards: 100%|██████████████████████████████████████| 4/4 [00:03<00:00, 1.28it/s]
Single forward pass
Shape of logits: torch.Size([1, 6578, 152128])
First values of logits: tensor([[1.8486, 3.4219, 1.3125],
[3.1191, 3.0195, 3.1660],
[4.2461, 4.7227, 9.9609]], device='cuda:0')
Traceback (most recent call last):
File "/root/autodl-tmp/convert.py", line 388, in <module>
convert_llava_to_hf(args.model_id, args.pytorch_dump_folder_path, args.push_to_hub)
File "/root/autodl-tmp/convert.py", line 288, in convert_llava_to_hf
assert torch.allclose(outputs.logits[0, :3, :3], expected_slice, atol=1e-4)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Half did not match Float
Expected behavior
The output logits remain consistent and do not produce an assertion error.
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Reactions: 1
- Comments: 20 (8 by maintainers)
Awesome, thanks for sharing! Would you like the new models to be added to
llava-hfrepository on the hub?I saw the discussion opened by you on the hub, so feel free to open a PR with updated conversion script that covers llava-critic models. After that PR I can convert and upload models to the official repo 😃
Regarding the questions:
Yes, as long as the logits match on your machine it is fine and should not result in big loss of precision. For the expected text, you can use the official repo but this time instead of
forwardcallmodel.generate()and make sure that the prompts are formatted to chat template in the same wayHi, the conversion is easy. The core code to convert a llava-ov model is : https://github.com/huggingface/transformers/blob/86701f2b6ff2085a3cd3ad1d30bc2ff2b10fbd94/src/transformers/models/llava_onevision/convert_llava_onevision_weights_to_hf.py#L98-L196
You only need to add an extra line to the text_model_id specifying process. For example, adding
lmms-lab/llava-critic-7bto the following block.By running the function, you will get a converted model under folder
output/.However, as we discussed above, we think that the current conversion has some problem, which may result in accuracy drop compared to the original model. You can use the converted model at your own risks.
Weird, this should not happen because we don’t resize dimensionality of lm-head. What can be different is the second-dim for token length depending on how we tokenized/formatted inputs. Yes, in that case I agree conversion is doing smth wrong
No worries, take your time and lmk if you need further assistance 🤗
It can be set when loading the model with
XXXModel.from_pretrained(model_id, torch_dtype="float16"). I guess the llava repo uses bf16 but I might be mistaken.Oh yeah, you’re right, it also influences. Can you see the
(logit_llava - logit_converted[:, :-1, :]).abs().max()by cropping the last token from converted model logits? Or maybe more than one token if we add more?IMO this is too much for simply converting the weights. What we usually do is to match to logits and the generated results. I’d love to help you out with debugging, but I might be slow this week. If you have a working branch feel free to open a PR so we can run and test it out together.
In general, I am okay as long as the logits match, the generation should match in that case also unless the inputs are formatted differently 😃
Hmm, afaik the llava implementation defaults to FA2 when loading the model + we need to check the dtypes when loading the model. I think that could be the reason why logits are slightly different and why generated text starts diverging as more tokens are generated
How much is the diff for the logits if we don’t take it as a slice but compare the whole tensor? If it is below tolerance level, I think we should be good even if generated texts don’t match 100%. The difference in that case if most probably is in the way model is loaded
The difference between the one you got from LLaVA-VL and the one in
expected_textinconvert_llava_onevision_weights_to_hf.pycan be explained by the differences in hardware probably, same way as you got different logits.So let’s better focus on getting same result when converting the weights with the same machine. If I am not mistaken, the logits are matching 100% so in that case the issue is probably the chat format yes. You can print the
prompt_questionto see how the question is formatted in LLaVA-VL repo and the print the result ofapply_chat_templatefrom below line to compare if they matchCool, adding it to the official repo sounds good!
It should be almost same as you did above, but just call
generateas below. I used this notebook when obtaining generation results -> https://github.com/LLaVA-VL/LLaVA-NeXT/blob/main/docs/LLaVA_OneVision_Tutorials.ipynbOh I have figured it out how to get the logits using the official llava-next framework’s guide. Put it here for anyone who might need it too:
I tried
lmms-lab/llava-onevision-qwen2-0.5b-ovon my RTX 2080Ti, and its output is the same as the converted model.Hey @FuryMartin !
Yes, the differences can be caused by the hardware and also by torch version. When I converted the weights I used 80GB A100 and I’ll try to run once more tomorrow to see if the logits will be similar. If you are trying to convert weights in your own fine-tuned model, I’d suggest to just make sure the logits match on your machine, then you should be good to go 😃