Initial commit
Browse files- README.md +140 -0
- added_tokens.json +26 -0
- chat_template.json +3 -0
- config.json +62 -0
- configuration_dreamvl.py +142 -0
- generation_config.json +8 -0
- generation_utils.py +573 -0
- image_processing_dreamvl.py +469 -0
- merges.txt +0 -0
- model-00001-of-00004.safetensors +3 -0
- model-00002-of-00004.safetensors +3 -0
- model-00003-of-00004.safetensors +3 -0
- model-00004-of-00004.safetensors +3 -0
- model.safetensors.index.json +741 -0
- modeling_dreamvl.py +1824 -0
- preprocessor_config.json +33 -0
- processing_dreamvl.py +183 -0
- processor_config.json +6 -0
- special_tokens_map.json +34 -0
- tokenization_dream.py +331 -0
- tokenizer_config.json +223 -0
- vocab.json +0 -0
README.md
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
tags:
|
| 4 |
+
- vlm
|
| 5 |
+
- image-text-to-text
|
| 6 |
+
- multimodal
|
| 7 |
+
- pretraining
|
| 8 |
+
license: apache-2.0
|
| 9 |
+
language:
|
| 10 |
+
- en
|
| 11 |
+
pipeline_tag: image-text-to-text
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# Dream-VL 7B
|
| 15 |
+
|
| 16 |
+
Dream-VL 7B is an open diffusion vision-language model trained on 12M multimodal data from the [MAmmoTH-VL-Instruct-12M](https://huggingface.co/datasets/MAmmoTH-VL/MAmmoTH-VL-Instruct-12M) dataset.
|
| 17 |
+
The model takes language instructions and images as input and generates language outputs.
|
| 18 |
+
|
| 19 |
+
All Dream-VL checkpoints, as well as our [training codebase](https://github.com/DreamLM/DreamVLX) are released under an Apache 2.0 License.
|
| 20 |
+
|
| 21 |
+
For full details, please read [our blog](https://hkunlp.github.io/blog/2025/dream-vlx/) and paper (pending).
|
| 22 |
+
|
| 23 |
+
## Model Summary
|
| 24 |
+
|
| 25 |
+
- **Model type:** Vision-language (language, image => language)
|
| 26 |
+
- **Language(s) (NLP):** en
|
| 27 |
+
- **License:** apache-2.0
|
| 28 |
+
- **Finetuned from:** [`Dream-7B`](https://huggingface.co/Dream-org/Dream-v0-Instruct-7B), with Qwen2ViT Vision Backbone.
|
| 29 |
+
- **Pretraining Dataset:** [MAmmoTH-VL-Instruct-12M](https://huggingface.co/datasets/MAmmoTH-VL/MAmmoTH-VL-Instruct-12M).
|
| 30 |
+
- **Repository:** [https://github.com/DreamLM/DreamVLX](https://github.com/DreamLM/DreamVLX)
|
| 31 |
+
- **Project Page & Videos:** [https://hkunlp.github.io/blog/2025/dream-vlx](https://hkunlp.github.io/blog/2025/dream-vlx/)
|
| 32 |
+
|
| 33 |
+
## Getting Started
|
| 34 |
+
|
| 35 |
+
```python
|
| 36 |
+
import torch
|
| 37 |
+
from transformers import AutoProcessor, AutoModel
|
| 38 |
+
|
| 39 |
+
model_name = "Dream-org/Dream-VL-7B"
|
| 40 |
+
|
| 41 |
+
model = AutoModel.from_pretrained(
|
| 42 |
+
model_name,
|
| 43 |
+
torch_dtype=torch.bfloat16,
|
| 44 |
+
trust_remote_code=True,
|
| 45 |
+
).to('cuda')
|
| 46 |
+
|
| 47 |
+
processor = AutoProcessor.from_pretrained(
|
| 48 |
+
model_name,
|
| 49 |
+
trust_remote_code=True
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
####### Method 1
|
| 53 |
+
from PIL import Image
|
| 54 |
+
import requests
|
| 55 |
+
url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"
|
| 56 |
+
image = Image.open(requests.get(url, stream=True).raw)
|
| 57 |
+
messages = [
|
| 58 |
+
{
|
| 59 |
+
"role": "user","content": [{"type": "image"}, {"type": "text", "text": "Describe this image"}]
|
| 60 |
+
}
|
| 61 |
+
]
|
| 62 |
+
text = processor.apply_chat_template(
|
| 63 |
+
messages, tokenize=False, add_generation_prompt=True
|
| 64 |
+
)
|
| 65 |
+
print(text)
|
| 66 |
+
inputs = processor(
|
| 67 |
+
text=[text], images=[image], padding=True, return_tensors="pt"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
####### Method 2: use qwen_vl_utils
|
| 71 |
+
# messages = [
|
| 72 |
+
# {
|
| 73 |
+
# "role": "user",
|
| 74 |
+
# "content": [
|
| 75 |
+
# {
|
| 76 |
+
# "type": "image",
|
| 77 |
+
# "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
|
| 78 |
+
# },
|
| 79 |
+
# {"type": "text", "text": "Describe this image."},
|
| 80 |
+
# ],
|
| 81 |
+
# }
|
| 82 |
+
# ]
|
| 83 |
+
# text = processor.apply_chat_template(
|
| 84 |
+
# messages, tokenize=False, add_generation_prompt=True
|
| 85 |
+
# )
|
| 86 |
+
# from qwen_vl_utils import process_vision_info
|
| 87 |
+
# image_inputs, video_inputs = process_vision_info(messages)
|
| 88 |
+
# inputs = processor(
|
| 89 |
+
# text=[text],
|
| 90 |
+
# images=image_inputs,
|
| 91 |
+
# videos=video_inputs,
|
| 92 |
+
# padding=True,
|
| 93 |
+
# return_tensors="pt",
|
| 94 |
+
# )
|
| 95 |
+
|
| 96 |
+
inputs = inputs.to("cuda")
|
| 97 |
+
input_ids = inputs.pop("input_ids")
|
| 98 |
+
output = model.diffusion_generate(
|
| 99 |
+
input_ids,
|
| 100 |
+
max_new_tokens=128,
|
| 101 |
+
output_history=True,
|
| 102 |
+
return_dict_in_generate=True,
|
| 103 |
+
steps=128,
|
| 104 |
+
temperature=0.1,
|
| 105 |
+
top_p=1,
|
| 106 |
+
alg="maskgit_plus",
|
| 107 |
+
alg_temp=0,
|
| 108 |
+
use_cache=False,
|
| 109 |
+
**inputs
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
generations = [
|
| 113 |
+
processor.tokenizer.decode(g[len(p):].cpu().tolist())
|
| 114 |
+
for p, g in zip(input_ids, output.sequences)
|
| 115 |
+
]
|
| 116 |
+
|
| 117 |
+
for j in range(len(messages)):
|
| 118 |
+
print("output:", j, generations[j].split(processor.tokenizer.eos_token)[0])
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
# output: The image depicts a serene beach scene featuring a young woman and a golden retriever.
|
| 122 |
+
# The woman, dressed in a plaid shirt and dark pants, is seated on the sandy shore, smiling warmly at the camera.
|
| 123 |
+
# The golden retriever, adorned with a colorful harness, sits attentively beside her, its gaze fixed on the woman.
|
| 124 |
+
# The background reveals the vast expanse of the ocean, with waves gently kissing the shore. The sky above is a clear blue, suggesting a sunny day.
|
| 125 |
+
# The overall atmosphere exudes a sense of peace and companionship between the woman and her dog.
|
| 126 |
+
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
## Citation
|
| 130 |
+
|
| 131 |
+
**BibTeX:**
|
| 132 |
+
|
| 133 |
+
```bibtex
|
| 134 |
+
@article{ye2025dreamvla,
|
| 135 |
+
title={Dream-VL & Dream-VLA: Open Vision-Language and Vision-Language-Action Models with Diffusion Language Model Backbone},
|
| 136 |
+
author={Ye, Jiacheng and Gong, Shansan and Gao, Jiahui and Fan, Junming and Wu, Shuang and Bi, Wei and Bai, Haoli and Shang, Lifeng and Kong, Lingpeng},
|
| 137 |
+
journal={arXiv preprint},
|
| 138 |
+
year={2025}
|
| 139 |
+
}
|
| 140 |
+
```
|
added_tokens.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"</tool_call>": 151658,
|
| 3 |
+
"<tool_call>": 151657,
|
| 4 |
+
"<|beginoftext|>": 151665,
|
| 5 |
+
"<|box_end|>": 151649,
|
| 6 |
+
"<|box_start|>": 151648,
|
| 7 |
+
"<|endoftext|>": 151643,
|
| 8 |
+
"<|file_sep|>": 151664,
|
| 9 |
+
"<|fim_middle|>": 151660,
|
| 10 |
+
"<|fim_pad|>": 151662,
|
| 11 |
+
"<|fim_prefix|>": 151659,
|
| 12 |
+
"<|fim_suffix|>": 151661,
|
| 13 |
+
"<|im_end|>": 151645,
|
| 14 |
+
"<|im_start|>": 151644,
|
| 15 |
+
"<|image_pad|>": 151655,
|
| 16 |
+
"<|mask|>": 151666,
|
| 17 |
+
"<|object_ref_end|>": 151647,
|
| 18 |
+
"<|object_ref_start|>": 151646,
|
| 19 |
+
"<|quad_end|>": 151651,
|
| 20 |
+
"<|quad_start|>": 151650,
|
| 21 |
+
"<|repo_name|>": 151663,
|
| 22 |
+
"<|video_pad|>": 151656,
|
| 23 |
+
"<|vision_end|>": 151653,
|
| 24 |
+
"<|vision_pad|>": 151654,
|
| 25 |
+
"<|vision_start|>": 151652
|
| 26 |
+
}
|
chat_template.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"chat_template": "{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n{% endif %}<|im_start|>{{ message['role'] }}\n{% if message['content'] is string %}{{ message['content'] }}<|im_end|>\n{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|image_pad|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|video_pad|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>\n{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}"
|
| 3 |
+
}
|
config.json
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"DreamVLModel"
|
| 4 |
+
],
|
| 5 |
+
"attention_dropout": 0.0,
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "configuration_dreamvl.DreamVLConfig",
|
| 8 |
+
"AutoModel": "modeling_dreamvl.DreamVLModel"
|
| 9 |
+
},
|
| 10 |
+
"bos_token_id": 151643,
|
| 11 |
+
"eos_token_id": 151643,
|
| 12 |
+
"full_attn_mask": true,
|
| 13 |
+
"hidden_act": "silu",
|
| 14 |
+
"hidden_size": 3584,
|
| 15 |
+
"image_token_id": 151655,
|
| 16 |
+
"initializer_range": 0.02,
|
| 17 |
+
"intermediate_size": 18944,
|
| 18 |
+
"mask_token_id": 151666,
|
| 19 |
+
"max_position_embeddings": 131072,
|
| 20 |
+
"max_window_layers": 28,
|
| 21 |
+
"model_type": "dream-vl",
|
| 22 |
+
"mrope_section": [
|
| 23 |
+
16,
|
| 24 |
+
24,
|
| 25 |
+
24
|
| 26 |
+
],
|
| 27 |
+
"num_attention_heads": 28,
|
| 28 |
+
"num_hidden_layers": 28,
|
| 29 |
+
"num_key_value_heads": 4,
|
| 30 |
+
"pad_token_id": 151643,
|
| 31 |
+
"projector_hidden_act": "gelu",
|
| 32 |
+
"rms_norm_eps": 1e-06,
|
| 33 |
+
"rope_scaling": null,
|
| 34 |
+
"rope_theta": 1000000.0,
|
| 35 |
+
"sliding_window": null,
|
| 36 |
+
"tie_word_embeddings": false,
|
| 37 |
+
"torch_dtype": "bfloat16",
|
| 38 |
+
"transformers_version": "4.51.3",
|
| 39 |
+
"use_cache": false,
|
| 40 |
+
"use_sliding_window": false,
|
| 41 |
+
"video_token_id": 151656,
|
| 42 |
+
"vision_config": {
|
| 43 |
+
"depth": 32,
|
| 44 |
+
"embed_dim": 1280,
|
| 45 |
+
"hidden_act": "quick_gelu",
|
| 46 |
+
"hidden_size": 3584,
|
| 47 |
+
"in_channels": 3,
|
| 48 |
+
"in_chans": 3,
|
| 49 |
+
"initializer_range": 0.02,
|
| 50 |
+
"mlp_ratio": 4,
|
| 51 |
+
"model_type": "dream_vl",
|
| 52 |
+
"num_heads": 16,
|
| 53 |
+
"patch_size": 14,
|
| 54 |
+
"spatial_merge_size": 2,
|
| 55 |
+
"spatial_patch_size": 14,
|
| 56 |
+
"temporal_patch_size": 2
|
| 57 |
+
},
|
| 58 |
+
"vision_end_token_id": 151653,
|
| 59 |
+
"vision_start_token_id": 151652,
|
| 60 |
+
"vision_token_id": 151654,
|
| 61 |
+
"vocab_size": 152064
|
| 62 |
+
}
|
configuration_dreamvl.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The DreamVL team and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""DreamVL model configuration"""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
from typing import Union
|
| 19 |
+
|
| 20 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 21 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
| 22 |
+
from transformers.utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger("DreamVL."+__name__)
|
| 26 |
+
|
| 27 |
+
class DreamVLVisionConfig(PretrainedConfig):
|
| 28 |
+
model_type = "dream_vl"
|
| 29 |
+
base_config_key = "vision_config"
|
| 30 |
+
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
depth=32,
|
| 34 |
+
embed_dim=1280,
|
| 35 |
+
hidden_size=3584,
|
| 36 |
+
hidden_act="quick_gelu",
|
| 37 |
+
mlp_ratio=4,
|
| 38 |
+
num_heads=16,
|
| 39 |
+
in_channels=3,
|
| 40 |
+
patch_size=14,
|
| 41 |
+
spatial_merge_size=2,
|
| 42 |
+
temporal_patch_size=2,
|
| 43 |
+
initializer_range=0.02,
|
| 44 |
+
**kwargs,
|
| 45 |
+
):
|
| 46 |
+
super().__init__(**kwargs)
|
| 47 |
+
|
| 48 |
+
self.depth = depth
|
| 49 |
+
self.embed_dim = embed_dim
|
| 50 |
+
self.hidden_size = hidden_size
|
| 51 |
+
self.hidden_act = hidden_act
|
| 52 |
+
self.mlp_ratio = mlp_ratio
|
| 53 |
+
self.num_heads = num_heads
|
| 54 |
+
self.in_channels = in_channels
|
| 55 |
+
self.patch_size = patch_size
|
| 56 |
+
self.spatial_merge_size = spatial_merge_size
|
| 57 |
+
self.temporal_patch_size = temporal_patch_size
|
| 58 |
+
self.initializer_range = initializer_range
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class DreamVLConfig(PretrainedConfig):
|
| 62 |
+
model_type = "dream-vl"
|
| 63 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 64 |
+
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
vocab_size=151936,
|
| 68 |
+
hidden_size=4096,
|
| 69 |
+
intermediate_size=22016,
|
| 70 |
+
num_hidden_layers=32,
|
| 71 |
+
num_attention_heads=32,
|
| 72 |
+
num_key_value_heads=32,
|
| 73 |
+
hidden_act="silu",
|
| 74 |
+
max_position_embeddings=32768,
|
| 75 |
+
initializer_range=0.02,
|
| 76 |
+
image_token_id = 151655,
|
| 77 |
+
video_token_id = 151656,
|
| 78 |
+
vision_end_token_id = 151653,
|
| 79 |
+
vision_start_token_id = 151652,
|
| 80 |
+
vision_token_id = 151654,
|
| 81 |
+
rms_norm_eps=1e-6,
|
| 82 |
+
use_cache=False,
|
| 83 |
+
tie_word_embeddings=False,
|
| 84 |
+
rope_theta=10000.0,
|
| 85 |
+
use_sliding_window=False,
|
| 86 |
+
sliding_window=4096,
|
| 87 |
+
max_window_layers=28,
|
| 88 |
+
attention_dropout=0.0,
|
| 89 |
+
mask_token_id=151666,
|
| 90 |
+
pad_token_id=151643,
|
| 91 |
+
vision_config=None,
|
| 92 |
+
rope_scaling=None,
|
| 93 |
+
mrope_section=[16,24,24],
|
| 94 |
+
projector_hidden_act=None,
|
| 95 |
+
**kwargs,
|
| 96 |
+
):
|
| 97 |
+
if isinstance(vision_config, dict):
|
| 98 |
+
self.vision_config = DreamVLVisionConfig(**vision_config)
|
| 99 |
+
elif vision_config is None:
|
| 100 |
+
self.vision_config = DreamVLVisionConfig()
|
| 101 |
+
|
| 102 |
+
self.vocab_size = vocab_size
|
| 103 |
+
self.max_position_embeddings = max_position_embeddings
|
| 104 |
+
self.hidden_size = hidden_size
|
| 105 |
+
self.intermediate_size = intermediate_size
|
| 106 |
+
self.num_hidden_layers = num_hidden_layers
|
| 107 |
+
self.num_attention_heads = num_attention_heads
|
| 108 |
+
self.use_sliding_window = use_sliding_window
|
| 109 |
+
self.sliding_window = sliding_window if use_sliding_window else None
|
| 110 |
+
self.max_window_layers = max_window_layers
|
| 111 |
+
self.projector_hidden_act = projector_hidden_act
|
| 112 |
+
|
| 113 |
+
# for backward compatibility
|
| 114 |
+
if num_key_value_heads is None:
|
| 115 |
+
num_key_value_heads = num_attention_heads
|
| 116 |
+
|
| 117 |
+
self.num_key_value_heads = num_key_value_heads
|
| 118 |
+
self.hidden_act = hidden_act
|
| 119 |
+
self.initializer_range = initializer_range
|
| 120 |
+
self.rms_norm_eps = rms_norm_eps
|
| 121 |
+
self.use_cache = use_cache
|
| 122 |
+
self.rope_theta = rope_theta
|
| 123 |
+
self.rope_scaling = rope_scaling
|
| 124 |
+
self.attention_dropout = attention_dropout
|
| 125 |
+
# Validate the correctness of rotary position embeddings parameters
|
| 126 |
+
# BC: if there is a 'type' field, move it to 'rope_type'.
|
| 127 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
| 128 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
| 129 |
+
rope_config_validation(self, ignore_keys={"mrope_section"})
|
| 130 |
+
self.mrope_section = mrope_section
|
| 131 |
+
|
| 132 |
+
super().__init__(
|
| 133 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 134 |
+
**kwargs,
|
| 135 |
+
)
|
| 136 |
+
self.mask_token_id = mask_token_id
|
| 137 |
+
self.pad_token_id = pad_token_id
|
| 138 |
+
self.image_token_id = image_token_id
|
| 139 |
+
self.video_token_id = video_token_id
|
| 140 |
+
self.vision_end_token_id = vision_end_token_id
|
| 141 |
+
self.vision_start_token_id = vision_start_token_id
|
| 142 |
+
self.vision_token_id = vision_token_id
|
generation_config.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 151643,
|
| 4 |
+
"eos_token_id": 151643,
|
| 5 |
+
"pad_token_id": 151643,
|
| 6 |
+
"transformers_version": "4.51.3",
|
| 7 |
+
"use_cache": false
|
| 8 |
+
}
|
generation_utils.py
ADDED
|
@@ -0,0 +1,573 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The DreamVL team and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import warnings
|
| 17 |
+
import copy
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.distributions as dists
|
| 23 |
+
from torch.nn import functional as F
|
| 24 |
+
from transformers import __version__
|
| 25 |
+
from transformers.generation.configuration_utils import (
|
| 26 |
+
GenerationConfig,
|
| 27 |
+
)
|
| 28 |
+
from transformers.utils import (
|
| 29 |
+
ModelOutput,
|
| 30 |
+
is_torchdynamo_compiling,
|
| 31 |
+
logging,
|
| 32 |
+
)
|
| 33 |
+
from transformers.cache_utils import (
|
| 34 |
+
Cache,
|
| 35 |
+
DynamicCache,
|
| 36 |
+
)
|
| 37 |
+
from transformers.generation.utils import GenerationMixin
|
| 38 |
+
from transformers import TextIteratorStreamer
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger("DreamVL."+__name__)
|
| 41 |
+
|
| 42 |
+
class FullSequenceStreamer(TextIteratorStreamer):
|
| 43 |
+
def __init__(self, tokenizer, **kwargs):
|
| 44 |
+
super().__init__(tokenizer, **kwargs)
|
| 45 |
+
|
| 46 |
+
def put(self, value, stream_end=False):
|
| 47 |
+
# Assume full token_ids are passed in every time
|
| 48 |
+
decoded = self.tokenizer.batch_decode(value, **self.decode_kwargs)
|
| 49 |
+
self.text_queue.put(decoded)
|
| 50 |
+
if stream_end:
|
| 51 |
+
self.text_queue.put(self.stop_signal, timeout=self.timeout)
|
| 52 |
+
|
| 53 |
+
def end(self):
|
| 54 |
+
self.text_queue.put(self.stop_signal, timeout=self.timeout)
|
| 55 |
+
|
| 56 |
+
def top_p_logits(logits, top_p=None):
|
| 57 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
|
| 58 |
+
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
| 59 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
| 60 |
+
# Shift the indices to the right to keep the first token above the threshold
|
| 61 |
+
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
| 62 |
+
sorted_indices_to_remove[..., 0] = 0
|
| 63 |
+
|
| 64 |
+
mask = torch.zeros_like(logits, dtype=torch.bool, device=logits.device)
|
| 65 |
+
mask = mask.scatter_(-1, sorted_indices, sorted_indices_to_remove)
|
| 66 |
+
logits = logits.masked_fill(mask, torch.finfo(logits.dtype).min)
|
| 67 |
+
return logits
|
| 68 |
+
|
| 69 |
+
def top_k_logits(logits, top_k=None):
|
| 70 |
+
top_k = min(top_k, logits.size(-1)) # Safety check
|
| 71 |
+
# Remove all tokens with a probability less than the last token of the top-k
|
| 72 |
+
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
|
| 73 |
+
logits = logits.masked_fill(indices_to_remove, torch.finfo(logits.dtype).min)
|
| 74 |
+
return logits
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def sample_tokens(logits, temperature=0.0, top_p=None, top_k=None, margin_confidence=False, neg_entropy=False):
|
| 78 |
+
|
| 79 |
+
if temperature > 0:
|
| 80 |
+
logits = logits / temperature
|
| 81 |
+
if top_p is not None and top_p < 1:
|
| 82 |
+
logits = top_p_logits(logits, top_p)
|
| 83 |
+
if top_k is not None:
|
| 84 |
+
logits = top_k_logits(logits, top_k)
|
| 85 |
+
probs = torch.softmax(logits, dim=-1)
|
| 86 |
+
|
| 87 |
+
if temperature > 0:
|
| 88 |
+
try:
|
| 89 |
+
x0 = dists.Categorical(probs=probs).sample()
|
| 90 |
+
confidence = torch.gather(probs, -1, x0.unsqueeze(-1)).squeeze(-1)
|
| 91 |
+
except:
|
| 92 |
+
confidence, x0 = probs.max(dim=-1)
|
| 93 |
+
else:
|
| 94 |
+
confidence, x0 = probs.max(dim=-1)
|
| 95 |
+
|
| 96 |
+
if margin_confidence:
|
| 97 |
+
sorted_probs, _ = torch.sort(probs, dim=-1, descending=True)
|
| 98 |
+
# Extract top1 and top2 probabilities
|
| 99 |
+
top1_probs = sorted_probs[:, 0]
|
| 100 |
+
top2_probs = sorted_probs[:, 1]
|
| 101 |
+
# Calculate confidence as top1 - top2
|
| 102 |
+
confidence = top1_probs - top2_probs
|
| 103 |
+
|
| 104 |
+
if neg_entropy:
|
| 105 |
+
epsilon = 1e-10
|
| 106 |
+
log_probs = torch.log(probs + epsilon)
|
| 107 |
+
confidence = torch.sum(probs * log_probs, dim=-1)
|
| 108 |
+
|
| 109 |
+
return confidence, x0
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@dataclass
|
| 113 |
+
class DreamVLModelOutput(ModelOutput):
|
| 114 |
+
sequences: torch.LongTensor = None
|
| 115 |
+
history: Optional[Tuple[torch.FloatTensor]] = None
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class DreamVLGenerationConfig(GenerationConfig):
|
| 119 |
+
def __init__(self, **kwargs):
|
| 120 |
+
# cache parameter
|
| 121 |
+
self.use_cache: bool = kwargs.pop("use_cache", False)
|
| 122 |
+
# general generation parameter
|
| 123 |
+
self.temperature: float = kwargs.pop("temperature", 0.0)
|
| 124 |
+
self.top_p: Optional[float] = kwargs.pop("top_p", None)
|
| 125 |
+
self.top_k: Optional[int] = kwargs.pop("top_k", None)
|
| 126 |
+
self.max_length = kwargs.pop("max_length", 20)
|
| 127 |
+
self.max_new_tokens = kwargs.pop("max_new_tokens", None)
|
| 128 |
+
# diffusion specific params
|
| 129 |
+
self.eps: float = kwargs.pop("eps", 1e-3)
|
| 130 |
+
self.steps: int = kwargs.pop("steps", 512)
|
| 131 |
+
self.alg: str = kwargs.pop("alg", 'origin')
|
| 132 |
+
self.alg_temp: Optional[float] = kwargs.pop("alg_temp", None)
|
| 133 |
+
self.eos_penalty: Optional[float] = kwargs.pop("eos_penalty", 0)
|
| 134 |
+
|
| 135 |
+
# Parameters that define the output variables of `generate`
|
| 136 |
+
self.num_return_sequences: int = kwargs.pop("num_return_sequences", 1)
|
| 137 |
+
self.return_dict_in_generate: bool = kwargs.pop("return_dict_in_generate", False)
|
| 138 |
+
self.output_history: bool = kwargs.pop("output_history", False)
|
| 139 |
+
|
| 140 |
+
# Special tokens that can be used at generation time
|
| 141 |
+
self.mask_token_id = kwargs.pop("mask_token_id", None)
|
| 142 |
+
self.pad_token_id = kwargs.pop("pad_token_id", None)
|
| 143 |
+
self.bos_token_id = kwargs.pop("bos_token_id", None)
|
| 144 |
+
self.eos_token_id = kwargs.pop("eos_token_id", None)
|
| 145 |
+
|
| 146 |
+
# Wild card
|
| 147 |
+
self.generation_kwargs = kwargs.pop("generation_kwargs", {})
|
| 148 |
+
|
| 149 |
+
# The remaining attributes do not parametrize `.generate()`, but are informative and/or used by the hub
|
| 150 |
+
# interface.
|
| 151 |
+
self._from_model_config = kwargs.pop("_from_model_config", False)
|
| 152 |
+
self._commit_hash = kwargs.pop("_commit_hash", None)
|
| 153 |
+
self.transformers_version = kwargs.pop("transformers_version", __version__)
|
| 154 |
+
|
| 155 |
+
# Additional attributes without default values
|
| 156 |
+
if not self._from_model_config:
|
| 157 |
+
# we don't want to copy values from the model config if we're initializing a `GenerationConfig` from a
|
| 158 |
+
# model's default configuration file
|
| 159 |
+
for key, value in kwargs.items():
|
| 160 |
+
try:
|
| 161 |
+
setattr(self, key, value)
|
| 162 |
+
except AttributeError as err:
|
| 163 |
+
logger.error(f"Can't set {key} with value {value} for {self}")
|
| 164 |
+
raise err
|
| 165 |
+
|
| 166 |
+
# Validate the values of the attributes
|
| 167 |
+
self.validate(is_init=True)
|
| 168 |
+
|
| 169 |
+
def validate(self, is_init=False):
|
| 170 |
+
pass
|
| 171 |
+
|
| 172 |
+
class DreamVLGenerationMixin:
|
| 173 |
+
@staticmethod
|
| 174 |
+
def _expand_inputs_for_generation(
|
| 175 |
+
expand_size: int = 1,
|
| 176 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 177 |
+
**model_kwargs
|
| 178 |
+
) -> Tuple[torch.LongTensor, Dict[str, Any]]:
|
| 179 |
+
"""Expands tensors from [batch_size, ...] to [batch_size * expand_size, ...]"""
|
| 180 |
+
pixel_values = model_kwargs.get("pixel_values", None)
|
| 181 |
+
image_grid_thw = model_kwargs.get("image_grid_thw", None)
|
| 182 |
+
if expand_size == 1:
|
| 183 |
+
return GenerationMixin._expand_inputs_for_generation(
|
| 184 |
+
expand_size=expand_size,
|
| 185 |
+
input_ids=input_ids,
|
| 186 |
+
**model_kwargs
|
| 187 |
+
)
|
| 188 |
+
elif pixel_values is None and image_grid_thw is None:
|
| 189 |
+
return GenerationMixin._expand_inputs_for_generation(
|
| 190 |
+
expand_size=expand_size,
|
| 191 |
+
input_ids=input_ids,
|
| 192 |
+
**model_kwargs
|
| 193 |
+
)
|
| 194 |
+
else:
|
| 195 |
+
raise ValueError(
|
| 196 |
+
"Does not support expansion for image inputs. "
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
def _validate_generated_length(self, generation_config, input_ids_length, has_default_max_length):
|
| 200 |
+
"""Performs validation related to the resulting generated length"""
|
| 201 |
+
|
| 202 |
+
# Can't throw warnings/exceptions during compilation
|
| 203 |
+
if is_torchdynamo_compiling():
|
| 204 |
+
return
|
| 205 |
+
|
| 206 |
+
# 1. Max length warnings related to poor parameterization
|
| 207 |
+
if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length == 20:
|
| 208 |
+
# 20 is the default max_length of the generation config
|
| 209 |
+
logger.warning_once(
|
| 210 |
+
f"Using the model-agnostic default `max_length` (={generation_config.max_length}) to control the "
|
| 211 |
+
"generation length. We recommend setting `max_new_tokens` to control the maximum length of the "
|
| 212 |
+
"generation."
|
| 213 |
+
)
|
| 214 |
+
if input_ids_length >= generation_config.max_length:
|
| 215 |
+
input_ids_string = "input_ids"
|
| 216 |
+
raise ValueError(
|
| 217 |
+
f"Input length of {input_ids_string} is {input_ids_length}, but `max_length` is set to"
|
| 218 |
+
f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
|
| 219 |
+
" increasing `max_length` or, better yet, setting `max_new_tokens`."
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
def _prepare_generated_length(
|
| 223 |
+
self,
|
| 224 |
+
generation_config,
|
| 225 |
+
has_default_max_length,
|
| 226 |
+
input_ids_length,
|
| 227 |
+
):
|
| 228 |
+
"""Prepared max and min length in generation configs to avoid clashes between similar attributes"""
|
| 229 |
+
|
| 230 |
+
if generation_config.max_new_tokens is not None:
|
| 231 |
+
if not has_default_max_length and generation_config.max_length is not None:
|
| 232 |
+
logger.warning_once(
|
| 233 |
+
f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
|
| 234 |
+
f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
|
| 235 |
+
"Please refer to the documentation for more information. "
|
| 236 |
+
"(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
|
| 237 |
+
)
|
| 238 |
+
generation_config.max_length = generation_config.max_new_tokens + input_ids_length
|
| 239 |
+
|
| 240 |
+
elif has_default_max_length:
|
| 241 |
+
if generation_config.max_length == DreamVLGenerationConfig().max_length:
|
| 242 |
+
generation_config.max_length = generation_config.max_length + input_ids_length
|
| 243 |
+
max_position_embeddings = getattr(self.config, "max_position_embeddings", None)
|
| 244 |
+
if max_position_embeddings is not None:
|
| 245 |
+
generation_config.max_length = min(generation_config.max_length, max_position_embeddings)
|
| 246 |
+
|
| 247 |
+
return generation_config
|
| 248 |
+
|
| 249 |
+
def _prepare_generation_config(
|
| 250 |
+
self, generation_config: Optional[DreamVLGenerationConfig], **kwargs: Dict
|
| 251 |
+
) -> DreamVLGenerationConfig:
|
| 252 |
+
"""
|
| 253 |
+
Prepares the base generation config, then applies any generation configuration options from kwargs. This
|
| 254 |
+
function handles retrocompatibility with respect to configuration files.
|
| 255 |
+
"""
|
| 256 |
+
# priority: `generation_config` argument > `model.generation_config` (the default generation config)
|
| 257 |
+
using_model_generation_config = False
|
| 258 |
+
if generation_config is None:
|
| 259 |
+
generation_config = DreamVLGenerationConfig.from_model_config(self.config)
|
| 260 |
+
using_model_generation_config = True
|
| 261 |
+
|
| 262 |
+
# `torch.compile` can't compile `copy.deepcopy`, arguments in `kwargs` that are part of `generation_config`
|
| 263 |
+
# will mutate the object with `.update`. As such, passing these arguments through `kwargs` is disabled -- an
|
| 264 |
+
# exception will be raised in `_validate_model_kwargs`
|
| 265 |
+
if not is_torchdynamo_compiling():
|
| 266 |
+
generation_config = copy.deepcopy(generation_config)
|
| 267 |
+
model_kwargs = generation_config.update(**kwargs)
|
| 268 |
+
# If `generation_config` is provided, let's fallback ALL special tokens to the default values for the model
|
| 269 |
+
if not using_model_generation_config:
|
| 270 |
+
if generation_config.bos_token_id is None:
|
| 271 |
+
generation_config.bos_token_id = self.generation_config.bos_token_id
|
| 272 |
+
if generation_config.eos_token_id is None:
|
| 273 |
+
generation_config.eos_token_id = self.generation_config.eos_token_id
|
| 274 |
+
if generation_config.pad_token_id is None:
|
| 275 |
+
generation_config.pad_token_id = self.generation_config.pad_token_id
|
| 276 |
+
if generation_config.mask_token_id is None:
|
| 277 |
+
generation_config.mask_token_id = self.generation_config.mask_token_id
|
| 278 |
+
|
| 279 |
+
return generation_config, model_kwargs
|
| 280 |
+
|
| 281 |
+
def _prepare_special_tokens(
|
| 282 |
+
self,
|
| 283 |
+
generation_config: DreamVLGenerationConfig,
|
| 284 |
+
device: Optional[Union[torch.device, str]] = None,
|
| 285 |
+
):
|
| 286 |
+
"""
|
| 287 |
+
Prepares the special tokens for generation, overwriting the generation config with their processed versions
|
| 288 |
+
converted to tensor.
|
| 289 |
+
Note that `generation_config` is changed in place and stops being serializable after this method is called.
|
| 290 |
+
That is no problem if called within `generate` (`generation_config` is a local copy that doesn't leave the
|
| 291 |
+
function). However, if called outside `generate`, consider creating a copy of `generation_config` first.
|
| 292 |
+
"""
|
| 293 |
+
|
| 294 |
+
# Convert special tokens to tensors
|
| 295 |
+
def _tensor_or_none(token, device=None):
|
| 296 |
+
if token is None:
|
| 297 |
+
return token
|
| 298 |
+
|
| 299 |
+
device = device if device is not None else self.device
|
| 300 |
+
if isinstance(token, torch.Tensor):
|
| 301 |
+
return token.to(device)
|
| 302 |
+
return torch.tensor(token, device=device, dtype=torch.long)
|
| 303 |
+
|
| 304 |
+
bos_token_tensor = _tensor_or_none(generation_config.bos_token_id, device=device)
|
| 305 |
+
eos_token_tensor = _tensor_or_none(generation_config.eos_token_id, device=device)
|
| 306 |
+
pad_token_tensor = _tensor_or_none(generation_config.pad_token_id, device=device)
|
| 307 |
+
mask_token_tensor = _tensor_or_none(generation_config.mask_token_id, device=device)
|
| 308 |
+
|
| 309 |
+
# We can have more than one eos token. Always treat it as a 1D tensor (when it exists).
|
| 310 |
+
if eos_token_tensor is not None and eos_token_tensor.ndim == 0:
|
| 311 |
+
eos_token_tensor = eos_token_tensor.unsqueeze(0)
|
| 312 |
+
|
| 313 |
+
# Set pad token if unset (and there are conditions to do so)
|
| 314 |
+
if pad_token_tensor is None and eos_token_tensor is not None:
|
| 315 |
+
pad_token_tensor = eos_token_tensor[0]
|
| 316 |
+
logger.warning_once(f"Setting `pad_token_id` to `eos_token_id`:{pad_token_tensor} for open-end generation.")
|
| 317 |
+
|
| 318 |
+
# Update generation config with the updated special tokens tensors
|
| 319 |
+
# NOTE: this must be written into a different attribute name than the one holding the original special tokens
|
| 320 |
+
# (in their non-tensor form), in order to enable end-to-end compilation. See
|
| 321 |
+
# https://pytorch.org/docs/stable/torch.compiler_cudagraph_trees.html#limitations
|
| 322 |
+
generation_config._bos_token_tensor = bos_token_tensor
|
| 323 |
+
generation_config._eos_token_tensor = eos_token_tensor
|
| 324 |
+
generation_config._pad_token_tensor = pad_token_tensor
|
| 325 |
+
generation_config._mask_token_tensor = mask_token_tensor
|
| 326 |
+
|
| 327 |
+
def _mask_pad_inputs_for_generation(
|
| 328 |
+
self,
|
| 329 |
+
input_ids: torch.LongTensor,
|
| 330 |
+
generation_config: DreamVLGenerationConfig,
|
| 331 |
+
**model_kwargs,
|
| 332 |
+
) -> Tuple[torch.LongTensor, Dict[str, Any]]:
|
| 333 |
+
"""
|
| 334 |
+
pad tokens in the input ids and attentions for generation. This is used to insert mask tokens into the input_ids
|
| 335 |
+
"""
|
| 336 |
+
max_length = generation_config.max_length
|
| 337 |
+
mask_token_id = generation_config.mask_token_id
|
| 338 |
+
attention_mask = model_kwargs.get("attention_mask", None)
|
| 339 |
+
|
| 340 |
+
# pad input_ids to max_length
|
| 341 |
+
input_ids = F.pad(input_ids, (0, max_length - input_ids.shape[1]), value=mask_token_id)
|
| 342 |
+
if attention_mask is not None:
|
| 343 |
+
attention_mask = F.pad(attention_mask, (0, max_length - attention_mask.shape[1]), value=1.0)
|
| 344 |
+
model_kwargs["attention_mask"] = attention_mask
|
| 345 |
+
else:
|
| 346 |
+
raise ValueError(
|
| 347 |
+
"attention_mask should be provided. "
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
return input_ids, model_kwargs
|
| 351 |
+
|
| 352 |
+
def _update_model_kwargs_for_generation(
|
| 353 |
+
self,
|
| 354 |
+
outputs: ModelOutput,
|
| 355 |
+
model_kwargs: Dict[str, Any]
|
| 356 |
+
) -> Dict[str, Any]:
|
| 357 |
+
# update past_key_values keeping its naming used in model code
|
| 358 |
+
if model_kwargs["use_cache"]:
|
| 359 |
+
assert outputs.past_key_values is not None, "Cache should not be None if use_cache is True"
|
| 360 |
+
assert outputs.past_key_values.get_seq_length() == model_kwargs["total_sequence_length"], \
|
| 361 |
+
f"Cache length {outputs.past_key_values.get_seq_length()} should be equal to the total sequence length {model_kwargs['total_sequence_length']}"
|
| 362 |
+
# The crop operation requires "left padding for batch processing"
|
| 363 |
+
outputs.past_key_values.crop(max_length = model_kwargs["prompt_length"])
|
| 364 |
+
# if model_kwargs["past_key_values"].get_seq_length() > 0:
|
| 365 |
+
# assert self.compare_past_key_values(model_kwargs["past_key_values"], outputs.past_key_values), \
|
| 366 |
+
# f"Cache {model_kwargs['past_key_values']} should be equal to the new cache {outputs.past_key_values}"
|
| 367 |
+
else:
|
| 368 |
+
assert outputs.past_key_values is None, "Cache should be None if use_cache is False"
|
| 369 |
+
model_kwargs["past_key_values"] = outputs.past_key_values
|
| 370 |
+
|
| 371 |
+
# update cache position
|
| 372 |
+
if model_kwargs["use_cache"]:
|
| 373 |
+
model_kwargs["cache_position"] = model_kwargs["cache_position"][-(model_kwargs["total_sequence_length"] - model_kwargs["prompt_length"]):]
|
| 374 |
+
else:
|
| 375 |
+
assert model_kwargs["cache_position"] is None, "Cache position should be None if use_cache is False"
|
| 376 |
+
|
| 377 |
+
if model_kwargs.get("rope_deltas", None) is not None:
|
| 378 |
+
assert torch.equal(
|
| 379 |
+
model_kwargs["rope_deltas"], outputs.rope_deltas), \
|
| 380 |
+
f"Rope deltas {model_kwargs['rope_deltas']} should be equal to the new rope deltas {outputs.rope_deltas}"
|
| 381 |
+
model_kwargs["rope_deltas"] = outputs.rope_deltas
|
| 382 |
+
return model_kwargs
|
| 383 |
+
|
| 384 |
+
@torch.no_grad()
|
| 385 |
+
def diffusion_generate(
|
| 386 |
+
self,
|
| 387 |
+
inputs: Optional[torch.Tensor] = None,
|
| 388 |
+
generation_config: Optional[DreamVLGenerationConfig] = None,
|
| 389 |
+
streamer: Optional[FullSequenceStreamer]=None,
|
| 390 |
+
**kwargs,
|
| 391 |
+
) -> Union[DreamVLModelOutput, torch.LongTensor]:
|
| 392 |
+
# 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
|
| 393 |
+
generation_config, model_kwargs = self._prepare_generation_config(generation_config, **kwargs)
|
| 394 |
+
generation_tokens_hook_func = model_kwargs.pop("generation_tokens_hook_func", lambda step, x, logits: x)
|
| 395 |
+
generation_logits_hook_func = model_kwargs.pop("generation_logits_hook_func", lambda step, x, logits: logits)
|
| 396 |
+
attention_mask = kwargs.pop("attention_mask", None)
|
| 397 |
+
|
| 398 |
+
# 2. Define model inputs
|
| 399 |
+
assert inputs is not None
|
| 400 |
+
input_ids = inputs
|
| 401 |
+
device = input_ids.device
|
| 402 |
+
self._prepare_special_tokens(generation_config, device=device)
|
| 403 |
+
|
| 404 |
+
# 3. Prepare `max_length`.
|
| 405 |
+
input_ids_length = input_ids.shape[-1]
|
| 406 |
+
has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
|
| 407 |
+
generation_config = self._prepare_generated_length(
|
| 408 |
+
generation_config=generation_config,
|
| 409 |
+
has_default_max_length=has_default_max_length,
|
| 410 |
+
input_ids_length=input_ids_length,
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
self._validate_generated_length(generation_config, input_ids_length, has_default_max_length)
|
| 414 |
+
|
| 415 |
+
# 4. Check input_ids
|
| 416 |
+
if not is_torchdynamo_compiling() and self.device.type != input_ids.device.type:
|
| 417 |
+
logger.warning_once(
|
| 418 |
+
"You are calling .generate() with the `input_ids` being on a device type different"
|
| 419 |
+
f" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model"
|
| 420 |
+
f" is on {self.device.type}. You may experience unexpected behaviors or slower generation."
|
| 421 |
+
" Please make sure that you have put `input_ids` to the"
|
| 422 |
+
f" correct device by calling for example input_ids = input_ids.to('{self.device.type}') before"
|
| 423 |
+
" running `.generate()`."
|
| 424 |
+
)
|
| 425 |
+
if (
|
| 426 |
+
hasattr(generation_config, "pad_token_id") and
|
| 427 |
+
torch.any(input_ids == generation_config.pad_token_id) and
|
| 428 |
+
attention_mask is None
|
| 429 |
+
):
|
| 430 |
+
logger.warning_once(
|
| 431 |
+
"Padding was detected but no attention mask is passed here. For correct "
|
| 432 |
+
"generation results, please set `attention_mask` when batch-padding inputs."
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
# 5. initialize kv cache
|
| 436 |
+
model_kwargs["use_cache"] = generation_config.use_cache
|
| 437 |
+
if model_kwargs["use_cache"]:
|
| 438 |
+
model_kwargs["past_key_values"] = DynamicCache()
|
| 439 |
+
model_kwargs["prompt_length"] = input_ids.shape[1] - 1
|
| 440 |
+
else:
|
| 441 |
+
model_kwargs["past_key_values"] = None
|
| 442 |
+
model_kwargs["prompt_length"] = input_ids.shape[1] - 1
|
| 443 |
+
|
| 444 |
+
# 6. Expand inputs for generation
|
| 445 |
+
input_ids, model_kwargs = self._expand_inputs_for_generation(
|
| 446 |
+
input_ids=input_ids,
|
| 447 |
+
expand_size=generation_config.num_return_sequences,
|
| 448 |
+
**model_kwargs,
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
# 7. pad mask for generation
|
| 452 |
+
input_ids, model_kwargs = self._mask_pad_inputs_for_generation(
|
| 453 |
+
input_ids=input_ids,
|
| 454 |
+
generation_config=generation_config,
|
| 455 |
+
**model_kwargs,
|
| 456 |
+
)
|
| 457 |
+
model_kwargs["total_sequence_length"] = input_ids.shape[1]
|
| 458 |
+
|
| 459 |
+
# 8. initialize cache position
|
| 460 |
+
if model_kwargs["use_cache"]:
|
| 461 |
+
model_kwargs["cache_position"] = torch.ones_like(input_ids[0, :], dtype=torch.int64).cumsum(0) - 1
|
| 462 |
+
else:
|
| 463 |
+
model_kwargs["cache_position"] = None
|
| 464 |
+
# 9. Generate
|
| 465 |
+
result = self._sample(
|
| 466 |
+
input_ids,
|
| 467 |
+
generation_config=generation_config,
|
| 468 |
+
generation_tokens_hook_func=generation_tokens_hook_func,
|
| 469 |
+
generation_logits_hook_func=generation_logits_hook_func,
|
| 470 |
+
streamer = streamer,
|
| 471 |
+
**model_kwargs,
|
| 472 |
+
)
|
| 473 |
+
return result
|
| 474 |
+
|
| 475 |
+
def _sample(
|
| 476 |
+
self,
|
| 477 |
+
input_ids: torch.LongTensor,
|
| 478 |
+
generation_config: DreamVLGenerationConfig,
|
| 479 |
+
generation_tokens_hook_func,
|
| 480 |
+
generation_logits_hook_func,
|
| 481 |
+
streamer: Optional[FullSequenceStreamer] = None,
|
| 482 |
+
**model_kwargs,
|
| 483 |
+
) -> Union[DreamVLModelOutput, torch.LongTensor]:
|
| 484 |
+
# init values
|
| 485 |
+
output_history = generation_config.output_history
|
| 486 |
+
return_dict_in_generate = generation_config.return_dict_in_generate
|
| 487 |
+
max_length = generation_config.max_length
|
| 488 |
+
mask_token_id = generation_config.mask_token_id
|
| 489 |
+
pad_token_id = generation_config.pad_token_id
|
| 490 |
+
steps = generation_config.steps
|
| 491 |
+
eps = generation_config.eps
|
| 492 |
+
alg = generation_config.alg
|
| 493 |
+
alg_temp = generation_config.alg_temp
|
| 494 |
+
temperature = generation_config.temperature
|
| 495 |
+
eos_penalty = generation_config.eos_penalty
|
| 496 |
+
top_p = generation_config.top_p
|
| 497 |
+
top_k = generation_config.top_k
|
| 498 |
+
|
| 499 |
+
histories = [] if (return_dict_in_generate and output_history) else None
|
| 500 |
+
|
| 501 |
+
timesteps = torch.linspace(1, eps, steps + 1, device=input_ids.device)
|
| 502 |
+
|
| 503 |
+
x = generation_tokens_hook_func(None, input_ids, None)
|
| 504 |
+
|
| 505 |
+
# this allows user-defined token control of the intermediate steps
|
| 506 |
+
for i in range(steps):
|
| 507 |
+
model_inputs = self.prepare_inputs_for_generation(x, **model_kwargs)
|
| 508 |
+
x = model_inputs.pop("input_ids").clone()
|
| 509 |
+
mask_index = (x == mask_token_id)
|
| 510 |
+
outputs = self(x, **model_inputs)
|
| 511 |
+
|
| 512 |
+
if 'inputs_embeds' not in model_kwargs:
|
| 513 |
+
# initialize the inputs_embeds for caching
|
| 514 |
+
model_kwargs['inputs_embeds'] = outputs.inputs_embeds
|
| 515 |
+
|
| 516 |
+
model_kwargs = self._update_model_kwargs_for_generation(outputs, model_kwargs)
|
| 517 |
+
|
| 518 |
+
logits = outputs.logits
|
| 519 |
+
assert torch.all(x[:,0] != mask_token_id), "The first token should not be a mask token"
|
| 520 |
+
logits = torch.cat([logits[:,:1], logits[:, :-1]], dim=1)
|
| 521 |
+
|
| 522 |
+
# this allows user-defined logits control of the intermediate steps
|
| 523 |
+
logits = generation_logits_hook_func(i, x, logits)
|
| 524 |
+
|
| 525 |
+
mask_logits = logits[mask_index]
|
| 526 |
+
t = timesteps[i]
|
| 527 |
+
s = timesteps[i + 1]
|
| 528 |
+
mask_logits[:,pad_token_id] += eos_penalty * torch.log(1-t+eps)
|
| 529 |
+
|
| 530 |
+
if alg == 'origin':
|
| 531 |
+
p_transfer = 1 - s / t if i < steps - 1 else 1
|
| 532 |
+
x0 = torch.zeros_like(x[mask_index], device=self.device, dtype=torch.long) + mask_token_id
|
| 533 |
+
transfer_index_t_s = torch.rand(*x0.shape, device=self.device) < p_transfer
|
| 534 |
+
_, x0[transfer_index_t_s]= sample_tokens(mask_logits[transfer_index_t_s], temperature=temperature, top_p=top_p, top_k=top_k)
|
| 535 |
+
x[mask_index] = x0.clone()
|
| 536 |
+
else:
|
| 537 |
+
if alg == 'maskgit_plus':
|
| 538 |
+
confidence, x0 = sample_tokens(mask_logits, temperature=temperature, top_p=top_p, top_k=top_k)
|
| 539 |
+
elif alg == 'topk_margin':
|
| 540 |
+
confidence, x0 = sample_tokens(mask_logits, temperature=temperature, top_p=top_p, top_k=top_k, margin_confidence=True)
|
| 541 |
+
elif alg == 'entropy':
|
| 542 |
+
confidence, x0 = sample_tokens(mask_logits, temperature, top_p=top_p, top_k=top_k, neg_entropy=True)
|
| 543 |
+
else:
|
| 544 |
+
raise RuntimeError(f"Unknown alg: {alg}")
|
| 545 |
+
num_mask_token = mask_index.sum()
|
| 546 |
+
number_transfer_tokens = int(num_mask_token * (1 - s / t)) if i < steps - 1 else num_mask_token
|
| 547 |
+
if number_transfer_tokens > 0:
|
| 548 |
+
if alg_temp is None or alg_temp == 0:
|
| 549 |
+
_, transfer_index = torch.topk(confidence, number_transfer_tokens)
|
| 550 |
+
else:
|
| 551 |
+
confidence = confidence / alg_temp
|
| 552 |
+
confidence = F.softmax(confidence, dim=-1)
|
| 553 |
+
transfer_index = torch.multinomial(confidence, num_samples=number_transfer_tokens)
|
| 554 |
+
x0_ = torch.zeros_like(x0, device=self.device, dtype=torch.long) + mask_token_id
|
| 555 |
+
x0_[transfer_index] = x0[transfer_index].clone()
|
| 556 |
+
x[mask_index] = x0_
|
| 557 |
+
|
| 558 |
+
# this allows user-defined token control of the intermediate steps
|
| 559 |
+
x = generation_tokens_hook_func(i, x, logits)
|
| 560 |
+
|
| 561 |
+
if histories is not None:
|
| 562 |
+
histories.append(x.clone())
|
| 563 |
+
|
| 564 |
+
## update inputs_embeds of all the mask tokens where some are just unmasked
|
| 565 |
+
model_kwargs['inputs_embeds'][mask_index] = self.get_input_embeddings()(x[mask_index])
|
| 566 |
+
|
| 567 |
+
if return_dict_in_generate:
|
| 568 |
+
return DreamVLModelOutput(
|
| 569 |
+
sequences=x,
|
| 570 |
+
history=histories,
|
| 571 |
+
)
|
| 572 |
+
else:
|
| 573 |
+
return x
|
image_processing_dreamvl.py
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 5 |
+
# and OPT implementations in this library. It has been modified from its
|
| 6 |
+
# original forms to accommodate minor architectural differences compared
|
| 7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
"""Image processor class for Dream-VL."""
|
| 21 |
+
|
| 22 |
+
import math
|
| 23 |
+
from typing import Dict, List, Optional, Union
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
|
| 28 |
+
from transformers.image_transforms import (
|
| 29 |
+
convert_to_rgb,
|
| 30 |
+
resize,
|
| 31 |
+
to_channel_dimension_format,
|
| 32 |
+
)
|
| 33 |
+
from transformers.image_utils import (
|
| 34 |
+
OPENAI_CLIP_MEAN,
|
| 35 |
+
OPENAI_CLIP_STD,
|
| 36 |
+
ChannelDimension,
|
| 37 |
+
ImageInput,
|
| 38 |
+
PILImageResampling,
|
| 39 |
+
VideoInput,
|
| 40 |
+
get_image_size,
|
| 41 |
+
infer_channel_dimension_format,
|
| 42 |
+
is_scaled_image,
|
| 43 |
+
is_valid_image,
|
| 44 |
+
make_list_of_images,
|
| 45 |
+
to_numpy_array,
|
| 46 |
+
valid_images,
|
| 47 |
+
validate_preprocess_arguments,
|
| 48 |
+
)
|
| 49 |
+
from transformers.utils import TensorType, is_vision_available, logging
|
| 50 |
+
|
| 51 |
+
logger = logging.get_logger(__name__)
|
| 52 |
+
|
| 53 |
+
if is_vision_available():
|
| 54 |
+
from PIL import Image
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def make_batched_images(images) -> List[List[ImageInput]]:
|
| 58 |
+
"""
|
| 59 |
+
Accepts images in list or nested list format, and makes a list of images for preprocessing.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
images (`Union[List[List[ImageInput]], List[ImageInput], ImageInput]`):
|
| 63 |
+
The input image.
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
list: A list of images.
|
| 67 |
+
"""
|
| 68 |
+
if isinstance(images, (list, tuple)) and isinstance(images[0], (list, tuple)) and is_valid_image(images[0][0]):
|
| 69 |
+
return [img for img_list in images for img in img_list]
|
| 70 |
+
|
| 71 |
+
elif isinstance(images, (list, tuple)) and is_valid_image(images[0]):
|
| 72 |
+
return images
|
| 73 |
+
|
| 74 |
+
elif is_valid_image(images):
|
| 75 |
+
return [images]
|
| 76 |
+
|
| 77 |
+
raise ValueError(f"Could not make batched images from {images}")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# Copied from transformers.models.emova_next_video.image_processing_emova_next_video.make_batched_videos
|
| 81 |
+
def make_batched_videos(videos) -> List[VideoInput]:
|
| 82 |
+
if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)) and is_valid_image(videos[0][0]):
|
| 83 |
+
return videos
|
| 84 |
+
|
| 85 |
+
elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
|
| 86 |
+
if isinstance(videos[0], Image.Image):
|
| 87 |
+
return [videos]
|
| 88 |
+
elif len(videos[0].shape) == 4:
|
| 89 |
+
return [list(video) for video in videos]
|
| 90 |
+
|
| 91 |
+
elif is_valid_image(videos) and len(videos.shape) == 4:
|
| 92 |
+
return [list(videos)]
|
| 93 |
+
|
| 94 |
+
raise ValueError(f"Could not make batched video from {videos}")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def smart_resize(
|
| 98 |
+
height: int, width: int, factor: int = 28, min_pixels: int = 56 * 56, max_pixels: int = 14 * 14 * 4 * 1280
|
| 99 |
+
):
|
| 100 |
+
"""Rescales the image so that the following conditions are met:
|
| 101 |
+
|
| 102 |
+
1. Both dimensions (height and width) are divisible by 'factor'.
|
| 103 |
+
|
| 104 |
+
2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
|
| 105 |
+
|
| 106 |
+
3. The aspect ratio of the image is maintained as closely as possible.
|
| 107 |
+
|
| 108 |
+
"""
|
| 109 |
+
if height < factor or width < factor:
|
| 110 |
+
# print("height, width", height, width)
|
| 111 |
+
if height < width:
|
| 112 |
+
h_bar = factor
|
| 113 |
+
w_bar = round(width / height * factor)
|
| 114 |
+
else:
|
| 115 |
+
h_bar = round(height / width * factor)
|
| 116 |
+
w_bar = factor
|
| 117 |
+
# print("h_bar, w_bar", h_bar, w_bar)
|
| 118 |
+
height, width = h_bar, w_bar
|
| 119 |
+
# raise ValueError(f"height:{height} or width:{width} must be larger than factor:{factor}")
|
| 120 |
+
elif max(height, width) / min(height, width) > 200:
|
| 121 |
+
raise ValueError(
|
| 122 |
+
f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
|
| 123 |
+
)
|
| 124 |
+
h_bar = round(height / factor) * factor
|
| 125 |
+
w_bar = round(width / factor) * factor
|
| 126 |
+
if h_bar * w_bar > max_pixels:
|
| 127 |
+
beta = math.sqrt((height * width) / max_pixels)
|
| 128 |
+
h_bar = math.floor(height / beta / factor) * factor
|
| 129 |
+
w_bar = math.floor(width / beta / factor) * factor
|
| 130 |
+
elif h_bar * w_bar < min_pixels:
|
| 131 |
+
beta = math.sqrt(min_pixels / (height * width))
|
| 132 |
+
h_bar = math.ceil(height * beta / factor) * factor
|
| 133 |
+
w_bar = math.ceil(width * beta / factor) * factor
|
| 134 |
+
return h_bar, w_bar
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class DreamVLImageProcessor(BaseImageProcessor):
|
| 138 |
+
r"""
|
| 139 |
+
Constructs a Dream-VL image processor that dynamically resizes images based on the original images.
|
| 140 |
+
|
| 141 |
+
Args:
|
| 142 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
| 143 |
+
Whether to resize the image's (height, width) dimensions.
|
| 144 |
+
resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
|
| 145 |
+
Resampling filter to use when resizing the image.
|
| 146 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
| 147 |
+
Whether to rescale the image by the specified scale `rescale_factor`.
|
| 148 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
| 149 |
+
Scale factor to use if rescaling the image.
|
| 150 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
| 151 |
+
Whether to normalize the image.
|
| 152 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
|
| 153 |
+
Mean to use if normalizing the image. This is a float or list of floats for each channel in the image.
|
| 154 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
|
| 155 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats for each channel in the image.
|
| 156 |
+
do_convert_rgb (`bool`, *optional*, defaults to `True`):
|
| 157 |
+
Whether to convert the image to RGB.
|
| 158 |
+
min_pixels (`int`, *optional*, defaults to `56 * 56`):
|
| 159 |
+
The min pixels of the image to resize the image.
|
| 160 |
+
max_pixels (`int`, *optional*, defaults to `28 * 28 * 1280`):
|
| 161 |
+
The max pixels of the image to resize the image.
|
| 162 |
+
patch_size (`int`, *optional*, defaults to 14):
|
| 163 |
+
The spacial patch size of the vision encoder.
|
| 164 |
+
temporal_patch_size (`int`, *optional*, defaults to 2):
|
| 165 |
+
The temporal patch size of the vision encoder.
|
| 166 |
+
merge_size (`int`, *optional*, defaults to 2):
|
| 167 |
+
The merge size of the vision encoder to llm encoder.
|
| 168 |
+
"""
|
| 169 |
+
|
| 170 |
+
model_input_names = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw"]
|
| 171 |
+
|
| 172 |
+
def __init__(
|
| 173 |
+
self,
|
| 174 |
+
do_resize: bool = True,
|
| 175 |
+
resample: PILImageResampling = PILImageResampling.BICUBIC,
|
| 176 |
+
do_rescale: bool = True,
|
| 177 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
| 178 |
+
do_normalize: bool = True,
|
| 179 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 180 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 181 |
+
do_convert_rgb: bool = True,
|
| 182 |
+
min_pixels: int = 56 * 56,
|
| 183 |
+
max_pixels: int = 28 * 28 * 1280,
|
| 184 |
+
patch_size: int = 14,
|
| 185 |
+
temporal_patch_size: int = 2,
|
| 186 |
+
merge_size: int = 2,
|
| 187 |
+
**kwargs,
|
| 188 |
+
) -> None:
|
| 189 |
+
super().__init__(**kwargs)
|
| 190 |
+
self.do_resize = do_resize
|
| 191 |
+
self.resample = resample
|
| 192 |
+
self.do_rescale = do_rescale
|
| 193 |
+
self.rescale_factor = rescale_factor
|
| 194 |
+
self.do_normalize = do_normalize
|
| 195 |
+
self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
|
| 196 |
+
self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
|
| 197 |
+
self.min_pixels = min_pixels
|
| 198 |
+
self.max_pixels = max_pixels
|
| 199 |
+
self.patch_size = patch_size
|
| 200 |
+
self.temporal_patch_size = temporal_patch_size
|
| 201 |
+
self.merge_size = merge_size
|
| 202 |
+
self.size = {"min_pixels": min_pixels, "max_pixels": max_pixels}
|
| 203 |
+
self.do_convert_rgb = do_convert_rgb
|
| 204 |
+
|
| 205 |
+
def _preprocess(
|
| 206 |
+
self,
|
| 207 |
+
images: Union[ImageInput, VideoInput],
|
| 208 |
+
do_resize: bool = None,
|
| 209 |
+
resample: PILImageResampling = None,
|
| 210 |
+
do_rescale: bool = None,
|
| 211 |
+
rescale_factor: float = None,
|
| 212 |
+
do_normalize: bool = None,
|
| 213 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 214 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 215 |
+
do_convert_rgb: bool = None,
|
| 216 |
+
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
|
| 217 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 218 |
+
):
|
| 219 |
+
"""
|
| 220 |
+
Preprocess an image or batch of images. Copy of the `preprocess` method from `CLIPImageProcessor`.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
images (`ImageInput`):
|
| 224 |
+
Image or batch of images to preprocess. Expects pixel values ranging from 0 to 255. If pixel values range from 0 to 1, set `do_rescale=False`.
|
| 225 |
+
vision_info (`List[Dict]`, *optional*):
|
| 226 |
+
Optional list of dictionaries containing additional information about vision inputs.
|
| 227 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 228 |
+
Whether to resize the image.
|
| 229 |
+
resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
|
| 230 |
+
Resampling filter to use if resizing the image. This can be one of the `PILImageResampling` enums.
|
| 231 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 232 |
+
Whether to rescale the image.
|
| 233 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 234 |
+
Scale factor to use if rescaling the image.
|
| 235 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 236 |
+
Whether to normalize the image.
|
| 237 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
| 238 |
+
Mean to use if normalizing the image. Can be a float or a list of floats corresponding to the number of channels in the image.
|
| 239 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
| 240 |
+
Standard deviation to use if normalizing the image. Can be a float or a list of floats corresponding to the number of channels in the image.
|
| 241 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
| 242 |
+
Whether to convert the image to RGB.
|
| 243 |
+
data_format (`ChannelDimension`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 244 |
+
The channel dimension format for the output image. Can be one of:
|
| 245 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 246 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 247 |
+
- Unset: Use the channel dimension format of the input image.
|
| 248 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 249 |
+
The channel dimension format for the input image. Can be one of:
|
| 250 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 251 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 252 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 253 |
+
"""
|
| 254 |
+
# import pdb; pdb.set_trace()
|
| 255 |
+
# print("images", images)
|
| 256 |
+
# for image in images:
|
| 257 |
+
# print("image", image.size)
|
| 258 |
+
images = make_list_of_images(images)
|
| 259 |
+
|
| 260 |
+
if do_convert_rgb:
|
| 261 |
+
images = [convert_to_rgb(image) for image in images]
|
| 262 |
+
|
| 263 |
+
# All transformations expect numpy arrays.
|
| 264 |
+
images = [to_numpy_array(image) for image in images]
|
| 265 |
+
|
| 266 |
+
if is_scaled_image(images[0]) and do_rescale:
|
| 267 |
+
logger.warning_once(
|
| 268 |
+
"It looks like you are trying to rescale already rescaled images. If the input"
|
| 269 |
+
" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
|
| 270 |
+
)
|
| 271 |
+
if input_data_format is None:
|
| 272 |
+
# We assume that all images have the same channel dimension format.
|
| 273 |
+
input_data_format = infer_channel_dimension_format(images[0])
|
| 274 |
+
|
| 275 |
+
height, width = get_image_size(images[0], channel_dim=input_data_format)
|
| 276 |
+
resized_height, resized_width = height, width
|
| 277 |
+
processed_images = []
|
| 278 |
+
for image in images:
|
| 279 |
+
if do_resize:
|
| 280 |
+
resized_height, resized_width = smart_resize(
|
| 281 |
+
height,
|
| 282 |
+
width,
|
| 283 |
+
factor=self.patch_size * self.merge_size,
|
| 284 |
+
min_pixels=self.min_pixels,
|
| 285 |
+
max_pixels=self.max_pixels,
|
| 286 |
+
)
|
| 287 |
+
image = resize(
|
| 288 |
+
image, size=(resized_height, resized_width), resample=resample, input_data_format=input_data_format
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
if do_rescale:
|
| 292 |
+
image = self.rescale(image, scale=rescale_factor, input_data_format=input_data_format)
|
| 293 |
+
|
| 294 |
+
if do_normalize:
|
| 295 |
+
image = self.normalize(
|
| 296 |
+
image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
|
| 300 |
+
processed_images.append(image)
|
| 301 |
+
|
| 302 |
+
patches = np.array(processed_images)
|
| 303 |
+
if data_format == ChannelDimension.LAST:
|
| 304 |
+
patches = patches.transpose(0, 3, 1, 2)
|
| 305 |
+
if patches.shape[0] == 1:
|
| 306 |
+
patches = np.tile(patches, (self.temporal_patch_size, 1, 1, 1))
|
| 307 |
+
channel = patches.shape[1]
|
| 308 |
+
grid_t = patches.shape[0] // self.temporal_patch_size
|
| 309 |
+
grid_h, grid_w = resized_height // self.patch_size, resized_width // self.patch_size
|
| 310 |
+
patches = patches.reshape(
|
| 311 |
+
grid_t,
|
| 312 |
+
self.temporal_patch_size,
|
| 313 |
+
channel,
|
| 314 |
+
grid_h // self.merge_size,
|
| 315 |
+
self.merge_size,
|
| 316 |
+
self.patch_size,
|
| 317 |
+
grid_w // self.merge_size,
|
| 318 |
+
self.merge_size,
|
| 319 |
+
self.patch_size,
|
| 320 |
+
)
|
| 321 |
+
patches = patches.transpose(0, 3, 6, 4, 7, 2, 1, 5, 8)
|
| 322 |
+
flatten_patches = patches.reshape(
|
| 323 |
+
grid_t * grid_h * grid_w, channel * self.temporal_patch_size * self.patch_size * self.patch_size
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
return flatten_patches, (grid_t, grid_h, grid_w)
|
| 327 |
+
|
| 328 |
+
def preprocess(
|
| 329 |
+
self,
|
| 330 |
+
images: ImageInput,
|
| 331 |
+
videos: VideoInput = None,
|
| 332 |
+
do_resize: bool = None,
|
| 333 |
+
size: Dict[str, int] = None,
|
| 334 |
+
resample: PILImageResampling = None,
|
| 335 |
+
do_rescale: bool = None,
|
| 336 |
+
rescale_factor: float = None,
|
| 337 |
+
do_normalize: bool = None,
|
| 338 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
| 339 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
| 340 |
+
do_convert_rgb: bool = None,
|
| 341 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 342 |
+
data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
|
| 343 |
+
input_data_format: Optional[Union[str, ChannelDimension]] = None,
|
| 344 |
+
):
|
| 345 |
+
"""
|
| 346 |
+
Args:
|
| 347 |
+
images (`ImageInput`):
|
| 348 |
+
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
|
| 349 |
+
passing in images with pixel values between 0 and 1, set `do_rescale=False`.
|
| 350 |
+
videos (`VideoInput`):
|
| 351 |
+
Video to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If
|
| 352 |
+
passing in videos with pixel values between 0 and 1, set `do_rescale=False`.
|
| 353 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
| 354 |
+
Whether to resize the image.
|
| 355 |
+
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
|
| 356 |
+
Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
|
| 357 |
+
the longest edge resized to keep the input aspect ratio.
|
| 358 |
+
resample (`int`, *optional*, defaults to `self.resample`):
|
| 359 |
+
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
|
| 360 |
+
has an effect if `do_resize` is set to `True`.
|
| 361 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
| 362 |
+
Whether to rescale the image.
|
| 363 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
| 364 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
| 365 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
| 366 |
+
Whether to normalize the image.
|
| 367 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
| 368 |
+
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
|
| 369 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
| 370 |
+
Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
|
| 371 |
+
`True`.
|
| 372 |
+
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
|
| 373 |
+
Whether to convert the image to RGB.
|
| 374 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
| 375 |
+
The type of tensors to return. Can be one of:
|
| 376 |
+
- Unset: Return a list of `np.ndarray`.
|
| 377 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
| 378 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
| 379 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
| 380 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
| 381 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
| 382 |
+
The channel dimension format for the output image. Can be one of:
|
| 383 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 384 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 385 |
+
- Unset: Use the channel dimension format of the input image.
|
| 386 |
+
input_data_format (`ChannelDimension` or `str`, *optional*):
|
| 387 |
+
The channel dimension format for the input image. If unset, the channel dimension format is inferred
|
| 388 |
+
from the input image. Can be one of:
|
| 389 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
| 390 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
| 391 |
+
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
|
| 392 |
+
|
| 393 |
+
"""
|
| 394 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
| 395 |
+
size = size if size is not None else self.size
|
| 396 |
+
resample = resample if resample is not None else self.resample
|
| 397 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
| 398 |
+
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
|
| 399 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
| 400 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
| 401 |
+
image_std = image_std if image_std is not None else self.image_std
|
| 402 |
+
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
|
| 403 |
+
|
| 404 |
+
if images is not None:
|
| 405 |
+
images = make_batched_images(images)
|
| 406 |
+
if videos is not None:
|
| 407 |
+
videos = make_batched_videos(videos)
|
| 408 |
+
|
| 409 |
+
if images is not None and not valid_images(images):
|
| 410 |
+
raise ValueError(
|
| 411 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
| 412 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
validate_preprocess_arguments(
|
| 416 |
+
rescale_factor=rescale_factor,
|
| 417 |
+
do_normalize=do_normalize,
|
| 418 |
+
image_mean=image_mean,
|
| 419 |
+
image_std=image_std,
|
| 420 |
+
do_resize=do_resize,
|
| 421 |
+
size=size,
|
| 422 |
+
resample=resample,
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
if images is not None:
|
| 426 |
+
pixel_values, vision_grid_thws = [], []
|
| 427 |
+
for image in images:
|
| 428 |
+
patches, image_grid_thw = self._preprocess(
|
| 429 |
+
image,
|
| 430 |
+
do_resize=do_resize,
|
| 431 |
+
resample=resample,
|
| 432 |
+
do_rescale=do_rescale,
|
| 433 |
+
rescale_factor=rescale_factor,
|
| 434 |
+
do_normalize=do_normalize,
|
| 435 |
+
image_mean=image_mean,
|
| 436 |
+
image_std=image_std,
|
| 437 |
+
data_format=data_format,
|
| 438 |
+
do_convert_rgb=do_convert_rgb,
|
| 439 |
+
input_data_format=input_data_format,
|
| 440 |
+
)
|
| 441 |
+
pixel_values.extend(patches)
|
| 442 |
+
vision_grid_thws.append(image_grid_thw)
|
| 443 |
+
pixel_values = np.array(pixel_values)
|
| 444 |
+
vision_grid_thws = np.array(vision_grid_thws)
|
| 445 |
+
data = {"pixel_values": pixel_values, "image_grid_thw": vision_grid_thws}
|
| 446 |
+
|
| 447 |
+
if videos is not None:
|
| 448 |
+
pixel_values, vision_grid_thws = [], []
|
| 449 |
+
for images in videos:
|
| 450 |
+
patches, video_grid_thw = self._preprocess(
|
| 451 |
+
images,
|
| 452 |
+
do_resize=do_resize,
|
| 453 |
+
resample=resample,
|
| 454 |
+
do_rescale=do_rescale,
|
| 455 |
+
rescale_factor=rescale_factor,
|
| 456 |
+
do_normalize=do_normalize,
|
| 457 |
+
image_mean=image_mean,
|
| 458 |
+
image_std=image_std,
|
| 459 |
+
data_format=data_format,
|
| 460 |
+
do_convert_rgb=do_convert_rgb,
|
| 461 |
+
input_data_format=input_data_format,
|
| 462 |
+
)
|
| 463 |
+
pixel_values.extend(patches)
|
| 464 |
+
vision_grid_thws.append(video_grid_thw)
|
| 465 |
+
pixel_values = np.array(pixel_values)
|
| 466 |
+
vision_grid_thws = np.array(vision_grid_thws)
|
| 467 |
+
data = {"pixel_values_videos": pixel_values, "video_grid_thw": vision_grid_thws}
|
| 468 |
+
|
| 469 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model-00001-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e02923172aea9f20f153dd757d6130b6b13b6127e9cfd5a21ab729876f353916
|
| 3 |
+
size 4966659944
|
model-00002-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bfb5526cece03cfc9eaae5165ab6e2051135fa94ade9162a58c65ef4d8fc5a51
|
| 3 |
+
size 4991495816
|
model-00003-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8de04723034801fb8c47bc623a5148a20031fbdfae8448dc41b162f25262824e
|
| 3 |
+
size 4932751040
|
model-00004-of-00004.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1988f4e1766b0948424ed1e6dfb8d97f2cbfe98bccc0172d96f8b30b1bcde2c4
|
| 3 |
+
size 1743319344
|
model.safetensors.index.json
ADDED
|
@@ -0,0 +1,741 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"metadata": {
|
| 3 |
+
"total_size": 16634145792
|
| 4 |
+
},
|
| 5 |
+
"weight_map": {
|
| 6 |
+
"lm_head.weight": "model-00004-of-00004.safetensors",
|
| 7 |
+
"model.embed_tokens.weight": "model-00001-of-00004.safetensors",
|
| 8 |
+
"model.layers.0.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 9 |
+
"model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
| 10 |
+
"model.layers.0.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
| 11 |
+
"model.layers.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
| 12 |
+
"model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 13 |
+
"model.layers.0.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
| 14 |
+
"model.layers.0.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
| 15 |
+
"model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
| 16 |
+
"model.layers.0.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
| 17 |
+
"model.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
| 18 |
+
"model.layers.0.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
| 19 |
+
"model.layers.0.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
| 20 |
+
"model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 21 |
+
"model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
| 22 |
+
"model.layers.1.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
| 23 |
+
"model.layers.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
| 24 |
+
"model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 25 |
+
"model.layers.1.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
| 26 |
+
"model.layers.1.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
| 27 |
+
"model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
| 28 |
+
"model.layers.1.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
| 29 |
+
"model.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
| 30 |
+
"model.layers.1.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
| 31 |
+
"model.layers.1.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
| 32 |
+
"model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 33 |
+
"model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 34 |
+
"model.layers.10.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 35 |
+
"model.layers.10.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 36 |
+
"model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 37 |
+
"model.layers.10.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
| 38 |
+
"model.layers.10.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 39 |
+
"model.layers.10.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 40 |
+
"model.layers.10.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
| 41 |
+
"model.layers.10.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 42 |
+
"model.layers.10.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
| 43 |
+
"model.layers.10.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 44 |
+
"model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 45 |
+
"model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 46 |
+
"model.layers.11.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 47 |
+
"model.layers.11.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 48 |
+
"model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 49 |
+
"model.layers.11.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
| 50 |
+
"model.layers.11.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 51 |
+
"model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 52 |
+
"model.layers.11.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
| 53 |
+
"model.layers.11.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 54 |
+
"model.layers.11.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
| 55 |
+
"model.layers.11.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 56 |
+
"model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 57 |
+
"model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 58 |
+
"model.layers.12.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 59 |
+
"model.layers.12.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 60 |
+
"model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 61 |
+
"model.layers.12.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
| 62 |
+
"model.layers.12.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 63 |
+
"model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 64 |
+
"model.layers.12.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
| 65 |
+
"model.layers.12.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 66 |
+
"model.layers.12.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
| 67 |
+
"model.layers.12.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 68 |
+
"model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 69 |
+
"model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 70 |
+
"model.layers.13.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 71 |
+
"model.layers.13.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 72 |
+
"model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 73 |
+
"model.layers.13.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
| 74 |
+
"model.layers.13.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 75 |
+
"model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 76 |
+
"model.layers.13.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
| 77 |
+
"model.layers.13.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 78 |
+
"model.layers.13.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
| 79 |
+
"model.layers.13.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 80 |
+
"model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 81 |
+
"model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 82 |
+
"model.layers.14.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 83 |
+
"model.layers.14.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 84 |
+
"model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 85 |
+
"model.layers.14.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
| 86 |
+
"model.layers.14.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 87 |
+
"model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 88 |
+
"model.layers.14.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
| 89 |
+
"model.layers.14.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 90 |
+
"model.layers.14.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
| 91 |
+
"model.layers.14.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 92 |
+
"model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 93 |
+
"model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 94 |
+
"model.layers.15.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 95 |
+
"model.layers.15.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 96 |
+
"model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 97 |
+
"model.layers.15.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
| 98 |
+
"model.layers.15.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 99 |
+
"model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 100 |
+
"model.layers.15.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
| 101 |
+
"model.layers.15.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 102 |
+
"model.layers.15.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
| 103 |
+
"model.layers.15.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 104 |
+
"model.layers.16.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 105 |
+
"model.layers.16.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 106 |
+
"model.layers.16.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 107 |
+
"model.layers.16.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 108 |
+
"model.layers.16.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 109 |
+
"model.layers.16.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
| 110 |
+
"model.layers.16.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 111 |
+
"model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 112 |
+
"model.layers.16.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
| 113 |
+
"model.layers.16.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 114 |
+
"model.layers.16.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
| 115 |
+
"model.layers.16.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 116 |
+
"model.layers.17.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 117 |
+
"model.layers.17.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 118 |
+
"model.layers.17.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 119 |
+
"model.layers.17.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 120 |
+
"model.layers.17.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 121 |
+
"model.layers.17.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
| 122 |
+
"model.layers.17.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 123 |
+
"model.layers.17.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 124 |
+
"model.layers.17.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
| 125 |
+
"model.layers.17.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 126 |
+
"model.layers.17.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
| 127 |
+
"model.layers.17.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 128 |
+
"model.layers.18.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 129 |
+
"model.layers.18.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 130 |
+
"model.layers.18.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 131 |
+
"model.layers.18.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 132 |
+
"model.layers.18.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 133 |
+
"model.layers.18.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
| 134 |
+
"model.layers.18.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 135 |
+
"model.layers.18.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 136 |
+
"model.layers.18.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
| 137 |
+
"model.layers.18.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 138 |
+
"model.layers.18.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
| 139 |
+
"model.layers.18.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 140 |
+
"model.layers.19.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 141 |
+
"model.layers.19.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 142 |
+
"model.layers.19.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 143 |
+
"model.layers.19.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 144 |
+
"model.layers.19.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 145 |
+
"model.layers.19.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
| 146 |
+
"model.layers.19.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 147 |
+
"model.layers.19.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 148 |
+
"model.layers.19.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
| 149 |
+
"model.layers.19.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 150 |
+
"model.layers.19.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
| 151 |
+
"model.layers.19.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 152 |
+
"model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 153 |
+
"model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
| 154 |
+
"model.layers.2.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
| 155 |
+
"model.layers.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
| 156 |
+
"model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 157 |
+
"model.layers.2.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
| 158 |
+
"model.layers.2.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
| 159 |
+
"model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
| 160 |
+
"model.layers.2.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
| 161 |
+
"model.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
| 162 |
+
"model.layers.2.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
| 163 |
+
"model.layers.2.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
| 164 |
+
"model.layers.20.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 165 |
+
"model.layers.20.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 166 |
+
"model.layers.20.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 167 |
+
"model.layers.20.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 168 |
+
"model.layers.20.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 169 |
+
"model.layers.20.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
| 170 |
+
"model.layers.20.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 171 |
+
"model.layers.20.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 172 |
+
"model.layers.20.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
| 173 |
+
"model.layers.20.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 174 |
+
"model.layers.20.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
| 175 |
+
"model.layers.20.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 176 |
+
"model.layers.21.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 177 |
+
"model.layers.21.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 178 |
+
"model.layers.21.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 179 |
+
"model.layers.21.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 180 |
+
"model.layers.21.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 181 |
+
"model.layers.21.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
| 182 |
+
"model.layers.21.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 183 |
+
"model.layers.21.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 184 |
+
"model.layers.21.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
| 185 |
+
"model.layers.21.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 186 |
+
"model.layers.21.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
| 187 |
+
"model.layers.21.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 188 |
+
"model.layers.22.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 189 |
+
"model.layers.22.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 190 |
+
"model.layers.22.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 191 |
+
"model.layers.22.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 192 |
+
"model.layers.22.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 193 |
+
"model.layers.22.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
| 194 |
+
"model.layers.22.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 195 |
+
"model.layers.22.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 196 |
+
"model.layers.22.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
| 197 |
+
"model.layers.22.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 198 |
+
"model.layers.22.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
| 199 |
+
"model.layers.22.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 200 |
+
"model.layers.23.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 201 |
+
"model.layers.23.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 202 |
+
"model.layers.23.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 203 |
+
"model.layers.23.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 204 |
+
"model.layers.23.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 205 |
+
"model.layers.23.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
| 206 |
+
"model.layers.23.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 207 |
+
"model.layers.23.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 208 |
+
"model.layers.23.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
| 209 |
+
"model.layers.23.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 210 |
+
"model.layers.23.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
| 211 |
+
"model.layers.23.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 212 |
+
"model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 213 |
+
"model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 214 |
+
"model.layers.24.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 215 |
+
"model.layers.24.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 216 |
+
"model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 217 |
+
"model.layers.24.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
| 218 |
+
"model.layers.24.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 219 |
+
"model.layers.24.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 220 |
+
"model.layers.24.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
| 221 |
+
"model.layers.24.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 222 |
+
"model.layers.24.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
| 223 |
+
"model.layers.24.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 224 |
+
"model.layers.25.input_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 225 |
+
"model.layers.25.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
|
| 226 |
+
"model.layers.25.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 227 |
+
"model.layers.25.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 228 |
+
"model.layers.25.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
|
| 229 |
+
"model.layers.25.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
| 230 |
+
"model.layers.25.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 231 |
+
"model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 232 |
+
"model.layers.25.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
| 233 |
+
"model.layers.25.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 234 |
+
"model.layers.25.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
| 235 |
+
"model.layers.25.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 236 |
+
"model.layers.26.input_layernorm.weight": "model-00004-of-00004.safetensors",
|
| 237 |
+
"model.layers.26.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
|
| 238 |
+
"model.layers.26.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
|
| 239 |
+
"model.layers.26.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
|
| 240 |
+
"model.layers.26.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
|
| 241 |
+
"model.layers.26.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
|
| 242 |
+
"model.layers.26.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
|
| 243 |
+
"model.layers.26.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
|
| 244 |
+
"model.layers.26.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
|
| 245 |
+
"model.layers.26.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
|
| 246 |
+
"model.layers.26.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
|
| 247 |
+
"model.layers.26.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
|
| 248 |
+
"model.layers.27.input_layernorm.weight": "model-00004-of-00004.safetensors",
|
| 249 |
+
"model.layers.27.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
|
| 250 |
+
"model.layers.27.mlp.gate_proj.weight": "model-00004-of-00004.safetensors",
|
| 251 |
+
"model.layers.27.mlp.up_proj.weight": "model-00004-of-00004.safetensors",
|
| 252 |
+
"model.layers.27.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
|
| 253 |
+
"model.layers.27.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
|
| 254 |
+
"model.layers.27.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
|
| 255 |
+
"model.layers.27.self_attn.o_proj.weight": "model-00004-of-00004.safetensors",
|
| 256 |
+
"model.layers.27.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
|
| 257 |
+
"model.layers.27.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
|
| 258 |
+
"model.layers.27.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
|
| 259 |
+
"model.layers.27.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
|
| 260 |
+
"model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 261 |
+
"model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
| 262 |
+
"model.layers.3.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
| 263 |
+
"model.layers.3.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
| 264 |
+
"model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 265 |
+
"model.layers.3.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
| 266 |
+
"model.layers.3.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
| 267 |
+
"model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
| 268 |
+
"model.layers.3.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
| 269 |
+
"model.layers.3.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
| 270 |
+
"model.layers.3.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
| 271 |
+
"model.layers.3.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
| 272 |
+
"model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 273 |
+
"model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
|
| 274 |
+
"model.layers.4.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
| 275 |
+
"model.layers.4.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
|
| 276 |
+
"model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
|
| 277 |
+
"model.layers.4.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
| 278 |
+
"model.layers.4.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
| 279 |
+
"model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
| 280 |
+
"model.layers.4.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
| 281 |
+
"model.layers.4.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
| 282 |
+
"model.layers.4.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
| 283 |
+
"model.layers.4.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
| 284 |
+
"model.layers.5.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 285 |
+
"model.layers.5.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 286 |
+
"model.layers.5.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
|
| 287 |
+
"model.layers.5.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 288 |
+
"model.layers.5.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 289 |
+
"model.layers.5.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
|
| 290 |
+
"model.layers.5.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
|
| 291 |
+
"model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
|
| 292 |
+
"model.layers.5.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
|
| 293 |
+
"model.layers.5.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
|
| 294 |
+
"model.layers.5.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
|
| 295 |
+
"model.layers.5.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
|
| 296 |
+
"model.layers.6.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 297 |
+
"model.layers.6.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 298 |
+
"model.layers.6.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 299 |
+
"model.layers.6.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 300 |
+
"model.layers.6.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 301 |
+
"model.layers.6.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
| 302 |
+
"model.layers.6.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 303 |
+
"model.layers.6.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 304 |
+
"model.layers.6.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
| 305 |
+
"model.layers.6.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 306 |
+
"model.layers.6.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
| 307 |
+
"model.layers.6.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 308 |
+
"model.layers.7.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 309 |
+
"model.layers.7.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 310 |
+
"model.layers.7.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 311 |
+
"model.layers.7.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 312 |
+
"model.layers.7.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 313 |
+
"model.layers.7.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
| 314 |
+
"model.layers.7.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 315 |
+
"model.layers.7.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 316 |
+
"model.layers.7.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
| 317 |
+
"model.layers.7.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 318 |
+
"model.layers.7.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
| 319 |
+
"model.layers.7.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 320 |
+
"model.layers.8.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 321 |
+
"model.layers.8.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 322 |
+
"model.layers.8.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 323 |
+
"model.layers.8.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 324 |
+
"model.layers.8.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 325 |
+
"model.layers.8.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
| 326 |
+
"model.layers.8.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 327 |
+
"model.layers.8.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 328 |
+
"model.layers.8.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
| 329 |
+
"model.layers.8.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 330 |
+
"model.layers.8.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
| 331 |
+
"model.layers.8.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 332 |
+
"model.layers.9.input_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 333 |
+
"model.layers.9.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
|
| 334 |
+
"model.layers.9.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
|
| 335 |
+
"model.layers.9.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
|
| 336 |
+
"model.layers.9.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
|
| 337 |
+
"model.layers.9.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
|
| 338 |
+
"model.layers.9.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
|
| 339 |
+
"model.layers.9.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
|
| 340 |
+
"model.layers.9.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
|
| 341 |
+
"model.layers.9.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
|
| 342 |
+
"model.layers.9.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
|
| 343 |
+
"model.layers.9.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
|
| 344 |
+
"model.norm.weight": "model-00004-of-00004.safetensors",
|
| 345 |
+
"projector.linear_1.bias": "model-00004-of-00004.safetensors",
|
| 346 |
+
"projector.linear_1.weight": "model-00004-of-00004.safetensors",
|
| 347 |
+
"projector.linear_2.bias": "model-00004-of-00004.safetensors",
|
| 348 |
+
"projector.linear_2.weight": "model-00004-of-00004.safetensors",
|
| 349 |
+
"visual.blocks.0.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 350 |
+
"visual.blocks.0.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 351 |
+
"visual.blocks.0.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 352 |
+
"visual.blocks.0.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 353 |
+
"visual.blocks.0.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 354 |
+
"visual.blocks.0.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 355 |
+
"visual.blocks.0.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 356 |
+
"visual.blocks.0.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 357 |
+
"visual.blocks.0.norm1.bias": "model-00001-of-00004.safetensors",
|
| 358 |
+
"visual.blocks.0.norm1.weight": "model-00001-of-00004.safetensors",
|
| 359 |
+
"visual.blocks.0.norm2.bias": "model-00001-of-00004.safetensors",
|
| 360 |
+
"visual.blocks.0.norm2.weight": "model-00001-of-00004.safetensors",
|
| 361 |
+
"visual.blocks.1.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 362 |
+
"visual.blocks.1.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 363 |
+
"visual.blocks.1.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 364 |
+
"visual.blocks.1.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 365 |
+
"visual.blocks.1.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 366 |
+
"visual.blocks.1.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 367 |
+
"visual.blocks.1.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 368 |
+
"visual.blocks.1.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 369 |
+
"visual.blocks.1.norm1.bias": "model-00001-of-00004.safetensors",
|
| 370 |
+
"visual.blocks.1.norm1.weight": "model-00001-of-00004.safetensors",
|
| 371 |
+
"visual.blocks.1.norm2.bias": "model-00001-of-00004.safetensors",
|
| 372 |
+
"visual.blocks.1.norm2.weight": "model-00001-of-00004.safetensors",
|
| 373 |
+
"visual.blocks.10.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 374 |
+
"visual.blocks.10.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 375 |
+
"visual.blocks.10.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 376 |
+
"visual.blocks.10.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 377 |
+
"visual.blocks.10.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 378 |
+
"visual.blocks.10.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 379 |
+
"visual.blocks.10.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 380 |
+
"visual.blocks.10.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 381 |
+
"visual.blocks.10.norm1.bias": "model-00001-of-00004.safetensors",
|
| 382 |
+
"visual.blocks.10.norm1.weight": "model-00001-of-00004.safetensors",
|
| 383 |
+
"visual.blocks.10.norm2.bias": "model-00001-of-00004.safetensors",
|
| 384 |
+
"visual.blocks.10.norm2.weight": "model-00001-of-00004.safetensors",
|
| 385 |
+
"visual.blocks.11.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 386 |
+
"visual.blocks.11.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 387 |
+
"visual.blocks.11.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 388 |
+
"visual.blocks.11.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 389 |
+
"visual.blocks.11.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 390 |
+
"visual.blocks.11.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 391 |
+
"visual.blocks.11.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 392 |
+
"visual.blocks.11.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 393 |
+
"visual.blocks.11.norm1.bias": "model-00001-of-00004.safetensors",
|
| 394 |
+
"visual.blocks.11.norm1.weight": "model-00001-of-00004.safetensors",
|
| 395 |
+
"visual.blocks.11.norm2.bias": "model-00001-of-00004.safetensors",
|
| 396 |
+
"visual.blocks.11.norm2.weight": "model-00001-of-00004.safetensors",
|
| 397 |
+
"visual.blocks.12.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 398 |
+
"visual.blocks.12.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 399 |
+
"visual.blocks.12.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 400 |
+
"visual.blocks.12.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 401 |
+
"visual.blocks.12.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 402 |
+
"visual.blocks.12.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 403 |
+
"visual.blocks.12.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 404 |
+
"visual.blocks.12.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 405 |
+
"visual.blocks.12.norm1.bias": "model-00001-of-00004.safetensors",
|
| 406 |
+
"visual.blocks.12.norm1.weight": "model-00001-of-00004.safetensors",
|
| 407 |
+
"visual.blocks.12.norm2.bias": "model-00001-of-00004.safetensors",
|
| 408 |
+
"visual.blocks.12.norm2.weight": "model-00001-of-00004.safetensors",
|
| 409 |
+
"visual.blocks.13.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 410 |
+
"visual.blocks.13.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 411 |
+
"visual.blocks.13.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 412 |
+
"visual.blocks.13.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 413 |
+
"visual.blocks.13.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 414 |
+
"visual.blocks.13.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 415 |
+
"visual.blocks.13.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 416 |
+
"visual.blocks.13.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 417 |
+
"visual.blocks.13.norm1.bias": "model-00001-of-00004.safetensors",
|
| 418 |
+
"visual.blocks.13.norm1.weight": "model-00001-of-00004.safetensors",
|
| 419 |
+
"visual.blocks.13.norm2.bias": "model-00001-of-00004.safetensors",
|
| 420 |
+
"visual.blocks.13.norm2.weight": "model-00001-of-00004.safetensors",
|
| 421 |
+
"visual.blocks.14.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 422 |
+
"visual.blocks.14.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 423 |
+
"visual.blocks.14.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 424 |
+
"visual.blocks.14.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 425 |
+
"visual.blocks.14.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 426 |
+
"visual.blocks.14.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 427 |
+
"visual.blocks.14.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 428 |
+
"visual.blocks.14.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 429 |
+
"visual.blocks.14.norm1.bias": "model-00001-of-00004.safetensors",
|
| 430 |
+
"visual.blocks.14.norm1.weight": "model-00001-of-00004.safetensors",
|
| 431 |
+
"visual.blocks.14.norm2.bias": "model-00001-of-00004.safetensors",
|
| 432 |
+
"visual.blocks.14.norm2.weight": "model-00001-of-00004.safetensors",
|
| 433 |
+
"visual.blocks.15.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 434 |
+
"visual.blocks.15.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 435 |
+
"visual.blocks.15.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 436 |
+
"visual.blocks.15.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 437 |
+
"visual.blocks.15.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 438 |
+
"visual.blocks.15.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 439 |
+
"visual.blocks.15.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 440 |
+
"visual.blocks.15.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 441 |
+
"visual.blocks.15.norm1.bias": "model-00001-of-00004.safetensors",
|
| 442 |
+
"visual.blocks.15.norm1.weight": "model-00001-of-00004.safetensors",
|
| 443 |
+
"visual.blocks.15.norm2.bias": "model-00001-of-00004.safetensors",
|
| 444 |
+
"visual.blocks.15.norm2.weight": "model-00001-of-00004.safetensors",
|
| 445 |
+
"visual.blocks.16.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 446 |
+
"visual.blocks.16.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 447 |
+
"visual.blocks.16.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 448 |
+
"visual.blocks.16.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 449 |
+
"visual.blocks.16.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 450 |
+
"visual.blocks.16.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 451 |
+
"visual.blocks.16.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 452 |
+
"visual.blocks.16.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 453 |
+
"visual.blocks.16.norm1.bias": "model-00001-of-00004.safetensors",
|
| 454 |
+
"visual.blocks.16.norm1.weight": "model-00001-of-00004.safetensors",
|
| 455 |
+
"visual.blocks.16.norm2.bias": "model-00001-of-00004.safetensors",
|
| 456 |
+
"visual.blocks.16.norm2.weight": "model-00001-of-00004.safetensors",
|
| 457 |
+
"visual.blocks.17.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 458 |
+
"visual.blocks.17.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 459 |
+
"visual.blocks.17.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 460 |
+
"visual.blocks.17.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 461 |
+
"visual.blocks.17.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 462 |
+
"visual.blocks.17.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 463 |
+
"visual.blocks.17.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 464 |
+
"visual.blocks.17.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 465 |
+
"visual.blocks.17.norm1.bias": "model-00001-of-00004.safetensors",
|
| 466 |
+
"visual.blocks.17.norm1.weight": "model-00001-of-00004.safetensors",
|
| 467 |
+
"visual.blocks.17.norm2.bias": "model-00001-of-00004.safetensors",
|
| 468 |
+
"visual.blocks.17.norm2.weight": "model-00001-of-00004.safetensors",
|
| 469 |
+
"visual.blocks.18.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 470 |
+
"visual.blocks.18.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 471 |
+
"visual.blocks.18.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 472 |
+
"visual.blocks.18.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 473 |
+
"visual.blocks.18.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 474 |
+
"visual.blocks.18.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 475 |
+
"visual.blocks.18.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 476 |
+
"visual.blocks.18.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 477 |
+
"visual.blocks.18.norm1.bias": "model-00001-of-00004.safetensors",
|
| 478 |
+
"visual.blocks.18.norm1.weight": "model-00001-of-00004.safetensors",
|
| 479 |
+
"visual.blocks.18.norm2.bias": "model-00001-of-00004.safetensors",
|
| 480 |
+
"visual.blocks.18.norm2.weight": "model-00001-of-00004.safetensors",
|
| 481 |
+
"visual.blocks.19.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 482 |
+
"visual.blocks.19.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 483 |
+
"visual.blocks.19.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 484 |
+
"visual.blocks.19.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 485 |
+
"visual.blocks.19.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 486 |
+
"visual.blocks.19.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 487 |
+
"visual.blocks.19.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 488 |
+
"visual.blocks.19.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 489 |
+
"visual.blocks.19.norm1.bias": "model-00001-of-00004.safetensors",
|
| 490 |
+
"visual.blocks.19.norm1.weight": "model-00001-of-00004.safetensors",
|
| 491 |
+
"visual.blocks.19.norm2.bias": "model-00001-of-00004.safetensors",
|
| 492 |
+
"visual.blocks.19.norm2.weight": "model-00001-of-00004.safetensors",
|
| 493 |
+
"visual.blocks.2.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 494 |
+
"visual.blocks.2.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 495 |
+
"visual.blocks.2.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 496 |
+
"visual.blocks.2.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 497 |
+
"visual.blocks.2.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 498 |
+
"visual.blocks.2.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 499 |
+
"visual.blocks.2.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 500 |
+
"visual.blocks.2.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 501 |
+
"visual.blocks.2.norm1.bias": "model-00001-of-00004.safetensors",
|
| 502 |
+
"visual.blocks.2.norm1.weight": "model-00001-of-00004.safetensors",
|
| 503 |
+
"visual.blocks.2.norm2.bias": "model-00001-of-00004.safetensors",
|
| 504 |
+
"visual.blocks.2.norm2.weight": "model-00001-of-00004.safetensors",
|
| 505 |
+
"visual.blocks.20.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 506 |
+
"visual.blocks.20.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 507 |
+
"visual.blocks.20.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 508 |
+
"visual.blocks.20.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 509 |
+
"visual.blocks.20.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 510 |
+
"visual.blocks.20.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 511 |
+
"visual.blocks.20.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 512 |
+
"visual.blocks.20.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 513 |
+
"visual.blocks.20.norm1.bias": "model-00001-of-00004.safetensors",
|
| 514 |
+
"visual.blocks.20.norm1.weight": "model-00001-of-00004.safetensors",
|
| 515 |
+
"visual.blocks.20.norm2.bias": "model-00001-of-00004.safetensors",
|
| 516 |
+
"visual.blocks.20.norm2.weight": "model-00001-of-00004.safetensors",
|
| 517 |
+
"visual.blocks.21.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 518 |
+
"visual.blocks.21.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 519 |
+
"visual.blocks.21.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 520 |
+
"visual.blocks.21.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 521 |
+
"visual.blocks.21.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 522 |
+
"visual.blocks.21.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 523 |
+
"visual.blocks.21.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 524 |
+
"visual.blocks.21.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 525 |
+
"visual.blocks.21.norm1.bias": "model-00001-of-00004.safetensors",
|
| 526 |
+
"visual.blocks.21.norm1.weight": "model-00001-of-00004.safetensors",
|
| 527 |
+
"visual.blocks.21.norm2.bias": "model-00001-of-00004.safetensors",
|
| 528 |
+
"visual.blocks.21.norm2.weight": "model-00001-of-00004.safetensors",
|
| 529 |
+
"visual.blocks.22.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 530 |
+
"visual.blocks.22.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 531 |
+
"visual.blocks.22.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 532 |
+
"visual.blocks.22.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 533 |
+
"visual.blocks.22.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 534 |
+
"visual.blocks.22.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 535 |
+
"visual.blocks.22.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 536 |
+
"visual.blocks.22.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 537 |
+
"visual.blocks.22.norm1.bias": "model-00001-of-00004.safetensors",
|
| 538 |
+
"visual.blocks.22.norm1.weight": "model-00001-of-00004.safetensors",
|
| 539 |
+
"visual.blocks.22.norm2.bias": "model-00001-of-00004.safetensors",
|
| 540 |
+
"visual.blocks.22.norm2.weight": "model-00001-of-00004.safetensors",
|
| 541 |
+
"visual.blocks.23.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 542 |
+
"visual.blocks.23.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 543 |
+
"visual.blocks.23.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 544 |
+
"visual.blocks.23.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 545 |
+
"visual.blocks.23.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 546 |
+
"visual.blocks.23.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 547 |
+
"visual.blocks.23.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 548 |
+
"visual.blocks.23.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 549 |
+
"visual.blocks.23.norm1.bias": "model-00001-of-00004.safetensors",
|
| 550 |
+
"visual.blocks.23.norm1.weight": "model-00001-of-00004.safetensors",
|
| 551 |
+
"visual.blocks.23.norm2.bias": "model-00001-of-00004.safetensors",
|
| 552 |
+
"visual.blocks.23.norm2.weight": "model-00001-of-00004.safetensors",
|
| 553 |
+
"visual.blocks.24.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 554 |
+
"visual.blocks.24.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 555 |
+
"visual.blocks.24.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 556 |
+
"visual.blocks.24.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 557 |
+
"visual.blocks.24.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 558 |
+
"visual.blocks.24.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 559 |
+
"visual.blocks.24.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 560 |
+
"visual.blocks.24.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 561 |
+
"visual.blocks.24.norm1.bias": "model-00001-of-00004.safetensors",
|
| 562 |
+
"visual.blocks.24.norm1.weight": "model-00001-of-00004.safetensors",
|
| 563 |
+
"visual.blocks.24.norm2.bias": "model-00001-of-00004.safetensors",
|
| 564 |
+
"visual.blocks.24.norm2.weight": "model-00001-of-00004.safetensors",
|
| 565 |
+
"visual.blocks.25.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 566 |
+
"visual.blocks.25.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 567 |
+
"visual.blocks.25.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 568 |
+
"visual.blocks.25.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 569 |
+
"visual.blocks.25.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 570 |
+
"visual.blocks.25.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 571 |
+
"visual.blocks.25.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 572 |
+
"visual.blocks.25.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 573 |
+
"visual.blocks.25.norm1.bias": "model-00001-of-00004.safetensors",
|
| 574 |
+
"visual.blocks.25.norm1.weight": "model-00001-of-00004.safetensors",
|
| 575 |
+
"visual.blocks.25.norm2.bias": "model-00001-of-00004.safetensors",
|
| 576 |
+
"visual.blocks.25.norm2.weight": "model-00001-of-00004.safetensors",
|
| 577 |
+
"visual.blocks.26.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 578 |
+
"visual.blocks.26.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 579 |
+
"visual.blocks.26.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 580 |
+
"visual.blocks.26.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 581 |
+
"visual.blocks.26.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 582 |
+
"visual.blocks.26.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 583 |
+
"visual.blocks.26.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 584 |
+
"visual.blocks.26.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 585 |
+
"visual.blocks.26.norm1.bias": "model-00001-of-00004.safetensors",
|
| 586 |
+
"visual.blocks.26.norm1.weight": "model-00001-of-00004.safetensors",
|
| 587 |
+
"visual.blocks.26.norm2.bias": "model-00001-of-00004.safetensors",
|
| 588 |
+
"visual.blocks.26.norm2.weight": "model-00001-of-00004.safetensors",
|
| 589 |
+
"visual.blocks.27.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 590 |
+
"visual.blocks.27.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 591 |
+
"visual.blocks.27.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 592 |
+
"visual.blocks.27.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 593 |
+
"visual.blocks.27.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 594 |
+
"visual.blocks.27.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 595 |
+
"visual.blocks.27.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 596 |
+
"visual.blocks.27.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 597 |
+
"visual.blocks.27.norm1.bias": "model-00001-of-00004.safetensors",
|
| 598 |
+
"visual.blocks.27.norm1.weight": "model-00001-of-00004.safetensors",
|
| 599 |
+
"visual.blocks.27.norm2.bias": "model-00001-of-00004.safetensors",
|
| 600 |
+
"visual.blocks.27.norm2.weight": "model-00001-of-00004.safetensors",
|
| 601 |
+
"visual.blocks.28.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 602 |
+
"visual.blocks.28.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 603 |
+
"visual.blocks.28.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 604 |
+
"visual.blocks.28.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 605 |
+
"visual.blocks.28.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 606 |
+
"visual.blocks.28.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 607 |
+
"visual.blocks.28.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 608 |
+
"visual.blocks.28.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 609 |
+
"visual.blocks.28.norm1.bias": "model-00001-of-00004.safetensors",
|
| 610 |
+
"visual.blocks.28.norm1.weight": "model-00001-of-00004.safetensors",
|
| 611 |
+
"visual.blocks.28.norm2.bias": "model-00001-of-00004.safetensors",
|
| 612 |
+
"visual.blocks.28.norm2.weight": "model-00001-of-00004.safetensors",
|
| 613 |
+
"visual.blocks.29.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 614 |
+
"visual.blocks.29.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 615 |
+
"visual.blocks.29.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 616 |
+
"visual.blocks.29.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 617 |
+
"visual.blocks.29.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 618 |
+
"visual.blocks.29.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 619 |
+
"visual.blocks.29.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 620 |
+
"visual.blocks.29.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 621 |
+
"visual.blocks.29.norm1.bias": "model-00001-of-00004.safetensors",
|
| 622 |
+
"visual.blocks.29.norm1.weight": "model-00001-of-00004.safetensors",
|
| 623 |
+
"visual.blocks.29.norm2.bias": "model-00001-of-00004.safetensors",
|
| 624 |
+
"visual.blocks.29.norm2.weight": "model-00001-of-00004.safetensors",
|
| 625 |
+
"visual.blocks.3.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 626 |
+
"visual.blocks.3.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 627 |
+
"visual.blocks.3.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 628 |
+
"visual.blocks.3.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 629 |
+
"visual.blocks.3.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 630 |
+
"visual.blocks.3.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 631 |
+
"visual.blocks.3.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 632 |
+
"visual.blocks.3.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 633 |
+
"visual.blocks.3.norm1.bias": "model-00001-of-00004.safetensors",
|
| 634 |
+
"visual.blocks.3.norm1.weight": "model-00001-of-00004.safetensors",
|
| 635 |
+
"visual.blocks.3.norm2.bias": "model-00001-of-00004.safetensors",
|
| 636 |
+
"visual.blocks.3.norm2.weight": "model-00001-of-00004.safetensors",
|
| 637 |
+
"visual.blocks.30.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 638 |
+
"visual.blocks.30.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 639 |
+
"visual.blocks.30.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 640 |
+
"visual.blocks.30.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 641 |
+
"visual.blocks.30.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 642 |
+
"visual.blocks.30.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 643 |
+
"visual.blocks.30.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 644 |
+
"visual.blocks.30.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 645 |
+
"visual.blocks.30.norm1.bias": "model-00001-of-00004.safetensors",
|
| 646 |
+
"visual.blocks.30.norm1.weight": "model-00001-of-00004.safetensors",
|
| 647 |
+
"visual.blocks.30.norm2.bias": "model-00001-of-00004.safetensors",
|
| 648 |
+
"visual.blocks.30.norm2.weight": "model-00001-of-00004.safetensors",
|
| 649 |
+
"visual.blocks.31.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 650 |
+
"visual.blocks.31.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 651 |
+
"visual.blocks.31.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 652 |
+
"visual.blocks.31.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 653 |
+
"visual.blocks.31.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 654 |
+
"visual.blocks.31.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 655 |
+
"visual.blocks.31.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 656 |
+
"visual.blocks.31.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 657 |
+
"visual.blocks.31.norm1.bias": "model-00001-of-00004.safetensors",
|
| 658 |
+
"visual.blocks.31.norm1.weight": "model-00001-of-00004.safetensors",
|
| 659 |
+
"visual.blocks.31.norm2.bias": "model-00001-of-00004.safetensors",
|
| 660 |
+
"visual.blocks.31.norm2.weight": "model-00001-of-00004.safetensors",
|
| 661 |
+
"visual.blocks.4.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 662 |
+
"visual.blocks.4.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 663 |
+
"visual.blocks.4.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 664 |
+
"visual.blocks.4.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 665 |
+
"visual.blocks.4.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 666 |
+
"visual.blocks.4.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 667 |
+
"visual.blocks.4.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 668 |
+
"visual.blocks.4.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 669 |
+
"visual.blocks.4.norm1.bias": "model-00001-of-00004.safetensors",
|
| 670 |
+
"visual.blocks.4.norm1.weight": "model-00001-of-00004.safetensors",
|
| 671 |
+
"visual.blocks.4.norm2.bias": "model-00001-of-00004.safetensors",
|
| 672 |
+
"visual.blocks.4.norm2.weight": "model-00001-of-00004.safetensors",
|
| 673 |
+
"visual.blocks.5.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 674 |
+
"visual.blocks.5.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 675 |
+
"visual.blocks.5.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 676 |
+
"visual.blocks.5.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 677 |
+
"visual.blocks.5.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 678 |
+
"visual.blocks.5.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 679 |
+
"visual.blocks.5.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 680 |
+
"visual.blocks.5.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 681 |
+
"visual.blocks.5.norm1.bias": "model-00001-of-00004.safetensors",
|
| 682 |
+
"visual.blocks.5.norm1.weight": "model-00001-of-00004.safetensors",
|
| 683 |
+
"visual.blocks.5.norm2.bias": "model-00001-of-00004.safetensors",
|
| 684 |
+
"visual.blocks.5.norm2.weight": "model-00001-of-00004.safetensors",
|
| 685 |
+
"visual.blocks.6.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 686 |
+
"visual.blocks.6.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 687 |
+
"visual.blocks.6.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 688 |
+
"visual.blocks.6.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 689 |
+
"visual.blocks.6.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 690 |
+
"visual.blocks.6.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 691 |
+
"visual.blocks.6.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 692 |
+
"visual.blocks.6.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 693 |
+
"visual.blocks.6.norm1.bias": "model-00001-of-00004.safetensors",
|
| 694 |
+
"visual.blocks.6.norm1.weight": "model-00001-of-00004.safetensors",
|
| 695 |
+
"visual.blocks.6.norm2.bias": "model-00001-of-00004.safetensors",
|
| 696 |
+
"visual.blocks.6.norm2.weight": "model-00001-of-00004.safetensors",
|
| 697 |
+
"visual.blocks.7.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 698 |
+
"visual.blocks.7.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 699 |
+
"visual.blocks.7.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 700 |
+
"visual.blocks.7.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 701 |
+
"visual.blocks.7.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 702 |
+
"visual.blocks.7.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 703 |
+
"visual.blocks.7.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 704 |
+
"visual.blocks.7.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 705 |
+
"visual.blocks.7.norm1.bias": "model-00001-of-00004.safetensors",
|
| 706 |
+
"visual.blocks.7.norm1.weight": "model-00001-of-00004.safetensors",
|
| 707 |
+
"visual.blocks.7.norm2.bias": "model-00001-of-00004.safetensors",
|
| 708 |
+
"visual.blocks.7.norm2.weight": "model-00001-of-00004.safetensors",
|
| 709 |
+
"visual.blocks.8.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 710 |
+
"visual.blocks.8.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 711 |
+
"visual.blocks.8.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 712 |
+
"visual.blocks.8.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 713 |
+
"visual.blocks.8.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 714 |
+
"visual.blocks.8.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 715 |
+
"visual.blocks.8.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 716 |
+
"visual.blocks.8.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 717 |
+
"visual.blocks.8.norm1.bias": "model-00001-of-00004.safetensors",
|
| 718 |
+
"visual.blocks.8.norm1.weight": "model-00001-of-00004.safetensors",
|
| 719 |
+
"visual.blocks.8.norm2.bias": "model-00001-of-00004.safetensors",
|
| 720 |
+
"visual.blocks.8.norm2.weight": "model-00001-of-00004.safetensors",
|
| 721 |
+
"visual.blocks.9.attn.proj.bias": "model-00001-of-00004.safetensors",
|
| 722 |
+
"visual.blocks.9.attn.proj.weight": "model-00001-of-00004.safetensors",
|
| 723 |
+
"visual.blocks.9.attn.qkv.bias": "model-00001-of-00004.safetensors",
|
| 724 |
+
"visual.blocks.9.attn.qkv.weight": "model-00001-of-00004.safetensors",
|
| 725 |
+
"visual.blocks.9.mlp.fc1.bias": "model-00001-of-00004.safetensors",
|
| 726 |
+
"visual.blocks.9.mlp.fc1.weight": "model-00001-of-00004.safetensors",
|
| 727 |
+
"visual.blocks.9.mlp.fc2.bias": "model-00001-of-00004.safetensors",
|
| 728 |
+
"visual.blocks.9.mlp.fc2.weight": "model-00001-of-00004.safetensors",
|
| 729 |
+
"visual.blocks.9.norm1.bias": "model-00001-of-00004.safetensors",
|
| 730 |
+
"visual.blocks.9.norm1.weight": "model-00001-of-00004.safetensors",
|
| 731 |
+
"visual.blocks.9.norm2.bias": "model-00001-of-00004.safetensors",
|
| 732 |
+
"visual.blocks.9.norm2.weight": "model-00001-of-00004.safetensors",
|
| 733 |
+
"visual.merger.ln_q.bias": "model-00001-of-00004.safetensors",
|
| 734 |
+
"visual.merger.ln_q.weight": "model-00001-of-00004.safetensors",
|
| 735 |
+
"visual.merger.mlp.0.bias": "model-00001-of-00004.safetensors",
|
| 736 |
+
"visual.merger.mlp.0.weight": "model-00001-of-00004.safetensors",
|
| 737 |
+
"visual.merger.mlp.2.bias": "model-00001-of-00004.safetensors",
|
| 738 |
+
"visual.merger.mlp.2.weight": "model-00001-of-00004.safetensors",
|
| 739 |
+
"visual.patch_embed.proj.weight": "model-00001-of-00004.safetensors"
|
| 740 |
+
}
|
| 741 |
+
}
|
modeling_dreamvl.py
ADDED
|
@@ -0,0 +1,1824 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The DreamVL team and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 5 |
+
# and OPT implementations in this library. It has been modified from its
|
| 6 |
+
# original forms to accommodate minor architectural differences compared
|
| 7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
"""PyTorch DreamVL model."""
|
| 21 |
+
|
| 22 |
+
import math, os
|
| 23 |
+
from dataclasses import dataclass
|
| 24 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 25 |
+
|
| 26 |
+
import torch
|
| 27 |
+
import torch.nn as nn
|
| 28 |
+
import torch.nn.functional as F
|
| 29 |
+
import torch.utils.checkpoint
|
| 30 |
+
from torch.nn import CrossEntropyLoss, LayerNorm
|
| 31 |
+
|
| 32 |
+
from transformers.activations import ACT2FN
|
| 33 |
+
from transformers.cache_utils import Cache, SlidingWindowCache, StaticCache, DynamicCache
|
| 34 |
+
from transformers.modeling_outputs import (
|
| 35 |
+
BaseModelOutputWithPast,
|
| 36 |
+
ModelOutput,
|
| 37 |
+
BaseModelOutput,
|
| 38 |
+
MaskedLMOutput,
|
| 39 |
+
)
|
| 40 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
| 41 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 42 |
+
from transformers.utils import (
|
| 43 |
+
add_start_docstrings,
|
| 44 |
+
add_start_docstrings_to_model_forward,
|
| 45 |
+
is_flash_attn_2_available,
|
| 46 |
+
is_flash_attn_greater_or_equal_2_10,
|
| 47 |
+
logging,
|
| 48 |
+
replace_return_docstrings,
|
| 49 |
+
is_torchdynamo_compiling
|
| 50 |
+
)
|
| 51 |
+
from transformers import PretrainedConfig
|
| 52 |
+
|
| 53 |
+
from transformers.modeling_attn_mask_utils import (
|
| 54 |
+
AttentionMaskConverter,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
from .configuration_dreamvl import DreamVLConfig, DreamVLVisionConfig
|
| 58 |
+
from .generation_utils import DreamVLGenerationMixin, DreamVLGenerationConfig
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
if is_flash_attn_2_available():
|
| 62 |
+
from flash_attn import flash_attn_varlen_func
|
| 63 |
+
|
| 64 |
+
from transformers.modeling_flash_attention_utils import _flash_attention_forward
|
| 65 |
+
else:
|
| 66 |
+
flash_attn_varlen_func = None
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
logger = logging.get_logger("DreamVL."+__name__)
|
| 70 |
+
|
| 71 |
+
_CHECKPOINT_FOR_DOC = "DreamVL-7B"
|
| 72 |
+
_CONFIG_FOR_DOC = "DreamVLConfig"
|
| 73 |
+
|
| 74 |
+
@dataclass
|
| 75 |
+
class DreamVLModelOutput(ModelOutput):
|
| 76 |
+
"""
|
| 77 |
+
Base class for DreamVL outputs.
|
| 78 |
+
Args:
|
| 79 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 80 |
+
Language modeling loss (for next-token prediction).
|
| 81 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 82 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 83 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 84 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
| 85 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`)
|
| 86 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
|
| 87 |
+
`past_key_values` input) to speed up sequential decoding.
|
| 88 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 89 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 90 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 91 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 92 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
| 93 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
| 94 |
+
sequence_length)`.
|
| 95 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
| 96 |
+
heads.
|
| 97 |
+
rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
|
| 98 |
+
The rope index difference between sequence length and multimodal rope.
|
| 99 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 100 |
+
The input embeddings, used for caching image feature during inference when use_cache=False.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
logits: torch.FloatTensor = None
|
| 104 |
+
loss: Optional[torch.FloatTensor] = None
|
| 105 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None
|
| 106 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 107 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 108 |
+
rope_deltas: Optional[torch.LongTensor] = None
|
| 109 |
+
inputs_embeds: Optional[torch.FloatTensor] = None
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class DreamVLRotaryEmbedding(nn.Module):
|
| 113 |
+
def __init__(
|
| 114 |
+
self,
|
| 115 |
+
dim=None,
|
| 116 |
+
max_position_embeddings=2048,
|
| 117 |
+
base=10000,
|
| 118 |
+
device=None,
|
| 119 |
+
scaling_factor=1.0,
|
| 120 |
+
rope_type="default",
|
| 121 |
+
config: Optional[DreamVLConfig] = None,
|
| 122 |
+
):
|
| 123 |
+
super().__init__()
|
| 124 |
+
# TODO (joao): remove the `if` below, only used for BC
|
| 125 |
+
self.rope_kwargs = {}
|
| 126 |
+
if config is None:
|
| 127 |
+
logger.warning_once(
|
| 128 |
+
"`DreamVLRotaryEmbedding` can now be fully parameterized by passing the model config through the "
|
| 129 |
+
"`config` argument. All other arguments will be removed in v4.46"
|
| 130 |
+
)
|
| 131 |
+
self.rope_kwargs = {
|
| 132 |
+
"rope_type": rope_type,
|
| 133 |
+
"factor": scaling_factor,
|
| 134 |
+
"dim": dim,
|
| 135 |
+
"base": base,
|
| 136 |
+
"max_position_embeddings": max_position_embeddings,
|
| 137 |
+
}
|
| 138 |
+
self.rope_type = rope_type
|
| 139 |
+
self.max_seq_len_cached = max_position_embeddings
|
| 140 |
+
self.original_max_seq_len = max_position_embeddings
|
| 141 |
+
else:
|
| 142 |
+
# BC: "rope_type" was originally "type"
|
| 143 |
+
if config.rope_scaling is not None:
|
| 144 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
| 145 |
+
else:
|
| 146 |
+
self.rope_type = "default"
|
| 147 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 148 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 149 |
+
|
| 150 |
+
self.config = config
|
| 151 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 152 |
+
|
| 153 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
|
| 154 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 155 |
+
self.original_inv_freq = self.inv_freq
|
| 156 |
+
|
| 157 |
+
def reset_parameters(self):
|
| 158 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, self.inv_freq.device, **self.rope_kwargs)
|
| 159 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 160 |
+
self.original_inv_freq = self.inv_freq
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
| 164 |
+
"""
|
| 165 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
| 166 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
| 167 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
| 168 |
+
"""
|
| 169 |
+
seq_len = torch.max(position_ids) + 1
|
| 170 |
+
if seq_len > self.max_seq_len_cached: # growth
|
| 171 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(
|
| 172 |
+
self.config, device, seq_len=seq_len, **self.rope_kwargs
|
| 173 |
+
)
|
| 174 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
| 175 |
+
self.max_seq_len_cached = seq_len
|
| 176 |
+
|
| 177 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
| 178 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
| 179 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
| 180 |
+
|
| 181 |
+
@torch.no_grad()
|
| 182 |
+
def forward(self, x, position_ids):
|
| 183 |
+
if "dynamic" in self.rope_type:
|
| 184 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
| 185 |
+
|
| 186 |
+
# Core RoPE block. In contrast to other models, DreamVL has different position ids for thw grids
|
| 187 |
+
# So we expand the inv_freq to shape (3, ...)
|
| 188 |
+
inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
|
| 189 |
+
position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions)
|
| 190 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
| 191 |
+
device_type = x.device.type
|
| 192 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
| 193 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
| 194 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3)
|
| 195 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 196 |
+
cos = emb.cos()
|
| 197 |
+
sin = emb.sin()
|
| 198 |
+
|
| 199 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
| 200 |
+
cos = cos * self.attention_scaling
|
| 201 |
+
sin = sin * self.attention_scaling
|
| 202 |
+
|
| 203 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 204 |
+
|
| 205 |
+
# Copied from transformers.models.qwen2.modeling_qwen2.Qwen2RMSNorm
|
| 206 |
+
class DreamVLRMSNorm(nn.Module):
|
| 207 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 208 |
+
"""
|
| 209 |
+
DreamVLRMSNorm is equivalent to T5LayerNorm
|
| 210 |
+
"""
|
| 211 |
+
super().__init__()
|
| 212 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 213 |
+
self.variance_epsilon = eps
|
| 214 |
+
|
| 215 |
+
def forward(self, hidden_states):
|
| 216 |
+
input_dtype = hidden_states.dtype
|
| 217 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 218 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 219 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 220 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 221 |
+
|
| 222 |
+
def extra_repr(self):
|
| 223 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 224 |
+
|
| 225 |
+
# Copied from transformers.models.llama.modeling_llama.rotate_half
|
| 226 |
+
def rotate_half(x):
|
| 227 |
+
"""Rotates half the hidden dims of the input."""
|
| 228 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 229 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 230 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1):
|
| 234 |
+
"""Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).
|
| 235 |
+
Explanation:
|
| 236 |
+
Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding
|
| 237 |
+
sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For
|
| 238 |
+
vision embedding part, we apply rotary position embedding on temporal, height and width dimension seperately.
|
| 239 |
+
Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding.
|
| 240 |
+
For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal,
|
| 241 |
+
height and width) of text embedding is always the same, so the text embedding rotary position embedding has no
|
| 242 |
+
difference with modern LLMs.
|
| 243 |
+
Args:
|
| 244 |
+
q (`torch.Tensor`): The query tensor.
|
| 245 |
+
k (`torch.Tensor`): The key tensor.
|
| 246 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 247 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 248 |
+
position_ids (`torch.Tensor`):
|
| 249 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
| 250 |
+
used to pass offsetted position ids when working with a KV-cache.
|
| 251 |
+
mrope_section(`List(int)`):
|
| 252 |
+
Multimodal rope section is for channel dimension of temporal, height and width in rope calculation.
|
| 253 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 254 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 255 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 256 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 257 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 258 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 259 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 260 |
+
Returns:
|
| 261 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 262 |
+
"""
|
| 263 |
+
mrope_section = mrope_section * 2
|
| 264 |
+
cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
|
| 265 |
+
unsqueeze_dim
|
| 266 |
+
)
|
| 267 |
+
sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
|
| 268 |
+
unsqueeze_dim
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 272 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 273 |
+
return q_embed, k_embed
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def apply_rotary_pos_emb_vision(
|
| 277 |
+
q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
|
| 278 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 279 |
+
orig_q_dtype = q.dtype
|
| 280 |
+
orig_k_dtype = k.dtype
|
| 281 |
+
q, k = q.float(), k.float()
|
| 282 |
+
cos, sin = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float()
|
| 283 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 284 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 285 |
+
q_embed = q_embed.to(orig_q_dtype)
|
| 286 |
+
k_embed = k_embed.to(orig_k_dtype)
|
| 287 |
+
return q_embed, k_embed
|
| 288 |
+
|
| 289 |
+
# Copied from transformers.models.qwen2.modeling_qwen2.Qwen2MLP
|
| 290 |
+
class DreamVLMLP(nn.Module):
|
| 291 |
+
def __init__(self, config):
|
| 292 |
+
super().__init__()
|
| 293 |
+
self.hidden_size = config.hidden_size
|
| 294 |
+
self.intermediate_size = config.intermediate_size
|
| 295 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 296 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 297 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 298 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 299 |
+
|
| 300 |
+
def forward(self, hidden_state):
|
| 301 |
+
return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
# Copied from transformers.models.llama.modeling_llama.repeat_kv
|
| 305 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 306 |
+
"""
|
| 307 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 308 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 309 |
+
"""
|
| 310 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 311 |
+
if n_rep == 1:
|
| 312 |
+
return hidden_states
|
| 313 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 314 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
class DreamVLAttention(nn.Module):
|
| 318 |
+
"""
|
| 319 |
+
Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
|
| 320 |
+
and "Generating Long Sequences with Sparse Transformers".
|
| 321 |
+
"""
|
| 322 |
+
|
| 323 |
+
def __init__(self, config: DreamVLConfig, layer_idx: Optional[int] = None):
|
| 324 |
+
super().__init__()
|
| 325 |
+
self.config = config
|
| 326 |
+
self.layer_idx = layer_idx
|
| 327 |
+
if layer_idx is None:
|
| 328 |
+
logger.warning_once(
|
| 329 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
| 330 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
| 331 |
+
"when creating this class."
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
self.hidden_size = config.hidden_size
|
| 335 |
+
self.num_heads = config.num_attention_heads
|
| 336 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 337 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 338 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 339 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 340 |
+
self.rope_theta = config.rope_theta
|
| 341 |
+
self.is_causal = False # not used in Dream
|
| 342 |
+
self.attention_dropout = config.attention_dropout
|
| 343 |
+
self.rope_scaling = config.rope_scaling # in Dream rope scaling is None
|
| 344 |
+
self.mrope_section = config.mrope_section
|
| 345 |
+
|
| 346 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
| 347 |
+
raise ValueError(
|
| 348 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
| 349 |
+
f" and `num_heads`: {self.num_heads})."
|
| 350 |
+
)
|
| 351 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
|
| 352 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
| 353 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
|
| 354 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
| 355 |
+
|
| 356 |
+
self.rotary_emb = DreamVLRotaryEmbedding(config=self.config)
|
| 357 |
+
|
| 358 |
+
def forward(
|
| 359 |
+
self,
|
| 360 |
+
hidden_states: torch.Tensor,
|
| 361 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 362 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 363 |
+
past_key_value: Optional[Cache] = None,
|
| 364 |
+
output_attentions: bool = False,
|
| 365 |
+
use_cache: bool = False,
|
| 366 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 367 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
| 368 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 369 |
+
bsz, q_len, _ = hidden_states.size()
|
| 370 |
+
|
| 371 |
+
query_states = self.q_proj(hidden_states)
|
| 372 |
+
key_states = self.k_proj(hidden_states)
|
| 373 |
+
value_states = self.v_proj(hidden_states)
|
| 374 |
+
|
| 375 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 376 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 377 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 378 |
+
|
| 379 |
+
if position_embeddings is None:
|
| 380 |
+
logger.warning_once(
|
| 381 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
| 382 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
| 383 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
|
| 384 |
+
"removed and `position_embeddings` will be mandatory."
|
| 385 |
+
)
|
| 386 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 387 |
+
else:
|
| 388 |
+
cos, sin = position_embeddings
|
| 389 |
+
query_states, key_states = apply_multimodal_rotary_pos_emb(
|
| 390 |
+
query_states, key_states, cos, sin, self.mrope_section
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
if past_key_value is not None:
|
| 394 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
|
| 395 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 396 |
+
|
| 397 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
| 398 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 399 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 400 |
+
|
| 401 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 402 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
| 403 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 404 |
+
attn_weights = attn_weights + causal_mask
|
| 405 |
+
|
| 406 |
+
# Fix precision issues in DreamVL float16 inference
|
| 407 |
+
# Replace inf values with zeros in attention weights to prevent NaN propagation
|
| 408 |
+
if query_states.dtype == torch.float16:
|
| 409 |
+
attn_weights = torch.where(torch.isinf(attn_weights), torch.zeros_like(attn_weights), attn_weights)
|
| 410 |
+
|
| 411 |
+
# upcast attention to fp32
|
| 412 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 413 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
| 414 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 415 |
+
|
| 416 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
| 417 |
+
raise ValueError(
|
| 418 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
| 419 |
+
f" {attn_output.size()}"
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 423 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 424 |
+
|
| 425 |
+
attn_output = self.o_proj(attn_output)
|
| 426 |
+
|
| 427 |
+
if not output_attentions:
|
| 428 |
+
attn_weights = None
|
| 429 |
+
|
| 430 |
+
return attn_output, attn_weights, past_key_value
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
class DreamVLFlashAttention2(DreamVLAttention):
|
| 435 |
+
|
| 436 |
+
def forward(
|
| 437 |
+
self,
|
| 438 |
+
hidden_states: torch.Tensor,
|
| 439 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 440 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 441 |
+
past_key_value: Optional[Cache] = None,
|
| 442 |
+
output_attentions: bool = False,
|
| 443 |
+
use_cache: bool = False,
|
| 444 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 445 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
|
| 446 |
+
):
|
| 447 |
+
bsz, q_len, _ = hidden_states.size()
|
| 448 |
+
|
| 449 |
+
query_states = self.q_proj(hidden_states)
|
| 450 |
+
key_states = self.k_proj(hidden_states)
|
| 451 |
+
value_states = self.v_proj(hidden_states)
|
| 452 |
+
|
| 453 |
+
query_states = query_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
|
| 454 |
+
key_states = key_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
|
| 455 |
+
value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2)
|
| 456 |
+
|
| 457 |
+
# Because the input can be padded, the absolute sequence length depends on the max position id.
|
| 458 |
+
if position_embeddings is None:
|
| 459 |
+
logger.warning_once(
|
| 460 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
| 461 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
| 462 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
|
| 463 |
+
"removed and `position_embeddings` will be mandatory."
|
| 464 |
+
)
|
| 465 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 466 |
+
else:
|
| 467 |
+
cos, sin = position_embeddings
|
| 468 |
+
query_states, key_states = apply_multimodal_rotary_pos_emb(
|
| 469 |
+
query_states, key_states, cos, sin, self.mrope_section
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
| 473 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 474 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 475 |
+
dropout_rate = 0.0 if not self.training else self.attention_dropout
|
| 476 |
+
|
| 477 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
| 478 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
| 479 |
+
# cast them back in float16 just to be sure everything works as expected.
|
| 480 |
+
input_dtype = query_states.dtype
|
| 481 |
+
if input_dtype == torch.float32:
|
| 482 |
+
if torch.is_autocast_enabled():
|
| 483 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
| 484 |
+
# Handle the case where the model is quantized
|
| 485 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
| 486 |
+
target_dtype = self.config._pre_quantization_dtype
|
| 487 |
+
else:
|
| 488 |
+
target_dtype = self.q_proj.weight.dtype
|
| 489 |
+
|
| 490 |
+
logger.warning_once(
|
| 491 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
| 492 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
| 493 |
+
f" {target_dtype}."
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
query_states = query_states.to(target_dtype)
|
| 497 |
+
key_states = key_states.to(target_dtype)
|
| 498 |
+
value_states = value_states.to(target_dtype)
|
| 499 |
+
|
| 500 |
+
# Reashape to the expected shape for Flash Attention
|
| 501 |
+
query_states = query_states.transpose(1, 2)
|
| 502 |
+
key_states = key_states.transpose(1, 2)
|
| 503 |
+
value_states = value_states.transpose(1, 2)
|
| 504 |
+
|
| 505 |
+
if (
|
| 506 |
+
self.config.use_sliding_window
|
| 507 |
+
and getattr(self.config, "sliding_window", None) is not None
|
| 508 |
+
and self.layer_idx >= self.config.max_window_layers
|
| 509 |
+
):
|
| 510 |
+
sliding_window = self.config.sliding_window
|
| 511 |
+
else:
|
| 512 |
+
sliding_window = None
|
| 513 |
+
|
| 514 |
+
attn_output = _flash_attention_forward(
|
| 515 |
+
query_states,
|
| 516 |
+
key_states,
|
| 517 |
+
value_states,
|
| 518 |
+
attention_mask,
|
| 519 |
+
q_len,
|
| 520 |
+
dropout=dropout_rate,
|
| 521 |
+
sliding_window=sliding_window,
|
| 522 |
+
is_causal=False
|
| 523 |
+
)
|
| 524 |
+
|
| 525 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
| 526 |
+
attn_output = self.o_proj(attn_output)
|
| 527 |
+
|
| 528 |
+
if not output_attentions:
|
| 529 |
+
attn_weights = None
|
| 530 |
+
|
| 531 |
+
return attn_output, attn_weights, past_key_value
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
class DreamVLSdpaAttention(DreamVLAttention):
|
| 535 |
+
"""
|
| 536 |
+
DreamVL attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
| 537 |
+
`DreamVLAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
| 538 |
+
SDPA API.
|
| 539 |
+
"""
|
| 540 |
+
|
| 541 |
+
# Adapted from DreamVLAttention.forward
|
| 542 |
+
def forward(
|
| 543 |
+
self,
|
| 544 |
+
hidden_states: torch.Tensor,
|
| 545 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 546 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 547 |
+
past_key_value: Optional[Cache] = None,
|
| 548 |
+
output_attentions: bool = False,
|
| 549 |
+
use_cache: bool = False,
|
| 550 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 551 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
| 552 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 553 |
+
if output_attentions:
|
| 554 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
| 555 |
+
logger.warning_once(
|
| 556 |
+
"DreamVLModel is using DreamVLSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
| 557 |
+
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 558 |
+
)
|
| 559 |
+
return super().forward(
|
| 560 |
+
hidden_states=hidden_states,
|
| 561 |
+
attention_mask=attention_mask,
|
| 562 |
+
position_ids=position_ids,
|
| 563 |
+
past_key_value=past_key_value,
|
| 564 |
+
output_attentions=output_attentions,
|
| 565 |
+
use_cache=use_cache,
|
| 566 |
+
# cache_position=cache_position, # not used in Dream
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
bsz, q_len, _ = hidden_states.size()
|
| 570 |
+
|
| 571 |
+
query_states = self.q_proj(hidden_states)
|
| 572 |
+
key_states = self.k_proj(hidden_states)
|
| 573 |
+
value_states = self.v_proj(hidden_states)
|
| 574 |
+
|
| 575 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 576 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 577 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 578 |
+
|
| 579 |
+
if position_embeddings is None:
|
| 580 |
+
logger.warning_once(
|
| 581 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
| 582 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
| 583 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
|
| 584 |
+
"removed and `position_embeddings` will be mandatory."
|
| 585 |
+
)
|
| 586 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 587 |
+
else:
|
| 588 |
+
cos, sin = position_embeddings
|
| 589 |
+
query_states, key_states = apply_multimodal_rotary_pos_emb(
|
| 590 |
+
query_states, key_states, cos, sin, self.mrope_section
|
| 591 |
+
)
|
| 592 |
+
|
| 593 |
+
if past_key_value is not None:
|
| 594 |
+
logger.warning_once(
|
| 595 |
+
f"In {self.__class__}, cache is used."
|
| 596 |
+
)
|
| 597 |
+
# print("cache is used")
|
| 598 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} # Specific to RoPE models
|
| 599 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 600 |
+
|
| 601 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 602 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 603 |
+
|
| 604 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
| 605 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
| 606 |
+
if query_states.device.type == "cuda" and attention_mask is not None:
|
| 607 |
+
query_states = query_states.contiguous()
|
| 608 |
+
key_states = key_states.contiguous()
|
| 609 |
+
value_states = value_states.contiguous()
|
| 610 |
+
|
| 611 |
+
if isinstance(attention_mask, torch.Tensor) and len(attention_mask.shape) == 2:
|
| 612 |
+
# attention_mask is of shape [B, N], here broadcast to [B, 1, N, N]
|
| 613 |
+
attention_mask = torch.logical_and(
|
| 614 |
+
attention_mask.unsqueeze(1).unsqueeze(-2),
|
| 615 |
+
attention_mask.unsqueeze(1).unsqueeze(-1),
|
| 616 |
+
)
|
| 617 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
|
| 618 |
+
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
|
| 619 |
+
# The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
|
| 620 |
+
# is_causal = True if causal_mask is None and q_len > 1 else False # not used in Dream
|
| 621 |
+
|
| 622 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
| 623 |
+
query_states,
|
| 624 |
+
key_states,
|
| 625 |
+
value_states,
|
| 626 |
+
attn_mask=attention_mask if isinstance(attention_mask, torch.Tensor) else None,
|
| 627 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
| 628 |
+
is_causal=False, # hard coded
|
| 629 |
+
)
|
| 630 |
+
# if torch.__version__ < "2.5":
|
| 631 |
+
# attn_output = torch.nan_to_num(attn_output, nan=0.0)
|
| 632 |
+
|
| 633 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 634 |
+
attn_output = attn_output.view(bsz, q_len, self.hidden_size)
|
| 635 |
+
|
| 636 |
+
attn_output = self.o_proj(attn_output)
|
| 637 |
+
|
| 638 |
+
return attn_output, None, past_key_value
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
DreamVL_ATTENTION_CLASSES = {
|
| 642 |
+
"eager": DreamVLAttention,
|
| 643 |
+
"flash_attention_2": DreamVLFlashAttention2,
|
| 644 |
+
"sdpa": DreamVLSdpaAttention,
|
| 645 |
+
}
|
| 646 |
+
|
| 647 |
+
|
| 648 |
+
class DreamVLDecoderLayer(nn.Module):
|
| 649 |
+
def __init__(self, config: DreamVLConfig, layer_idx: int):
|
| 650 |
+
super().__init__()
|
| 651 |
+
self.hidden_size = config.hidden_size
|
| 652 |
+
|
| 653 |
+
if config.sliding_window and config._attn_implementation != "flash_attention_2":
|
| 654 |
+
logger.warning_once(
|
| 655 |
+
f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; "
|
| 656 |
+
"unexpected results may be encountered."
|
| 657 |
+
)
|
| 658 |
+
# self.self_attn = DreamVL_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
|
| 659 |
+
self.self_attn = DreamVLSdpaAttention(config, layer_idx)
|
| 660 |
+
# self.self_attn = DreamVLFlashAttention2(config, layer_idx)
|
| 661 |
+
|
| 662 |
+
self.mlp = DreamVLMLP(config)
|
| 663 |
+
self.input_layernorm = DreamVLRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 664 |
+
self.post_attention_layernorm = DreamVLRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 665 |
+
|
| 666 |
+
def forward(
|
| 667 |
+
self,
|
| 668 |
+
hidden_states: torch.Tensor,
|
| 669 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 670 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 671 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 672 |
+
output_attentions: Optional[bool] = False,
|
| 673 |
+
use_cache: Optional[bool] = False,
|
| 674 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 675 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
| 676 |
+
**kwargs,
|
| 677 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 678 |
+
"""
|
| 679 |
+
Args:
|
| 680 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 681 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
| 682 |
+
`(batch, sequence_length)` where padding elements are indicated by 0.
|
| 683 |
+
output_attentions (`bool`, *optional*):
|
| 684 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 685 |
+
returned tensors for more detail.
|
| 686 |
+
use_cache (`bool`, *optional*):
|
| 687 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 688 |
+
(see `past_key_values`).
|
| 689 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
| 690 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 691 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
| 692 |
+
position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
|
| 693 |
+
Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
|
| 694 |
+
with `head_dim` being the embedding dimension of each attention head.
|
| 695 |
+
kwargs (`dict`, *optional*):
|
| 696 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
| 697 |
+
into the model
|
| 698 |
+
"""
|
| 699 |
+
|
| 700 |
+
residual = hidden_states
|
| 701 |
+
|
| 702 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 703 |
+
|
| 704 |
+
# Self Attention
|
| 705 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 706 |
+
hidden_states=hidden_states,
|
| 707 |
+
attention_mask=attention_mask,
|
| 708 |
+
position_ids=position_ids,
|
| 709 |
+
past_key_value=past_key_value,
|
| 710 |
+
output_attentions=output_attentions,
|
| 711 |
+
use_cache=use_cache,
|
| 712 |
+
cache_position=cache_position,
|
| 713 |
+
position_embeddings=position_embeddings,
|
| 714 |
+
)
|
| 715 |
+
hidden_states = residual + hidden_states
|
| 716 |
+
|
| 717 |
+
# Fully Connected
|
| 718 |
+
residual = hidden_states
|
| 719 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 720 |
+
hidden_states = self.mlp(hidden_states)
|
| 721 |
+
hidden_states = residual + hidden_states
|
| 722 |
+
|
| 723 |
+
outputs = (hidden_states,)
|
| 724 |
+
|
| 725 |
+
if output_attentions:
|
| 726 |
+
outputs += (self_attn_weights,)
|
| 727 |
+
|
| 728 |
+
if use_cache:
|
| 729 |
+
outputs += (present_key_value,)
|
| 730 |
+
|
| 731 |
+
return outputs
|
| 732 |
+
|
| 733 |
+
######## START VISION ########
|
| 734 |
+
class VisionRotaryEmbedding(nn.Module):
|
| 735 |
+
def __init__(self, dim: int, theta: float = 10000.0) -> None:
|
| 736 |
+
super().__init__()
|
| 737 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
|
| 738 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 739 |
+
|
| 740 |
+
def forward(self, seqlen: int) -> torch.Tensor:
|
| 741 |
+
seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
|
| 742 |
+
freqs = torch.outer(seq, self.inv_freq)
|
| 743 |
+
return freqs
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
class PatchEmbed(nn.Module):
|
| 747 |
+
def __init__(
|
| 748 |
+
self,
|
| 749 |
+
patch_size: int = 14,
|
| 750 |
+
temporal_patch_size: int = 2,
|
| 751 |
+
in_channels: int = 3,
|
| 752 |
+
embed_dim: int = 1152,
|
| 753 |
+
) -> None:
|
| 754 |
+
super().__init__()
|
| 755 |
+
self.patch_size = patch_size
|
| 756 |
+
self.temporal_patch_size = temporal_patch_size
|
| 757 |
+
self.in_channels = in_channels
|
| 758 |
+
self.embed_dim = embed_dim
|
| 759 |
+
|
| 760 |
+
kernel_size = [temporal_patch_size, patch_size, patch_size]
|
| 761 |
+
self.proj = nn.Conv3d(in_channels, embed_dim, kernel_size=kernel_size, stride=kernel_size, bias=False)
|
| 762 |
+
|
| 763 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 764 |
+
target_dtype = self.proj.weight.dtype
|
| 765 |
+
hidden_states = hidden_states.view(
|
| 766 |
+
-1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size
|
| 767 |
+
)
|
| 768 |
+
hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).view(-1, self.embed_dim)
|
| 769 |
+
return hidden_states
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
class PatchMerger(nn.Module):
|
| 773 |
+
def __init__(self, dim: int, context_dim: int, spatial_merge_size: int = 2) -> None:
|
| 774 |
+
super().__init__()
|
| 775 |
+
self.hidden_size = context_dim * (spatial_merge_size**2)
|
| 776 |
+
self.ln_q = LayerNorm(context_dim, eps=1e-6)
|
| 777 |
+
self.mlp = nn.Sequential(
|
| 778 |
+
nn.Linear(self.hidden_size, self.hidden_size),
|
| 779 |
+
nn.GELU(),
|
| 780 |
+
nn.Linear(self.hidden_size, dim),
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 784 |
+
x = self.mlp(self.ln_q(x).view(-1, self.hidden_size))
|
| 785 |
+
return x
|
| 786 |
+
|
| 787 |
+
class VisionMlp(nn.Module):
|
| 788 |
+
def __init__(self, dim: int, hidden_dim: int, hidden_act: str) -> None:
|
| 789 |
+
super().__init__()
|
| 790 |
+
self.fc1 = nn.Linear(dim, hidden_dim)
|
| 791 |
+
self.act = ACT2FN[hidden_act]
|
| 792 |
+
self.fc2 = nn.Linear(hidden_dim, dim)
|
| 793 |
+
|
| 794 |
+
def forward(self, x) -> torch.Tensor:
|
| 795 |
+
return self.fc2(self.act(self.fc1(x)))
|
| 796 |
+
|
| 797 |
+
class VisionAttention(nn.Module):
|
| 798 |
+
def __init__(self, dim: int, num_heads: int = 16) -> None:
|
| 799 |
+
super().__init__()
|
| 800 |
+
self.num_heads = num_heads
|
| 801 |
+
self.head_dim = dim // num_heads
|
| 802 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=True)
|
| 803 |
+
self.proj = nn.Linear(dim, dim)
|
| 804 |
+
|
| 805 |
+
def forward(
|
| 806 |
+
self,
|
| 807 |
+
hidden_states: torch.Tensor,
|
| 808 |
+
cu_seqlens: torch.Tensor,
|
| 809 |
+
rotary_pos_emb: Optional[torch.Tensor] = None,
|
| 810 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 811 |
+
) -> torch.Tensor:
|
| 812 |
+
seq_length = hidden_states.shape[0]
|
| 813 |
+
q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
|
| 814 |
+
if position_embeddings is None:
|
| 815 |
+
logger.warning_once(
|
| 816 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
| 817 |
+
"through `rotary_pos_emb` (2D tensor of RoPE theta values), to using externally computed "
|
| 818 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.54 `rotary_pos_emb` will be "
|
| 819 |
+
"removed and `position_embeddings` will be mandatory."
|
| 820 |
+
)
|
| 821 |
+
emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
|
| 822 |
+
cos = emb.cos()
|
| 823 |
+
sin = emb.sin()
|
| 824 |
+
else:
|
| 825 |
+
cos, sin = position_embeddings
|
| 826 |
+
q, k = apply_rotary_pos_emb_vision(q, k, cos, sin)
|
| 827 |
+
|
| 828 |
+
attention_mask = torch.full(
|
| 829 |
+
[1, seq_length, seq_length], torch.finfo(q.dtype).min, device=q.device, dtype=q.dtype
|
| 830 |
+
)
|
| 831 |
+
for i in range(1, len(cu_seqlens)):
|
| 832 |
+
attention_mask[..., cu_seqlens[i - 1] : cu_seqlens[i], cu_seqlens[i - 1] : cu_seqlens[i]] = 0
|
| 833 |
+
|
| 834 |
+
q = q.transpose(0, 1)
|
| 835 |
+
k = k.transpose(0, 1)
|
| 836 |
+
v = v.transpose(0, 1)
|
| 837 |
+
attn_weights = torch.matmul(q, k.transpose(1, 2)) / math.sqrt(self.head_dim)
|
| 838 |
+
attn_weights = attn_weights + attention_mask
|
| 839 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q.dtype)
|
| 840 |
+
attn_output = torch.matmul(attn_weights, v)
|
| 841 |
+
attn_output = attn_output.transpose(0, 1)
|
| 842 |
+
attn_output = attn_output.reshape(seq_length, -1)
|
| 843 |
+
attn_output = self.proj(attn_output)
|
| 844 |
+
return attn_output
|
| 845 |
+
|
| 846 |
+
class VisionFlashAttention2(nn.Module):
|
| 847 |
+
def __init__(self, dim: int, num_heads: int = 16) -> None:
|
| 848 |
+
super().__init__()
|
| 849 |
+
self.num_heads = num_heads
|
| 850 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=True)
|
| 851 |
+
self.proj = nn.Linear(dim, dim)
|
| 852 |
+
|
| 853 |
+
def forward(
|
| 854 |
+
self,
|
| 855 |
+
hidden_states: torch.Tensor,
|
| 856 |
+
cu_seqlens: torch.Tensor,
|
| 857 |
+
rotary_pos_emb: Optional[torch.Tensor] = None,
|
| 858 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 859 |
+
) -> torch.Tensor:
|
| 860 |
+
seq_length = hidden_states.shape[0]
|
| 861 |
+
q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
|
| 862 |
+
if position_embeddings is None:
|
| 863 |
+
logger.warning_once(
|
| 864 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
| 865 |
+
"through `rotary_pos_emb` (2D tensor of RoPE theta values), to using externally computed "
|
| 866 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.54 `rotary_pos_emb` will be "
|
| 867 |
+
"removed and `position_embeddings` will be mandatory."
|
| 868 |
+
)
|
| 869 |
+
emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
|
| 870 |
+
cos = emb.cos()
|
| 871 |
+
sin = emb.sin()
|
| 872 |
+
else:
|
| 873 |
+
cos, sin = position_embeddings
|
| 874 |
+
q, k = apply_rotary_pos_emb_vision(q, k, cos, sin)
|
| 875 |
+
q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
| 876 |
+
k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
| 877 |
+
|
| 878 |
+
max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max().item()
|
| 879 |
+
attn_output = flash_attn_varlen_func(q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen).reshape(
|
| 880 |
+
seq_length, -1
|
| 881 |
+
)
|
| 882 |
+
attn_output = self.proj(attn_output)
|
| 883 |
+
return attn_output
|
| 884 |
+
|
| 885 |
+
class VisionSdpaAttention(nn.Module):
|
| 886 |
+
def __init__(self, dim: int, num_heads: int = 16) -> None:
|
| 887 |
+
super().__init__()
|
| 888 |
+
self.num_heads = num_heads
|
| 889 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=True)
|
| 890 |
+
self.proj = nn.Linear(dim, dim)
|
| 891 |
+
|
| 892 |
+
def forward(
|
| 893 |
+
self,
|
| 894 |
+
hidden_states: torch.Tensor,
|
| 895 |
+
cu_seqlens: torch.Tensor,
|
| 896 |
+
rotary_pos_emb: Optional[torch.Tensor] = None,
|
| 897 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 898 |
+
) -> torch.Tensor:
|
| 899 |
+
seq_length = hidden_states.shape[0]
|
| 900 |
+
q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
|
| 901 |
+
if position_embeddings is None:
|
| 902 |
+
logger.warning_once(
|
| 903 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
| 904 |
+
"through `rotary_pos_emb` (2D tensor of RoPE theta values), to using externally computed "
|
| 905 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.54 `rotary_pos_emb` will be "
|
| 906 |
+
"removed and `position_embeddings` will be mandatory."
|
| 907 |
+
)
|
| 908 |
+
emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
|
| 909 |
+
cos = emb.cos()
|
| 910 |
+
sin = emb.sin()
|
| 911 |
+
else:
|
| 912 |
+
cos, sin = position_embeddings
|
| 913 |
+
q, k = apply_rotary_pos_emb_vision(q, k, cos, sin)
|
| 914 |
+
|
| 915 |
+
attention_mask = torch.zeros([1, seq_length, seq_length], device=q.device, dtype=torch.bool)
|
| 916 |
+
for i in range(1, len(cu_seqlens)):
|
| 917 |
+
attention_mask[..., cu_seqlens[i - 1] : cu_seqlens[i], cu_seqlens[i - 1] : cu_seqlens[i]] = True
|
| 918 |
+
q = q.transpose(0, 1)
|
| 919 |
+
k = k.transpose(0, 1)
|
| 920 |
+
v = v.transpose(0, 1)
|
| 921 |
+
attn_output = F.scaled_dot_product_attention(
|
| 922 |
+
q.unsqueeze(0), k.unsqueeze(0), v.unsqueeze(0), attention_mask, dropout_p=0.0
|
| 923 |
+
)
|
| 924 |
+
attn_output = attn_output.squeeze(0).transpose(0, 1)
|
| 925 |
+
attn_output = attn_output.reshape(seq_length, -1)
|
| 926 |
+
attn_output = self.proj(attn_output)
|
| 927 |
+
return attn_output
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
VISION_ATTENTION_CLASSES = {
|
| 931 |
+
"eager": VisionAttention,
|
| 932 |
+
"flash_attention_2": VisionFlashAttention2,
|
| 933 |
+
"sdpa": VisionSdpaAttention,
|
| 934 |
+
}
|
| 935 |
+
|
| 936 |
+
class VisionBlock(nn.Module):
|
| 937 |
+
def __init__(self, config, attn_implementation: str = "sdpa") -> None:
|
| 938 |
+
super().__init__()
|
| 939 |
+
self.norm1 = LayerNorm(config.embed_dim, eps=1e-6)
|
| 940 |
+
self.norm2 = LayerNorm(config.embed_dim, eps=1e-6)
|
| 941 |
+
mlp_hidden_dim = int(config.embed_dim * config.mlp_ratio)
|
| 942 |
+
|
| 943 |
+
self.attn = VISION_ATTENTION_CLASSES[attn_implementation](
|
| 944 |
+
config.embed_dim, num_heads=config.num_heads
|
| 945 |
+
)
|
| 946 |
+
self.mlp = VisionMlp(dim=config.embed_dim, hidden_dim=mlp_hidden_dim, hidden_act=config.hidden_act)
|
| 947 |
+
|
| 948 |
+
def forward(
|
| 949 |
+
self,
|
| 950 |
+
hidden_states: torch.Tensor,
|
| 951 |
+
cu_seqlens: torch.Tensor,
|
| 952 |
+
rotary_pos_emb: Optional[torch.Tensor] = None,
|
| 953 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
| 954 |
+
) -> torch.Tensor:
|
| 955 |
+
hidden_states = hidden_states + self.attn(
|
| 956 |
+
self.norm1(hidden_states),
|
| 957 |
+
cu_seqlens=cu_seqlens,
|
| 958 |
+
rotary_pos_emb=rotary_pos_emb,
|
| 959 |
+
position_embeddings=position_embeddings,
|
| 960 |
+
)
|
| 961 |
+
hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
|
| 962 |
+
return hidden_states
|
| 963 |
+
|
| 964 |
+
|
| 965 |
+
######## END VISION ########
|
| 966 |
+
|
| 967 |
+
DreamVL_START_DOCSTRING = r"""
|
| 968 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 969 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 970 |
+
etc.)
|
| 971 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 972 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 973 |
+
and behavior.
|
| 974 |
+
Parameters:
|
| 975 |
+
config ([`DreamVLConfig`]):
|
| 976 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
| 977 |
+
load the weights associated with the model, only the configuration. Check out the
|
| 978 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 979 |
+
"""
|
| 980 |
+
|
| 981 |
+
|
| 982 |
+
@add_start_docstrings(
|
| 983 |
+
"The bare DreamVL Model outputting raw hidden-states without any specific head on top.",
|
| 984 |
+
DreamVL_START_DOCSTRING,
|
| 985 |
+
)
|
| 986 |
+
class DreamVLPreTrainedModel(PreTrainedModel):
|
| 987 |
+
config_class = DreamVLConfig
|
| 988 |
+
base_model_prefix = "model"
|
| 989 |
+
supports_gradient_checkpointing = True
|
| 990 |
+
_no_split_modules = ["DreamVLDecoderLayer", "DreamVLVisionBlock"]
|
| 991 |
+
_skip_keys_device_placement = "past_key_values"
|
| 992 |
+
_supports_flash_attn_2 = True
|
| 993 |
+
_supports_sdpa = True
|
| 994 |
+
_supports_cache_class = True
|
| 995 |
+
_supports_quantized_cache = True
|
| 996 |
+
_supports_static_cache = True
|
| 997 |
+
|
| 998 |
+
def _init_weights(self, module):
|
| 999 |
+
std = self.config.initializer_range
|
| 1000 |
+
if isinstance(module, (nn.Linear, nn.Conv3d)):
|
| 1001 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 1002 |
+
if module.bias is not None:
|
| 1003 |
+
module.bias.data.zero_()
|
| 1004 |
+
elif isinstance(module, nn.Embedding):
|
| 1005 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 1006 |
+
if module.padding_idx is not None:
|
| 1007 |
+
module.weight.data[module.padding_idx].zero_()
|
| 1008 |
+
elif isinstance(module, DreamVLRMSNorm):
|
| 1009 |
+
module.weight.data.fill_(1.0)
|
| 1010 |
+
|
| 1011 |
+
@classmethod
|
| 1012 |
+
def from_pretrained(
|
| 1013 |
+
cls,
|
| 1014 |
+
pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
|
| 1015 |
+
*model_args,
|
| 1016 |
+
config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,
|
| 1017 |
+
cache_dir: Optional[Union[str, os.PathLike]] = None,
|
| 1018 |
+
ignore_mismatched_sizes: bool = False,
|
| 1019 |
+
force_download: bool = False,
|
| 1020 |
+
local_files_only: bool = False,
|
| 1021 |
+
token: Optional[Union[str, bool]] = None,
|
| 1022 |
+
revision: str = "main",
|
| 1023 |
+
use_safetensors: Optional[bool] = None,
|
| 1024 |
+
weights_only: bool = True,
|
| 1025 |
+
**kwargs,
|
| 1026 |
+
):
|
| 1027 |
+
_model = super().from_pretrained(
|
| 1028 |
+
pretrained_model_name_or_path,
|
| 1029 |
+
*model_args,
|
| 1030 |
+
config=config,
|
| 1031 |
+
cache_dir=cache_dir,
|
| 1032 |
+
ignore_mismatched_sizes=ignore_mismatched_sizes,
|
| 1033 |
+
force_download=force_download,
|
| 1034 |
+
local_files_only=local_files_only,
|
| 1035 |
+
token=token,
|
| 1036 |
+
revision=revision,
|
| 1037 |
+
use_safetensors=use_safetensors,
|
| 1038 |
+
weights_only=weights_only,
|
| 1039 |
+
**kwargs,
|
| 1040 |
+
)
|
| 1041 |
+
# NOTE(Lin): we need to override the generation config
|
| 1042 |
+
# because the generation config loaded in `from_pretrained`
|
| 1043 |
+
# does not include all the attributes of DreamVLGenerationConfig
|
| 1044 |
+
resume_download = kwargs.get("resume_download", None)
|
| 1045 |
+
proxies = kwargs.get("proxies", None)
|
| 1046 |
+
subfolder = kwargs.get("subfolder", "")
|
| 1047 |
+
from_auto_class = kwargs.get("_from_auto", False)
|
| 1048 |
+
from_pipeline = kwargs.get("_from_pipeline", None)
|
| 1049 |
+
_model.generation_config = DreamVLGenerationConfig.from_pretrained(
|
| 1050 |
+
pretrained_model_name_or_path,
|
| 1051 |
+
cache_dir=cache_dir,
|
| 1052 |
+
force_download=force_download,
|
| 1053 |
+
resume_download=resume_download,
|
| 1054 |
+
proxies=proxies,
|
| 1055 |
+
local_files_only=local_files_only,
|
| 1056 |
+
token=token,
|
| 1057 |
+
revision=revision,
|
| 1058 |
+
subfolder=subfolder,
|
| 1059 |
+
_from_auto=from_auto_class,
|
| 1060 |
+
_from_pipeline=from_pipeline,
|
| 1061 |
+
)
|
| 1062 |
+
return _model
|
| 1063 |
+
|
| 1064 |
+
|
| 1065 |
+
class DreamVLVisionTransformerPretrainedModel(DreamVLPreTrainedModel):
|
| 1066 |
+
config_class = DreamVLVisionConfig
|
| 1067 |
+
_no_split_modules = ["DreamVLVisionBlock"]
|
| 1068 |
+
|
| 1069 |
+
def __init__(self, config) -> None:
|
| 1070 |
+
super().__init__(config)
|
| 1071 |
+
self.spatial_merge_size = config.spatial_merge_size
|
| 1072 |
+
|
| 1073 |
+
self.patch_embed = PatchEmbed(
|
| 1074 |
+
patch_size=config.patch_size,
|
| 1075 |
+
temporal_patch_size=config.temporal_patch_size,
|
| 1076 |
+
in_channels=config.in_channels,
|
| 1077 |
+
embed_dim=config.embed_dim,
|
| 1078 |
+
)
|
| 1079 |
+
|
| 1080 |
+
head_dim = config.embed_dim // config.num_heads
|
| 1081 |
+
self.rotary_pos_emb = VisionRotaryEmbedding(head_dim // 2)
|
| 1082 |
+
|
| 1083 |
+
self.blocks = nn.ModuleList(
|
| 1084 |
+
[VisionBlock(config, config._attn_implementation) for _ in range(config.depth)]
|
| 1085 |
+
)
|
| 1086 |
+
self.merger = PatchMerger(
|
| 1087 |
+
dim=config.hidden_size, context_dim=config.embed_dim, spatial_merge_size=config.spatial_merge_size
|
| 1088 |
+
)
|
| 1089 |
+
self.gradient_checkpointing = False
|
| 1090 |
+
|
| 1091 |
+
def rot_pos_emb(self, grid_thw):
|
| 1092 |
+
pos_ids = []
|
| 1093 |
+
for t, h, w in grid_thw:
|
| 1094 |
+
hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
|
| 1095 |
+
hpos_ids = hpos_ids.reshape(
|
| 1096 |
+
h // self.spatial_merge_size,
|
| 1097 |
+
self.spatial_merge_size,
|
| 1098 |
+
w // self.spatial_merge_size,
|
| 1099 |
+
self.spatial_merge_size,
|
| 1100 |
+
)
|
| 1101 |
+
hpos_ids = hpos_ids.permute(0, 2, 1, 3)
|
| 1102 |
+
hpos_ids = hpos_ids.flatten()
|
| 1103 |
+
|
| 1104 |
+
wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
|
| 1105 |
+
wpos_ids = wpos_ids.reshape(
|
| 1106 |
+
h // self.spatial_merge_size,
|
| 1107 |
+
self.spatial_merge_size,
|
| 1108 |
+
w // self.spatial_merge_size,
|
| 1109 |
+
self.spatial_merge_size,
|
| 1110 |
+
)
|
| 1111 |
+
wpos_ids = wpos_ids.permute(0, 2, 1, 3)
|
| 1112 |
+
wpos_ids = wpos_ids.flatten()
|
| 1113 |
+
pos_ids.append(torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1))
|
| 1114 |
+
pos_ids = torch.cat(pos_ids, dim=0)
|
| 1115 |
+
max_grid_size = grid_thw[:, 1:].max()
|
| 1116 |
+
rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size)
|
| 1117 |
+
rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
|
| 1118 |
+
return rotary_pos_emb
|
| 1119 |
+
|
| 1120 |
+
def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor) -> torch.Tensor:
|
| 1121 |
+
r"""
|
| 1122 |
+
grid_thw (`torch.LongTensor` of shape `(num_images, 3)`):
|
| 1123 |
+
The temporal, height and width dimensions of feature shape for each image. Each row contains [t, h, w] values.
|
| 1124 |
+
"""
|
| 1125 |
+
hidden_states = self.patch_embed(hidden_states)
|
| 1126 |
+
rotary_pos_emb = self.rot_pos_emb(grid_thw)
|
| 1127 |
+
emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1)
|
| 1128 |
+
position_embeddings = (emb.cos(), emb.sin())
|
| 1129 |
+
|
| 1130 |
+
cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
|
| 1131 |
+
dim=0,
|
| 1132 |
+
# Select dtype based on the following factors:
|
| 1133 |
+
# - FA2 requires that cu_seqlens_q must have dtype int32
|
| 1134 |
+
# - torch.onnx.export requires that cu_seqlens_q must have same dtype as grid_thw
|
| 1135 |
+
# See https://github.com/huggingface/transformers/pull/34852 for more information
|
| 1136 |
+
dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
|
| 1137 |
+
)
|
| 1138 |
+
cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
|
| 1139 |
+
|
| 1140 |
+
for blk in self.blocks:
|
| 1141 |
+
if self.gradient_checkpointing and self.training:
|
| 1142 |
+
hidden_states = self._gradient_checkpointing_func(
|
| 1143 |
+
blk.__call__, hidden_states, cu_seqlens, None, position_embeddings
|
| 1144 |
+
)
|
| 1145 |
+
else:
|
| 1146 |
+
hidden_states = blk(hidden_states, cu_seqlens=cu_seqlens, position_embeddings=position_embeddings)
|
| 1147 |
+
|
| 1148 |
+
return self.merger(hidden_states)
|
| 1149 |
+
|
| 1150 |
+
# Copied from transformers.models.llava.modeling_llava.LlavaMultiModalProjector with Llava->DreamVL
|
| 1151 |
+
class DreamVLMultiModalProjector(nn.Module):
|
| 1152 |
+
def __init__(self, config: DreamVLConfig):
|
| 1153 |
+
super().__init__()
|
| 1154 |
+
|
| 1155 |
+
self.linear_1 = nn.Linear(config.vision_config.hidden_size, config.hidden_size, bias=True)
|
| 1156 |
+
self.act = ACT2FN[config.projector_hidden_act]
|
| 1157 |
+
self.linear_2 = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
|
| 1158 |
+
|
| 1159 |
+
def forward(self, image_features):
|
| 1160 |
+
hidden_states = self.linear_1(image_features)
|
| 1161 |
+
hidden_states = self.act(hidden_states)
|
| 1162 |
+
hidden_states = self.linear_2(hidden_states)
|
| 1163 |
+
return hidden_states
|
| 1164 |
+
|
| 1165 |
+
@add_start_docstrings(
|
| 1166 |
+
"The bare DreamVL Model outputting raw hidden-states without any specific head on top.",
|
| 1167 |
+
DreamVL_START_DOCSTRING,
|
| 1168 |
+
)
|
| 1169 |
+
class DreamVLBaseModel(DreamVLPreTrainedModel):
|
| 1170 |
+
def __init__(self, config: DreamVLConfig):
|
| 1171 |
+
super().__init__(config)
|
| 1172 |
+
self.padding_idx = config.pad_token_id
|
| 1173 |
+
self.vocab_size = config.vocab_size
|
| 1174 |
+
|
| 1175 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 1176 |
+
self.layers = nn.ModuleList(
|
| 1177 |
+
[DreamVLDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 1178 |
+
)
|
| 1179 |
+
self._attn_implementation = config._attn_implementation
|
| 1180 |
+
self.norm = DreamVLRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 1181 |
+
self.rotary_emb = DreamVLRotaryEmbedding(config=config)
|
| 1182 |
+
|
| 1183 |
+
self.gradient_checkpointing = False
|
| 1184 |
+
# Initialize weights and apply final processing
|
| 1185 |
+
self.post_init()
|
| 1186 |
+
|
| 1187 |
+
def get_input_embeddings(self):
|
| 1188 |
+
return self.embed_tokens
|
| 1189 |
+
|
| 1190 |
+
def set_input_embeddings(self, value):
|
| 1191 |
+
self.embed_tokens = value
|
| 1192 |
+
|
| 1193 |
+
def forward(
|
| 1194 |
+
self,
|
| 1195 |
+
input_ids: torch.LongTensor = None,
|
| 1196 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1197 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1198 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1199 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1200 |
+
use_cache: Optional[bool] = None,
|
| 1201 |
+
output_attentions: Optional[bool] = None,
|
| 1202 |
+
output_hidden_states: Optional[bool] = None,
|
| 1203 |
+
return_dict: Optional[bool] = None,
|
| 1204 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 1205 |
+
) -> Union[Tuple, BaseModelOutput]:
|
| 1206 |
+
|
| 1207 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1208 |
+
output_hidden_states = (
|
| 1209 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1210 |
+
)
|
| 1211 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1212 |
+
|
| 1213 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1214 |
+
|
| 1215 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 1216 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 1217 |
+
|
| 1218 |
+
if self.gradient_checkpointing and self.training:
|
| 1219 |
+
if use_cache:
|
| 1220 |
+
use_cache = False
|
| 1221 |
+
|
| 1222 |
+
if inputs_embeds is None:
|
| 1223 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 1224 |
+
|
| 1225 |
+
if use_cache and past_key_values is None:
|
| 1226 |
+
logger.warning_once(
|
| 1227 |
+
"This should not be triggered, in either training or inference, but if it is, please report it to us."
|
| 1228 |
+
)
|
| 1229 |
+
past_key_values = DynamicCache()
|
| 1230 |
+
|
| 1231 |
+
if cache_position is None:
|
| 1232 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 1233 |
+
cache_position = torch.arange(
|
| 1234 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 1235 |
+
)
|
| 1236 |
+
|
| 1237 |
+
# the hard coded `3` is for temporal, height and width.
|
| 1238 |
+
if position_ids is None:
|
| 1239 |
+
logger.warning_once(
|
| 1240 |
+
"This should not be triggered, in either training or inference, but if it is, please report it to us."
|
| 1241 |
+
)
|
| 1242 |
+
position_ids = cache_position.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1)
|
| 1243 |
+
elif position_ids.dim() == 2:
|
| 1244 |
+
logger.warning_once(
|
| 1245 |
+
"This should not be triggered, in either training or inference, but if it is, please report it to us."
|
| 1246 |
+
)
|
| 1247 |
+
position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
|
| 1248 |
+
|
| 1249 |
+
hidden_states = inputs_embeds
|
| 1250 |
+
|
| 1251 |
+
# create position embeddings to be shared across the decoder layers
|
| 1252 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 1253 |
+
|
| 1254 |
+
# decoder layers
|
| 1255 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1256 |
+
all_self_attns = () if output_attentions else None
|
| 1257 |
+
|
| 1258 |
+
for decoder_layer in self.layers:
|
| 1259 |
+
if output_hidden_states:
|
| 1260 |
+
all_hidden_states += (hidden_states,)
|
| 1261 |
+
|
| 1262 |
+
if self.gradient_checkpointing and self.training:
|
| 1263 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 1264 |
+
decoder_layer.__call__,
|
| 1265 |
+
hidden_states,
|
| 1266 |
+
attention_mask,
|
| 1267 |
+
position_ids,
|
| 1268 |
+
past_key_values,
|
| 1269 |
+
output_attentions,
|
| 1270 |
+
use_cache,
|
| 1271 |
+
cache_position,
|
| 1272 |
+
position_embeddings,
|
| 1273 |
+
)
|
| 1274 |
+
else:
|
| 1275 |
+
layer_outputs = decoder_layer(
|
| 1276 |
+
hidden_states,
|
| 1277 |
+
attention_mask=attention_mask,
|
| 1278 |
+
position_ids=position_ids,
|
| 1279 |
+
past_key_value=past_key_values,
|
| 1280 |
+
output_attentions=output_attentions,
|
| 1281 |
+
use_cache=use_cache,
|
| 1282 |
+
cache_position=cache_position,
|
| 1283 |
+
position_embeddings=position_embeddings,
|
| 1284 |
+
)
|
| 1285 |
+
|
| 1286 |
+
hidden_states = layer_outputs[0]
|
| 1287 |
+
|
| 1288 |
+
if output_attentions:
|
| 1289 |
+
all_self_attns += (layer_outputs[1],)
|
| 1290 |
+
|
| 1291 |
+
hidden_states = self.norm(hidden_states)
|
| 1292 |
+
|
| 1293 |
+
# add hidden states from the last decoder layer
|
| 1294 |
+
if output_hidden_states:
|
| 1295 |
+
all_hidden_states += (hidden_states,)
|
| 1296 |
+
|
| 1297 |
+
if not return_dict:
|
| 1298 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attns] if v is not None)
|
| 1299 |
+
return BaseModelOutputWithPast(
|
| 1300 |
+
last_hidden_state=hidden_states,
|
| 1301 |
+
past_key_values=past_key_values,
|
| 1302 |
+
hidden_states=all_hidden_states,
|
| 1303 |
+
attentions=all_self_attns,
|
| 1304 |
+
)
|
| 1305 |
+
|
| 1306 |
+
DreamVL_INPUTS_DOCSTRING = r"""
|
| 1307 |
+
Args:
|
| 1308 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 1309 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 1310 |
+
it.
|
| 1311 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1312 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1313 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1314 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1315 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 1316 |
+
- 1 for tokens that are **not masked**,
|
| 1317 |
+
- 0 for tokens that are **masked**.
|
| 1318 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 1319 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1320 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1321 |
+
If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
|
| 1322 |
+
`past_key_values`).
|
| 1323 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
| 1324 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
| 1325 |
+
information on the default strategy.
|
| 1326 |
+
- 1 indicates the head is **not masked**,
|
| 1327 |
+
- 0 indicates the head is **masked**.
|
| 1328 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1329 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
| 1330 |
+
config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
|
| 1331 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
|
| 1332 |
+
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
|
| 1333 |
+
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
|
| 1334 |
+
`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
|
| 1335 |
+
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
| 1336 |
+
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
|
| 1337 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
| 1338 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
| 1339 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
| 1340 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 1341 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 1342 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 1343 |
+
model's internal embedding lookup matrix.
|
| 1344 |
+
use_cache (`bool`, *optional*):
|
| 1345 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
| 1346 |
+
`past_key_values`).
|
| 1347 |
+
output_attentions (`bool`, *optional*):
|
| 1348 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 1349 |
+
tensors for more detail.
|
| 1350 |
+
output_hidden_states (`bool`, *optional*):
|
| 1351 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 1352 |
+
more detail.
|
| 1353 |
+
return_dict (`bool`, *optional*):
|
| 1354 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 1355 |
+
pixel_values (`torch.FloatTensor` of shape `(seq_length, num_channels * image_size * image_size)):
|
| 1356 |
+
The tensors corresponding to the input images. Pixel values can be obtained using
|
| 1357 |
+
[`AutoImageProcessor`]. See [`DreamVLImageProcessor.__call__`] for details. [`DreamVLProcessor`] uses
|
| 1358 |
+
[`DreamVLImageProcessor`] for processing images.
|
| 1359 |
+
pixel_values_videos (`torch.FloatTensor` of shape `(seq_length, num_channels * temporal_size * image_size * image_size)):
|
| 1360 |
+
The tensors corresponding to the input videos. Pixel values can be obtained using
|
| 1361 |
+
[`AutoImageProcessor`]. See [`DreamVLImageProcessor.__call__`] for details. [`DreamVLProcessor`] uses
|
| 1362 |
+
[`DreamVLImageProcessor`] for processing videos.
|
| 1363 |
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
| 1364 |
+
The temporal, height and width of feature shape of each image in LLM.
|
| 1365 |
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
| 1366 |
+
The temporal, height and width of feature shape of each video in LLM.
|
| 1367 |
+
rope_deltas (`torch.LongTensor` of shape `(batch_size, )`, *optional*):
|
| 1368 |
+
The rope index difference between sequence length and multimodal rope.
|
| 1369 |
+
"""
|
| 1370 |
+
|
| 1371 |
+
|
| 1372 |
+
class DreamVLModel(DreamVLGenerationMixin, DreamVLPreTrainedModel):
|
| 1373 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 1374 |
+
|
| 1375 |
+
def __init__(self, config):
|
| 1376 |
+
super().__init__(config)
|
| 1377 |
+
self.visual = DreamVLVisionTransformerPretrainedModel._from_config(config.vision_config)
|
| 1378 |
+
self.model = DreamVLBaseModel(config)
|
| 1379 |
+
self.projector = DreamVLMultiModalProjector(config)
|
| 1380 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1381 |
+
# Initialize weights and apply final processing
|
| 1382 |
+
self.post_init()
|
| 1383 |
+
|
| 1384 |
+
def reset_rope_parameters(self):
|
| 1385 |
+
self.model.rotary_emb.reset_parameters()
|
| 1386 |
+
for layer in self.model.layers:
|
| 1387 |
+
layer.self_attn.rotary_emb.reset_parameters()
|
| 1388 |
+
|
| 1389 |
+
def get_input_embeddings(self):
|
| 1390 |
+
return self.model.embed_tokens
|
| 1391 |
+
|
| 1392 |
+
def set_input_embeddings(self, value):
|
| 1393 |
+
self.model.embed_tokens = value
|
| 1394 |
+
|
| 1395 |
+
def get_output_embeddings(self):
|
| 1396 |
+
return self.lm_head
|
| 1397 |
+
|
| 1398 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1399 |
+
self.lm_head = new_embeddings
|
| 1400 |
+
|
| 1401 |
+
def set_decoder(self, decoder):
|
| 1402 |
+
self.model = decoder
|
| 1403 |
+
|
| 1404 |
+
def get_decoder(self):
|
| 1405 |
+
return self.model
|
| 1406 |
+
|
| 1407 |
+
def get_rope_index(
|
| 1408 |
+
self,
|
| 1409 |
+
input_ids: torch.LongTensor,
|
| 1410 |
+
image_grid_thw: Optional[torch.LongTensor] = None,
|
| 1411 |
+
video_grid_thw: Optional[torch.LongTensor] = None,
|
| 1412 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1413 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 1414 |
+
"""
|
| 1415 |
+
Calculate the 3D rope index based on image and video's temporal, height and width in LLM.
|
| 1416 |
+
Explanation:
|
| 1417 |
+
Each embedding sequence contains vision embedding and text embedding or just contains text embedding.
|
| 1418 |
+
For pure text embedding sequence, the rotary position embedding has no difference with mordern LLMs.
|
| 1419 |
+
Examples:
|
| 1420 |
+
input_ids: [T T T T T], here T is for text.
|
| 1421 |
+
temporal position_ids: [0, 1, 2, 3, 4]
|
| 1422 |
+
height position_ids: [0, 1, 2, 3, 4]
|
| 1423 |
+
width position_ids: [0, 1, 2, 3, 4]
|
| 1424 |
+
For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part
|
| 1425 |
+
and 1D rotary position embeddin for text part.
|
| 1426 |
+
Examples:
|
| 1427 |
+
Assume we have a video input with 3 temporal patches, 2 height patches and 2 width patches.
|
| 1428 |
+
input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision.
|
| 1429 |
+
vision temporal position_ids: [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]
|
| 1430 |
+
vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1]
|
| 1431 |
+
vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
|
| 1432 |
+
text temporal position_ids: [3, 4, 5, 6, 7]
|
| 1433 |
+
text height position_ids: [3, 4, 5, 6, 7]
|
| 1434 |
+
text width position_ids: [3, 4, 5, 6, 7]
|
| 1435 |
+
Here we calculate the text start position_ids as the max vision position_ids plus 1.
|
| 1436 |
+
Args:
|
| 1437 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
| 1438 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
| 1439 |
+
it.
|
| 1440 |
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
| 1441 |
+
The temporal, height and width of feature shape of each image in LLM.
|
| 1442 |
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
| 1443 |
+
The temporal, height and width of feature shape of each video in LLM.
|
| 1444 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1445 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 1446 |
+
- 1 for tokens that are **not masked**,
|
| 1447 |
+
- 0 for tokens that are **masked**.
|
| 1448 |
+
Returns:
|
| 1449 |
+
position_ids (`torch.LongTensor` of shape `(3, batch_size, sequence_length)`)
|
| 1450 |
+
mrope_position_deltas (`torch.Tensor` of shape `(batch_size)`)
|
| 1451 |
+
"""
|
| 1452 |
+
spatial_merge_size = self.config.vision_config.spatial_merge_size
|
| 1453 |
+
image_token_id = self.config.image_token_id
|
| 1454 |
+
video_token_id = self.config.video_token_id
|
| 1455 |
+
vision_start_token_id = self.config.vision_start_token_id
|
| 1456 |
+
mrope_position_deltas = []
|
| 1457 |
+
if image_grid_thw is not None or video_grid_thw is not None:
|
| 1458 |
+
total_input_ids = input_ids
|
| 1459 |
+
if attention_mask is None:
|
| 1460 |
+
attention_mask = torch.ones_like(total_input_ids)
|
| 1461 |
+
position_ids = torch.ones(
|
| 1462 |
+
3, input_ids.shape[0], input_ids.shape[1], dtype=input_ids.dtype, device=input_ids.device
|
| 1463 |
+
)
|
| 1464 |
+
image_index, video_index = 0, 0
|
| 1465 |
+
for i, input_ids in enumerate(total_input_ids):
|
| 1466 |
+
input_ids = input_ids[attention_mask[i] == 1]
|
| 1467 |
+
image_nums, video_nums = 0, 0
|
| 1468 |
+
vision_start_indices = torch.argwhere(input_ids == vision_start_token_id).squeeze(1)
|
| 1469 |
+
vision_tokens = input_ids[vision_start_indices + 1]
|
| 1470 |
+
image_nums = (vision_tokens == image_token_id).sum()
|
| 1471 |
+
video_nums = (vision_tokens == video_token_id).sum()
|
| 1472 |
+
input_tokens = input_ids.tolist()
|
| 1473 |
+
llm_pos_ids_list: list = []
|
| 1474 |
+
st = 0
|
| 1475 |
+
remain_images, remain_videos = image_nums, video_nums
|
| 1476 |
+
for _ in range(image_nums + video_nums):
|
| 1477 |
+
if image_token_id in input_tokens and remain_images > 0:
|
| 1478 |
+
ed_image = input_tokens.index(image_token_id, st)
|
| 1479 |
+
else:
|
| 1480 |
+
ed_image = len(input_tokens) + 1
|
| 1481 |
+
if video_token_id in input_tokens and remain_videos > 0:
|
| 1482 |
+
ed_video = input_tokens.index(video_token_id, st)
|
| 1483 |
+
else:
|
| 1484 |
+
ed_video = len(input_tokens) + 1
|
| 1485 |
+
if ed_image < ed_video:
|
| 1486 |
+
t, h, w = (
|
| 1487 |
+
image_grid_thw[image_index][0],
|
| 1488 |
+
image_grid_thw[image_index][1],
|
| 1489 |
+
image_grid_thw[image_index][2],
|
| 1490 |
+
)
|
| 1491 |
+
image_index += 1
|
| 1492 |
+
remain_images -= 1
|
| 1493 |
+
ed = ed_image
|
| 1494 |
+
else:
|
| 1495 |
+
t, h, w = (
|
| 1496 |
+
video_grid_thw[video_index][0],
|
| 1497 |
+
video_grid_thw[video_index][1],
|
| 1498 |
+
video_grid_thw[video_index][2],
|
| 1499 |
+
)
|
| 1500 |
+
video_index += 1
|
| 1501 |
+
remain_videos -= 1
|
| 1502 |
+
ed = ed_video
|
| 1503 |
+
llm_grid_t, llm_grid_h, llm_grid_w = (
|
| 1504 |
+
t.item(),
|
| 1505 |
+
h.item() // spatial_merge_size,
|
| 1506 |
+
w.item() // spatial_merge_size,
|
| 1507 |
+
)
|
| 1508 |
+
text_len = ed - st
|
| 1509 |
+
|
| 1510 |
+
st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
|
| 1511 |
+
llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
|
| 1512 |
+
|
| 1513 |
+
t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten()
|
| 1514 |
+
h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten()
|
| 1515 |
+
w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten()
|
| 1516 |
+
llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx)
|
| 1517 |
+
st = ed + llm_grid_t * llm_grid_h * llm_grid_w
|
| 1518 |
+
|
| 1519 |
+
if st < len(input_tokens):
|
| 1520 |
+
st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
|
| 1521 |
+
text_len = len(input_tokens) - st
|
| 1522 |
+
llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
|
| 1523 |
+
|
| 1524 |
+
llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
|
| 1525 |
+
position_ids[..., i, attention_mask[i] == 1] = llm_positions.to(position_ids.device)
|
| 1526 |
+
mrope_position_deltas.append(llm_positions.max() + 1 - len(total_input_ids[i]))
|
| 1527 |
+
mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
|
| 1528 |
+
return position_ids, mrope_position_deltas
|
| 1529 |
+
else:
|
| 1530 |
+
if attention_mask is not None:
|
| 1531 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 1532 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 1533 |
+
position_ids = position_ids.unsqueeze(0).expand(3, -1, -1).to(input_ids.device)
|
| 1534 |
+
max_position_ids = position_ids.max(0, keepdim=False)[0].max(-1, keepdim=True)[0]
|
| 1535 |
+
mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]
|
| 1536 |
+
else:
|
| 1537 |
+
position_ids = (
|
| 1538 |
+
torch.arange(input_ids.shape[1], device=input_ids.device)
|
| 1539 |
+
.view(1, 1, -1)
|
| 1540 |
+
.expand(3, input_ids.shape[0], -1)
|
| 1541 |
+
)
|
| 1542 |
+
mrope_position_deltas = torch.zeros(
|
| 1543 |
+
[input_ids.shape[0], 1],
|
| 1544 |
+
device=input_ids.device,
|
| 1545 |
+
dtype=input_ids.dtype,
|
| 1546 |
+
)
|
| 1547 |
+
|
| 1548 |
+
return position_ids, mrope_position_deltas
|
| 1549 |
+
|
| 1550 |
+
def get_video_features(
|
| 1551 |
+
self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None
|
| 1552 |
+
):
|
| 1553 |
+
"""
|
| 1554 |
+
Encodes videos into continuous embeddings that can be forwarded to the language model.
|
| 1555 |
+
|
| 1556 |
+
Args:
|
| 1557 |
+
pixel_values_videos (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 1558 |
+
The tensors corresponding to the input videos.
|
| 1559 |
+
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
|
| 1560 |
+
The temporal, height and width of feature shape of each video in LLM.
|
| 1561 |
+
"""
|
| 1562 |
+
pixel_values_videos = pixel_values_videos.type(self.visual.dtype)
|
| 1563 |
+
video_embeds = self.visual(pixel_values_videos, grid_thw=video_grid_thw)
|
| 1564 |
+
split_sizes = (video_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
|
| 1565 |
+
video_embeds = torch.split(video_embeds, split_sizes)
|
| 1566 |
+
return video_embeds
|
| 1567 |
+
|
| 1568 |
+
def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None):
|
| 1569 |
+
"""
|
| 1570 |
+
Encodes images into continuous embeddings that can be forwarded to the language model.
|
| 1571 |
+
|
| 1572 |
+
Args:
|
| 1573 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
|
| 1574 |
+
The tensors corresponding to the input images.
|
| 1575 |
+
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
|
| 1576 |
+
The temporal, height and width of feature shape of each image in LLM.
|
| 1577 |
+
"""
|
| 1578 |
+
pixel_values = pixel_values.type(self.visual.dtype)
|
| 1579 |
+
image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw)
|
| 1580 |
+
split_sizes = (image_grid_thw.prod(-1) // self.visual.spatial_merge_size**2).tolist()
|
| 1581 |
+
image_embeds = torch.split(image_embeds, split_sizes)
|
| 1582 |
+
return image_embeds
|
| 1583 |
+
|
| 1584 |
+
@add_start_docstrings_to_model_forward(DreamVL_INPUTS_DOCSTRING)
|
| 1585 |
+
@replace_return_docstrings(output_type=DreamVLModelOutput, config_class=_CONFIG_FOR_DOC)
|
| 1586 |
+
def forward(
|
| 1587 |
+
self,
|
| 1588 |
+
input_ids: torch.LongTensor = None,
|
| 1589 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1590 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1591 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1592 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1593 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1594 |
+
use_cache: Optional[bool] = None,
|
| 1595 |
+
output_attentions: Optional[bool] = None,
|
| 1596 |
+
output_hidden_states: Optional[bool] = None,
|
| 1597 |
+
return_dict: Optional[bool] = None,
|
| 1598 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 1599 |
+
pixel_values_videos: Optional[torch.FloatTensor] = None,
|
| 1600 |
+
image_grid_thw: Optional[torch.LongTensor] = None,
|
| 1601 |
+
video_grid_thw: Optional[torch.LongTensor] = None,
|
| 1602 |
+
rope_deltas: Optional[torch.LongTensor] = None,
|
| 1603 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 1604 |
+
num_logits_to_keep: int = 0,
|
| 1605 |
+
**loss_kwargs,
|
| 1606 |
+
) -> Union[Tuple, DreamVLModelOutput]:
|
| 1607 |
+
r"""
|
| 1608 |
+
Args:
|
| 1609 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1610 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1611 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1612 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1613 |
+
Returns:
|
| 1614 |
+
Example:
|
| 1615 |
+
```python
|
| 1616 |
+
>>> from PIL import Image
|
| 1617 |
+
>>> import requests
|
| 1618 |
+
>>> from transformers import AutoProcessor, DreamVLForConditionalGeneration
|
| 1619 |
+
>>> model = DreamVLForConditionalGeneration.from_pretrained(" ")
|
| 1620 |
+
>>> processor = AutoProcessor.from_pretrained(" ")
|
| 1621 |
+
>>> messages = [
|
| 1622 |
+
{
|
| 1623 |
+
"role": "user",
|
| 1624 |
+
"content": [
|
| 1625 |
+
{"type": "image"},
|
| 1626 |
+
{"type": "text", "text": "What is shown in this image?"},
|
| 1627 |
+
],
|
| 1628 |
+
},
|
| 1629 |
+
]
|
| 1630 |
+
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
|
| 1631 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 1632 |
+
>>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 1633 |
+
>>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
|
| 1634 |
+
>>> # Generate
|
| 1635 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 1636 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 1637 |
+
"The image shows a street scene with a red stop sign in the foreground. In the background, there is a large red gate with Chinese characters ..."
|
| 1638 |
+
```"""
|
| 1639 |
+
|
| 1640 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1641 |
+
output_hidden_states = (
|
| 1642 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1643 |
+
)
|
| 1644 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1645 |
+
|
| 1646 |
+
if inputs_embeds is None:
|
| 1647 |
+
inputs_embeds = self.get_input_embeddings()(input_ids)
|
| 1648 |
+
if pixel_values is not None:
|
| 1649 |
+
image_embeds = self.get_image_features(pixel_values, image_grid_thw)
|
| 1650 |
+
image_embeds = torch.cat(image_embeds, dim=0)
|
| 1651 |
+
n_image_tokens = (input_ids == self.config.image_token_id).sum()
|
| 1652 |
+
n_image_features = image_embeds.shape[0]
|
| 1653 |
+
if not is_torchdynamo_compiling() and n_image_tokens != n_image_features:
|
| 1654 |
+
raise ValueError(
|
| 1655 |
+
f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
|
| 1656 |
+
)
|
| 1657 |
+
|
| 1658 |
+
mask = input_ids == self.config.image_token_id
|
| 1659 |
+
mask_unsqueezed = mask.unsqueeze(-1)
|
| 1660 |
+
mask_expanded = mask_unsqueezed.expand_as(inputs_embeds)
|
| 1661 |
+
|
| 1662 |
+
image_mask = mask_expanded.to(inputs_embeds.device)
|
| 1663 |
+
image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
|
| 1664 |
+
image_embeds_projected = self.projector(image_embeds)
|
| 1665 |
+
|
| 1666 |
+
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds_projected)
|
| 1667 |
+
|
| 1668 |
+
if pixel_values_videos is not None:
|
| 1669 |
+
video_embeds = self.get_video_features(pixel_values_videos, video_grid_thw)
|
| 1670 |
+
video_embeds = torch.cat(video_embeds, dim=0)
|
| 1671 |
+
n_video_tokens = (input_ids == self.config.video_token_id).sum()
|
| 1672 |
+
n_video_features = video_embeds.shape[0]
|
| 1673 |
+
if not is_torchdynamo_compiling() and n_video_tokens != n_video_features:
|
| 1674 |
+
raise ValueError(
|
| 1675 |
+
f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}"
|
| 1676 |
+
)
|
| 1677 |
+
|
| 1678 |
+
mask = input_ids == self.config.video_token_id
|
| 1679 |
+
mask_unsqueezed = mask.unsqueeze(-1)
|
| 1680 |
+
mask_expanded = mask_unsqueezed.expand_as(inputs_embeds)
|
| 1681 |
+
|
| 1682 |
+
video_mask = mask_expanded.to(inputs_embeds.device)
|
| 1683 |
+
video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
|
| 1684 |
+
video_embeds_projected = self.projector(video_embeds)
|
| 1685 |
+
|
| 1686 |
+
inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds_projected)
|
| 1687 |
+
|
| 1688 |
+
outputs = self.model(
|
| 1689 |
+
attention_mask=attention_mask,
|
| 1690 |
+
position_ids=position_ids,
|
| 1691 |
+
past_key_values=past_key_values,
|
| 1692 |
+
inputs_embeds=inputs_embeds,
|
| 1693 |
+
use_cache=use_cache,
|
| 1694 |
+
output_attentions=output_attentions,
|
| 1695 |
+
output_hidden_states=output_hidden_states,
|
| 1696 |
+
return_dict=return_dict,
|
| 1697 |
+
cache_position=cache_position,
|
| 1698 |
+
)
|
| 1699 |
+
|
| 1700 |
+
hidden_states = outputs[0]
|
| 1701 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 1702 |
+
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
|
| 1703 |
+
|
| 1704 |
+
loss = None
|
| 1705 |
+
if labels is not None:
|
| 1706 |
+
loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs)
|
| 1707 |
+
|
| 1708 |
+
if not return_dict:
|
| 1709 |
+
output = (logits,) + outputs[1:]
|
| 1710 |
+
return (loss,) + output if loss is not None else output
|
| 1711 |
+
|
| 1712 |
+
return DreamVLModelOutput(
|
| 1713 |
+
logits=logits,
|
| 1714 |
+
loss=loss,
|
| 1715 |
+
past_key_values=outputs.past_key_values,
|
| 1716 |
+
hidden_states=outputs.hidden_states,
|
| 1717 |
+
attentions=outputs.attentions,
|
| 1718 |
+
rope_deltas=rope_deltas,
|
| 1719 |
+
inputs_embeds=inputs_embeds
|
| 1720 |
+
)
|
| 1721 |
+
|
| 1722 |
+
def prepare_inputs_for_generation(
|
| 1723 |
+
self,
|
| 1724 |
+
input_ids,
|
| 1725 |
+
past_key_values=None,
|
| 1726 |
+
attention_mask=None,
|
| 1727 |
+
inputs_embeds=None,
|
| 1728 |
+
cache_position=None,
|
| 1729 |
+
position_ids=None,
|
| 1730 |
+
use_cache=True,
|
| 1731 |
+
pixel_values=None,
|
| 1732 |
+
pixel_values_videos=None,
|
| 1733 |
+
image_grid_thw=None,
|
| 1734 |
+
video_grid_thw=None,
|
| 1735 |
+
rope_deltas = None,
|
| 1736 |
+
**kwargs,
|
| 1737 |
+
):
|
| 1738 |
+
# never remove input ids
|
| 1739 |
+
|
| 1740 |
+
if use_cache:
|
| 1741 |
+
if past_key_values is None:
|
| 1742 |
+
raise ValueError(
|
| 1743 |
+
"If `use_cache=True`, `past_key_values` must be provided. Please make sure to pass `past_key_values` to the model."
|
| 1744 |
+
)
|
| 1745 |
+
else:
|
| 1746 |
+
pass
|
| 1747 |
+
else:
|
| 1748 |
+
past_key_values = None
|
| 1749 |
+
|
| 1750 |
+
if use_cache:
|
| 1751 |
+
if cache_position is None:
|
| 1752 |
+
raise ValueError(
|
| 1753 |
+
"If `use_cache=True`, `cache_position` must be provided. Please make sure to pass `cache_position` to the model."
|
| 1754 |
+
)
|
| 1755 |
+
else:
|
| 1756 |
+
pass
|
| 1757 |
+
else:
|
| 1758 |
+
cache_position = None
|
| 1759 |
+
|
| 1760 |
+
if use_cache:
|
| 1761 |
+
if input_ids.shape[1] != cache_position.shape[0]:
|
| 1762 |
+
input_ids = input_ids[:, cache_position]
|
| 1763 |
+
else:
|
| 1764 |
+
pass
|
| 1765 |
+
else:
|
| 1766 |
+
pass
|
| 1767 |
+
|
| 1768 |
+
if position_ids is None:
|
| 1769 |
+
if not use_cache:
|
| 1770 |
+
position_ids, rope_deltas = self.get_rope_index(
|
| 1771 |
+
input_ids, image_grid_thw, video_grid_thw, attention_mask
|
| 1772 |
+
)
|
| 1773 |
+
else:
|
| 1774 |
+
if cache_position[0] == 0:
|
| 1775 |
+
position_ids, rope_deltas = self.get_rope_index(
|
| 1776 |
+
input_ids, image_grid_thw, video_grid_thw, attention_mask
|
| 1777 |
+
)
|
| 1778 |
+
else:
|
| 1779 |
+
batch_size, seq_length = input_ids.shape
|
| 1780 |
+
delta = (
|
| 1781 |
+
cache_position[0] + rope_deltas if cache_position is not None and rope_deltas is not None else 0
|
| 1782 |
+
)
|
| 1783 |
+
position_ids = torch.arange(seq_length, device=input_ids.device)
|
| 1784 |
+
position_ids = position_ids.view(1, -1).expand(batch_size, -1)
|
| 1785 |
+
position_ids = position_ids.add(delta)
|
| 1786 |
+
position_ids = position_ids.unsqueeze(0).expand(3, -1, -1)
|
| 1787 |
+
|
| 1788 |
+
else:
|
| 1789 |
+
raise NotImplementedError(
|
| 1790 |
+
"position_ids is not None, please check the code in prepare_inputs_for_generation"
|
| 1791 |
+
)
|
| 1792 |
+
|
| 1793 |
+
if use_cache:
|
| 1794 |
+
if cache_position[0] != 0:
|
| 1795 |
+
pixel_values = None
|
| 1796 |
+
pixel_values_videos = None
|
| 1797 |
+
logger.debug(f"after prefill, the pixel_values and pixel_values_videos are None.")
|
| 1798 |
+
else:
|
| 1799 |
+
pass
|
| 1800 |
+
|
| 1801 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 1802 |
+
# if inputs_embeds is not None:
|
| 1803 |
+
# raise NotImplementedError(
|
| 1804 |
+
# "inputs_embeds is not None, please check the code in prepare_inputs_for_generation"
|
| 1805 |
+
# )
|
| 1806 |
+
# else:
|
| 1807 |
+
# model_inputs = {"input_ids": input_ids, "inputs_embeds": None}
|
| 1808 |
+
|
| 1809 |
+
model_inputs = {
|
| 1810 |
+
"input_ids": input_ids,
|
| 1811 |
+
"inputs_embeds": inputs_embeds,
|
| 1812 |
+
"position_ids": position_ids,
|
| 1813 |
+
"past_key_values": past_key_values,
|
| 1814 |
+
"use_cache": use_cache,
|
| 1815 |
+
"attention_mask": attention_mask,
|
| 1816 |
+
"pixel_values": pixel_values,
|
| 1817 |
+
"pixel_values_videos": pixel_values_videos,
|
| 1818 |
+
"image_grid_thw": image_grid_thw,
|
| 1819 |
+
"video_grid_thw": video_grid_thw,
|
| 1820 |
+
"cache_position": cache_position,
|
| 1821 |
+
"rope_deltas": rope_deltas,
|
| 1822 |
+
}
|
| 1823 |
+
|
| 1824 |
+
return model_inputs
|
preprocessor_config.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"auto_map": {
|
| 3 |
+
"AutoImageProcessor": "image_processing_dreamvl.DreamVLImageProcessor",
|
| 4 |
+
"AutoProcessor": "processing_dreamvl.DreamVLProcessor"
|
| 5 |
+
},
|
| 6 |
+
"do_convert_rgb": true,
|
| 7 |
+
"do_normalize": true,
|
| 8 |
+
"do_rescale": true,
|
| 9 |
+
"do_resize": true,
|
| 10 |
+
"image_mean": [
|
| 11 |
+
0.48145466,
|
| 12 |
+
0.4578275,
|
| 13 |
+
0.40821073
|
| 14 |
+
],
|
| 15 |
+
"image_processor_type": "DreamVLImageProcessor",
|
| 16 |
+
"image_std": [
|
| 17 |
+
0.26862954,
|
| 18 |
+
0.26130258,
|
| 19 |
+
0.27577711
|
| 20 |
+
],
|
| 21 |
+
"max_pixels": 3211264,
|
| 22 |
+
"merge_size": 2,
|
| 23 |
+
"min_pixels": 3136,
|
| 24 |
+
"patch_size": 14,
|
| 25 |
+
"processor_class": "DreamVLProcessor",
|
| 26 |
+
"resample": 3,
|
| 27 |
+
"rescale_factor": 0.00392156862745098,
|
| 28 |
+
"size": {
|
| 29 |
+
"max_pixels": 3211264,
|
| 30 |
+
"min_pixels": 3136
|
| 31 |
+
},
|
| 32 |
+
"temporal_patch_size": 2
|
| 33 |
+
}
|
processing_dreamvl.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 5 |
+
# and OPT implementations in this library. It has been modified from its
|
| 6 |
+
# original forms to accommodate minor architectural differences compared
|
| 7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
"""
|
| 21 |
+
Processor class for Dream-VL.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
from typing import List, Union
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
from typing import Unpack
|
| 28 |
+
except ImportError:
|
| 29 |
+
from typing_extensions import Unpack
|
| 30 |
+
|
| 31 |
+
from transformers.feature_extraction_utils import BatchFeature
|
| 32 |
+
from transformers.image_utils import ImageInput, VideoInput
|
| 33 |
+
from transformers.processing_utils import (
|
| 34 |
+
ProcessingKwargs,
|
| 35 |
+
ProcessorMixin,
|
| 36 |
+
)
|
| 37 |
+
from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
|
| 38 |
+
from transformers.utils import logging
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger(__name__)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class DreamVLProcessorKwargs(ProcessingKwargs, total=False):
|
| 44 |
+
_defaults = {
|
| 45 |
+
"text_kwargs": {
|
| 46 |
+
"padding": False,
|
| 47 |
+
},
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class DreamVLProcessor(ProcessorMixin):
|
| 52 |
+
r"""
|
| 53 |
+
Constructs a Dream-VL processor which wraps a Dream-VL image processor and a Dream tokenizer into a single processor.
|
| 54 |
+
[`DreamVLProcessor`] offers all the functionalities of [`DreamVLImageProcessor`] and [`DreamTokenizer`]. See the
|
| 55 |
+
[`~DreamVLProcessor.__call__`] and [`~DreamVLProcessor.decode`] for more information.
|
| 56 |
+
Args:
|
| 57 |
+
image_processor ([`DreamVLImageProcessor`], *optional*):
|
| 58 |
+
The image processor is a required input.
|
| 59 |
+
tokenizer ([`DreamTokenizer`], *optional*):
|
| 60 |
+
The tokenizer is a required input.
|
| 61 |
+
chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
|
| 62 |
+
in a chat into a tokenizable string.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
attributes = ["image_processor", "tokenizer"]
|
| 66 |
+
valid_kwargs = ["chat_template"]
|
| 67 |
+
image_processor_class = "AutoImageProcessor"
|
| 68 |
+
tokenizer_class = ("AutoTokenizer")
|
| 69 |
+
|
| 70 |
+
def __init__(self, image_processor=None, tokenizer=None, chat_template=None, **kwargs):
|
| 71 |
+
super().__init__(image_processor, tokenizer, chat_template=chat_template)
|
| 72 |
+
|
| 73 |
+
def __call__(
|
| 74 |
+
self,
|
| 75 |
+
images: ImageInput = None,
|
| 76 |
+
text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
|
| 77 |
+
videos: VideoInput = None,
|
| 78 |
+
**kwargs: Unpack[DreamVLProcessorKwargs],
|
| 79 |
+
) -> BatchFeature:
|
| 80 |
+
"""
|
| 81 |
+
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
|
| 82 |
+
and `kwargs` arguments to DreamTokenizer's [`~DreamTokenizer.__call__`] if `text` is not `None` to encode
|
| 83 |
+
the text. To prepare the vision inputs, this method forwards the `vision_infos` and `kwrags` arguments to
|
| 84 |
+
DreamVLImageProcessor's [`~DreamVLImageProcessor.__call__`] if `vision_infos` is not `None`.
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
| 88 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 89 |
+
tensor. Both channels-first and channels-last formats are supported.
|
| 90 |
+
text (`str`, `List[str]`, `List[List[str]]`):
|
| 91 |
+
The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
|
| 92 |
+
(pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
|
| 93 |
+
`is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
|
| 94 |
+
videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
|
| 95 |
+
The image or batch of videos to be prepared. Each video can be a 4D NumPy array or PyTorch
|
| 96 |
+
tensor, or a nested list of 3D frames. Both channels-first and channels-last formats are supported.
|
| 97 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 98 |
+
If set, will return tensors of a particular framework. Acceptable values are:
|
| 99 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 100 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 101 |
+
- `'np'`: Return NumPy `np.ndarray` objects.
|
| 102 |
+
- `'jax'`: Return JAX `jnp.ndarray` objects.
|
| 103 |
+
|
| 104 |
+
Returns:
|
| 105 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 106 |
+
|
| 107 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
| 108 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 109 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 110 |
+
`None`).
|
| 111 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 112 |
+
- **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
|
| 113 |
+
- **image_grid_thw** -- List of image 3D grid in LLM. Returned when `images` is not `None`.
|
| 114 |
+
- **video_grid_thw** -- List of video 3D grid in LLM. Returned when `videos` is not `None`.
|
| 115 |
+
"""
|
| 116 |
+
output_kwargs = self._merge_kwargs(
|
| 117 |
+
DreamVLProcessorKwargs,
|
| 118 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 119 |
+
**kwargs,
|
| 120 |
+
)
|
| 121 |
+
if images is not None:
|
| 122 |
+
image_inputs = self.image_processor(images=images, videos=None, **output_kwargs["images_kwargs"])
|
| 123 |
+
image_grid_thw = image_inputs["image_grid_thw"]
|
| 124 |
+
else:
|
| 125 |
+
image_inputs = {}
|
| 126 |
+
image_grid_thw = None
|
| 127 |
+
|
| 128 |
+
if videos is not None:
|
| 129 |
+
videos_inputs = self.image_processor(images=None, videos=videos, **output_kwargs["videos_kwargs"])
|
| 130 |
+
video_grid_thw = videos_inputs["video_grid_thw"]
|
| 131 |
+
else:
|
| 132 |
+
videos_inputs = {}
|
| 133 |
+
video_grid_thw = None
|
| 134 |
+
|
| 135 |
+
if not isinstance(text, list):
|
| 136 |
+
text = [text]
|
| 137 |
+
|
| 138 |
+
if image_grid_thw is not None:
|
| 139 |
+
merge_length = self.image_processor.merge_size ** 2
|
| 140 |
+
index = 0
|
| 141 |
+
for i in range(len(text)):
|
| 142 |
+
while "<|image_pad|>" in text[i]:
|
| 143 |
+
text[i] = text[i].replace(
|
| 144 |
+
"<|image_pad|>", "<|placeholder|>" * (image_grid_thw[index].prod() // merge_length), 1
|
| 145 |
+
)
|
| 146 |
+
index += 1
|
| 147 |
+
text[i] = text[i].replace("<|placeholder|>", "<|image_pad|>")
|
| 148 |
+
|
| 149 |
+
if video_grid_thw is not None:
|
| 150 |
+
merge_length = self.image_processor.merge_size ** 2
|
| 151 |
+
index = 0
|
| 152 |
+
for i in range(len(text)):
|
| 153 |
+
while "<|video_pad|>" in text[i]:
|
| 154 |
+
text[i] = text[i].replace(
|
| 155 |
+
"<|video_pad|>", "<|placeholder|>" * (video_grid_thw[index].prod() // merge_length), 1
|
| 156 |
+
)
|
| 157 |
+
index += 1
|
| 158 |
+
text[i] = text[i].replace("<|placeholder|>", "<|video_pad|>")
|
| 159 |
+
|
| 160 |
+
_ = output_kwargs["text_kwargs"].pop("padding_side", None)
|
| 161 |
+
text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
| 162 |
+
|
| 163 |
+
return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs})
|
| 164 |
+
|
| 165 |
+
def batch_decode(self, *args, **kwargs):
|
| 166 |
+
"""
|
| 167 |
+
This method forwards all its arguments to DreamTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
|
| 168 |
+
refer to the docstring of this method for more information.
|
| 169 |
+
"""
|
| 170 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 171 |
+
|
| 172 |
+
def decode(self, *args, **kwargs):
|
| 173 |
+
"""
|
| 174 |
+
This method forwards all its arguments to DreamTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to
|
| 175 |
+
the docstring of this method for more information.
|
| 176 |
+
"""
|
| 177 |
+
return self.tokenizer.decode(*args, **kwargs)
|
| 178 |
+
|
| 179 |
+
@property
|
| 180 |
+
def model_input_names(self):
|
| 181 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
| 182 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 183 |
+
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
processor_config.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"auto_map": {
|
| 3 |
+
"AutoProcessor": "processing_dreamvl.DreamVLProcessor"
|
| 4 |
+
},
|
| 5 |
+
"processor_class": "DreamVLProcessor"
|
| 6 |
+
}
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"additional_special_tokens": [
|
| 3 |
+
"<|beginoftext|>",
|
| 4 |
+
"<|mask|>"
|
| 5 |
+
],
|
| 6 |
+
"bos_token": {
|
| 7 |
+
"content": "<|beginoftext|>",
|
| 8 |
+
"lstrip": false,
|
| 9 |
+
"normalized": false,
|
| 10 |
+
"rstrip": false,
|
| 11 |
+
"single_word": false
|
| 12 |
+
},
|
| 13 |
+
"eos_token": {
|
| 14 |
+
"content": "<|endoftext|>",
|
| 15 |
+
"lstrip": false,
|
| 16 |
+
"normalized": false,
|
| 17 |
+
"rstrip": false,
|
| 18 |
+
"single_word": false
|
| 19 |
+
},
|
| 20 |
+
"mask_token": {
|
| 21 |
+
"content": "<|mask|>",
|
| 22 |
+
"lstrip": false,
|
| 23 |
+
"normalized": false,
|
| 24 |
+
"rstrip": false,
|
| 25 |
+
"single_word": false
|
| 26 |
+
},
|
| 27 |
+
"pad_token": {
|
| 28 |
+
"content": "<|endoftext|>",
|
| 29 |
+
"lstrip": false,
|
| 30 |
+
"normalized": false,
|
| 31 |
+
"rstrip": false,
|
| 32 |
+
"single_word": false
|
| 33 |
+
}
|
| 34 |
+
}
|
tokenization_dream.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The Dream team, HKUNLP Group and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on Qwen's implementations in this library.
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""Tokenization classes for Dream."""
|
| 17 |
+
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import unicodedata
|
| 21 |
+
from functools import lru_cache
|
| 22 |
+
from typing import Optional, Tuple
|
| 23 |
+
|
| 24 |
+
import regex as re
|
| 25 |
+
|
| 26 |
+
from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
|
| 27 |
+
from transformers.utils import logging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
VOCAB_FILES_NAMES = {
|
| 33 |
+
"vocab_file": "vocab.json",
|
| 34 |
+
"merges_file": "merges.txt",
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
MAX_MODEL_INPUT_SIZES = {"dream/dream-tokenizer": 32768}
|
| 39 |
+
|
| 40 |
+
PRETOKENIZE_REGEX = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@lru_cache()
|
| 44 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.bytes_to_unicode
|
| 45 |
+
def bytes_to_unicode():
|
| 46 |
+
"""
|
| 47 |
+
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
|
| 48 |
+
characters the bpe code barfs on.
|
| 49 |
+
The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
|
| 50 |
+
if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
|
| 51 |
+
decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
|
| 52 |
+
tables between utf-8 bytes and unicode strings.
|
| 53 |
+
"""
|
| 54 |
+
bs = (
|
| 55 |
+
list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
|
| 56 |
+
)
|
| 57 |
+
cs = bs[:]
|
| 58 |
+
n = 0
|
| 59 |
+
for b in range(2**8):
|
| 60 |
+
if b not in bs:
|
| 61 |
+
bs.append(b)
|
| 62 |
+
cs.append(2**8 + n)
|
| 63 |
+
n += 1
|
| 64 |
+
cs = [chr(n) for n in cs]
|
| 65 |
+
return dict(zip(bs, cs))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.get_pairs
|
| 69 |
+
def get_pairs(word):
|
| 70 |
+
"""
|
| 71 |
+
Return set of symbol pairs in a word.
|
| 72 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
| 73 |
+
"""
|
| 74 |
+
pairs = set()
|
| 75 |
+
prev_char = word[0]
|
| 76 |
+
for char in word[1:]:
|
| 77 |
+
pairs.add((prev_char, char))
|
| 78 |
+
prev_char = char
|
| 79 |
+
return pairs
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class DreamTokenizer(PreTrainedTokenizer):
|
| 83 |
+
"""
|
| 84 |
+
Construct a Dream tokenizer. Based on byte-level Byte-Pair-Encoding.
|
| 85 |
+
Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
|
| 86 |
+
be encoded differently whether it is at the beginning of the sentence (without space) or not:
|
| 87 |
+
```python
|
| 88 |
+
>>> from transformers import AutoTokenizer
|
| 89 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("Dream-org/Dream-v0-Base-7B", trust_remote_code=True)
|
| 90 |
+
>>> tokenizer("Hello world")["input_ids"]
|
| 91 |
+
[9707, 1879]
|
| 92 |
+
>>> tokenizer(" Hello world")["input_ids"]
|
| 93 |
+
[21927, 1879]
|
| 94 |
+
```
|
| 95 |
+
This is expected.
|
| 96 |
+
You should not use GPT2Tokenizer instead, because of the different pretokenization rules.
|
| 97 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
| 98 |
+
this superclass for more information regarding those methods.
|
| 99 |
+
Args:
|
| 100 |
+
vocab_file (`str`):
|
| 101 |
+
Path to the vocabulary file.
|
| 102 |
+
merges_file (`str`):
|
| 103 |
+
Path to the merges file.
|
| 104 |
+
errors (`str`, *optional*, defaults to `"replace"`):
|
| 105 |
+
Paradigm to follow when decoding bytes to UTF-8. See
|
| 106 |
+
[bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
|
| 107 |
+
unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
| 108 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
| 109 |
+
token instead.
|
| 110 |
+
bos_token (`str`, *optional*):
|
| 111 |
+
The beginning of sequence token. Not applicable for this tokenizer.
|
| 112 |
+
eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
| 113 |
+
The end of sequence token.
|
| 114 |
+
pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
|
| 115 |
+
The token used for padding, for example when batching sequences of different lengths.
|
| 116 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
|
| 117 |
+
Whether or not the model should cleanup the spaces that were added when splitting the input text during the
|
| 118 |
+
tokenization process. Not applicable to this tokenizer, since tokenization does not add spaces.
|
| 119 |
+
split_special_tokens (`bool`, *optional*, defaults to `False`):
|
| 120 |
+
Whether or not the special tokens should be split during the tokenization process. The default behavior is
|
| 121 |
+
to not split special tokens. This means that if `<|endoftext|>` is the `eos_token`, then `tokenizer.tokenize("<|endoftext|>") =
|
| 122 |
+
['<|endoftext|>`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize("<|endoftext|>")` will be give `['<',
|
| 123 |
+
'|', 'endo', 'ft', 'ext', '|', '>']`. This argument is only supported for `slow` tokenizers for the moment.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
| 127 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 128 |
+
|
| 129 |
+
def __init__(
|
| 130 |
+
self,
|
| 131 |
+
vocab_file,
|
| 132 |
+
merges_file,
|
| 133 |
+
errors="replace",
|
| 134 |
+
unk_token="<|endoftext|>",
|
| 135 |
+
bos_token=None,
|
| 136 |
+
eos_token="<|endoftext|>",
|
| 137 |
+
pad_token="<|endoftext|>",
|
| 138 |
+
clean_up_tokenization_spaces=False,
|
| 139 |
+
split_special_tokens=False,
|
| 140 |
+
**kwargs,
|
| 141 |
+
):
|
| 142 |
+
# Dream vocab does not contain control tokens; added tokens need to be special
|
| 143 |
+
bos_token = (
|
| 144 |
+
AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
| 145 |
+
if isinstance(bos_token, str)
|
| 146 |
+
else bos_token
|
| 147 |
+
)
|
| 148 |
+
eos_token = (
|
| 149 |
+
AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
| 150 |
+
if isinstance(eos_token, str)
|
| 151 |
+
else eos_token
|
| 152 |
+
)
|
| 153 |
+
unk_token = (
|
| 154 |
+
AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
| 155 |
+
if isinstance(unk_token, str)
|
| 156 |
+
else unk_token
|
| 157 |
+
)
|
| 158 |
+
pad_token = (
|
| 159 |
+
AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
|
| 160 |
+
if isinstance(pad_token, str)
|
| 161 |
+
else pad_token
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
| 165 |
+
self.encoder = json.load(vocab_handle)
|
| 166 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 167 |
+
self.errors = errors # how to handle errors in decoding
|
| 168 |
+
self.byte_encoder = bytes_to_unicode()
|
| 169 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
| 170 |
+
bpe_merges = []
|
| 171 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
| 172 |
+
for i, line in enumerate(merges_handle):
|
| 173 |
+
line = line.strip()
|
| 174 |
+
if (i == 0 and line.startswith("#version:")) or not line:
|
| 175 |
+
continue
|
| 176 |
+
bpe_merges.append(tuple(line.split()))
|
| 177 |
+
self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
|
| 178 |
+
# NOTE: the cache can grow without bound and will get really large for long running processes
|
| 179 |
+
# (esp. for texts of language that do not use space between word, e.g. Chinese); technically
|
| 180 |
+
# not a memory leak but appears as one.
|
| 181 |
+
# GPT2Tokenizer has the same problem, so let's be consistent.
|
| 182 |
+
self.cache = {}
|
| 183 |
+
|
| 184 |
+
self.pat = re.compile(PRETOKENIZE_REGEX)
|
| 185 |
+
|
| 186 |
+
if kwargs.get("add_prefix_space", False):
|
| 187 |
+
logger.warning_once(
|
| 188 |
+
f"{self.__class__.__name} does not support `add_prefix_space`, setting it to True has no effect."
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
super().__init__(
|
| 192 |
+
errors=errors,
|
| 193 |
+
bos_token=bos_token,
|
| 194 |
+
eos_token=eos_token,
|
| 195 |
+
pad_token=pad_token,
|
| 196 |
+
unk_token=unk_token,
|
| 197 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 198 |
+
split_special_tokens=split_special_tokens,
|
| 199 |
+
**kwargs,
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
@property
|
| 203 |
+
def vocab_size(self) -> int:
|
| 204 |
+
return len(self.encoder)
|
| 205 |
+
|
| 206 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.get_vocab
|
| 207 |
+
def get_vocab(self):
|
| 208 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
| 209 |
+
|
| 210 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.bpe
|
| 211 |
+
def bpe(self, token):
|
| 212 |
+
if token in self.cache:
|
| 213 |
+
return self.cache[token]
|
| 214 |
+
word = tuple(token)
|
| 215 |
+
pairs = get_pairs(word)
|
| 216 |
+
|
| 217 |
+
if not pairs:
|
| 218 |
+
return token
|
| 219 |
+
|
| 220 |
+
while True:
|
| 221 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
| 222 |
+
if bigram not in self.bpe_ranks:
|
| 223 |
+
break
|
| 224 |
+
first, second = bigram
|
| 225 |
+
new_word = []
|
| 226 |
+
i = 0
|
| 227 |
+
while i < len(word):
|
| 228 |
+
try:
|
| 229 |
+
j = word.index(first, i)
|
| 230 |
+
except ValueError:
|
| 231 |
+
new_word.extend(word[i:])
|
| 232 |
+
break
|
| 233 |
+
else:
|
| 234 |
+
new_word.extend(word[i:j])
|
| 235 |
+
i = j
|
| 236 |
+
|
| 237 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
| 238 |
+
new_word.append(first + second)
|
| 239 |
+
i += 2
|
| 240 |
+
else:
|
| 241 |
+
new_word.append(word[i])
|
| 242 |
+
i += 1
|
| 243 |
+
new_word = tuple(new_word)
|
| 244 |
+
word = new_word
|
| 245 |
+
if len(word) == 1:
|
| 246 |
+
break
|
| 247 |
+
else:
|
| 248 |
+
pairs = get_pairs(word)
|
| 249 |
+
word = " ".join(word)
|
| 250 |
+
self.cache[token] = word
|
| 251 |
+
return word
|
| 252 |
+
|
| 253 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._tokenize
|
| 254 |
+
def _tokenize(self, text):
|
| 255 |
+
"""Tokenize a string."""
|
| 256 |
+
bpe_tokens = []
|
| 257 |
+
for token in re.findall(self.pat, text):
|
| 258 |
+
token = "".join(
|
| 259 |
+
self.byte_encoder[b] for b in token.encode("utf-8")
|
| 260 |
+
) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
|
| 261 |
+
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
|
| 262 |
+
return bpe_tokens
|
| 263 |
+
|
| 264 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_token_to_id
|
| 265 |
+
def _convert_token_to_id(self, token):
|
| 266 |
+
"""Converts a token (str) in an id using the vocab."""
|
| 267 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
| 268 |
+
|
| 269 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_id_to_token
|
| 270 |
+
def _convert_id_to_token(self, index):
|
| 271 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
| 272 |
+
return self.decoder.get(index)
|
| 273 |
+
|
| 274 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.convert_tokens_to_string
|
| 275 |
+
def convert_tokens_to_string(self, tokens):
|
| 276 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
| 277 |
+
text = "".join(tokens)
|
| 278 |
+
text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
|
| 279 |
+
return text
|
| 280 |
+
|
| 281 |
+
def decode(
|
| 282 |
+
self,
|
| 283 |
+
token_ids,
|
| 284 |
+
skip_special_tokens: bool = False,
|
| 285 |
+
clean_up_tokenization_spaces: Optional[bool] = False,
|
| 286 |
+
spaces_between_special_tokens: bool = False,
|
| 287 |
+
**kwargs,
|
| 288 |
+
) -> str:
|
| 289 |
+
# `spaces_between_special_tokens` defaults to True for _decode in slow tokenizers
|
| 290 |
+
# and cannot be configured elsewhere, but it should default to False for DreamTokenizer
|
| 291 |
+
return super().decode(
|
| 292 |
+
token_ids,
|
| 293 |
+
skip_special_tokens=skip_special_tokens,
|
| 294 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 295 |
+
spaces_between_special_tokens=spaces_between_special_tokens,
|
| 296 |
+
**kwargs,
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
# Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.save_vocabulary
|
| 300 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
| 301 |
+
if not os.path.isdir(save_directory):
|
| 302 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
| 303 |
+
return
|
| 304 |
+
vocab_file = os.path.join(
|
| 305 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
| 306 |
+
)
|
| 307 |
+
merge_file = os.path.join(
|
| 308 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
| 312 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
| 313 |
+
|
| 314 |
+
index = 0
|
| 315 |
+
with open(merge_file, "w", encoding="utf-8") as writer:
|
| 316 |
+
writer.write("#version: 0.2\n")
|
| 317 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
|
| 318 |
+
if index != token_index:
|
| 319 |
+
logger.warning(
|
| 320 |
+
f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
|
| 321 |
+
" Please check that the tokenizer is not corrupted!"
|
| 322 |
+
)
|
| 323 |
+
index = token_index
|
| 324 |
+
writer.write(" ".join(bpe_tokens) + "\n")
|
| 325 |
+
index += 1
|
| 326 |
+
|
| 327 |
+
return vocab_file, merge_file
|
| 328 |
+
|
| 329 |
+
def prepare_for_tokenization(self, text, **kwargs):
|
| 330 |
+
text = unicodedata.normalize("NFC", text)
|
| 331 |
+
return (text, kwargs)
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": false,
|
| 3 |
+
"add_prefix_space": false,
|
| 4 |
+
"added_tokens_decoder": {
|
| 5 |
+
"151643": {
|
| 6 |
+
"content": "<|endoftext|>",
|
| 7 |
+
"lstrip": false,
|
| 8 |
+
"normalized": false,
|
| 9 |
+
"rstrip": false,
|
| 10 |
+
"single_word": false,
|
| 11 |
+
"special": true
|
| 12 |
+
},
|
| 13 |
+
"151644": {
|
| 14 |
+
"content": "<|im_start|>",
|
| 15 |
+
"lstrip": false,
|
| 16 |
+
"normalized": false,
|
| 17 |
+
"rstrip": false,
|
| 18 |
+
"single_word": false,
|
| 19 |
+
"special": true
|
| 20 |
+
},
|
| 21 |
+
"151645": {
|
| 22 |
+
"content": "<|im_end|>",
|
| 23 |
+
"lstrip": false,
|
| 24 |
+
"normalized": false,
|
| 25 |
+
"rstrip": false,
|
| 26 |
+
"single_word": false,
|
| 27 |
+
"special": true
|
| 28 |
+
},
|
| 29 |
+
"151646": {
|
| 30 |
+
"content": "<|object_ref_start|>",
|
| 31 |
+
"lstrip": false,
|
| 32 |
+
"normalized": false,
|
| 33 |
+
"rstrip": false,
|
| 34 |
+
"single_word": false,
|
| 35 |
+
"special": true
|
| 36 |
+
},
|
| 37 |
+
"151647": {
|
| 38 |
+
"content": "<|object_ref_end|>",
|
| 39 |
+
"lstrip": false,
|
| 40 |
+
"normalized": false,
|
| 41 |
+
"rstrip": false,
|
| 42 |
+
"single_word": false,
|
| 43 |
+
"special": true
|
| 44 |
+
},
|
| 45 |
+
"151648": {
|
| 46 |
+
"content": "<|box_start|>",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"normalized": false,
|
| 49 |
+
"rstrip": false,
|
| 50 |
+
"single_word": false,
|
| 51 |
+
"special": true
|
| 52 |
+
},
|
| 53 |
+
"151649": {
|
| 54 |
+
"content": "<|box_end|>",
|
| 55 |
+
"lstrip": false,
|
| 56 |
+
"normalized": false,
|
| 57 |
+
"rstrip": false,
|
| 58 |
+
"single_word": false,
|
| 59 |
+
"special": true
|
| 60 |
+
},
|
| 61 |
+
"151650": {
|
| 62 |
+
"content": "<|quad_start|>",
|
| 63 |
+
"lstrip": false,
|
| 64 |
+
"normalized": false,
|
| 65 |
+
"rstrip": false,
|
| 66 |
+
"single_word": false,
|
| 67 |
+
"special": true
|
| 68 |
+
},
|
| 69 |
+
"151651": {
|
| 70 |
+
"content": "<|quad_end|>",
|
| 71 |
+
"lstrip": false,
|
| 72 |
+
"normalized": false,
|
| 73 |
+
"rstrip": false,
|
| 74 |
+
"single_word": false,
|
| 75 |
+
"special": true
|
| 76 |
+
},
|
| 77 |
+
"151652": {
|
| 78 |
+
"content": "<|vision_start|>",
|
| 79 |
+
"lstrip": false,
|
| 80 |
+
"normalized": false,
|
| 81 |
+
"rstrip": false,
|
| 82 |
+
"single_word": false,
|
| 83 |
+
"special": true
|
| 84 |
+
},
|
| 85 |
+
"151653": {
|
| 86 |
+
"content": "<|vision_end|>",
|
| 87 |
+
"lstrip": false,
|
| 88 |
+
"normalized": false,
|
| 89 |
+
"rstrip": false,
|
| 90 |
+
"single_word": false,
|
| 91 |
+
"special": true
|
| 92 |
+
},
|
| 93 |
+
"151654": {
|
| 94 |
+
"content": "<|vision_pad|>",
|
| 95 |
+
"lstrip": false,
|
| 96 |
+
"normalized": false,
|
| 97 |
+
"rstrip": false,
|
| 98 |
+
"single_word": false,
|
| 99 |
+
"special": true
|
| 100 |
+
},
|
| 101 |
+
"151655": {
|
| 102 |
+
"content": "<|image_pad|>",
|
| 103 |
+
"lstrip": false,
|
| 104 |
+
"normalized": false,
|
| 105 |
+
"rstrip": false,
|
| 106 |
+
"single_word": false,
|
| 107 |
+
"special": true
|
| 108 |
+
},
|
| 109 |
+
"151656": {
|
| 110 |
+
"content": "<|video_pad|>",
|
| 111 |
+
"lstrip": false,
|
| 112 |
+
"normalized": false,
|
| 113 |
+
"rstrip": false,
|
| 114 |
+
"single_word": false,
|
| 115 |
+
"special": true
|
| 116 |
+
},
|
| 117 |
+
"151657": {
|
| 118 |
+
"content": "<tool_call>",
|
| 119 |
+
"lstrip": false,
|
| 120 |
+
"normalized": false,
|
| 121 |
+
"rstrip": false,
|
| 122 |
+
"single_word": false,
|
| 123 |
+
"special": false
|
| 124 |
+
},
|
| 125 |
+
"151658": {
|
| 126 |
+
"content": "</tool_call>",
|
| 127 |
+
"lstrip": false,
|
| 128 |
+
"normalized": false,
|
| 129 |
+
"rstrip": false,
|
| 130 |
+
"single_word": false,
|
| 131 |
+
"special": false
|
| 132 |
+
},
|
| 133 |
+
"151659": {
|
| 134 |
+
"content": "<|fim_prefix|>",
|
| 135 |
+
"lstrip": false,
|
| 136 |
+
"normalized": false,
|
| 137 |
+
"rstrip": false,
|
| 138 |
+
"single_word": false,
|
| 139 |
+
"special": false
|
| 140 |
+
},
|
| 141 |
+
"151660": {
|
| 142 |
+
"content": "<|fim_middle|>",
|
| 143 |
+
"lstrip": false,
|
| 144 |
+
"normalized": false,
|
| 145 |
+
"rstrip": false,
|
| 146 |
+
"single_word": false,
|
| 147 |
+
"special": false
|
| 148 |
+
},
|
| 149 |
+
"151661": {
|
| 150 |
+
"content": "<|fim_suffix|>",
|
| 151 |
+
"lstrip": false,
|
| 152 |
+
"normalized": false,
|
| 153 |
+
"rstrip": false,
|
| 154 |
+
"single_word": false,
|
| 155 |
+
"special": false
|
| 156 |
+
},
|
| 157 |
+
"151662": {
|
| 158 |
+
"content": "<|fim_pad|>",
|
| 159 |
+
"lstrip": false,
|
| 160 |
+
"normalized": false,
|
| 161 |
+
"rstrip": false,
|
| 162 |
+
"single_word": false,
|
| 163 |
+
"special": false
|
| 164 |
+
},
|
| 165 |
+
"151663": {
|
| 166 |
+
"content": "<|repo_name|>",
|
| 167 |
+
"lstrip": false,
|
| 168 |
+
"normalized": false,
|
| 169 |
+
"rstrip": false,
|
| 170 |
+
"single_word": false,
|
| 171 |
+
"special": false
|
| 172 |
+
},
|
| 173 |
+
"151664": {
|
| 174 |
+
"content": "<|file_sep|>",
|
| 175 |
+
"lstrip": false,
|
| 176 |
+
"normalized": false,
|
| 177 |
+
"rstrip": false,
|
| 178 |
+
"single_word": false,
|
| 179 |
+
"special": false
|
| 180 |
+
},
|
| 181 |
+
"151665": {
|
| 182 |
+
"content": "<|beginoftext|>",
|
| 183 |
+
"lstrip": false,
|
| 184 |
+
"normalized": false,
|
| 185 |
+
"rstrip": false,
|
| 186 |
+
"single_word": false,
|
| 187 |
+
"special": true
|
| 188 |
+
},
|
| 189 |
+
"151666": {
|
| 190 |
+
"content": "<|mask|>",
|
| 191 |
+
"lstrip": false,
|
| 192 |
+
"normalized": false,
|
| 193 |
+
"rstrip": false,
|
| 194 |
+
"single_word": false,
|
| 195 |
+
"special": true
|
| 196 |
+
}
|
| 197 |
+
},
|
| 198 |
+
"additional_special_tokens": [
|
| 199 |
+
"<|beginoftext|>",
|
| 200 |
+
"<|mask|>"
|
| 201 |
+
],
|
| 202 |
+
"auto_map": {
|
| 203 |
+
"AutoProcessor": "processing_dreamvl.DreamVLProcessor",
|
| 204 |
+
"AutoTokenizer": [
|
| 205 |
+
"tokenization_dream.DreamTokenizer",
|
| 206 |
+
null
|
| 207 |
+
]
|
| 208 |
+
},
|
| 209 |
+
"bos_token": "<|beginoftext|>",
|
| 210 |
+
"chat_template": "{% set image_count = namespace(value=0) %}{% set video_count = namespace(value=0) %}{% for message in messages %}{% if loop.first and message['role'] != 'system' %}<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n{% endif %}<|im_start|>{{ message['role'] }}\n{% if message['content'] is string %}{{ message['content'] }}<|im_end|>\n{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' or 'image' in content or 'image_url' in content %}{% set image_count.value = image_count.value + 1 %}{% if add_vision_id %}Picture {{ image_count.value }}: {% endif %}<|image_pad|>{% elif content['type'] == 'video' or 'video' in content %}{% set video_count.value = video_count.value + 1 %}{% if add_vision_id %}Video {{ video_count.value }}: {% endif %}<|video_pad|>{% elif 'text' in content %}{{ content['text'] }}{% endif %}{% endfor %}<|im_end|>\n{% endif %}{% endfor %}{% if add_generation_prompt %}<|im_start|>assistant\n{% endif %}",
|
| 211 |
+
"clean_up_tokenization_spaces": false,
|
| 212 |
+
"eos_token": "<|endoftext|>",
|
| 213 |
+
"errors": "replace",
|
| 214 |
+
"extra_special_tokens": {},
|
| 215 |
+
"mask_token": "<|mask|>",
|
| 216 |
+
"model_max_length": 8192,
|
| 217 |
+
"pad_token": "<|endoftext|>",
|
| 218 |
+
"padding_side": "right",
|
| 219 |
+
"processor_class": "DreamVLProcessor",
|
| 220 |
+
"split_special_tokens": false,
|
| 221 |
+
"tokenizer_class": "DreamTokenizer",
|
| 222 |
+
"unk_token": null
|
| 223 |
+
}
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|