happyme531 commited on
Commit
63ec5f9
1 Parent(s): 86d5a1c

Upload 23 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ librkllmrt.so filter=lfs diff=lfs merge=lfs -text
37
+ qwen.rkllm filter=lfs diff=lfs merge=lfs -text
38
+ vision_transformer.rknn filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 注意: 由于疑似RKLLM那边的问题, 目前此模型的推理输出结果不正常 (https://github.com/airockchip/rknn-llm/issues/101), 未来修复后这个repo会更新.
2
+
3
+ NOTE: Due to suspected issues in RKLLM(https://github.com/airockchip/rknn-llm/issues/101) , the model cannot be used normally for inference at the moment. Once fixed, this repo will be updated.
4
+
5
+ # MiniCPM-V-2_6-rkllm
6
+
7
+ ## (English README see below)
8
+
9
+ 在RK3588上运行强大的MiniCPM-V-2.6 视觉大模型!
10
+
11
+ - 推理速度(RK3588): 视觉编码器 4.8s(单核) + LLM 填充 2.2s (92 tokens / 42.5 tps) + 解码 3.25 tps
12
+ - 内存占用(RK3588, 默认上下文长度): 视觉编码器 1.9GB + LLM 7.8GB = 9.7GB
13
+
14
+ ## 使用方法
15
+
16
+ 1. 克隆或者下载此仓库到本地. 模型较大, 请确保有足够的磁盘空间.
17
+
18
+ 2. 开发板的RKNPU2内核驱动版本必须>=0.9.6才能运行这么大的模型.
19
+ 使用root权限运行以下命令检查驱动版本:
20
+ ```bash
21
+ > cat /sys/kernel/debug/rknpu/version
22
+ RKNPU driver: v0.9.8
23
+ ```
24
+ 如果版本过低, 请更新驱动. 你可能需要更新内核, 或查找官方文档以获取帮助.
25
+
26
+ 3. 安装依赖
27
+
28
+ ```bash
29
+ pip install numpy<2 opencv-python
30
+ ```
31
+ 你还需要手动安装rknn-toolkit2-lite2.
32
+
33
+ 4. 运行
34
+
35
+ ```bash
36
+ python run_rknn.py
37
+ ```
38
+
39
+ 你可以修改`run_rknn.py`中的内容来测试不同的输入.
40
+
41
+ ## 模型转换
42
+
43
+ #### 准备工作
44
+
45
+ 1. 安装rknn-toolkit2 v2.1.0或更高版本, 以及rkllm-toolkit v1.1.0或更高版本.
46
+ 2. 下载此仓库到本地, 但不需要下载`.rkllm`和`.rknn`结尾的模型文件.
47
+ 3. 下载MiniCPM-V-2.6的huggingface模型仓库到本地. (https://huggingface.co/openbmb/MiniCPM-V-2_6)
48
+
49
+ #### 转换LLM
50
+
51
+ 1. 将此仓库中的`rename_tensors.py`文件复制到MiniCPM-V-2.6的huggingface模型仓库根目录并运行. 稍等片刻, 会生成`model-renamed-00001-of-00004.safetensors`等4个safetensors文件和一个json文件.
52
+ 2. 不用管那个json文件, 将那4个safetensors文件移动到此仓库根目录下.
53
+ 3. 执行`rkllm-convert.py`. 等一会, 会生成`qwen.rkllm`, 就是转换后的模型.
54
+
55
+ #### 转换视觉编码器
56
+
57
+ 1. 将此仓库中的`patched_modeling_navit_siglip.py`和`patched_resampler.py`复制到MiniCPM-V-2.6的huggingface模型仓库根目录下, 重命名为`modeling_navit_siglip.py`和`resampler.py`, 替换掉原来的文件.
58
+
59
+ 2. 打开`vision_export_onnx.py`, 修改其中的`MODEL_PATH`为MiniCPM-V-2.6模型文件夹的路径. 然后执行. 等一会, 会生成`vision_encoder.onnx`.
60
+ 3. 执行`vision_convert_rknn.py`. 等一会, 会生成`vision_encoder.rknn`, 这就是转换后的视觉编码器.
61
+
62
+ ## 已知问题
63
+
64
+ - 由于疑似RKLLM中存在的问题, 目前此模型无法正常推理.
65
+ - 由于RKLLM中存在的问题, 目前视觉编码器和LLM无法同时被加载, 必须先卸载掉视觉编码器, 再重新加载LLM. 如果要推理多次, 必须重复执行卸载和加载操作, 速度非常慢.
66
+ - 视觉编码器转换ONNX的代码取自 https://github.com/sophgo/LLM-TPU/tree/main/models/MiniCPM-V-2_6 , 感谢Sophgo提供的代码. 但是这个转换方法似乎将原模型中的自适应图像分块算法删除了, 可能会导致精度下降.
67
+
68
+ ## 参考
69
+
70
+ [sophgo/LLM-TPU models/MiniCPM-V-2_6](https://github.com/sophgo/LLM-TPU/tree/main/models/MiniCPM-V-2_6)
71
+ [openbmb/MiniCPM-V-2_6](https://huggingface.co/openbmb/MiniCPM-V-2_6)
72
+ [Qwen/Qwen2-7B](https://huggingface.co/Qwen/Qwen2-7B)
73
+
74
+
75
+ ## English README
76
+
77
+ Run the Powerful MiniCPM-V-2.6 Visual Language Model on RK3588!
78
+
79
+ - Inference speed (RK3588): Visual encoder 4.8s (single core) + LLM filling 2.2s (92 tokens / 42.5 tps) + decoding 3.25 tps
80
+ - Memory usage (RK3588, default context length): Visual encoder 1.9GB + LLM 7.8GB = 9.7GB
81
+
82
+ ## Usage
83
+
84
+ 1. Clone or download this repository locally. The model is large, so make sure you have enough disk space.
85
+
86
+ 2. The RKNPU2 kernel driver version on the development board must be >=0.9.6 to run such a large model.
87
+ Use the following command with root privileges to check the driver version:
88
+ ```bash
89
+ > cat /sys/kernel/debug/rknpu/version
90
+ RKNPU driver: v0.9.8
91
+ ```
92
+ If the version is too low, please update the driver. You may need to update the kernel or refer to official documentation for help.
93
+
94
+ 3. Install dependencies
95
+
96
+ ```bash
97
+ pip install numpy<2 opencv-python
98
+ ```
99
+ You also need to manually install rknn-toolkit2-lite2.
100
+
101
+ 4. Run
102
+
103
+ ```bash
104
+ python run_rknn.py
105
+ ```
106
+
107
+ You can modify the content in `run_rknn.py` to test different inputs.
108
+
109
+ ## Model Conversion
110
+
111
+ #### Preparation
112
+
113
+ 1. Install rknn-toolkit2 v2.1.0 or higher, and rkllm-toolkit v1.1.0 or higher.
114
+ 2. Download this repository locally, but you don't need to download the model files ending with `.rkllm` and `.rknn`.
115
+ 3. Download the MiniCPM-V-2.6 Hugging Face model repository locally. (https://huggingface.co/openbmb/MiniCPM-V-2_6)
116
+
117
+ #### Converting LLM
118
+
119
+ 1. Copy the `rename_tensors.py` file from this repository to the root directory of the MiniCPM-V-2.6 Hugging Face model repository and run it. Wait for a moment, it will generate 4 safetensors files like `model-renamed-00001-of-00004.safetensors` and a json file.
120
+ 2. Ignore the json file, move those 4 safetensors files to the root directory of this repository.
121
+ 3. Execute `rkllm-convert.py`. After a while, it will generate `qwen.rkllm`, which is the converted model.
122
+
123
+ #### Converting Visual Encoder
124
+
125
+ 1. Copy `patched_modeling_navit_siglip.py` and `patched_resampler.py` from this repository to the root directory of the MiniCPM-V-2.6 Hugging Face model repository, rename them to `modeling_navit_siglip.py` and `resampler.py`, replacing the original files.
126
+
127
+ 2. Open `vision_export_onnx.py`, modify the `MODEL_PATH` to the path of the MiniCPM-V-2.6 model folder. Then execute it. After a while, it will generate `vision_encoder.onnx`.
128
+ 3. Execute `vision_convert_rknn.py`. After a while, it will generate `vision_encoder.rknn`, which is the converted visual encoder.
129
+
130
+ ## Known Issues
131
+
132
+ - Due to a suspected issue in RKLLM, this model currently cannot perform inference normally.
133
+ - Due to an issue in RKLLM, the visual encoder and LLM cannot be loaded simultaneously at present. The visual encoder must be unloaded first, then the LLM reloaded. If multiple inferences are required, the unloading and loading operations must be repeated, which is very slow.
134
+ - The code for converting the visual encoder to ONNX is taken from https://github.com/sophgo/LLM-TPU/tree/main/models/MiniCPM-V-2_6, thanks to Sophgo for providing the code. However, this conversion method seems to have removed the adaptive image partitioning algorithm from the original model, which may lead to a decrease in accuracy.
135
+
136
+ ## References
137
+
138
+ [sophgo/LLM-TPU models/MiniCPM-V-2_6](https://github.com/sophgo/LLM-TPU/tree/main/models/MiniCPM-V-2_6)
139
+ [openbmb/MiniCPM-V-2_6](https://huggingface.co/openbmb/MiniCPM-V-2_6)
140
+ [Qwen/Qwen2-7B](https://huggingface.co/Qwen/Qwen2-7B)
added_tokens.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</box>": 151651,
3
+ "</image>": 151647,
4
+ "</image_id>": 151659,
5
+ "</point>": 151655,
6
+ "</quad>": 151653,
7
+ "</ref>": 151649,
8
+ "</slice>": 151657,
9
+ "<box>": 151650,
10
+ "<image>": 151646,
11
+ "<image_id>": 151658,
12
+ "<point>": 151654,
13
+ "<quad>": 151652,
14
+ "<ref>": 151648,
15
+ "<slice>": 151656,
16
+ "<|endoftext|>": 151643,
17
+ "<|im_end|>": 151645,
18
+ "<|im_start|>": 151644,
19
+ "<|reserved_special_token_0|>": 151660,
20
+ "<|reserved_special_token_1|>": 151661,
21
+ "<|reserved_special_token_2|>": 151662,
22
+ "<|reserved_special_token_3|>": 151663,
23
+ "<|reserved_special_token_4|>": 151664,
24
+ "<|reserved_special_token_5|>": 151665
25
+ }
config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen2ForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "bos_token_id": 151643,
7
+ "eos_token_id": 151645,
8
+ "hidden_act": "silu",
9
+ "hidden_size": 3584,
10
+ "initializer_range": 0.02,
11
+ "intermediate_size": 18944,
12
+ "max_position_embeddings": 32768,
13
+ "max_window_layers": 28,
14
+ "model_type": "qwen2",
15
+ "num_attention_heads": 28,
16
+ "num_hidden_layers": 28,
17
+ "num_key_value_heads": 4,
18
+ "rms_norm_eps": 1e-06,
19
+ "rope_theta": 1000000.0,
20
+ "sliding_window": 131072,
21
+ "tie_word_embeddings": false,
22
+ "torch_dtype": "bfloat16",
23
+ "transformers_version": "4.37.2",
24
+ "use_cache": true,
25
+ "use_sliding_window": false,
26
+ "vocab_size": 151666
27
+ }
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": false,
4
+ "eos_token_id": 151643,
5
+ "max_new_tokens": 2048,
6
+ "transformers_version": "4.37.0"
7
+ }
librkllmrt.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0f55d476a55680ebedc145c771d29be66334c60c0d9b9eafc8587a2bcf4fddb6
3
+ size 6230968
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors.index.json ADDED
@@ -0,0 +1,796 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 16198350304
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-renamed-00004-of-00004.safetensors",
7
+ "model.embed_tokens.weight": "model-renamed-00001-of-00004.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-renamed-00001-of-00004.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-renamed-00001-of-00004.safetensors",
10
+ "model.layers.0.mlp.gate_proj.weight": "model-renamed-00001-of-00004.safetensors",
11
+ "model.layers.0.mlp.up_proj.weight": "model-renamed-00001-of-00004.safetensors",
12
+ "model.layers.0.post_attention_layernorm.weight": "model-renamed-00001-of-00004.safetensors",
13
+ "model.layers.0.self_attn.k_proj.bias": "model-renamed-00001-of-00004.safetensors",
14
+ "model.layers.0.self_attn.k_proj.weight": "model-renamed-00001-of-00004.safetensors",
15
+ "model.layers.0.self_attn.o_proj.weight": "model-renamed-00001-of-00004.safetensors",
16
+ "model.layers.0.self_attn.q_proj.bias": "model-renamed-00001-of-00004.safetensors",
17
+ "model.layers.0.self_attn.q_proj.weight": "model-renamed-00001-of-00004.safetensors",
18
+ "model.layers.0.self_attn.v_proj.bias": "model-renamed-00001-of-00004.safetensors",
19
+ "model.layers.0.self_attn.v_proj.weight": "model-renamed-00001-of-00004.safetensors",
20
+ "model.layers.1.input_layernorm.weight": "model-renamed-00001-of-00004.safetensors",
21
+ "model.layers.1.mlp.down_proj.weight": "model-renamed-00001-of-00004.safetensors",
22
+ "model.layers.1.mlp.gate_proj.weight": "model-renamed-00001-of-00004.safetensors",
23
+ "model.layers.1.mlp.up_proj.weight": "model-renamed-00001-of-00004.safetensors",
24
+ "model.layers.1.post_attention_layernorm.weight": "model-renamed-00001-of-00004.safetensors",
25
+ "model.layers.1.self_attn.k_proj.bias": "model-renamed-00001-of-00004.safetensors",
26
+ "model.layers.1.self_attn.k_proj.weight": "model-renamed-00001-of-00004.safetensors",
27
+ "model.layers.1.self_attn.o_proj.weight": "model-renamed-00001-of-00004.safetensors",
28
+ "model.layers.1.self_attn.q_proj.bias": "model-renamed-00001-of-00004.safetensors",
29
+ "model.layers.1.self_attn.q_proj.weight": "model-renamed-00001-of-00004.safetensors",
30
+ "model.layers.1.self_attn.v_proj.bias": "model-renamed-00001-of-00004.safetensors",
31
+ "model.layers.1.self_attn.v_proj.weight": "model-renamed-00001-of-00004.safetensors",
32
+ "model.layers.10.input_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
33
+ "model.layers.10.mlp.down_proj.weight": "model-renamed-00002-of-00004.safetensors",
34
+ "model.layers.10.mlp.gate_proj.weight": "model-renamed-00002-of-00004.safetensors",
35
+ "model.layers.10.mlp.up_proj.weight": "model-renamed-00002-of-00004.safetensors",
36
+ "model.layers.10.post_attention_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
37
+ "model.layers.10.self_attn.k_proj.bias": "model-renamed-00002-of-00004.safetensors",
38
+ "model.layers.10.self_attn.k_proj.weight": "model-renamed-00002-of-00004.safetensors",
39
+ "model.layers.10.self_attn.o_proj.weight": "model-renamed-00002-of-00004.safetensors",
40
+ "model.layers.10.self_attn.q_proj.bias": "model-renamed-00002-of-00004.safetensors",
41
+ "model.layers.10.self_attn.q_proj.weight": "model-renamed-00002-of-00004.safetensors",
42
+ "model.layers.10.self_attn.v_proj.bias": "model-renamed-00002-of-00004.safetensors",
43
+ "model.layers.10.self_attn.v_proj.weight": "model-renamed-00002-of-00004.safetensors",
44
+ "model.layers.11.input_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
45
+ "model.layers.11.mlp.down_proj.weight": "model-renamed-00002-of-00004.safetensors",
46
+ "model.layers.11.mlp.gate_proj.weight": "model-renamed-00002-of-00004.safetensors",
47
+ "model.layers.11.mlp.up_proj.weight": "model-renamed-00002-of-00004.safetensors",
48
+ "model.layers.11.post_attention_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
49
+ "model.layers.11.self_attn.k_proj.bias": "model-renamed-00002-of-00004.safetensors",
50
+ "model.layers.11.self_attn.k_proj.weight": "model-renamed-00002-of-00004.safetensors",
51
+ "model.layers.11.self_attn.o_proj.weight": "model-renamed-00002-of-00004.safetensors",
52
+ "model.layers.11.self_attn.q_proj.bias": "model-renamed-00002-of-00004.safetensors",
53
+ "model.layers.11.self_attn.q_proj.weight": "model-renamed-00002-of-00004.safetensors",
54
+ "model.layers.11.self_attn.v_proj.bias": "model-renamed-00002-of-00004.safetensors",
55
+ "model.layers.11.self_attn.v_proj.weight": "model-renamed-00002-of-00004.safetensors",
56
+ "model.layers.12.input_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
57
+ "model.layers.12.mlp.down_proj.weight": "model-renamed-00002-of-00004.safetensors",
58
+ "model.layers.12.mlp.gate_proj.weight": "model-renamed-00002-of-00004.safetensors",
59
+ "model.layers.12.mlp.up_proj.weight": "model-renamed-00002-of-00004.safetensors",
60
+ "model.layers.12.post_attention_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
61
+ "model.layers.12.self_attn.k_proj.bias": "model-renamed-00002-of-00004.safetensors",
62
+ "model.layers.12.self_attn.k_proj.weight": "model-renamed-00002-of-00004.safetensors",
63
+ "model.layers.12.self_attn.o_proj.weight": "model-renamed-00002-of-00004.safetensors",
64
+ "model.layers.12.self_attn.q_proj.bias": "model-renamed-00002-of-00004.safetensors",
65
+ "model.layers.12.self_attn.q_proj.weight": "model-renamed-00002-of-00004.safetensors",
66
+ "model.layers.12.self_attn.v_proj.bias": "model-renamed-00002-of-00004.safetensors",
67
+ "model.layers.12.self_attn.v_proj.weight": "model-renamed-00002-of-00004.safetensors",
68
+ "model.layers.13.input_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
69
+ "model.layers.13.mlp.down_proj.weight": "model-renamed-00002-of-00004.safetensors",
70
+ "model.layers.13.mlp.gate_proj.weight": "model-renamed-00002-of-00004.safetensors",
71
+ "model.layers.13.mlp.up_proj.weight": "model-renamed-00002-of-00004.safetensors",
72
+ "model.layers.13.post_attention_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
73
+ "model.layers.13.self_attn.k_proj.bias": "model-renamed-00002-of-00004.safetensors",
74
+ "model.layers.13.self_attn.k_proj.weight": "model-renamed-00002-of-00004.safetensors",
75
+ "model.layers.13.self_attn.o_proj.weight": "model-renamed-00002-of-00004.safetensors",
76
+ "model.layers.13.self_attn.q_proj.bias": "model-renamed-00002-of-00004.safetensors",
77
+ "model.layers.13.self_attn.q_proj.weight": "model-renamed-00002-of-00004.safetensors",
78
+ "model.layers.13.self_attn.v_proj.bias": "model-renamed-00002-of-00004.safetensors",
79
+ "model.layers.13.self_attn.v_proj.weight": "model-renamed-00002-of-00004.safetensors",
80
+ "model.layers.14.input_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
81
+ "model.layers.14.mlp.down_proj.weight": "model-renamed-00002-of-00004.safetensors",
82
+ "model.layers.14.mlp.gate_proj.weight": "model-renamed-00002-of-00004.safetensors",
83
+ "model.layers.14.mlp.up_proj.weight": "model-renamed-00002-of-00004.safetensors",
84
+ "model.layers.14.post_attention_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
85
+ "model.layers.14.self_attn.k_proj.bias": "model-renamed-00002-of-00004.safetensors",
86
+ "model.layers.14.self_attn.k_proj.weight": "model-renamed-00002-of-00004.safetensors",
87
+ "model.layers.14.self_attn.o_proj.weight": "model-renamed-00002-of-00004.safetensors",
88
+ "model.layers.14.self_attn.q_proj.bias": "model-renamed-00002-of-00004.safetensors",
89
+ "model.layers.14.self_attn.q_proj.weight": "model-renamed-00002-of-00004.safetensors",
90
+ "model.layers.14.self_attn.v_proj.bias": "model-renamed-00002-of-00004.safetensors",
91
+ "model.layers.14.self_attn.v_proj.weight": "model-renamed-00002-of-00004.safetensors",
92
+ "model.layers.15.input_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
93
+ "model.layers.15.mlp.down_proj.weight": "model-renamed-00002-of-00004.safetensors",
94
+ "model.layers.15.mlp.gate_proj.weight": "model-renamed-00002-of-00004.safetensors",
95
+ "model.layers.15.mlp.up_proj.weight": "model-renamed-00002-of-00004.safetensors",
96
+ "model.layers.15.post_attention_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
97
+ "model.layers.15.self_attn.k_proj.bias": "model-renamed-00002-of-00004.safetensors",
98
+ "model.layers.15.self_attn.k_proj.weight": "model-renamed-00002-of-00004.safetensors",
99
+ "model.layers.15.self_attn.o_proj.weight": "model-renamed-00002-of-00004.safetensors",
100
+ "model.layers.15.self_attn.q_proj.bias": "model-renamed-00002-of-00004.safetensors",
101
+ "model.layers.15.self_attn.q_proj.weight": "model-renamed-00002-of-00004.safetensors",
102
+ "model.layers.15.self_attn.v_proj.bias": "model-renamed-00002-of-00004.safetensors",
103
+ "model.layers.15.self_attn.v_proj.weight": "model-renamed-00002-of-00004.safetensors",
104
+ "model.layers.16.input_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
105
+ "model.layers.16.mlp.down_proj.weight": "model-renamed-00002-of-00004.safetensors",
106
+ "model.layers.16.mlp.gate_proj.weight": "model-renamed-00002-of-00004.safetensors",
107
+ "model.layers.16.mlp.up_proj.weight": "model-renamed-00002-of-00004.safetensors",
108
+ "model.layers.16.post_attention_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
109
+ "model.layers.16.self_attn.k_proj.bias": "model-renamed-00002-of-00004.safetensors",
110
+ "model.layers.16.self_attn.k_proj.weight": "model-renamed-00002-of-00004.safetensors",
111
+ "model.layers.16.self_attn.o_proj.weight": "model-renamed-00002-of-00004.safetensors",
112
+ "model.layers.16.self_attn.q_proj.bias": "model-renamed-00002-of-00004.safetensors",
113
+ "model.layers.16.self_attn.q_proj.weight": "model-renamed-00002-of-00004.safetensors",
114
+ "model.layers.16.self_attn.v_proj.bias": "model-renamed-00002-of-00004.safetensors",
115
+ "model.layers.16.self_attn.v_proj.weight": "model-renamed-00002-of-00004.safetensors",
116
+ "model.layers.17.input_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
117
+ "model.layers.17.mlp.down_proj.weight": "model-renamed-00002-of-00004.safetensors",
118
+ "model.layers.17.mlp.gate_proj.weight": "model-renamed-00002-of-00004.safetensors",
119
+ "model.layers.17.mlp.up_proj.weight": "model-renamed-00002-of-00004.safetensors",
120
+ "model.layers.17.post_attention_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
121
+ "model.layers.17.self_attn.k_proj.bias": "model-renamed-00002-of-00004.safetensors",
122
+ "model.layers.17.self_attn.k_proj.weight": "model-renamed-00002-of-00004.safetensors",
123
+ "model.layers.17.self_attn.o_proj.weight": "model-renamed-00002-of-00004.safetensors",
124
+ "model.layers.17.self_attn.q_proj.bias": "model-renamed-00002-of-00004.safetensors",
125
+ "model.layers.17.self_attn.q_proj.weight": "model-renamed-00002-of-00004.safetensors",
126
+ "model.layers.17.self_attn.v_proj.bias": "model-renamed-00002-of-00004.safetensors",
127
+ "model.layers.17.self_attn.v_proj.weight": "model-renamed-00002-of-00004.safetensors",
128
+ "model.layers.18.input_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
129
+ "model.layers.18.mlp.down_proj.weight": "model-renamed-00003-of-00004.safetensors",
130
+ "model.layers.18.mlp.gate_proj.weight": "model-renamed-00002-of-00004.safetensors",
131
+ "model.layers.18.mlp.up_proj.weight": "model-renamed-00002-of-00004.safetensors",
132
+ "model.layers.18.post_attention_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
133
+ "model.layers.18.self_attn.k_proj.bias": "model-renamed-00002-of-00004.safetensors",
134
+ "model.layers.18.self_attn.k_proj.weight": "model-renamed-00002-of-00004.safetensors",
135
+ "model.layers.18.self_attn.o_proj.weight": "model-renamed-00002-of-00004.safetensors",
136
+ "model.layers.18.self_attn.q_proj.bias": "model-renamed-00002-of-00004.safetensors",
137
+ "model.layers.18.self_attn.q_proj.weight": "model-renamed-00002-of-00004.safetensors",
138
+ "model.layers.18.self_attn.v_proj.bias": "model-renamed-00002-of-00004.safetensors",
139
+ "model.layers.18.self_attn.v_proj.weight": "model-renamed-00002-of-00004.safetensors",
140
+ "model.layers.19.input_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
141
+ "model.layers.19.mlp.down_proj.weight": "model-renamed-00003-of-00004.safetensors",
142
+ "model.layers.19.mlp.gate_proj.weight": "model-renamed-00003-of-00004.safetensors",
143
+ "model.layers.19.mlp.up_proj.weight": "model-renamed-00003-of-00004.safetensors",
144
+ "model.layers.19.post_attention_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
145
+ "model.layers.19.self_attn.k_proj.bias": "model-renamed-00003-of-00004.safetensors",
146
+ "model.layers.19.self_attn.k_proj.weight": "model-renamed-00003-of-00004.safetensors",
147
+ "model.layers.19.self_attn.o_proj.weight": "model-renamed-00003-of-00004.safetensors",
148
+ "model.layers.19.self_attn.q_proj.bias": "model-renamed-00003-of-00004.safetensors",
149
+ "model.layers.19.self_attn.q_proj.weight": "model-renamed-00003-of-00004.safetensors",
150
+ "model.layers.19.self_attn.v_proj.bias": "model-renamed-00003-of-00004.safetensors",
151
+ "model.layers.19.self_attn.v_proj.weight": "model-renamed-00003-of-00004.safetensors",
152
+ "model.layers.2.input_layernorm.weight": "model-renamed-00001-of-00004.safetensors",
153
+ "model.layers.2.mlp.down_proj.weight": "model-renamed-00001-of-00004.safetensors",
154
+ "model.layers.2.mlp.gate_proj.weight": "model-renamed-00001-of-00004.safetensors",
155
+ "model.layers.2.mlp.up_proj.weight": "model-renamed-00001-of-00004.safetensors",
156
+ "model.layers.2.post_attention_layernorm.weight": "model-renamed-00001-of-00004.safetensors",
157
+ "model.layers.2.self_attn.k_proj.bias": "model-renamed-00001-of-00004.safetensors",
158
+ "model.layers.2.self_attn.k_proj.weight": "model-renamed-00001-of-00004.safetensors",
159
+ "model.layers.2.self_attn.o_proj.weight": "model-renamed-00001-of-00004.safetensors",
160
+ "model.layers.2.self_attn.q_proj.bias": "model-renamed-00001-of-00004.safetensors",
161
+ "model.layers.2.self_attn.q_proj.weight": "model-renamed-00001-of-00004.safetensors",
162
+ "model.layers.2.self_attn.v_proj.bias": "model-renamed-00001-of-00004.safetensors",
163
+ "model.layers.2.self_attn.v_proj.weight": "model-renamed-00001-of-00004.safetensors",
164
+ "model.layers.20.input_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
165
+ "model.layers.20.mlp.down_proj.weight": "model-renamed-00003-of-00004.safetensors",
166
+ "model.layers.20.mlp.gate_proj.weight": "model-renamed-00003-of-00004.safetensors",
167
+ "model.layers.20.mlp.up_proj.weight": "model-renamed-00003-of-00004.safetensors",
168
+ "model.layers.20.post_attention_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
169
+ "model.layers.20.self_attn.k_proj.bias": "model-renamed-00003-of-00004.safetensors",
170
+ "model.layers.20.self_attn.k_proj.weight": "model-renamed-00003-of-00004.safetensors",
171
+ "model.layers.20.self_attn.o_proj.weight": "model-renamed-00003-of-00004.safetensors",
172
+ "model.layers.20.self_attn.q_proj.bias": "model-renamed-00003-of-00004.safetensors",
173
+ "model.layers.20.self_attn.q_proj.weight": "model-renamed-00003-of-00004.safetensors",
174
+ "model.layers.20.self_attn.v_proj.bias": "model-renamed-00003-of-00004.safetensors",
175
+ "model.layers.20.self_attn.v_proj.weight": "model-renamed-00003-of-00004.safetensors",
176
+ "model.layers.21.input_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
177
+ "model.layers.21.mlp.down_proj.weight": "model-renamed-00003-of-00004.safetensors",
178
+ "model.layers.21.mlp.gate_proj.weight": "model-renamed-00003-of-00004.safetensors",
179
+ "model.layers.21.mlp.up_proj.weight": "model-renamed-00003-of-00004.safetensors",
180
+ "model.layers.21.post_attention_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
181
+ "model.layers.21.self_attn.k_proj.bias": "model-renamed-00003-of-00004.safetensors",
182
+ "model.layers.21.self_attn.k_proj.weight": "model-renamed-00003-of-00004.safetensors",
183
+ "model.layers.21.self_attn.o_proj.weight": "model-renamed-00003-of-00004.safetensors",
184
+ "model.layers.21.self_attn.q_proj.bias": "model-renamed-00003-of-00004.safetensors",
185
+ "model.layers.21.self_attn.q_proj.weight": "model-renamed-00003-of-00004.safetensors",
186
+ "model.layers.21.self_attn.v_proj.bias": "model-renamed-00003-of-00004.safetensors",
187
+ "model.layers.21.self_attn.v_proj.weight": "model-renamed-00003-of-00004.safetensors",
188
+ "model.layers.22.input_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
189
+ "model.layers.22.mlp.down_proj.weight": "model-renamed-00003-of-00004.safetensors",
190
+ "model.layers.22.mlp.gate_proj.weight": "model-renamed-00003-of-00004.safetensors",
191
+ "model.layers.22.mlp.up_proj.weight": "model-renamed-00003-of-00004.safetensors",
192
+ "model.layers.22.post_attention_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
193
+ "model.layers.22.self_attn.k_proj.bias": "model-renamed-00003-of-00004.safetensors",
194
+ "model.layers.22.self_attn.k_proj.weight": "model-renamed-00003-of-00004.safetensors",
195
+ "model.layers.22.self_attn.o_proj.weight": "model-renamed-00003-of-00004.safetensors",
196
+ "model.layers.22.self_attn.q_proj.bias": "model-renamed-00003-of-00004.safetensors",
197
+ "model.layers.22.self_attn.q_proj.weight": "model-renamed-00003-of-00004.safetensors",
198
+ "model.layers.22.self_attn.v_proj.bias": "model-renamed-00003-of-00004.safetensors",
199
+ "model.layers.22.self_attn.v_proj.weight": "model-renamed-00003-of-00004.safetensors",
200
+ "model.layers.23.input_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
201
+ "model.layers.23.mlp.down_proj.weight": "model-renamed-00003-of-00004.safetensors",
202
+ "model.layers.23.mlp.gate_proj.weight": "model-renamed-00003-of-00004.safetensors",
203
+ "model.layers.23.mlp.up_proj.weight": "model-renamed-00003-of-00004.safetensors",
204
+ "model.layers.23.post_attention_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
205
+ "model.layers.23.self_attn.k_proj.bias": "model-renamed-00003-of-00004.safetensors",
206
+ "model.layers.23.self_attn.k_proj.weight": "model-renamed-00003-of-00004.safetensors",
207
+ "model.layers.23.self_attn.o_proj.weight": "model-renamed-00003-of-00004.safetensors",
208
+ "model.layers.23.self_attn.q_proj.bias": "model-renamed-00003-of-00004.safetensors",
209
+ "model.layers.23.self_attn.q_proj.weight": "model-renamed-00003-of-00004.safetensors",
210
+ "model.layers.23.self_attn.v_proj.bias": "model-renamed-00003-of-00004.safetensors",
211
+ "model.layers.23.self_attn.v_proj.weight": "model-renamed-00003-of-00004.safetensors",
212
+ "model.layers.24.input_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
213
+ "model.layers.24.mlp.down_proj.weight": "model-renamed-00003-of-00004.safetensors",
214
+ "model.layers.24.mlp.gate_proj.weight": "model-renamed-00003-of-00004.safetensors",
215
+ "model.layers.24.mlp.up_proj.weight": "model-renamed-00003-of-00004.safetensors",
216
+ "model.layers.24.post_attention_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
217
+ "model.layers.24.self_attn.k_proj.bias": "model-renamed-00003-of-00004.safetensors",
218
+ "model.layers.24.self_attn.k_proj.weight": "model-renamed-00003-of-00004.safetensors",
219
+ "model.layers.24.self_attn.o_proj.weight": "model-renamed-00003-of-00004.safetensors",
220
+ "model.layers.24.self_attn.q_proj.bias": "model-renamed-00003-of-00004.safetensors",
221
+ "model.layers.24.self_attn.q_proj.weight": "model-renamed-00003-of-00004.safetensors",
222
+ "model.layers.24.self_attn.v_proj.bias": "model-renamed-00003-of-00004.safetensors",
223
+ "model.layers.24.self_attn.v_proj.weight": "model-renamed-00003-of-00004.safetensors",
224
+ "model.layers.25.input_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
225
+ "model.layers.25.mlp.down_proj.weight": "model-renamed-00003-of-00004.safetensors",
226
+ "model.layers.25.mlp.gate_proj.weight": "model-renamed-00003-of-00004.safetensors",
227
+ "model.layers.25.mlp.up_proj.weight": "model-renamed-00003-of-00004.safetensors",
228
+ "model.layers.25.post_attention_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
229
+ "model.layers.25.self_attn.k_proj.bias": "model-renamed-00003-of-00004.safetensors",
230
+ "model.layers.25.self_attn.k_proj.weight": "model-renamed-00003-of-00004.safetensors",
231
+ "model.layers.25.self_attn.o_proj.weight": "model-renamed-00003-of-00004.safetensors",
232
+ "model.layers.25.self_attn.q_proj.bias": "model-renamed-00003-of-00004.safetensors",
233
+ "model.layers.25.self_attn.q_proj.weight": "model-renamed-00003-of-00004.safetensors",
234
+ "model.layers.25.self_attn.v_proj.bias": "model-renamed-00003-of-00004.safetensors",
235
+ "model.layers.25.self_attn.v_proj.weight": "model-renamed-00003-of-00004.safetensors",
236
+ "model.layers.26.input_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
237
+ "model.layers.26.mlp.down_proj.weight": "model-renamed-00003-of-00004.safetensors",
238
+ "model.layers.26.mlp.gate_proj.weight": "model-renamed-00003-of-00004.safetensors",
239
+ "model.layers.26.mlp.up_proj.weight": "model-renamed-00003-of-00004.safetensors",
240
+ "model.layers.26.post_attention_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
241
+ "model.layers.26.self_attn.k_proj.bias": "model-renamed-00003-of-00004.safetensors",
242
+ "model.layers.26.self_attn.k_proj.weight": "model-renamed-00003-of-00004.safetensors",
243
+ "model.layers.26.self_attn.o_proj.weight": "model-renamed-00003-of-00004.safetensors",
244
+ "model.layers.26.self_attn.q_proj.bias": "model-renamed-00003-of-00004.safetensors",
245
+ "model.layers.26.self_attn.q_proj.weight": "model-renamed-00003-of-00004.safetensors",
246
+ "model.layers.26.self_attn.v_proj.bias": "model-renamed-00003-of-00004.safetensors",
247
+ "model.layers.26.self_attn.v_proj.weight": "model-renamed-00003-of-00004.safetensors",
248
+ "model.layers.27.input_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
249
+ "model.layers.27.mlp.down_proj.weight": "model-renamed-00003-of-00004.safetensors",
250
+ "model.layers.27.mlp.gate_proj.weight": "model-renamed-00003-of-00004.safetensors",
251
+ "model.layers.27.mlp.up_proj.weight": "model-renamed-00003-of-00004.safetensors",
252
+ "model.layers.27.post_attention_layernorm.weight": "model-renamed-00003-of-00004.safetensors",
253
+ "model.layers.27.self_attn.k_proj.bias": "model-renamed-00003-of-00004.safetensors",
254
+ "model.layers.27.self_attn.k_proj.weight": "model-renamed-00003-of-00004.safetensors",
255
+ "model.layers.27.self_attn.o_proj.weight": "model-renamed-00003-of-00004.safetensors",
256
+ "model.layers.27.self_attn.q_proj.bias": "model-renamed-00003-of-00004.safetensors",
257
+ "model.layers.27.self_attn.q_proj.weight": "model-renamed-00003-of-00004.safetensors",
258
+ "model.layers.27.self_attn.v_proj.bias": "model-renamed-00003-of-00004.safetensors",
259
+ "model.layers.27.self_attn.v_proj.weight": "model-renamed-00003-of-00004.safetensors",
260
+ "model.layers.3.input_layernorm.weight": "model-renamed-00001-of-00004.safetensors",
261
+ "model.layers.3.mlp.down_proj.weight": "model-renamed-00001-of-00004.safetensors",
262
+ "model.layers.3.mlp.gate_proj.weight": "model-renamed-00001-of-00004.safetensors",
263
+ "model.layers.3.mlp.up_proj.weight": "model-renamed-00001-of-00004.safetensors",
264
+ "model.layers.3.post_attention_layernorm.weight": "model-renamed-00001-of-00004.safetensors",
265
+ "model.layers.3.self_attn.k_proj.bias": "model-renamed-00001-of-00004.safetensors",
266
+ "model.layers.3.self_attn.k_proj.weight": "model-renamed-00001-of-00004.safetensors",
267
+ "model.layers.3.self_attn.o_proj.weight": "model-renamed-00001-of-00004.safetensors",
268
+ "model.layers.3.self_attn.q_proj.bias": "model-renamed-00001-of-00004.safetensors",
269
+ "model.layers.3.self_attn.q_proj.weight": "model-renamed-00001-of-00004.safetensors",
270
+ "model.layers.3.self_attn.v_proj.bias": "model-renamed-00001-of-00004.safetensors",
271
+ "model.layers.3.self_attn.v_proj.weight": "model-renamed-00001-of-00004.safetensors",
272
+ "model.layers.4.input_layernorm.weight": "model-renamed-00001-of-00004.safetensors",
273
+ "model.layers.4.mlp.down_proj.weight": "model-renamed-00001-of-00004.safetensors",
274
+ "model.layers.4.mlp.gate_proj.weight": "model-renamed-00001-of-00004.safetensors",
275
+ "model.layers.4.mlp.up_proj.weight": "model-renamed-00001-of-00004.safetensors",
276
+ "model.layers.4.post_attention_layernorm.weight": "model-renamed-00001-of-00004.safetensors",
277
+ "model.layers.4.self_attn.k_proj.bias": "model-renamed-00001-of-00004.safetensors",
278
+ "model.layers.4.self_attn.k_proj.weight": "model-renamed-00001-of-00004.safetensors",
279
+ "model.layers.4.self_attn.o_proj.weight": "model-renamed-00001-of-00004.safetensors",
280
+ "model.layers.4.self_attn.q_proj.bias": "model-renamed-00001-of-00004.safetensors",
281
+ "model.layers.4.self_attn.q_proj.weight": "model-renamed-00001-of-00004.safetensors",
282
+ "model.layers.4.self_attn.v_proj.bias": "model-renamed-00001-of-00004.safetensors",
283
+ "model.layers.4.self_attn.v_proj.weight": "model-renamed-00001-of-00004.safetensors",
284
+ "model.layers.5.input_layernorm.weight": "model-renamed-00001-of-00004.safetensors",
285
+ "model.layers.5.mlp.down_proj.weight": "model-renamed-00001-of-00004.safetensors",
286
+ "model.layers.5.mlp.gate_proj.weight": "model-renamed-00001-of-00004.safetensors",
287
+ "model.layers.5.mlp.up_proj.weight": "model-renamed-00001-of-00004.safetensors",
288
+ "model.layers.5.post_attention_layernorm.weight": "model-renamed-00001-of-00004.safetensors",
289
+ "model.layers.5.self_attn.k_proj.bias": "model-renamed-00001-of-00004.safetensors",
290
+ "model.layers.5.self_attn.k_proj.weight": "model-renamed-00001-of-00004.safetensors",
291
+ "model.layers.5.self_attn.o_proj.weight": "model-renamed-00001-of-00004.safetensors",
292
+ "model.layers.5.self_attn.q_proj.bias": "model-renamed-00001-of-00004.safetensors",
293
+ "model.layers.5.self_attn.q_proj.weight": "model-renamed-00001-of-00004.safetensors",
294
+ "model.layers.5.self_attn.v_proj.bias": "model-renamed-00001-of-00004.safetensors",
295
+ "model.layers.5.self_attn.v_proj.weight": "model-renamed-00001-of-00004.safetensors",
296
+ "model.layers.6.input_layernorm.weight": "model-renamed-00001-of-00004.safetensors",
297
+ "model.layers.6.mlp.down_proj.weight": "model-renamed-00001-of-00004.safetensors",
298
+ "model.layers.6.mlp.gate_proj.weight": "model-renamed-00001-of-00004.safetensors",
299
+ "model.layers.6.mlp.up_proj.weight": "model-renamed-00001-of-00004.safetensors",
300
+ "model.layers.6.post_attention_layernorm.weight": "model-renamed-00001-of-00004.safetensors",
301
+ "model.layers.6.self_attn.k_proj.bias": "model-renamed-00001-of-00004.safetensors",
302
+ "model.layers.6.self_attn.k_proj.weight": "model-renamed-00001-of-00004.safetensors",
303
+ "model.layers.6.self_attn.o_proj.weight": "model-renamed-00001-of-00004.safetensors",
304
+ "model.layers.6.self_attn.q_proj.bias": "model-renamed-00001-of-00004.safetensors",
305
+ "model.layers.6.self_attn.q_proj.weight": "model-renamed-00001-of-00004.safetensors",
306
+ "model.layers.6.self_attn.v_proj.bias": "model-renamed-00001-of-00004.safetensors",
307
+ "model.layers.6.self_attn.v_proj.weight": "model-renamed-00001-of-00004.safetensors",
308
+ "model.layers.7.input_layernorm.weight": "model-renamed-00001-of-00004.safetensors",
309
+ "model.layers.7.mlp.down_proj.weight": "model-renamed-00001-of-00004.safetensors",
310
+ "model.layers.7.mlp.gate_proj.weight": "model-renamed-00001-of-00004.safetensors",
311
+ "model.layers.7.mlp.up_proj.weight": "model-renamed-00001-of-00004.safetensors",
312
+ "model.layers.7.post_attention_layernorm.weight": "model-renamed-00001-of-00004.safetensors",
313
+ "model.layers.7.self_attn.k_proj.bias": "model-renamed-00001-of-00004.safetensors",
314
+ "model.layers.7.self_attn.k_proj.weight": "model-renamed-00001-of-00004.safetensors",
315
+ "model.layers.7.self_attn.o_proj.weight": "model-renamed-00001-of-00004.safetensors",
316
+ "model.layers.7.self_attn.q_proj.bias": "model-renamed-00001-of-00004.safetensors",
317
+ "model.layers.7.self_attn.q_proj.weight": "model-renamed-00001-of-00004.safetensors",
318
+ "model.layers.7.self_attn.v_proj.bias": "model-renamed-00001-of-00004.safetensors",
319
+ "model.layers.7.self_attn.v_proj.weight": "model-renamed-00001-of-00004.safetensors",
320
+ "model.layers.8.input_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
321
+ "model.layers.8.mlp.down_proj.weight": "model-renamed-00002-of-00004.safetensors",
322
+ "model.layers.8.mlp.gate_proj.weight": "model-renamed-00002-of-00004.safetensors",
323
+ "model.layers.8.mlp.up_proj.weight": "model-renamed-00002-of-00004.safetensors",
324
+ "model.layers.8.post_attention_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
325
+ "model.layers.8.self_attn.k_proj.bias": "model-renamed-00001-of-00004.safetensors",
326
+ "model.layers.8.self_attn.k_proj.weight": "model-renamed-00001-of-00004.safetensors",
327
+ "model.layers.8.self_attn.o_proj.weight": "model-renamed-00001-of-00004.safetensors",
328
+ "model.layers.8.self_attn.q_proj.bias": "model-renamed-00001-of-00004.safetensors",
329
+ "model.layers.8.self_attn.q_proj.weight": "model-renamed-00001-of-00004.safetensors",
330
+ "model.layers.8.self_attn.v_proj.bias": "model-renamed-00001-of-00004.safetensors",
331
+ "model.layers.8.self_attn.v_proj.weight": "model-renamed-00001-of-00004.safetensors",
332
+ "model.layers.9.input_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
333
+ "model.layers.9.mlp.down_proj.weight": "model-renamed-00002-of-00004.safetensors",
334
+ "model.layers.9.mlp.gate_proj.weight": "model-renamed-00002-of-00004.safetensors",
335
+ "model.layers.9.mlp.up_proj.weight": "model-renamed-00002-of-00004.safetensors",
336
+ "model.layers.9.post_attention_layernorm.weight": "model-renamed-00002-of-00004.safetensors",
337
+ "model.layers.9.self_attn.k_proj.bias": "model-renamed-00002-of-00004.safetensors",
338
+ "model.layers.9.self_attn.k_proj.weight": "model-renamed-00002-of-00004.safetensors",
339
+ "model.layers.9.self_attn.o_proj.weight": "model-renamed-00002-of-00004.safetensors",
340
+ "model.layers.9.self_attn.q_proj.bias": "model-renamed-00002-of-00004.safetensors",
341
+ "model.layers.9.self_attn.q_proj.weight": "model-renamed-00002-of-00004.safetensors",
342
+ "model.layers.9.self_attn.v_proj.bias": "model-renamed-00002-of-00004.safetensors",
343
+ "model.layers.9.self_attn.v_proj.weight": "model-renamed-00002-of-00004.safetensors",
344
+ "model.norm.weight": "model-renamed-00003-of-00004.safetensors",
345
+ "resampler.attn.in_proj_bias": "model-renamed-00004-of-00004.safetensors",
346
+ "resampler.attn.in_proj_weight": "model-renamed-00004-of-00004.safetensors",
347
+ "resampler.attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
348
+ "resampler.attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
349
+ "resampler.kv_proj.weight": "model-renamed-00004-of-00004.safetensors",
350
+ "resampler.ln_kv.bias": "model-renamed-00004-of-00004.safetensors",
351
+ "resampler.ln_kv.weight": "model-renamed-00004-of-00004.safetensors",
352
+ "resampler.ln_post.bias": "model-renamed-00004-of-00004.safetensors",
353
+ "resampler.ln_post.weight": "model-renamed-00004-of-00004.safetensors",
354
+ "resampler.ln_q.bias": "model-renamed-00004-of-00004.safetensors",
355
+ "resampler.ln_q.weight": "model-renamed-00004-of-00004.safetensors",
356
+ "resampler.proj": "model-renamed-00004-of-00004.safetensors",
357
+ "resampler.query": "model-renamed-00004-of-00004.safetensors",
358
+ "vpm.embeddings.patch_embedding.bias": "model-renamed-00004-of-00004.safetensors",
359
+ "vpm.embeddings.patch_embedding.weight": "model-renamed-00004-of-00004.safetensors",
360
+ "vpm.embeddings.position_embedding.weight": "model-renamed-00004-of-00004.safetensors",
361
+ "vpm.encoder.layers.0.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
362
+ "vpm.encoder.layers.0.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
363
+ "vpm.encoder.layers.0.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
364
+ "vpm.encoder.layers.0.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
365
+ "vpm.encoder.layers.0.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
366
+ "vpm.encoder.layers.0.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
367
+ "vpm.encoder.layers.0.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
368
+ "vpm.encoder.layers.0.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
369
+ "vpm.encoder.layers.0.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
370
+ "vpm.encoder.layers.0.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
371
+ "vpm.encoder.layers.0.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
372
+ "vpm.encoder.layers.0.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
373
+ "vpm.encoder.layers.0.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
374
+ "vpm.encoder.layers.0.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
375
+ "vpm.encoder.layers.0.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
376
+ "vpm.encoder.layers.0.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
377
+ "vpm.encoder.layers.1.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
378
+ "vpm.encoder.layers.1.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
379
+ "vpm.encoder.layers.1.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
380
+ "vpm.encoder.layers.1.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
381
+ "vpm.encoder.layers.1.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
382
+ "vpm.encoder.layers.1.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
383
+ "vpm.encoder.layers.1.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
384
+ "vpm.encoder.layers.1.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
385
+ "vpm.encoder.layers.1.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
386
+ "vpm.encoder.layers.1.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
387
+ "vpm.encoder.layers.1.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
388
+ "vpm.encoder.layers.1.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
389
+ "vpm.encoder.layers.1.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
390
+ "vpm.encoder.layers.1.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
391
+ "vpm.encoder.layers.1.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
392
+ "vpm.encoder.layers.1.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
393
+ "vpm.encoder.layers.10.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
394
+ "vpm.encoder.layers.10.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
395
+ "vpm.encoder.layers.10.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
396
+ "vpm.encoder.layers.10.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
397
+ "vpm.encoder.layers.10.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
398
+ "vpm.encoder.layers.10.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
399
+ "vpm.encoder.layers.10.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
400
+ "vpm.encoder.layers.10.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
401
+ "vpm.encoder.layers.10.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
402
+ "vpm.encoder.layers.10.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
403
+ "vpm.encoder.layers.10.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
404
+ "vpm.encoder.layers.10.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
405
+ "vpm.encoder.layers.10.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
406
+ "vpm.encoder.layers.10.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
407
+ "vpm.encoder.layers.10.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
408
+ "vpm.encoder.layers.10.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
409
+ "vpm.encoder.layers.11.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
410
+ "vpm.encoder.layers.11.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
411
+ "vpm.encoder.layers.11.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
412
+ "vpm.encoder.layers.11.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
413
+ "vpm.encoder.layers.11.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
414
+ "vpm.encoder.layers.11.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
415
+ "vpm.encoder.layers.11.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
416
+ "vpm.encoder.layers.11.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
417
+ "vpm.encoder.layers.11.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
418
+ "vpm.encoder.layers.11.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
419
+ "vpm.encoder.layers.11.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
420
+ "vpm.encoder.layers.11.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
421
+ "vpm.encoder.layers.11.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
422
+ "vpm.encoder.layers.11.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
423
+ "vpm.encoder.layers.11.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
424
+ "vpm.encoder.layers.11.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
425
+ "vpm.encoder.layers.12.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
426
+ "vpm.encoder.layers.12.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
427
+ "vpm.encoder.layers.12.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
428
+ "vpm.encoder.layers.12.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
429
+ "vpm.encoder.layers.12.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
430
+ "vpm.encoder.layers.12.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
431
+ "vpm.encoder.layers.12.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
432
+ "vpm.encoder.layers.12.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
433
+ "vpm.encoder.layers.12.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
434
+ "vpm.encoder.layers.12.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
435
+ "vpm.encoder.layers.12.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
436
+ "vpm.encoder.layers.12.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
437
+ "vpm.encoder.layers.12.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
438
+ "vpm.encoder.layers.12.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
439
+ "vpm.encoder.layers.12.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
440
+ "vpm.encoder.layers.12.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
441
+ "vpm.encoder.layers.13.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
442
+ "vpm.encoder.layers.13.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
443
+ "vpm.encoder.layers.13.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
444
+ "vpm.encoder.layers.13.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
445
+ "vpm.encoder.layers.13.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
446
+ "vpm.encoder.layers.13.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
447
+ "vpm.encoder.layers.13.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
448
+ "vpm.encoder.layers.13.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
449
+ "vpm.encoder.layers.13.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
450
+ "vpm.encoder.layers.13.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
451
+ "vpm.encoder.layers.13.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
452
+ "vpm.encoder.layers.13.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
453
+ "vpm.encoder.layers.13.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
454
+ "vpm.encoder.layers.13.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
455
+ "vpm.encoder.layers.13.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
456
+ "vpm.encoder.layers.13.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
457
+ "vpm.encoder.layers.14.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
458
+ "vpm.encoder.layers.14.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
459
+ "vpm.encoder.layers.14.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
460
+ "vpm.encoder.layers.14.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
461
+ "vpm.encoder.layers.14.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
462
+ "vpm.encoder.layers.14.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
463
+ "vpm.encoder.layers.14.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
464
+ "vpm.encoder.layers.14.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
465
+ "vpm.encoder.layers.14.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
466
+ "vpm.encoder.layers.14.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
467
+ "vpm.encoder.layers.14.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
468
+ "vpm.encoder.layers.14.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
469
+ "vpm.encoder.layers.14.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
470
+ "vpm.encoder.layers.14.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
471
+ "vpm.encoder.layers.14.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
472
+ "vpm.encoder.layers.14.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
473
+ "vpm.encoder.layers.15.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
474
+ "vpm.encoder.layers.15.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
475
+ "vpm.encoder.layers.15.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
476
+ "vpm.encoder.layers.15.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
477
+ "vpm.encoder.layers.15.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
478
+ "vpm.encoder.layers.15.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
479
+ "vpm.encoder.layers.15.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
480
+ "vpm.encoder.layers.15.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
481
+ "vpm.encoder.layers.15.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
482
+ "vpm.encoder.layers.15.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
483
+ "vpm.encoder.layers.15.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
484
+ "vpm.encoder.layers.15.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
485
+ "vpm.encoder.layers.15.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
486
+ "vpm.encoder.layers.15.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
487
+ "vpm.encoder.layers.15.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
488
+ "vpm.encoder.layers.15.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
489
+ "vpm.encoder.layers.16.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
490
+ "vpm.encoder.layers.16.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
491
+ "vpm.encoder.layers.16.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
492
+ "vpm.encoder.layers.16.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
493
+ "vpm.encoder.layers.16.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
494
+ "vpm.encoder.layers.16.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
495
+ "vpm.encoder.layers.16.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
496
+ "vpm.encoder.layers.16.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
497
+ "vpm.encoder.layers.16.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
498
+ "vpm.encoder.layers.16.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
499
+ "vpm.encoder.layers.16.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
500
+ "vpm.encoder.layers.16.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
501
+ "vpm.encoder.layers.16.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
502
+ "vpm.encoder.layers.16.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
503
+ "vpm.encoder.layers.16.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
504
+ "vpm.encoder.layers.16.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
505
+ "vpm.encoder.layers.17.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
506
+ "vpm.encoder.layers.17.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
507
+ "vpm.encoder.layers.17.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
508
+ "vpm.encoder.layers.17.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
509
+ "vpm.encoder.layers.17.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
510
+ "vpm.encoder.layers.17.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
511
+ "vpm.encoder.layers.17.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
512
+ "vpm.encoder.layers.17.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
513
+ "vpm.encoder.layers.17.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
514
+ "vpm.encoder.layers.17.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
515
+ "vpm.encoder.layers.17.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
516
+ "vpm.encoder.layers.17.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
517
+ "vpm.encoder.layers.17.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
518
+ "vpm.encoder.layers.17.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
519
+ "vpm.encoder.layers.17.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
520
+ "vpm.encoder.layers.17.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
521
+ "vpm.encoder.layers.18.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
522
+ "vpm.encoder.layers.18.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
523
+ "vpm.encoder.layers.18.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
524
+ "vpm.encoder.layers.18.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
525
+ "vpm.encoder.layers.18.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
526
+ "vpm.encoder.layers.18.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
527
+ "vpm.encoder.layers.18.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
528
+ "vpm.encoder.layers.18.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
529
+ "vpm.encoder.layers.18.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
530
+ "vpm.encoder.layers.18.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
531
+ "vpm.encoder.layers.18.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
532
+ "vpm.encoder.layers.18.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
533
+ "vpm.encoder.layers.18.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
534
+ "vpm.encoder.layers.18.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
535
+ "vpm.encoder.layers.18.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
536
+ "vpm.encoder.layers.18.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
537
+ "vpm.encoder.layers.19.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
538
+ "vpm.encoder.layers.19.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
539
+ "vpm.encoder.layers.19.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
540
+ "vpm.encoder.layers.19.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
541
+ "vpm.encoder.layers.19.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
542
+ "vpm.encoder.layers.19.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
543
+ "vpm.encoder.layers.19.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
544
+ "vpm.encoder.layers.19.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
545
+ "vpm.encoder.layers.19.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
546
+ "vpm.encoder.layers.19.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
547
+ "vpm.encoder.layers.19.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
548
+ "vpm.encoder.layers.19.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
549
+ "vpm.encoder.layers.19.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
550
+ "vpm.encoder.layers.19.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
551
+ "vpm.encoder.layers.19.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
552
+ "vpm.encoder.layers.19.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
553
+ "vpm.encoder.layers.2.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
554
+ "vpm.encoder.layers.2.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
555
+ "vpm.encoder.layers.2.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
556
+ "vpm.encoder.layers.2.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
557
+ "vpm.encoder.layers.2.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
558
+ "vpm.encoder.layers.2.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
559
+ "vpm.encoder.layers.2.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
560
+ "vpm.encoder.layers.2.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
561
+ "vpm.encoder.layers.2.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
562
+ "vpm.encoder.layers.2.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
563
+ "vpm.encoder.layers.2.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
564
+ "vpm.encoder.layers.2.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
565
+ "vpm.encoder.layers.2.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
566
+ "vpm.encoder.layers.2.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
567
+ "vpm.encoder.layers.2.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
568
+ "vpm.encoder.layers.2.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
569
+ "vpm.encoder.layers.20.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
570
+ "vpm.encoder.layers.20.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
571
+ "vpm.encoder.layers.20.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
572
+ "vpm.encoder.layers.20.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
573
+ "vpm.encoder.layers.20.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
574
+ "vpm.encoder.layers.20.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
575
+ "vpm.encoder.layers.20.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
576
+ "vpm.encoder.layers.20.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
577
+ "vpm.encoder.layers.20.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
578
+ "vpm.encoder.layers.20.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
579
+ "vpm.encoder.layers.20.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
580
+ "vpm.encoder.layers.20.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
581
+ "vpm.encoder.layers.20.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
582
+ "vpm.encoder.layers.20.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
583
+ "vpm.encoder.layers.20.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
584
+ "vpm.encoder.layers.20.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
585
+ "vpm.encoder.layers.21.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
586
+ "vpm.encoder.layers.21.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
587
+ "vpm.encoder.layers.21.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
588
+ "vpm.encoder.layers.21.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
589
+ "vpm.encoder.layers.21.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
590
+ "vpm.encoder.layers.21.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
591
+ "vpm.encoder.layers.21.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
592
+ "vpm.encoder.layers.21.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
593
+ "vpm.encoder.layers.21.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
594
+ "vpm.encoder.layers.21.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
595
+ "vpm.encoder.layers.21.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
596
+ "vpm.encoder.layers.21.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
597
+ "vpm.encoder.layers.21.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
598
+ "vpm.encoder.layers.21.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
599
+ "vpm.encoder.layers.21.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
600
+ "vpm.encoder.layers.21.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
601
+ "vpm.encoder.layers.22.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
602
+ "vpm.encoder.layers.22.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
603
+ "vpm.encoder.layers.22.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
604
+ "vpm.encoder.layers.22.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
605
+ "vpm.encoder.layers.22.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
606
+ "vpm.encoder.layers.22.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
607
+ "vpm.encoder.layers.22.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
608
+ "vpm.encoder.layers.22.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
609
+ "vpm.encoder.layers.22.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
610
+ "vpm.encoder.layers.22.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
611
+ "vpm.encoder.layers.22.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
612
+ "vpm.encoder.layers.22.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
613
+ "vpm.encoder.layers.22.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
614
+ "vpm.encoder.layers.22.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
615
+ "vpm.encoder.layers.22.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
616
+ "vpm.encoder.layers.22.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
617
+ "vpm.encoder.layers.23.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
618
+ "vpm.encoder.layers.23.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
619
+ "vpm.encoder.layers.23.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
620
+ "vpm.encoder.layers.23.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
621
+ "vpm.encoder.layers.23.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
622
+ "vpm.encoder.layers.23.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
623
+ "vpm.encoder.layers.23.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
624
+ "vpm.encoder.layers.23.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
625
+ "vpm.encoder.layers.23.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
626
+ "vpm.encoder.layers.23.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
627
+ "vpm.encoder.layers.23.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
628
+ "vpm.encoder.layers.23.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
629
+ "vpm.encoder.layers.23.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
630
+ "vpm.encoder.layers.23.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
631
+ "vpm.encoder.layers.23.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
632
+ "vpm.encoder.layers.23.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
633
+ "vpm.encoder.layers.24.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
634
+ "vpm.encoder.layers.24.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
635
+ "vpm.encoder.layers.24.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
636
+ "vpm.encoder.layers.24.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
637
+ "vpm.encoder.layers.24.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
638
+ "vpm.encoder.layers.24.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
639
+ "vpm.encoder.layers.24.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
640
+ "vpm.encoder.layers.24.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
641
+ "vpm.encoder.layers.24.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
642
+ "vpm.encoder.layers.24.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
643
+ "vpm.encoder.layers.24.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
644
+ "vpm.encoder.layers.24.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
645
+ "vpm.encoder.layers.24.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
646
+ "vpm.encoder.layers.24.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
647
+ "vpm.encoder.layers.24.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
648
+ "vpm.encoder.layers.24.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
649
+ "vpm.encoder.layers.25.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
650
+ "vpm.encoder.layers.25.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
651
+ "vpm.encoder.layers.25.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
652
+ "vpm.encoder.layers.25.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
653
+ "vpm.encoder.layers.25.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
654
+ "vpm.encoder.layers.25.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
655
+ "vpm.encoder.layers.25.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
656
+ "vpm.encoder.layers.25.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
657
+ "vpm.encoder.layers.25.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
658
+ "vpm.encoder.layers.25.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
659
+ "vpm.encoder.layers.25.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
660
+ "vpm.encoder.layers.25.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
661
+ "vpm.encoder.layers.25.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
662
+ "vpm.encoder.layers.25.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
663
+ "vpm.encoder.layers.25.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
664
+ "vpm.encoder.layers.25.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
665
+ "vpm.encoder.layers.26.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
666
+ "vpm.encoder.layers.26.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
667
+ "vpm.encoder.layers.26.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
668
+ "vpm.encoder.layers.26.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
669
+ "vpm.encoder.layers.26.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
670
+ "vpm.encoder.layers.26.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
671
+ "vpm.encoder.layers.26.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
672
+ "vpm.encoder.layers.26.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
673
+ "vpm.encoder.layers.26.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
674
+ "vpm.encoder.layers.26.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
675
+ "vpm.encoder.layers.26.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
676
+ "vpm.encoder.layers.26.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
677
+ "vpm.encoder.layers.26.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
678
+ "vpm.encoder.layers.26.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
679
+ "vpm.encoder.layers.26.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
680
+ "vpm.encoder.layers.26.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
681
+ "vpm.encoder.layers.3.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
682
+ "vpm.encoder.layers.3.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
683
+ "vpm.encoder.layers.3.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
684
+ "vpm.encoder.layers.3.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
685
+ "vpm.encoder.layers.3.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
686
+ "vpm.encoder.layers.3.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
687
+ "vpm.encoder.layers.3.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
688
+ "vpm.encoder.layers.3.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
689
+ "vpm.encoder.layers.3.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
690
+ "vpm.encoder.layers.3.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
691
+ "vpm.encoder.layers.3.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
692
+ "vpm.encoder.layers.3.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
693
+ "vpm.encoder.layers.3.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
694
+ "vpm.encoder.layers.3.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
695
+ "vpm.encoder.layers.3.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
696
+ "vpm.encoder.layers.3.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
697
+ "vpm.encoder.layers.4.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
698
+ "vpm.encoder.layers.4.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
699
+ "vpm.encoder.layers.4.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
700
+ "vpm.encoder.layers.4.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
701
+ "vpm.encoder.layers.4.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
702
+ "vpm.encoder.layers.4.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
703
+ "vpm.encoder.layers.4.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
704
+ "vpm.encoder.layers.4.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
705
+ "vpm.encoder.layers.4.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
706
+ "vpm.encoder.layers.4.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
707
+ "vpm.encoder.layers.4.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
708
+ "vpm.encoder.layers.4.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
709
+ "vpm.encoder.layers.4.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
710
+ "vpm.encoder.layers.4.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
711
+ "vpm.encoder.layers.4.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
712
+ "vpm.encoder.layers.4.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
713
+ "vpm.encoder.layers.5.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
714
+ "vpm.encoder.layers.5.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
715
+ "vpm.encoder.layers.5.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
716
+ "vpm.encoder.layers.5.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
717
+ "vpm.encoder.layers.5.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
718
+ "vpm.encoder.layers.5.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
719
+ "vpm.encoder.layers.5.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
720
+ "vpm.encoder.layers.5.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
721
+ "vpm.encoder.layers.5.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
722
+ "vpm.encoder.layers.5.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
723
+ "vpm.encoder.layers.5.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
724
+ "vpm.encoder.layers.5.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
725
+ "vpm.encoder.layers.5.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
726
+ "vpm.encoder.layers.5.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
727
+ "vpm.encoder.layers.5.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
728
+ "vpm.encoder.layers.5.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
729
+ "vpm.encoder.layers.6.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
730
+ "vpm.encoder.layers.6.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
731
+ "vpm.encoder.layers.6.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
732
+ "vpm.encoder.layers.6.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
733
+ "vpm.encoder.layers.6.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
734
+ "vpm.encoder.layers.6.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
735
+ "vpm.encoder.layers.6.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
736
+ "vpm.encoder.layers.6.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
737
+ "vpm.encoder.layers.6.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
738
+ "vpm.encoder.layers.6.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
739
+ "vpm.encoder.layers.6.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
740
+ "vpm.encoder.layers.6.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
741
+ "vpm.encoder.layers.6.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
742
+ "vpm.encoder.layers.6.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
743
+ "vpm.encoder.layers.6.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
744
+ "vpm.encoder.layers.6.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
745
+ "vpm.encoder.layers.7.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
746
+ "vpm.encoder.layers.7.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
747
+ "vpm.encoder.layers.7.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
748
+ "vpm.encoder.layers.7.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
749
+ "vpm.encoder.layers.7.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
750
+ "vpm.encoder.layers.7.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
751
+ "vpm.encoder.layers.7.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
752
+ "vpm.encoder.layers.7.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
753
+ "vpm.encoder.layers.7.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
754
+ "vpm.encoder.layers.7.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
755
+ "vpm.encoder.layers.7.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
756
+ "vpm.encoder.layers.7.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
757
+ "vpm.encoder.layers.7.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
758
+ "vpm.encoder.layers.7.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
759
+ "vpm.encoder.layers.7.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
760
+ "vpm.encoder.layers.7.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
761
+ "vpm.encoder.layers.8.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
762
+ "vpm.encoder.layers.8.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
763
+ "vpm.encoder.layers.8.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
764
+ "vpm.encoder.layers.8.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
765
+ "vpm.encoder.layers.8.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
766
+ "vpm.encoder.layers.8.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
767
+ "vpm.encoder.layers.8.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
768
+ "vpm.encoder.layers.8.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
769
+ "vpm.encoder.layers.8.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
770
+ "vpm.encoder.layers.8.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
771
+ "vpm.encoder.layers.8.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
772
+ "vpm.encoder.layers.8.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
773
+ "vpm.encoder.layers.8.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
774
+ "vpm.encoder.layers.8.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
775
+ "vpm.encoder.layers.8.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
776
+ "vpm.encoder.layers.8.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
777
+ "vpm.encoder.layers.9.layer_norm1.bias": "model-renamed-00004-of-00004.safetensors",
778
+ "vpm.encoder.layers.9.layer_norm1.weight": "model-renamed-00004-of-00004.safetensors",
779
+ "vpm.encoder.layers.9.layer_norm2.bias": "model-renamed-00004-of-00004.safetensors",
780
+ "vpm.encoder.layers.9.layer_norm2.weight": "model-renamed-00004-of-00004.safetensors",
781
+ "vpm.encoder.layers.9.mlp.fc1.bias": "model-renamed-00004-of-00004.safetensors",
782
+ "vpm.encoder.layers.9.mlp.fc1.weight": "model-renamed-00004-of-00004.safetensors",
783
+ "vpm.encoder.layers.9.mlp.fc2.bias": "model-renamed-00004-of-00004.safetensors",
784
+ "vpm.encoder.layers.9.mlp.fc2.weight": "model-renamed-00004-of-00004.safetensors",
785
+ "vpm.encoder.layers.9.self_attn.k_proj.bias": "model-renamed-00004-of-00004.safetensors",
786
+ "vpm.encoder.layers.9.self_attn.k_proj.weight": "model-renamed-00004-of-00004.safetensors",
787
+ "vpm.encoder.layers.9.self_attn.out_proj.bias": "model-renamed-00004-of-00004.safetensors",
788
+ "vpm.encoder.layers.9.self_attn.out_proj.weight": "model-renamed-00004-of-00004.safetensors",
789
+ "vpm.encoder.layers.9.self_attn.q_proj.bias": "model-renamed-00004-of-00004.safetensors",
790
+ "vpm.encoder.layers.9.self_attn.q_proj.weight": "model-renamed-00004-of-00004.safetensors",
791
+ "vpm.encoder.layers.9.self_attn.v_proj.bias": "model-renamed-00004-of-00004.safetensors",
792
+ "vpm.encoder.layers.9.self_attn.v_proj.weight": "model-renamed-00004-of-00004.safetensors",
793
+ "vpm.post_layernorm.bias": "model-renamed-00004-of-00004.safetensors",
794
+ "vpm.post_layernorm.weight": "model-renamed-00004-of-00004.safetensors"
795
+ }
796
+ }
patched_modeling_navit_siglip.py ADDED
@@ -0,0 +1,893 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Google AI and The HuggingFace 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
+ """ PyTorch Siglip model. """
16
+ # Copied from HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit and add tgt_sizes
17
+
18
+
19
+ import os
20
+ import math
21
+ import warnings
22
+ from dataclasses import dataclass
23
+ from typing import Any, Optional, Tuple, Union
24
+
25
+ import numpy as np
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn.init import _calculate_fan_in_and_fan_out
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
34
+ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
35
+ from transformers.modeling_utils import PreTrainedModel
36
+ from transformers.configuration_utils import PretrainedConfig
37
+ from transformers.utils import (
38
+ ModelOutput,
39
+ add_start_docstrings,
40
+ add_start_docstrings_to_model_forward,
41
+ is_flash_attn_2_available,
42
+ logging,
43
+ replace_return_docstrings,
44
+ )
45
+ from transformers.utils import logging
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+ class SiglipVisionConfig(PretrainedConfig):
50
+ r"""
51
+ This is the configuration class to store the configuration of a [`SiglipVisionModel`]. It is used to instantiate a
52
+ Siglip vision encoder according to the specified arguments, defining the model architecture. Instantiating a
53
+ configuration with the defaults will yield a similar configuration to that of the vision encoder of the Siglip
54
+ [google/siglip-base-patch16-224](https://huggingface.co/google/siglip-base-patch16-224) architecture.
55
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
56
+ documentation from [`PretrainedConfig`] for more information.
57
+ Args:
58
+ hidden_size (`int`, *optional*, defaults to 768):
59
+ Dimensionality of the encoder layers and the pooler layer.
60
+ intermediate_size (`int`, *optional*, defaults to 3072):
61
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
62
+ num_hidden_layers (`int`, *optional*, defaults to 12):
63
+ Number of hidden layers in the Transformer encoder.
64
+ num_attention_heads (`int`, *optional*, defaults to 12):
65
+ Number of attention heads for each attention layer in the Transformer encoder.
66
+ num_channels (`int`, *optional*, defaults to 3):
67
+ Number of channels in the input images.
68
+ image_size (`int`, *optional*, defaults to 224):
69
+ The size (resolution) of each image.
70
+ patch_size (`int`, *optional*, defaults to 16):
71
+ The size (resolution) of each patch.
72
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
73
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
74
+ `"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
75
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
76
+ The epsilon used by the layer normalization layers.
77
+ attention_dropout (`float`, *optional*, defaults to 0.0):
78
+ The dropout ratio for the attention probabilities.
79
+ Example:
80
+ ```python
81
+ >>> from transformers import SiglipVisionConfig, SiglipVisionModel
82
+ >>> # Initializing a SiglipVisionConfig with google/siglip-base-patch16-224 style configuration
83
+ >>> configuration = SiglipVisionConfig()
84
+ >>> # Initializing a SiglipVisionModel (with random weights) from the google/siglip-base-patch16-224 style configuration
85
+ >>> model = SiglipVisionModel(configuration)
86
+ >>> # Accessing the model configuration
87
+ >>> configuration = model.config
88
+ ```"""
89
+
90
+ model_type = "siglip_vision_model"
91
+
92
+ def __init__(
93
+ self,
94
+ hidden_size=768,
95
+ intermediate_size=3072,
96
+ num_hidden_layers=12,
97
+ num_attention_heads=12,
98
+ num_channels=3,
99
+ image_size=224,
100
+ patch_size=16,
101
+ hidden_act="gelu_pytorch_tanh",
102
+ layer_norm_eps=1e-6,
103
+ attention_dropout=0.0,
104
+ **kwargs,
105
+ ):
106
+ super().__init__(**kwargs)
107
+
108
+ self.hidden_size = hidden_size
109
+ self.intermediate_size = intermediate_size
110
+ self.num_hidden_layers = num_hidden_layers
111
+ self.num_attention_heads = num_attention_heads
112
+ self.num_channels = num_channels
113
+ self.patch_size = patch_size
114
+ self.image_size = image_size
115
+ self.attention_dropout = attention_dropout
116
+ self.layer_norm_eps = layer_norm_eps
117
+ self.hidden_act = hidden_act
118
+
119
+ @classmethod
120
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
121
+ cls._set_token_in_kwargs(kwargs)
122
+
123
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
124
+
125
+ # get the vision config dict if we are loading from SiglipConfig
126
+ if config_dict.get("model_type") == "siglip":
127
+ config_dict = config_dict["vision_config"]
128
+
129
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
130
+ logger.warning(
131
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
132
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
133
+ )
134
+
135
+ return cls.from_dict(config_dict, **kwargs)
136
+
137
+
138
+ _CHECKPOINT_FOR_DOC = "google/siglip-base-patch16-224"
139
+
140
+ SIGLIP_PRETRAINED_MODEL_ARCHIVE_LIST = [
141
+ "google/siglip-base-patch16-224",
142
+ # See all SigLIP models at https://huggingface.co/models?filter=siglip
143
+ ]
144
+
145
+ if is_flash_attn_2_available():
146
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
147
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
148
+
149
+
150
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
151
+ def _get_unpad_data(attention_mask):
152
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
153
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
154
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
155
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
156
+ return (
157
+ indices,
158
+ cu_seqlens,
159
+ max_seqlen_in_batch,
160
+ )
161
+
162
+
163
+ def _trunc_normal_(tensor, mean, std, a, b):
164
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
165
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
166
+ def norm_cdf(x):
167
+ # Computes standard normal cumulative distribution function
168
+ return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
169
+
170
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
171
+ warnings.warn(
172
+ "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
173
+ "The distribution of values may be incorrect.",
174
+ stacklevel=2,
175
+ )
176
+
177
+ # Values are generated by using a truncated uniform distribution and
178
+ # then using the inverse CDF for the normal distribution.
179
+ # Get upper and lower cdf values
180
+ l = norm_cdf((a - mean) / std)
181
+ u = norm_cdf((b - mean) / std)
182
+
183
+ # Uniformly fill tensor with values from [l, u], then translate to
184
+ # [2l-1, 2u-1].
185
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
186
+
187
+ # Use inverse cdf transform for normal distribution to get truncated
188
+ # standard normal
189
+ if tensor.dtype in [torch.float16, torch.bfloat16]:
190
+ # The `erfinv_` op is not (yet?) defined in float16+cpu, bfloat16+gpu
191
+ og_dtype = tensor.dtype
192
+ tensor = tensor.to(torch.float32)
193
+ tensor.erfinv_()
194
+ tensor = tensor.to(og_dtype)
195
+ else:
196
+ tensor.erfinv_()
197
+
198
+ # Transform to proper mean, std
199
+ tensor.mul_(std * math.sqrt(2.0))
200
+ tensor.add_(mean)
201
+
202
+ # Clamp to ensure it's in the proper range
203
+ if tensor.dtype == torch.float16:
204
+ # The `clamp_` op is not (yet?) defined in float16+cpu
205
+ tensor = tensor.to(torch.float32)
206
+ tensor.clamp_(min=a, max=b)
207
+ tensor = tensor.to(torch.float16)
208
+ else:
209
+ tensor.clamp_(min=a, max=b)
210
+
211
+
212
+ def trunc_normal_tf_(
213
+ tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0
214
+ ) -> torch.Tensor:
215
+ """Fills the input Tensor with values drawn from a truncated
216
+ normal distribution. The values are effectively drawn from the
217
+ normal distribution :math:`\\mathcal{N}(\text{mean}, \text{std}^2)`
218
+ with values outside :math:`[a, b]` redrawn until they are within
219
+ the bounds. The method used for generating the random values works
220
+ best when :math:`a \\leq \text{mean} \\leq b`.
221
+ NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
222
+ bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
223
+ and the result is subsquently scaled and shifted by the mean and std args.
224
+ Args:
225
+ tensor: an n-dimensional `torch.Tensor`
226
+ mean: the mean of the normal distribution
227
+ std: the standard deviation of the normal distribution
228
+ a: the minimum cutoff value
229
+ b: the maximum cutoff value
230
+ """
231
+ with torch.no_grad():
232
+ _trunc_normal_(tensor, 0, 1.0, a, b)
233
+ tensor.mul_(std).add_(mean)
234
+
235
+
236
+ def variance_scaling_(tensor, scale=1.0, mode="fan_in", distribution="normal"):
237
+ fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
238
+ if mode == "fan_in":
239
+ denom = fan_in
240
+ elif mode == "fan_out":
241
+ denom = fan_out
242
+ elif mode == "fan_avg":
243
+ denom = (fan_in + fan_out) / 2
244
+
245
+ variance = scale / denom
246
+
247
+ if distribution == "truncated_normal":
248
+ # constant is stddev of standard normal truncated to (-2, 2)
249
+ trunc_normal_tf_(tensor, std=math.sqrt(variance) / 0.87962566103423978)
250
+ elif distribution == "normal":
251
+ with torch.no_grad():
252
+ tensor.normal_(std=math.sqrt(variance))
253
+ elif distribution == "uniform":
254
+ bound = math.sqrt(3 * variance)
255
+ with torch.no_grad():
256
+ tensor.uniform_(-bound, bound)
257
+ else:
258
+ raise ValueError(f"invalid distribution {distribution}")
259
+
260
+
261
+ def lecun_normal_(tensor):
262
+ variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
263
+
264
+
265
+ def default_flax_embed_init(tensor):
266
+ variance_scaling_(tensor, mode="fan_in", distribution="normal")
267
+
268
+
269
+ @dataclass
270
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->Siglip
271
+ class SiglipVisionModelOutput(ModelOutput):
272
+ """
273
+ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
274
+ Args:
275
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
276
+ The image embeddings obtained by applying the projection layer to the pooler_output.
277
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
278
+ Sequence of hidden-states at the output of the last layer of the model.
279
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
280
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
281
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
282
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
283
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
284
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
285
+ sequence_length)`.
286
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
287
+ heads.
288
+ """
289
+
290
+ image_embeds: Optional[torch.FloatTensor] = None
291
+ last_hidden_state: torch.FloatTensor = None
292
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
293
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
294
+
295
+
296
+ class SiglipVisionEmbeddings(nn.Module):
297
+ def __init__(self, config: SiglipVisionConfig):
298
+ super().__init__()
299
+ self.config = config
300
+ self.embed_dim = config.hidden_size
301
+ self.image_size = config.image_size
302
+ self.patch_size = config.patch_size
303
+
304
+ self.patch_embedding = nn.Conv2d(
305
+ in_channels=config.num_channels,
306
+ out_channels=self.embed_dim,
307
+ kernel_size=self.patch_size,
308
+ stride=self.patch_size,
309
+ padding="valid",
310
+ )
311
+
312
+ self.num_patches_per_side = self.image_size // self.patch_size
313
+ self.num_patches = self.num_patches_per_side**2
314
+ self.num_positions = self.num_patches
315
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
316
+
317
+ boundaries = torch.arange(1 / self.num_patches_per_side, 1.0, 1 / self.num_patches_per_side)
318
+
319
+ nb_patches_h = 32
320
+ nb_patches_w = 32
321
+ fractional_coords_h = torch.arange(0, 1 - 1e-6, 1 / nb_patches_h)
322
+ fractional_coords_w = torch.arange(0, 1 - 1e-6, 1 / nb_patches_w)
323
+
324
+ bucket_coords_h = torch.bucketize(fractional_coords_h, boundaries, right=True)
325
+ bucket_coords_w = torch.bucketize(fractional_coords_w, boundaries, right=True)
326
+
327
+ position_ids = (bucket_coords_h[:, None] * self.num_patches_per_side + bucket_coords_w).flatten()
328
+ self.position_ids = position_ids
329
+
330
+ def forward(self, pixel_values: torch.FloatTensor, patch_attention_mask: torch.BoolTensor=None, tgt_sizes: Optional[torch.IntTensor]=None) -> torch.Tensor:
331
+
332
+ patch_embeds = self.patch_embedding(pixel_values).view(1, 1152, 1024)
333
+ embeddings = patch_embeds.transpose(1, 2)
334
+ embeddings = embeddings + self.position_embedding(self.position_ids)
335
+ return embeddings
336
+
337
+
338
+ class SiglipAttention(nn.Module):
339
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
340
+
341
+ # Copied from transformers.models.clip.modeling_clip.CLIPAttention.__init__
342
+ def __init__(self, config):
343
+ super().__init__()
344
+ self.config = config
345
+ self.embed_dim = config.hidden_size
346
+ self.num_heads = config.num_attention_heads
347
+ self.head_dim = self.embed_dim // self.num_heads
348
+ if self.head_dim * self.num_heads != self.embed_dim:
349
+ raise ValueError(
350
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
351
+ f" {self.num_heads})."
352
+ )
353
+ self.scale = self.head_dim**-0.5
354
+ self.dropout = config.attention_dropout
355
+
356
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
357
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
358
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
359
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
360
+
361
+ def forward(
362
+ self,
363
+ hidden_states: torch.Tensor,
364
+ attention_mask: Optional[torch.Tensor] = None,
365
+ output_attentions: Optional[bool] = False,
366
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
367
+ """Input shape: Batch x Time x Channel"""
368
+
369
+ batch_size, q_len = 1, 1024
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(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
376
+ key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
377
+ value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
378
+
379
+ k_v_seq_len = 1024
380
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
381
+
382
+ if attn_weights.size() != (batch_size, self.num_heads, q_len, k_v_seq_len):
383
+ raise ValueError(
384
+ f"Attention weights should be of size {(batch_size, self.num_heads, q_len, k_v_seq_len)}, but is"
385
+ f" {attn_weights.size()}"
386
+ )
387
+
388
+ if attention_mask is not None:
389
+ if attention_mask.size() != (batch_size, 1, q_len, k_v_seq_len):
390
+ raise ValueError(
391
+ f"Attention mask should be of size {(batch_size, 1, q_len, k_v_seq_len)}, but is {attention_mask.size()}"
392
+ )
393
+ attn_weights = attn_weights + attention_mask
394
+
395
+ # upcast attention to fp32
396
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
397
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
398
+ attn_output = torch.matmul(attn_weights, value_states)
399
+
400
+ if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim):
401
+ raise ValueError(
402
+ f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is"
403
+ f" {attn_output.size()}"
404
+ )
405
+
406
+ attn_output = attn_output.transpose(1, 2).contiguous()
407
+ attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
408
+
409
+ attn_output = self.out_proj(attn_output)
410
+
411
+ return attn_output, attn_weights
412
+
413
+
414
+ class SiglipFlashAttention2(SiglipAttention):
415
+ """
416
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
417
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
418
+ flash attention and deal with padding tokens in case the input contains any of them.
419
+ """
420
+
421
+ def __init__(self, *args, **kwargs):
422
+ super().__init__(*args, **kwargs)
423
+ self.is_causal = False # Hack to make sure we don't use a causal mask
424
+
425
+ def forward(
426
+ self,
427
+ hidden_states: torch.Tensor,
428
+ attention_mask: Optional[torch.LongTensor] = None,
429
+ position_ids: Optional[torch.LongTensor] = None,
430
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
431
+ output_attentions: bool = False,
432
+ use_cache: bool = False,
433
+ **kwargs,
434
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
435
+ output_attentions = False
436
+
437
+ bsz, q_len, _ = hidden_states.size()
438
+
439
+ query_states = self.q_proj(hidden_states)
440
+ key_states = self.k_proj(hidden_states)
441
+ value_states = self.v_proj(hidden_states)
442
+
443
+ # Flash attention requires the input to have the shape
444
+ # batch_size x seq_length x head_dim x hidden_dim
445
+ # therefore we just need to keep the original shape
446
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
447
+ key_states = key_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
448
+ value_states = value_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
449
+
450
+ kv_seq_len = key_states.shape[-2]
451
+ if past_key_value is not None:
452
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
453
+ # cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
454
+ # query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
455
+
456
+ # if past_key_value is not None:
457
+ # cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
458
+ # key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
459
+
460
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
461
+ # to be able to avoid many of these transpose/reshape/view.
462
+ query_states = query_states.transpose(1, 2)
463
+ key_states = key_states.transpose(1, 2)
464
+ value_states = value_states.transpose(1, 2)
465
+
466
+ dropout_rate = self.dropout if self.training else 0.0
467
+
468
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
469
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
470
+ # cast them back in the correct dtype just to be sure everything works as expected.
471
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
472
+ # in fp32. (LlamaRMSNorm handles it correctly)
473
+
474
+ input_dtype = query_states.dtype
475
+ if input_dtype == torch.float32:
476
+ if torch.is_autocast_enabled():
477
+ target_dtype = torch.get_autocast_gpu_dtype()
478
+ # Handle the case where the model is quantized
479
+ elif hasattr(self.config, "_pre_quantization_dtype"):
480
+ target_dtype = self.config._pre_quantization_dtype
481
+ else:
482
+ target_dtype = self.q_proj.weight.dtype
483
+
484
+ logger.warning_once(
485
+ "The input hidden states seems to be silently casted in float32, this might be related to the fact"
486
+ " you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
487
+ f" {target_dtype}."
488
+ )
489
+
490
+ query_states = query_states.to(target_dtype)
491
+ key_states = key_states.to(target_dtype)
492
+ value_states = value_states.to(target_dtype)
493
+
494
+ attn_output = self._flash_attention_forward(
495
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
496
+ )
497
+
498
+ attn_output = attn_output.reshape(bsz, q_len, self.embed_dim).contiguous()
499
+ attn_output = self.out_proj(attn_output)
500
+
501
+ if not output_attentions:
502
+ attn_weights = None
503
+
504
+ return attn_output, attn_weights
505
+
506
+ def _flash_attention_forward(
507
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
508
+ ):
509
+ """
510
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
511
+ first unpad the input, then computes the attention scores and pad the final attention scores.
512
+ Args:
513
+ query_states (`torch.Tensor`):
514
+ Input query states to be passed to Flash Attention API
515
+ key_states (`torch.Tensor`):
516
+ Input key states to be passed to Flash Attention API
517
+ value_states (`torch.Tensor`):
518
+ Input value states to be passed to Flash Attention API
519
+ attention_mask (`torch.Tensor`):
520
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
521
+ position of padding tokens and 1 for the position of non-padding tokens.
522
+ dropout (`int`, *optional*):
523
+ Attention dropout
524
+ softmax_scale (`float`, *optional*):
525
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
526
+ """
527
+
528
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
529
+ causal = self.is_causal and query_length != 1
530
+
531
+ # Contains at least one padding token in the sequence
532
+ if attention_mask is not None:
533
+ batch_size = query_states.shape[0]
534
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
535
+ query_states, key_states, value_states, attention_mask, query_length
536
+ )
537
+
538
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
539
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
540
+
541
+ attn_output_unpad = flash_attn_varlen_func(
542
+ query_states,
543
+ key_states,
544
+ value_states,
545
+ cu_seqlens_q=cu_seqlens_q,
546
+ cu_seqlens_k=cu_seqlens_k,
547
+ max_seqlen_q=max_seqlen_in_batch_q,
548
+ max_seqlen_k=max_seqlen_in_batch_k,
549
+ dropout_p=dropout,
550
+ softmax_scale=softmax_scale,
551
+ causal=causal,
552
+ )
553
+
554
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
555
+ else:
556
+ attn_output = flash_attn_func(
557
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
558
+ )
559
+
560
+ return attn_output
561
+
562
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
563
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
564
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
565
+
566
+ key_layer = index_first_axis(
567
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
568
+ )
569
+ value_layer = index_first_axis(
570
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
571
+ )
572
+ if query_length == kv_seq_len:
573
+ query_layer = index_first_axis(
574
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
575
+ )
576
+ cu_seqlens_q = cu_seqlens_k
577
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
578
+ indices_q = indices_k
579
+ elif query_length == 1:
580
+ max_seqlen_in_batch_q = 1
581
+ cu_seqlens_q = torch.arange(
582
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
583
+ ) # There is a memcpy here, that is very bad.
584
+ indices_q = cu_seqlens_q[:-1]
585
+ query_layer = query_layer.squeeze(1)
586
+ else:
587
+ # The -q_len: slice assumes left padding.
588
+ attention_mask = attention_mask[:, -query_length:]
589
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
590
+
591
+ return (
592
+ query_layer,
593
+ key_layer,
594
+ value_layer,
595
+ indices_q,
596
+ (cu_seqlens_q, cu_seqlens_k),
597
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
598
+ )
599
+
600
+
601
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Siglip
602
+ class SiglipMLP(nn.Module):
603
+ def __init__(self, config):
604
+ super().__init__()
605
+ self.config = config
606
+ self.activation_fn = ACT2FN[config.hidden_act]
607
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
608
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
609
+
610
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
611
+ hidden_states = self.fc1(hidden_states)
612
+ hidden_states = self.activation_fn(hidden_states)
613
+ hidden_states = self.fc2(hidden_states)
614
+ return hidden_states
615
+
616
+
617
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->Siglip
618
+ class SiglipEncoderLayer(nn.Module):
619
+ def __init__(self, config: SiglipVisionConfig):
620
+ super().__init__()
621
+ self.embed_dim = config.hidden_size
622
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
623
+ self.self_attn = (
624
+ SiglipAttention(config)
625
+ if not self._use_flash_attention_2
626
+ else SiglipFlashAttention2(config)
627
+ )
628
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
629
+ self.mlp = SiglipMLP(config)
630
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
631
+
632
+ def forward(
633
+ self,
634
+ hidden_states: torch.Tensor,
635
+ attention_mask: torch.Tensor,
636
+ output_attentions: Optional[bool] = False,
637
+ ) -> Tuple[torch.FloatTensor]:
638
+ """
639
+ Args:
640
+ hidden_states (`torch.FloatTensor`):
641
+ Input to the layer of shape `(batch, seq_len, embed_dim)`.
642
+ attention_mask (`torch.FloatTensor`):
643
+ Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
644
+ output_attentions (`bool`, *optional*, defaults to `False`):
645
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
646
+ returned tensors for more detail.
647
+ """
648
+ residual = hidden_states
649
+
650
+ hidden_states = self.layer_norm1(hidden_states)
651
+ hidden_states, attn_weights = self.self_attn(
652
+ hidden_states=hidden_states,
653
+ attention_mask=attention_mask,
654
+ output_attentions=output_attentions,
655
+ )
656
+ hidden_states = residual + hidden_states
657
+
658
+ residual = hidden_states
659
+ hidden_states = self.layer_norm2(hidden_states)
660
+ hidden_states = self.mlp(hidden_states)
661
+ hidden_states = residual + hidden_states
662
+
663
+ outputs = (hidden_states,)
664
+
665
+ if output_attentions:
666
+ outputs += (attn_weights,)
667
+
668
+ return outputs
669
+
670
+
671
+ class SiglipPreTrainedModel(PreTrainedModel):
672
+ """
673
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
674
+ models.
675
+ """
676
+
677
+ config_class = SiglipVisionConfig
678
+ base_model_prefix = "siglip"
679
+ supports_gradient_checkpointing = True
680
+
681
+ def _init_weights(self, module):
682
+ """Initialize the weights"""
683
+
684
+ if isinstance(module, SiglipVisionEmbeddings):
685
+ width = self.config.hidden_size
686
+ nn.init.normal_(module.position_embedding.weight, std=1 / np.sqrt(width))
687
+ elif isinstance(module, nn.Embedding):
688
+ default_flax_embed_init(module.weight)
689
+ elif isinstance(module, SiglipAttention):
690
+ nn.init.normal_(module.q_proj.weight)
691
+ nn.init.normal_(module.k_proj.weight)
692
+ nn.init.normal_(module.v_proj.weight)
693
+ nn.init.normal_(module.out_proj.weight)
694
+ nn.init.zeros_(module.q_proj.bias)
695
+ nn.init.zeros_(module.k_proj.bias)
696
+ nn.init.zeros_(module.v_proj.bias)
697
+ nn.init.zeros_(module.out_proj.bias)
698
+ elif isinstance(module, SiglipMLP):
699
+ nn.init.normal_(module.fc1.weight)
700
+ nn.init.normal_(module.fc2.weight)
701
+ nn.init.normal_(module.fc1.bias, std=1e-6)
702
+ nn.init.normal_(module.fc2.bias, std=1e-6)
703
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
704
+ lecun_normal_(module.weight)
705
+ if module.bias is not None:
706
+ nn.init.zeros_(module.bias)
707
+ elif isinstance(module, nn.LayerNorm):
708
+ module.bias.data.zero_()
709
+ module.weight.data.fill_(1.0)
710
+
711
+
712
+ SIGLIP_START_DOCSTRING = r"""
713
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
714
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
715
+ etc.)
716
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
717
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
718
+ and behavior.
719
+ Parameters:
720
+ config ([`SiglipVisionConfig`]): Model configuration class with all the parameters of the model.
721
+ Initializing with a config file does not load the weights associated with the model, only the
722
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
723
+ """
724
+
725
+
726
+ SIGLIP_VISION_INPUTS_DOCSTRING = r"""
727
+ Args:
728
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
729
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
730
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
731
+ output_attentions (`bool`, *optional*):
732
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
733
+ tensors for more detail.
734
+ output_hidden_states (`bool`, *optional*):
735
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
736
+ more detail.
737
+ return_dict (`bool`, *optional*):
738
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
739
+ """
740
+
741
+
742
+ # Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->Siglip
743
+ class SiglipEncoder(nn.Module):
744
+ """
745
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
746
+ [`SiglipEncoderLayer`].
747
+ Args:
748
+ config: SiglipConfig
749
+ """
750
+
751
+ def __init__(self, config: SiglipVisionConfig):
752
+ super().__init__()
753
+ self.config = config
754
+ self.layers = nn.ModuleList([SiglipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
755
+ self.gradient_checkpointing = False
756
+
757
+ # Ignore copy
758
+ def forward(
759
+ self,
760
+ inputs_embeds,
761
+ attention_mask: Optional[torch.Tensor] = None,
762
+ output_attentions: Optional[bool] = None,
763
+ output_hidden_states: Optional[bool] = None,
764
+ return_dict: Optional[bool] = None,
765
+ ) -> Union[Tuple, BaseModelOutput]:
766
+ r"""
767
+ Args:
768
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
769
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
770
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
771
+ than the model's internal embedding lookup matrix.
772
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
773
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
774
+ - 1 for tokens that are **not masked**,
775
+ - 0 for tokens that are **masked**.
776
+ [What are attention masks?](../glossary#attention-mask)
777
+ output_attentions (`bool`, *optional*):
778
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
779
+ returned tensors for more detail.
780
+ output_hidden_states (`bool`, *optional*):
781
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
782
+ for more detail.
783
+ return_dict (`bool`, *optional*):
784
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
785
+ """
786
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
787
+ output_hidden_states = (
788
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
789
+ )
790
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
791
+
792
+ encoder_states = () if output_hidden_states else None
793
+ all_attentions = () if output_attentions else None
794
+
795
+ hidden_states = inputs_embeds
796
+ for encoder_layer in self.layers:
797
+ if output_hidden_states:
798
+ encoder_states = encoder_states + (hidden_states,)
799
+ if self.gradient_checkpointing and self.training:
800
+ layer_outputs = self._gradient_checkpointing_func(
801
+ encoder_layer.__call__,
802
+ hidden_states,
803
+ attention_mask,
804
+ output_attentions,
805
+ )
806
+ else:
807
+ layer_outputs = encoder_layer(
808
+ hidden_states,
809
+ attention_mask,
810
+ output_attentions=output_attentions,
811
+ )
812
+
813
+ hidden_states = layer_outputs[0]
814
+
815
+ if output_attentions:
816
+ all_attentions = all_attentions + (layer_outputs[1],)
817
+
818
+ if output_hidden_states:
819
+ encoder_states = encoder_states + (hidden_states,)
820
+
821
+ if not return_dict:
822
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
823
+ return BaseModelOutput(
824
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
825
+ )
826
+
827
+ @add_start_docstrings(
828
+ """The vision model from SigLIP without any head or projection on top.""",
829
+ SIGLIP_START_DOCSTRING
830
+ )
831
+ class SiglipVisionTransformer(SiglipPreTrainedModel):
832
+ config_class = SiglipVisionConfig
833
+ main_input_name = "pixel_values"
834
+ _supports_flash_attn_2 = True
835
+
836
+ def __init__(self, config: SiglipVisionConfig):
837
+ super().__init__(config)
838
+ self.config = config
839
+ embed_dim = config.hidden_size
840
+
841
+ self.embeddings = SiglipVisionEmbeddings(config)
842
+ self.encoder = SiglipEncoder(config)
843
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
844
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
845
+
846
+ # Initialize weights and apply final processing
847
+ self.post_init()
848
+
849
+ def get_input_embeddings(self) -> nn.Module:
850
+ return self.embeddings.patch_embedding
851
+
852
+ @add_start_docstrings_to_model_forward(SIGLIP_VISION_INPUTS_DOCSTRING)
853
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipVisionConfig)
854
+ def forward(
855
+ self,
856
+ pixel_values,
857
+ patch_attention_mask: Optional[torch.BoolTensor] = None,
858
+ tgt_sizes: Optional[torch.IntTensor] = None,
859
+ output_attentions: Optional[bool] = None,
860
+ output_hidden_states: Optional[bool] = None,
861
+ return_dict: Optional[bool] = None,
862
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
863
+ r"""
864
+ Returns:
865
+ """
866
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
867
+ output_hidden_states = (
868
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
869
+ )
870
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
871
+
872
+ hidden_states = self.embeddings(pixel_values=pixel_values, patch_attention_mask=patch_attention_mask, tgt_sizes=tgt_sizes)
873
+
874
+ encoder_outputs = self.encoder(
875
+ inputs_embeds=hidden_states,
876
+ attention_mask=None,
877
+ output_attentions=output_attentions,
878
+ output_hidden_states=output_hidden_states,
879
+ return_dict=return_dict,
880
+ )
881
+
882
+ last_hidden_state = encoder_outputs[0]
883
+ last_hidden_state = self.post_layernorm(last_hidden_state)
884
+
885
+ if not return_dict:
886
+ return (last_hidden_state, None) + encoder_outputs[1:]
887
+
888
+ return BaseModelOutputWithPooling(
889
+ last_hidden_state=last_hidden_state,
890
+ pooler_output=None,
891
+ hidden_states=encoder_outputs.hidden_states,
892
+ attentions=encoder_outputs.attentions,
893
+ )
patched_resampler.py ADDED
@@ -0,0 +1,771 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+ from typing import Optional, Tuple
3
+ import numpy as np
4
+ import warnings
5
+
6
+ import torch
7
+ from torch import nn
8
+ from torch import Tensor
9
+ import torch.nn.functional as F
10
+ from torch.nn.functional import *
11
+ from torch.nn.modules.activation import *
12
+ from torch.nn.init import trunc_normal_, constant_, xavier_normal_, xavier_uniform_
13
+
14
+ from transformers.integrations import is_deepspeed_zero3_enabled
15
+
16
+ def get_2d_sincos_pos_embed(embed_dim, image_size):
17
+ """
18
+ image_size: image_size or (image_height, image_width)
19
+ return:
20
+ pos_embed: [image_height, image_width, embed_dim]
21
+ """
22
+ if isinstance(image_size, int):
23
+ grid_h_size, grid_w_size = image_size, image_size
24
+ else:
25
+ grid_h_size, grid_w_size = image_size[0], image_size[1]
26
+
27
+ grid_h = np.arange(grid_h_size, dtype=np.float32)
28
+ grid_w = np.arange(grid_w_size, dtype=np.float32)
29
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
30
+ grid = np.stack(grid, axis=0)
31
+
32
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
33
+ return pos_embed
34
+
35
+
36
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
37
+ assert embed_dim % 2 == 0
38
+
39
+ # use half of dimensions to encode grid_h
40
+ emb_h = get_1d_sincos_pos_embed_from_grid_new(embed_dim // 2, grid[0]) # (H, W, D/2)
41
+ emb_w = get_1d_sincos_pos_embed_from_grid_new(embed_dim // 2, grid[1]) # (H, W, D/2)
42
+
43
+ emb = np.concatenate([emb_h, emb_w], axis=-1) # (H, W, D)
44
+ return emb
45
+
46
+
47
+ def get_1d_sincos_pos_embed_from_grid_new(embed_dim, pos):
48
+ """
49
+ embed_dim: output dimension for each position
50
+ pos: a list of positions to be encoded: size (H, W)
51
+ out: (H, W, D)
52
+ """
53
+ assert embed_dim % 2 == 0
54
+ omega = np.arange(embed_dim // 2, dtype=np.float32)
55
+ omega /= embed_dim / 2.
56
+ omega = 1. / 10000 ** omega # (D/2,)
57
+
58
+ out = np.einsum('hw,d->hwd', pos, omega) # (H, W, D/2), outer product
59
+
60
+ emb_sin = np.sin(out) # (H, W, D/2)
61
+ emb_cos = np.cos(out) # (H, W, D/2)
62
+
63
+ emb = np.concatenate([emb_sin, emb_cos], axis=-1) # (H, W, D)
64
+ return emb
65
+
66
+
67
+ class Resampler(nn.Module):
68
+ """
69
+ A 2D perceiver-resampler network with one cross attention layers by
70
+ given learnable queries and 2d sincos pos_emb
71
+ Outputs:
72
+ A tensor with the shape of (batch_size, num_queries, embed_dim)
73
+ """
74
+
75
+ def __init__(
76
+ self,
77
+ num_queries,
78
+ embed_dim,
79
+ num_heads,
80
+ kv_dim=None,
81
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
82
+ adaptive=False,
83
+ max_size=(70, 70),
84
+ ):
85
+ super().__init__()
86
+ self.num_queries = num_queries
87
+ self.embed_dim = embed_dim
88
+ self.num_heads = num_heads
89
+ self.adaptive = adaptive
90
+ self.max_size = max_size
91
+
92
+ self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
93
+
94
+ if kv_dim is not None and kv_dim != embed_dim:
95
+ self.kv_proj = nn.Linear(kv_dim, embed_dim, bias=False)
96
+ else:
97
+ self.kv_proj = nn.Identity()
98
+
99
+ self.attn = MultiheadAttention(embed_dim, num_heads)
100
+ self.ln_q = norm_layer(embed_dim)
101
+ self.ln_kv = norm_layer(embed_dim)
102
+
103
+ self.ln_post = norm_layer(embed_dim)
104
+ self.proj = nn.Parameter((embed_dim ** -0.5) * torch.randn(embed_dim, embed_dim))
105
+
106
+ self._set_2d_pos_cache(self.max_size)
107
+ self._adjust_pos_cache([32,32])
108
+ pos_embed = []
109
+ # for i in range(bs):
110
+ tgt_h, tgt_w = 32, 32
111
+ pos_embed.append(self.pos_embed[:tgt_h, :tgt_w, :].reshape((tgt_h * tgt_w, -1))) # patches * D
112
+ # key_padding_mask[:, patch_len:] = True
113
+ self.pos_embed = torch.nn.utils.rnn.pad_sequence(
114
+ pos_embed, batch_first=True, padding_value=0.0).permute(1, 0, 2) # BLD => L * B * D
115
+
116
+ def _set_2d_pos_cache(self, max_size, device='cpu'):
117
+ if is_deepspeed_zero3_enabled():
118
+ device='cuda'
119
+ pos_embed = torch.from_numpy(get_2d_sincos_pos_embed(self.embed_dim, max_size)).float().to(device)
120
+ self.register_buffer("pos_embed", pos_embed, persistent=False)
121
+
122
+ def _adjust_pos_cache(self, tgt_sizes, device):
123
+ max_h = 32
124
+ max_w = 32
125
+ if max_h > self.max_size[0] or max_w > self.max_size[1]:
126
+ self.max_size = [max(max_h, self.max_size[0]), max(max_w, self.max_size[1])]
127
+ self._set_2d_pos_cache(self.max_size, device)
128
+
129
+ def _init_weights(self, m):
130
+ if isinstance(m, nn.Linear):
131
+ trunc_normal_(m.weight, std=.02)
132
+ if isinstance(m, nn.Linear) and m.bias is not None:
133
+ nn.init.constant_(m.bias, 0)
134
+ elif isinstance(m, nn.LayerNorm):
135
+ nn.init.constant_(m.bias, 0)
136
+ nn.init.constant_(m.weight, 1.0)
137
+
138
+ def forward(self, x, tgt_sizes=None):
139
+ dtype = x.dtype
140
+
141
+
142
+ x = self.kv_proj(x) # B * L * D
143
+ x = self.ln_kv(x).permute(1, 0, 2) # L * B * D
144
+
145
+ q = self.ln_q(self.query) # Q * D
146
+
147
+ out = self.attn(
148
+ q.unsqueeze(1), # Q * B * D
149
+ x + self.pos_embed.to(dtype), # L * B * D + L * B * D
150
+ x,
151
+ key_padding_mask=None)[0]
152
+ # out: Q * B * D
153
+ x = out.permute(1, 0, 2) # B * Q * D
154
+
155
+ x = self.ln_post(x)
156
+ x = x @ self.proj
157
+ return x
158
+
159
+ def _repeat(self, query, N: int):
160
+ return query.unsqueeze(1).repeat(1, N, 1)
161
+
162
+
163
+ class MultiheadAttention(nn.MultiheadAttention):
164
+ def __init__(self, embed_dim, num_heads, dropout=0., bias=True, add_bias_kv=False,
165
+ add_zero_attn=False, kdim=None, vdim=None, batch_first=False, device=None, dtype=None):
166
+ super().__init__(embed_dim, num_heads, dropout, bias, add_bias_kv, add_zero_attn, kdim, vdim, batch_first, device, dtype)
167
+
168
+ # rewrite out_proj layer,with nn.Linear
169
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias, device=device, dtype=dtype)
170
+
171
+ def forward(
172
+ self,
173
+ query: Tensor,
174
+ key: Tensor,
175
+ value: Tensor,
176
+ key_padding_mask: Optional[Tensor] = None,
177
+ need_weights: bool = True,
178
+ attn_mask: Optional[Tensor] = None,
179
+ average_attn_weights: bool = True,
180
+ is_causal : bool = False) -> Tuple[Tensor, Optional[Tensor]]:
181
+ why_not_fast_path = ''
182
+ if ((attn_mask is not None and torch.is_floating_point(attn_mask))
183
+ or (key_padding_mask is not None) and torch.is_floating_point(key_padding_mask)):
184
+ why_not_fast_path = "floating-point masks are not supported for fast path."
185
+
186
+ is_batched = query.dim() == 3
187
+
188
+ key_padding_mask = _canonical_mask(
189
+ mask=key_padding_mask,
190
+ mask_name="key_padding_mask",
191
+ other_type=F._none_or_dtype(attn_mask),
192
+ other_name="attn_mask",
193
+ target_type=query.dtype
194
+ )
195
+
196
+ attn_mask = _canonical_mask(
197
+ mask=attn_mask,
198
+ mask_name="attn_mask",
199
+ other_type=None,
200
+ other_name="",
201
+ target_type=query.dtype,
202
+ check_other=False,
203
+ )
204
+
205
+
206
+ if not is_batched:
207
+ why_not_fast_path = f"input not batched; expected query.dim() of 3 but got {query.dim()}"
208
+ elif query is not key or key is not value:
209
+ # When lifting this restriction, don't forget to either
210
+ # enforce that the dtypes all match or test cases where
211
+ # they don't!
212
+ why_not_fast_path = "non-self attention was used (query, key, and value are not the same Tensor)"
213
+ elif self.in_proj_bias is not None and query.dtype != self.in_proj_bias.dtype:
214
+ why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_bias ({self.in_proj_bias.dtype}) don't match"
215
+ elif self.in_proj_weight is None:
216
+ why_not_fast_path = "in_proj_weight was None"
217
+ elif query.dtype != self.in_proj_weight.dtype:
218
+ # this case will fail anyway, but at least they'll get a useful error message.
219
+ why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_weight ({self.in_proj_weight.dtype}) don't match"
220
+ elif self.training:
221
+ why_not_fast_path = "training is enabled"
222
+ elif (self.num_heads % 2) != 0:
223
+ why_not_fast_path = "self.num_heads is not even"
224
+ elif not self.batch_first:
225
+ why_not_fast_path = "batch_first was not True"
226
+ elif self.bias_k is not None:
227
+ why_not_fast_path = "self.bias_k was not None"
228
+ elif self.bias_v is not None:
229
+ why_not_fast_path = "self.bias_v was not None"
230
+ elif self.add_zero_attn:
231
+ why_not_fast_path = "add_zero_attn was enabled"
232
+ elif not self._qkv_same_embed_dim:
233
+ why_not_fast_path = "_qkv_same_embed_dim was not True"
234
+ elif query.is_nested and (key_padding_mask is not None or attn_mask is not None):
235
+ why_not_fast_path = "supplying both src_key_padding_mask and src_mask at the same time \
236
+ is not supported with NestedTensor input"
237
+ elif torch.is_autocast_enabled():
238
+ why_not_fast_path = "autocast is enabled"
239
+
240
+ if not why_not_fast_path:
241
+ tensor_args = (
242
+ query,
243
+ key,
244
+ value,
245
+ self.in_proj_weight,
246
+ self.in_proj_bias,
247
+ self.out_proj.weight,
248
+ self.out_proj.bias,
249
+ )
250
+ # We have to use list comprehensions below because TorchScript does not support
251
+ # generator expressions.
252
+ if torch.overrides.has_torch_function(tensor_args):
253
+ why_not_fast_path = "some Tensor argument has_torch_function"
254
+ elif _is_make_fx_tracing():
255
+ why_not_fast_path = "we are running make_fx tracing"
256
+ elif not all(_check_arg_device(x) for x in tensor_args):
257
+ why_not_fast_path = ("some Tensor argument's device is neither one of "
258
+ f"cpu, cuda or {torch.utils.backend_registration._privateuse1_backend_name}")
259
+ elif torch.is_grad_enabled() and any(_arg_requires_grad(x) for x in tensor_args):
260
+ why_not_fast_path = ("grad is enabled and at least one of query or the "
261
+ "input/output projection weights or biases requires_grad")
262
+ if not why_not_fast_path:
263
+ merged_mask, mask_type = self.merge_masks(attn_mask, key_padding_mask, query)
264
+
265
+ if self.in_proj_bias is not None and self.in_proj_weight is not None:
266
+ return torch._native_multi_head_attention(
267
+ query,
268
+ key,
269
+ value,
270
+ self.embed_dim,
271
+ self.num_heads,
272
+ self.in_proj_weight,
273
+ self.in_proj_bias,
274
+ self.out_proj.weight,
275
+ self.out_proj.bias,
276
+ merged_mask,
277
+ need_weights,
278
+ average_attn_weights,
279
+ mask_type)
280
+
281
+ any_nested = query.is_nested or key.is_nested or value.is_nested
282
+ assert not any_nested, ("MultiheadAttention does not support NestedTensor outside of its fast path. " +
283
+ f"The fast path was not hit because {why_not_fast_path}")
284
+
285
+ if self.batch_first and is_batched:
286
+ # make sure that the transpose op does not affect the "is" property
287
+ if key is value:
288
+ if query is key:
289
+ query = key = value = query.transpose(1, 0)
290
+ else:
291
+ query, key = (x.transpose(1, 0) for x in (query, key))
292
+ value = key
293
+ else:
294
+ query, key, value = (x.transpose(1, 0) for x in (query, key, value))
295
+
296
+ if not self._qkv_same_embed_dim:
297
+ attn_output, attn_output_weights = self.multi_head_attention_forward(
298
+ query, key, value, self.embed_dim, self.num_heads,
299
+ self.in_proj_weight, self.in_proj_bias,
300
+ self.bias_k, self.bias_v, self.add_zero_attn,
301
+ self.dropout, self.out_proj.weight, self.out_proj.bias,
302
+ training=self.training,
303
+ key_padding_mask=key_padding_mask, need_weights=need_weights,
304
+ attn_mask=attn_mask,
305
+ use_separate_proj_weight=True,
306
+ q_proj_weight=self.q_proj_weight, k_proj_weight=self.k_proj_weight,
307
+ v_proj_weight=self.v_proj_weight,
308
+ average_attn_weights=average_attn_weights,
309
+ is_causal=is_causal)
310
+ else:
311
+ attn_output, attn_output_weights = self.multi_head_attention_forward(
312
+ query, key, value, self.embed_dim, self.num_heads,
313
+ self.in_proj_weight, self.in_proj_bias,
314
+ self.bias_k, self.bias_v, self.add_zero_attn,
315
+ self.dropout, self.out_proj.weight, self.out_proj.bias,
316
+ training=self.training,
317
+ key_padding_mask=key_padding_mask,
318
+ need_weights=need_weights,
319
+ attn_mask=attn_mask,
320
+ average_attn_weights=average_attn_weights,
321
+ is_causal=is_causal)
322
+ if self.batch_first and is_batched:
323
+ return attn_output.transpose(1, 0), attn_output_weights
324
+ else:
325
+ return attn_output, attn_output_weights
326
+
327
+ def multi_head_attention_forward(
328
+ self,
329
+ query: Tensor,
330
+ key: Tensor,
331
+ value: Tensor,
332
+ embed_dim_to_check: int,
333
+ num_heads: int,
334
+ in_proj_weight: Optional[Tensor],
335
+ in_proj_bias: Optional[Tensor],
336
+ bias_k: Optional[Tensor],
337
+ bias_v: Optional[Tensor],
338
+ add_zero_attn: bool,
339
+ dropout_p: float,
340
+ out_proj_weight: Tensor,
341
+ out_proj_bias: Optional[Tensor],
342
+ training: bool = True,
343
+ key_padding_mask: Optional[Tensor] = None,
344
+ need_weights: bool = True,
345
+ attn_mask: Optional[Tensor] = None,
346
+ use_separate_proj_weight: bool = False,
347
+ q_proj_weight: Optional[Tensor] = None,
348
+ k_proj_weight: Optional[Tensor] = None,
349
+ v_proj_weight: Optional[Tensor] = None,
350
+ static_k: Optional[Tensor] = None,
351
+ static_v: Optional[Tensor] = None,
352
+ average_attn_weights: bool = True,
353
+ is_causal: bool = False,
354
+ ) -> Tuple[Tensor, Optional[Tensor]]:
355
+ tens_ops = (query, key, value, in_proj_weight, in_proj_bias, bias_k, bias_v, out_proj_weight, out_proj_bias)
356
+
357
+ is_batched = _mha_shape_check(query, key, value, key_padding_mask, attn_mask, num_heads)
358
+
359
+ # For unbatched input, we unsqueeze at the expected batch-dim to pretend that the input
360
+ # is batched, run the computation and before returning squeeze the
361
+ # batch dimension so that the output doesn't carry this temporary batch dimension.
362
+ if not is_batched:
363
+ # unsqueeze if the input is unbatched
364
+ query = query.unsqueeze(1)
365
+ key = key.unsqueeze(1)
366
+ value = value.unsqueeze(1)
367
+ if key_padding_mask is not None:
368
+ key_padding_mask = key_padding_mask.unsqueeze(0)
369
+
370
+ # set up shape vars
371
+ tgt_len, bsz, embed_dim = query.shape
372
+ src_len, _, _ = key.shape
373
+
374
+ key_padding_mask = _canonical_mask(
375
+ mask=key_padding_mask,
376
+ mask_name="key_padding_mask",
377
+ other_type=_none_or_dtype(attn_mask),
378
+ other_name="attn_mask",
379
+ target_type=query.dtype
380
+ )
381
+
382
+ if is_causal and attn_mask is None:
383
+ raise RuntimeError(
384
+ "Need attn_mask if specifying the is_causal hint. "
385
+ "You may use the Transformer module method "
386
+ "`generate_square_subsequent_mask` to create this mask."
387
+ )
388
+
389
+ if is_causal and key_padding_mask is None and not need_weights:
390
+ # when we have a kpm or need weights, we need attn_mask
391
+ # Otherwise, we use the is_causal hint go as is_causal
392
+ # indicator to SDPA.
393
+ attn_mask = None
394
+ else:
395
+ attn_mask = _canonical_mask(
396
+ mask=attn_mask,
397
+ mask_name="attn_mask",
398
+ other_type=None,
399
+ other_name="",
400
+ target_type=query.dtype,
401
+ check_other=False,
402
+ )
403
+
404
+ if key_padding_mask is not None:
405
+ # We have the attn_mask, and use that to merge kpm into it.
406
+ # Turn off use of is_causal hint, as the merged mask is no
407
+ # longer causal.
408
+ is_causal = False
409
+
410
+ assert embed_dim == embed_dim_to_check, \
411
+ f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}"
412
+ if isinstance(embed_dim, torch.Tensor):
413
+ # embed_dim can be a tensor when JIT tracing
414
+ head_dim = embed_dim.div(num_heads, rounding_mode='trunc')
415
+ else:
416
+ head_dim = embed_dim // num_heads
417
+ assert head_dim * num_heads == embed_dim, f"embed_dim {embed_dim} not divisible by num_heads {num_heads}"
418
+ if use_separate_proj_weight:
419
+ # allow MHA to have different embedding dimensions when separate projection weights are used
420
+ assert key.shape[:2] == value.shape[:2], \
421
+ f"key's sequence and batch dims {key.shape[:2]} do not match value's {value.shape[:2]}"
422
+ else:
423
+ assert key.shape == value.shape, f"key shape {key.shape} does not match value shape {value.shape}"
424
+
425
+ #
426
+ # compute in-projection
427
+ #
428
+ if not use_separate_proj_weight:
429
+ assert in_proj_weight is not None, "use_separate_proj_weight is False but in_proj_weight is None"
430
+ q, k, v = _in_projection_packed(query, key, value, in_proj_weight, in_proj_bias)
431
+ else:
432
+ assert q_proj_weight is not None, "use_separate_proj_weight is True but q_proj_weight is None"
433
+ assert k_proj_weight is not None, "use_separate_proj_weight is True but k_proj_weight is None"
434
+ assert v_proj_weight is not None, "use_separate_proj_weight is True but v_proj_weight is None"
435
+ if in_proj_bias is None:
436
+ b_q = b_k = b_v = None
437
+ else:
438
+ b_q, b_k, b_v = in_proj_bias.chunk(3)
439
+ q, k, v = _in_projection(query, key, value, q_proj_weight, k_proj_weight, v_proj_weight, b_q, b_k, b_v)
440
+
441
+ # prep attention mask
442
+
443
+ if attn_mask is not None:
444
+ # ensure attn_mask's dim is 3
445
+ if attn_mask.dim() == 2:
446
+ correct_2d_size = (tgt_len, src_len)
447
+ if attn_mask.shape != correct_2d_size:
448
+ raise RuntimeError(f"The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}.")
449
+ attn_mask = attn_mask.unsqueeze(0)
450
+ elif attn_mask.dim() == 3:
451
+ correct_3d_size = (bsz * num_heads, tgt_len, src_len)
452
+ if attn_mask.shape != correct_3d_size:
453
+ raise RuntimeError(f"The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}.")
454
+ else:
455
+ raise RuntimeError(f"attn_mask's dimension {attn_mask.dim()} is not supported")
456
+
457
+ # add bias along batch dimension (currently second)
458
+ if bias_k is not None and bias_v is not None:
459
+ assert static_k is None, "bias cannot be added to static key."
460
+ assert static_v is None, "bias cannot be added to static value."
461
+ k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
462
+ v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
463
+ if attn_mask is not None:
464
+ attn_mask = pad(attn_mask, (0, 1))
465
+ if key_padding_mask is not None:
466
+ key_padding_mask = pad(key_padding_mask, (0, 1))
467
+ else:
468
+ assert bias_k is None
469
+ assert bias_v is None
470
+
471
+ #
472
+ # reshape q, k, v for multihead attention and make em batch first
473
+ #
474
+ q = q.view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
475
+ if static_k is None:
476
+ k = k.view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
477
+ else:
478
+ # TODO finish disentangling control flow so we don't do in-projections when statics are passed
479
+ assert static_k.size(0) == bsz * num_heads, \
480
+ f"expecting static_k.size(0) of {bsz * num_heads}, but got {static_k.size(0)}"
481
+ assert static_k.size(2) == head_dim, \
482
+ f"expecting static_k.size(2) of {head_dim}, but got {static_k.size(2)}"
483
+ k = static_k
484
+ if static_v is None:
485
+ v = v.view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
486
+ else:
487
+ # TODO finish disentangling control flow so we don't do in-projections when statics are passed
488
+ assert static_v.size(0) == bsz * num_heads, \
489
+ f"expecting static_v.size(0) of {bsz * num_heads}, but got {static_v.size(0)}"
490
+ assert static_v.size(2) == head_dim, \
491
+ f"expecting static_v.size(2) of {head_dim}, but got {static_v.size(2)}"
492
+ v = static_v
493
+
494
+ # add zero attention along batch dimension (now first)
495
+ if add_zero_attn:
496
+ zero_attn_shape = (bsz * num_heads, 1, head_dim)
497
+ k = torch.cat([k, torch.zeros(zero_attn_shape, dtype=k.dtype, device=k.device)], dim=1)
498
+ v = torch.cat([v, torch.zeros(zero_attn_shape, dtype=v.dtype, device=v.device)], dim=1)
499
+ if attn_mask is not None:
500
+ attn_mask = pad(attn_mask, (0, 1))
501
+ if key_padding_mask is not None:
502
+ key_padding_mask = pad(key_padding_mask, (0, 1))
503
+
504
+ # update source sequence length after adjustments
505
+ src_len = k.size(1)
506
+
507
+ # merge key padding and attention masks
508
+ if key_padding_mask is not None:
509
+ assert key_padding_mask.shape == (bsz, src_len), \
510
+ f"expecting key_padding_mask shape of {(bsz, src_len)}, but got {key_padding_mask.shape}"
511
+ key_padding_mask = key_padding_mask.view(bsz, 1, 1, src_len). \
512
+ expand(-1, num_heads, -1, -1).reshape(bsz * num_heads, 1, src_len)
513
+ if attn_mask is None:
514
+ attn_mask = key_padding_mask
515
+ else:
516
+ attn_mask = attn_mask + key_padding_mask
517
+
518
+ # adjust dropout probability
519
+ if not training:
520
+ dropout_p = 0.0
521
+
522
+ #
523
+ # (deep breath) calculate attention and out projection
524
+ #
525
+
526
+ if need_weights:
527
+ B, Nt, E = 28, 64, 128
528
+ q_scaled = q / math.sqrt(E)
529
+
530
+ assert not (is_causal and attn_mask is None), "FIXME: is_causal not implemented for need_weights"
531
+
532
+ if attn_mask is not None:
533
+ attn_output_weights = torch.baddbmm(attn_mask, q_scaled, k.transpose(-2, -1))
534
+ else:
535
+ attn_output_weights = torch.bmm(q_scaled, k.transpose(-2, -1))
536
+ attn_output_weights = softmax(attn_output_weights, dim=-1)
537
+ if dropout_p > 0.0:
538
+ attn_output_weights = dropout(attn_output_weights, p=dropout_p)
539
+
540
+ attn_output = torch.bmm(attn_output_weights, v)
541
+
542
+ attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len * bsz, embed_dim)
543
+ attn_output = self.out_proj(attn_output)
544
+ attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
545
+
546
+ # optionally average attention weights over heads
547
+ attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
548
+ if average_attn_weights:
549
+ attn_output_weights = attn_output_weights.mean(dim=1)
550
+
551
+ if not is_batched:
552
+ # squeeze the output if input was unbatched
553
+ attn_output = attn_output.squeeze(1)
554
+ attn_output_weights = attn_output_weights.squeeze(0)
555
+ return attn_output, attn_output_weights
556
+ else:
557
+ # attn_mask can be either (L,S) or (N*num_heads, L, S)
558
+ # if attn_mask's shape is (1, L, S) we need to unsqueeze to (1, 1, L, S)
559
+ # in order to match the input for SDPA of (N, num_heads, L, S)
560
+ if attn_mask is not None:
561
+ if attn_mask.size(0) == 1 and attn_mask.dim() == 3:
562
+ attn_mask = attn_mask.unsqueeze(0)
563
+ else:
564
+ attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
565
+
566
+ q = q.view(bsz, num_heads, tgt_len, head_dim)
567
+ k = k.view(bsz, num_heads, src_len, head_dim)
568
+ v = v.view(bsz, num_heads, src_len, head_dim)
569
+
570
+ attn_output = F.scaled_dot_product_attention(q, k, v, attn_mask, dropout_p, is_causal)
571
+ attn_output = attn_output.permute(2, 0, 1, 3).contiguous().view(bsz * tgt_len, embed_dim)
572
+
573
+ attn_output = self.out_proj(attn_output)
574
+ attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
575
+ if not is_batched:
576
+ # squeeze the output if input was unbatched
577
+ attn_output = attn_output.squeeze(1)
578
+ return attn_output, None
579
+
580
+
581
+ def _mha_shape_check(query: Tensor, key: Tensor, value: Tensor,
582
+ key_padding_mask: Optional[Tensor], attn_mask: Optional[Tensor], num_heads: int):
583
+ # Verifies the expected shape for `query, `key`, `value`, `key_padding_mask` and `attn_mask`
584
+ # and returns if the input is batched or not.
585
+ # Raises an error if `query` is not 2-D (unbatched) or 3-D (batched) tensor.
586
+
587
+ # Shape check.
588
+ if query.dim() == 3:
589
+ # Batched Inputs
590
+ is_batched = True
591
+ assert key.dim() == 3 and value.dim() == 3, \
592
+ ("For batched (3-D) `query`, expected `key` and `value` to be 3-D"
593
+ f" but found {key.dim()}-D and {value.dim()}-D tensors respectively")
594
+ if key_padding_mask is not None:
595
+ assert key_padding_mask.dim() == 2, \
596
+ ("For batched (3-D) `query`, expected `key_padding_mask` to be `None` or 2-D"
597
+ f" but found {key_padding_mask.dim()}-D tensor instead")
598
+ if attn_mask is not None:
599
+ assert attn_mask.dim() in (2, 3), \
600
+ ("For batched (3-D) `query`, expected `attn_mask` to be `None`, 2-D or 3-D"
601
+ f" but found {attn_mask.dim()}-D tensor instead")
602
+ elif query.dim() == 2:
603
+ # Unbatched Inputs
604
+ is_batched = False
605
+ assert key.dim() == 2 and value.dim() == 2, \
606
+ ("For unbatched (2-D) `query`, expected `key` and `value` to be 2-D"
607
+ f" but found {key.dim()}-D and {value.dim()}-D tensors respectively")
608
+
609
+ if key_padding_mask is not None:
610
+ assert key_padding_mask.dim() == 1, \
611
+ ("For unbatched (2-D) `query`, expected `key_padding_mask` to be `None` or 1-D"
612
+ f" but found {key_padding_mask.dim()}-D tensor instead")
613
+
614
+ if attn_mask is not None:
615
+ assert attn_mask.dim() in (2, 3), \
616
+ ("For unbatched (2-D) `query`, expected `attn_mask` to be `None`, 2-D or 3-D"
617
+ f" but found {attn_mask.dim()}-D tensor instead")
618
+ if attn_mask.dim() == 3:
619
+ expected_shape = (num_heads, query.shape[0], key.shape[0])
620
+ assert attn_mask.shape == expected_shape, \
621
+ (f"Expected `attn_mask` shape to be {expected_shape} but got {attn_mask.shape}")
622
+ else:
623
+ raise AssertionError(
624
+ f"query should be unbatched 2D or batched 3D tensor but received {query.dim()}-D query tensor")
625
+
626
+ return is_batched
627
+
628
+
629
+ def _canonical_mask(
630
+ mask: Optional[Tensor],
631
+ mask_name: str,
632
+ other_type: Optional[DType],
633
+ other_name: str,
634
+ target_type: DType,
635
+ check_other: bool = True,
636
+ ) -> Optional[Tensor]:
637
+
638
+ if mask is not None:
639
+ _mask_dtype = mask.dtype
640
+ _mask_is_float = torch.is_floating_point(mask)
641
+ if _mask_dtype != torch.bool and not _mask_is_float:
642
+ raise AssertionError(
643
+ f"only bool and floating types of {mask_name} are supported")
644
+ if check_other and other_type is not None:
645
+ if _mask_dtype != other_type:
646
+ warnings.warn(
647
+ f"Support for mismatched {mask_name} and {other_name} "
648
+ "is deprecated. Use same type for both instead."
649
+ )
650
+ if not _mask_is_float:
651
+ mask = (
652
+ torch.zeros_like(mask, dtype=target_type)
653
+ .masked_fill_(mask, float("-inf"))
654
+ )
655
+ return mask
656
+
657
+
658
+ def _none_or_dtype(input: Optional[Tensor]) -> Optional[DType]:
659
+ if input is None:
660
+ return None
661
+ elif isinstance(input, torch.Tensor):
662
+ return input.dtype
663
+ raise RuntimeError("input to _none_or_dtype() must be None or torch.Tensor")
664
+
665
+ def _in_projection_packed(
666
+ q: Tensor,
667
+ k: Tensor,
668
+ v: Tensor,
669
+ w: Tensor,
670
+ b: Optional[Tensor] = None,
671
+ ) -> List[Tensor]:
672
+ r"""
673
+ Performs the in-projection step of the attention operation, using packed weights.
674
+ Output is a triple containing projection tensors for query, key and value.
675
+ Args:
676
+ q, k, v: query, key and value tensors to be projected. For self-attention,
677
+ these are typically the same tensor; for encoder-decoder attention,
678
+ k and v are typically the same tensor. (We take advantage of these
679
+ identities for performance if they are present.) Regardless, q, k and v
680
+ must share a common embedding dimension; otherwise their shapes may vary.
681
+ w: projection weights for q, k and v, packed into a single tensor. Weights
682
+ are packed along dimension 0, in q, k, v order.
683
+ b: optional projection biases for q, k and v, packed into a single tensor
684
+ in q, k, v order.
685
+ Shape:
686
+ Inputs:
687
+ - q: :math:`(..., E)` where E is the embedding dimension
688
+ - k: :math:`(..., E)` where E is the embedding dimension
689
+ - v: :math:`(..., E)` where E is the embedding dimension
690
+ - w: :math:`(E * 3, E)` where E is the embedding dimension
691
+ - b: :math:`E * 3` where E is the embedding dimension
692
+ Output:
693
+ - in output list :math:`[q', k', v']`, each output tensor will have the
694
+ same shape as the corresponding input tensor.
695
+ """
696
+ E = q.size(-1)
697
+ if k is v:
698
+ if q is k:
699
+ # self-attention
700
+ proj = linear(q, w, b)
701
+ # reshape to 3, E and not E, 3 is deliberate for better memory coalescing and keeping same order as chunk()
702
+ proj = proj.unflatten(-1, (3, E)).unsqueeze(0).transpose(0, -2).squeeze(-2).contiguous()
703
+ return proj[0], proj[1], proj[2]
704
+ else:
705
+ # encoder-decoder attention
706
+ w_q, w_kv = w.split([E, E * 2])
707
+ if b is None:
708
+ b_q = b_kv = None
709
+ else:
710
+ b_q, b_kv = b.split([E, E * 2])
711
+ q_proj = linear(q, w_q, b_q)
712
+ kv_proj = linear(k, w_kv, b_kv)
713
+ # reshape to 2, E and not E, 2 is deliberate for better memory coalescing and keeping same order as chunk()
714
+ kv_proj = kv_proj.unflatten(-1, (2, E)).unsqueeze(0).transpose(0, -2).squeeze(-2).contiguous()
715
+ return (q_proj, kv_proj[0], kv_proj[1])
716
+ else:
717
+ w_q, w_k, w_v = w.chunk(3)
718
+ if b is None:
719
+ b_q = b_k = b_v = None
720
+ else:
721
+ b_q, b_k, b_v = b.chunk(3)
722
+ return linear(q, w_q, b_q), linear(k, w_k, b_k), linear(v, w_v, b_v)
723
+
724
+
725
+ def _in_projection(
726
+ q: Tensor,
727
+ k: Tensor,
728
+ v: Tensor,
729
+ w_q: Tensor,
730
+ w_k: Tensor,
731
+ w_v: Tensor,
732
+ b_q: Optional[Tensor] = None,
733
+ b_k: Optional[Tensor] = None,
734
+ b_v: Optional[Tensor] = None,
735
+ ) -> Tuple[Tensor, Tensor, Tensor]:
736
+ r"""
737
+ Performs the in-projection step of the attention operation. This is simply
738
+ a triple of linear projections, with shape constraints on the weights which
739
+ ensure embedding dimension uniformity in the projected outputs.
740
+ Output is a triple containing projection tensors for query, key and value.
741
+ Args:
742
+ q, k, v: query, key and value tensors to be projected.
743
+ w_q, w_k, w_v: weights for q, k and v, respectively.
744
+ b_q, b_k, b_v: optional biases for q, k and v, respectively.
745
+ Shape:
746
+ Inputs:
747
+ - q: :math:`(Qdims..., Eq)` where Eq is the query embedding dimension and Qdims are any
748
+ number of leading dimensions.
749
+ - k: :math:`(Kdims..., Ek)` where Ek is the key embedding dimension and Kdims are any
750
+ number of leading dimensions.
751
+ - v: :math:`(Vdims..., Ev)` where Ev is the value embedding dimension and Vdims are any
752
+ number of leading dimensions.
753
+ - w_q: :math:`(Eq, Eq)`
754
+ - w_k: :math:`(Eq, Ek)`
755
+ - w_v: :math:`(Eq, Ev)`
756
+ - b_q: :math:`(Eq)`
757
+ - b_k: :math:`(Eq)`
758
+ - b_v: :math:`(Eq)`
759
+ Output: in output triple :math:`(q', k', v')`,
760
+ - q': :math:`[Qdims..., Eq]`
761
+ - k': :math:`[Kdims..., Eq]`
762
+ - v': :math:`[Vdims..., Eq]`
763
+ """
764
+ Eq, Ek, Ev = q.size(-1), k.size(-1), v.size(-1)
765
+ assert w_q.shape == (Eq, Eq), f"expecting query weights shape of {(Eq, Eq)}, but got {w_q.shape}"
766
+ assert w_k.shape == (Eq, Ek), f"expecting key weights shape of {(Eq, Ek)}, but got {w_k.shape}"
767
+ assert w_v.shape == (Eq, Ev), f"expecting value weights shape of {(Eq, Ev)}, but got {w_v.shape}"
768
+ assert b_q is None or b_q.shape == (Eq,), f"expecting query bias shape of {(Eq,)}, but got {b_q.shape}"
769
+ assert b_k is None or b_k.shape == (Eq,), f"expecting key bias shape of {(Eq,)}, but got {b_k.shape}"
770
+ assert b_v is None or b_v.shape == (Eq,), f"expecting value bias shape of {(Eq,)}, but got {b_v.shape}"
771
+ return linear(q, w_q, b_q), linear(k, w_k, b_k), linear(v, w_v, b_v)
qwen.rkllm ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34b91108056dc595a3eb4c9f340217160974adf35d4399ac5187eae6f22bb6a0
3
+ size 8681282052
rename_tensors.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import shutil
4
+ import mmap
5
+ import re
6
+
7
+ def rename_tensors():
8
+ # 读取JSON文件
9
+ with open('model.safetensors.index.json', 'r') as f:
10
+ data = json.load(f)
11
+
12
+ # 获取所有唯一的safetensors文件名
13
+ safetensor_files = set(data['weight_map'].values())
14
+
15
+ # 复制并重命名safetensors文件
16
+ for file in safetensor_files:
17
+ new_file = file.replace('model-', 'model-renamed-')
18
+ shutil.copy(file, new_file)
19
+
20
+ # 在新文件的前1MB范围内替换字符串
21
+ with open(new_file, 'r+b') as f:
22
+ mm = mmap.mmap(f.fileno(), 1024*1024) # 映射前1MB
23
+ content = mm.read()
24
+ # 使用字节字符串进行替换
25
+ content = content.replace(b'"llm.', b' "')
26
+ mm.seek(0)
27
+ mm.write(content)
28
+ mm.close()
29
+
30
+ # 更新JSON数据
31
+ new_weight_map = {}
32
+ for key, value in data['weight_map'].items():
33
+ new_key = re.sub(r'^llm\.', '', key)
34
+ new_value = value.replace('model-', 'model-renamed-')
35
+ new_weight_map[new_key] = new_value
36
+
37
+ data['weight_map'] = new_weight_map
38
+
39
+ # 写入新的JSON文件
40
+ with open('model-renamed.safetensors.index.json', 'w') as f:
41
+ json.dump(data, f, indent=2)
42
+
43
+ print("处理完成。新的JSON文件已生成:model-renamed.safetensors.index.json")
44
+
45
+ if __name__ == "__main__":
46
+ rename_tensors()
rkllm-convert.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from rkllm.api import RKLLM
2
+
3
+ modelpath = '.'
4
+ llm = RKLLM()
5
+
6
+ ret = llm.load_huggingface(model=modelpath, model_lora=None, device='cpu')
7
+ if ret != 0:
8
+ print('Load model failed!')
9
+ exit(ret)
10
+
11
+ qparams = None
12
+ ret = llm.build(do_quantization=True, optimization_level=1, quantized_dtype='w8a8_g128',
13
+ quantized_algorithm='normal', target_platform='rk3588', num_npu_core=3, extra_qparams=qparams)
14
+
15
+ if ret != 0:
16
+ print('Build model failed!')
17
+ exit(ret)
18
+
19
+ # Export rkllm model
20
+ ret = llm.export_rkllm("./qwen.rkllm")
21
+ if ret != 0:
22
+ print('Export model failed!')
23
+ exit(ret)
rkllm_binding.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ctypes
2
+ import numpy as np
3
+ from enum import IntEnum
4
+ from typing import Callable, Any
5
+
6
+ # Load the shared library
7
+ _lib = ctypes.CDLL("librkllmrt.so") # Adjust the library name if necessary
8
+
9
+ # Define enums
10
+ class LLMCallState(IntEnum):
11
+ RKLLM_RUN_NORMAL = 0
12
+ RKLLM_RUN_WAITING = 1
13
+ RKLLM_RUN_FINISH = 2
14
+ RKLLM_RUN_ERROR = 3
15
+ RKLLM_RUN_GET_LAST_HIDDEN_LAYER = 4
16
+
17
+ class RKLLMInputType(IntEnum):
18
+ RKLLM_INPUT_PROMPT = 0
19
+ RKLLM_INPUT_TOKEN = 1
20
+ RKLLM_INPUT_EMBED = 2
21
+ RKLLM_INPUT_MULTIMODAL = 3
22
+
23
+ class RKLLMInferMode(IntEnum):
24
+ RKLLM_INFER_GENERATE = 0
25
+ RKLLM_INFER_GET_LAST_HIDDEN_LAYER = 1
26
+
27
+ # Define structures
28
+ class RKLLMExtendParam(ctypes.Structure):
29
+ _fields_ = [
30
+ ("base_domain_id", ctypes.c_int32),
31
+ ("reserved", ctypes.c_uint8 * 112)
32
+ ]
33
+
34
+ class RKLLMParam(ctypes.Structure):
35
+ _fields_ = [
36
+ ("model_path", ctypes.c_char_p),
37
+ ("max_context_len", ctypes.c_int32),
38
+ ("max_new_tokens", ctypes.c_int32),
39
+ ("top_k", ctypes.c_int32),
40
+ ("top_p", ctypes.c_float),
41
+ ("temperature", ctypes.c_float),
42
+ ("repeat_penalty", ctypes.c_float),
43
+ ("frequency_penalty", ctypes.c_float),
44
+ ("presence_penalty", ctypes.c_float),
45
+ ("mirostat", ctypes.c_int32),
46
+ ("mirostat_tau", ctypes.c_float),
47
+ ("mirostat_eta", ctypes.c_float),
48
+ ("skip_special_token", ctypes.c_bool),
49
+ ("is_async", ctypes.c_bool),
50
+ ("img_start", ctypes.c_char_p),
51
+ ("img_end", ctypes.c_char_p),
52
+ ("img_content", ctypes.c_char_p),
53
+ ("extend_param", RKLLMExtendParam)
54
+ ]
55
+
56
+ class RKLLMLoraAdapter(ctypes.Structure):
57
+ _fields_ = [
58
+ ("lora_adapter_path", ctypes.c_char_p),
59
+ ("lora_adapter_name", ctypes.c_char_p),
60
+ ("scale", ctypes.c_float)
61
+ ]
62
+
63
+ class RKLLMEmbedInput(ctypes.Structure):
64
+ _fields_ = [
65
+ ("embed", ctypes.POINTER(ctypes.c_float)),
66
+ ("n_tokens", ctypes.c_size_t)
67
+ ]
68
+
69
+ class RKLLMTokenInput(ctypes.Structure):
70
+ _fields_ = [
71
+ ("input_ids", ctypes.POINTER(ctypes.c_int32)),
72
+ ("n_tokens", ctypes.c_size_t)
73
+ ]
74
+
75
+ class RKLLMMultiModelInput(ctypes.Structure):
76
+ _fields_ = [
77
+ ("prompt", ctypes.c_char_p),
78
+ ("image_embed", ctypes.POINTER(ctypes.c_float)),
79
+ ("n_image_tokens", ctypes.c_size_t)
80
+ ]
81
+
82
+ class RKLLMInput(ctypes.Structure):
83
+ class _InputUnion(ctypes.Union):
84
+ _fields_ = [
85
+ ("prompt_input", ctypes.c_char_p),
86
+ ("embed_input", RKLLMEmbedInput),
87
+ ("token_input", RKLLMTokenInput),
88
+ ("multimodal_input", RKLLMMultiModelInput)
89
+ ]
90
+ _fields_ = [
91
+ ("input_type", ctypes.c_int),
92
+ ("_input", _InputUnion)
93
+ ]
94
+
95
+ class RKLLMLoraParam(ctypes.Structure):
96
+ _fields_ = [
97
+ ("lora_adapter_name", ctypes.c_char_p)
98
+ ]
99
+
100
+ class RKLLMPromptCacheParam(ctypes.Structure):
101
+ _fields_ = [
102
+ ("save_prompt_cache", ctypes.c_int),
103
+ ("prompt_cache_path", ctypes.c_char_p)
104
+ ]
105
+
106
+ class RKLLMInferParam(ctypes.Structure):
107
+ _fields_ = [
108
+ ("mode", ctypes.c_int),
109
+ ("lora_params", ctypes.POINTER(RKLLMLoraParam)),
110
+ ("prompt_cache_params", ctypes.POINTER(RKLLMPromptCacheParam))
111
+ ]
112
+
113
+ class RKLLMResultLastHiddenLayer(ctypes.Structure):
114
+ _fields_ = [
115
+ ("hidden_states", ctypes.POINTER(ctypes.c_float)),
116
+ ("embd_size", ctypes.c_int),
117
+ ("num_tokens", ctypes.c_int)
118
+ ]
119
+
120
+ class RKLLMResult(ctypes.Structure):
121
+ _fields_ = [
122
+ ("text", ctypes.c_char_p),
123
+ ("token_id", ctypes.c_int32),
124
+ ("last_hidden_layer", RKLLMResultLastHiddenLayer)
125
+ ]
126
+
127
+ # Define callback type
128
+ LLMResultCallback = ctypes.CFUNCTYPE(None, ctypes.POINTER(RKLLMResult), ctypes.c_void_p, ctypes.c_int)
129
+
130
+ # Define function prototypes
131
+ _lib.rkllm_createDefaultParam.restype = RKLLMParam
132
+ _lib.rkllm_init.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(RKLLMParam), LLMResultCallback]
133
+ _lib.rkllm_init.restype = ctypes.c_int
134
+ _lib.rkllm_load_lora.argtypes = [ctypes.c_void_p, ctypes.POINTER(RKLLMLoraAdapter)]
135
+ _lib.rkllm_load_lora.restype = ctypes.c_int
136
+ _lib.rkllm_load_prompt_cache.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
137
+ _lib.rkllm_load_prompt_cache.restype = ctypes.c_int
138
+ _lib.rkllm_release_prompt_cache.argtypes = [ctypes.c_void_p]
139
+ _lib.rkllm_release_prompt_cache.restype = ctypes.c_int
140
+ _lib.rkllm_destroy.argtypes = [ctypes.c_void_p]
141
+ _lib.rkllm_destroy.restype = ctypes.c_int
142
+ _lib.rkllm_run.argtypes = [ctypes.c_void_p, ctypes.POINTER(RKLLMInput), ctypes.POINTER(RKLLMInferParam), ctypes.c_void_p]
143
+ _lib.rkllm_run.restype = ctypes.c_int
144
+ _lib.rkllm_run_async.argtypes = [ctypes.c_void_p, ctypes.POINTER(RKLLMInput), ctypes.POINTER(RKLLMInferParam), ctypes.c_void_p]
145
+ _lib.rkllm_run_async.restype = ctypes.c_int
146
+ _lib.rkllm_abort.argtypes = [ctypes.c_void_p]
147
+ _lib.rkllm_abort.restype = ctypes.c_int
148
+ _lib.rkllm_is_running.argtypes = [ctypes.c_void_p]
149
+ _lib.rkllm_is_running.restype = ctypes.c_int
150
+
151
+ # Python wrapper functions
152
+ def create_default_param() -> RKLLMParam:
153
+ return _lib.rkllm_createDefaultParam()
154
+
155
+ def init(param: RKLLMParam, callback: Callable[[RKLLMResult, Any, LLMCallState], None]) -> ctypes.c_void_p:
156
+ handle = ctypes.c_void_p()
157
+ c_callback = LLMResultCallback(callback)
158
+ status = _lib.rkllm_init(ctypes.byref(handle), ctypes.byref(param), c_callback)
159
+ if status != 0:
160
+ raise RuntimeError(f"Failed to initialize RKLLM: {status}")
161
+ return handle
162
+
163
+ def load_lora(handle: ctypes.c_void_p, lora_adapter: RKLLMLoraAdapter) -> None:
164
+ status = _lib.rkllm_load_lora(handle, ctypes.byref(lora_adapter))
165
+ if status != 0:
166
+ raise RuntimeError(f"Failed to load Lora adapter: {status}")
167
+
168
+ def load_prompt_cache(handle: ctypes.c_void_p, prompt_cache_path: str) -> None:
169
+ status = _lib.rkllm_load_prompt_cache(handle, prompt_cache_path.encode())
170
+ if status != 0:
171
+ raise RuntimeError(f"Failed to load prompt cache: {status}")
172
+
173
+ def release_prompt_cache(handle: ctypes.c_void_p) -> None:
174
+ status = _lib.rkllm_release_prompt_cache(handle)
175
+ if status != 0:
176
+ raise RuntimeError(f"Failed to release prompt cache: {status}")
177
+
178
+ def destroy(handle: ctypes.c_void_p) -> None:
179
+ status = _lib.rkllm_destroy(handle)
180
+ if status != 0:
181
+ raise RuntimeError(f"Failed to destroy RKLLM: {status}")
182
+
183
+ def run(handle: ctypes.c_void_p, rkllm_input: RKLLMInput, rkllm_infer_params: RKLLMInferParam, userdata: Any) -> None:
184
+ status = _lib.rkllm_run(handle, ctypes.byref(rkllm_input), ctypes.byref(rkllm_infer_params), userdata)
185
+ if status != 0:
186
+ raise RuntimeError(f"Failed to run RKLLM: {status}")
187
+
188
+ def run_async(handle: ctypes.c_void_p, rkllm_input: RKLLMInput, rkllm_infer_params: RKLLMInferParam, userdata: Any) -> None:
189
+ status = _lib.rkllm_run_async(handle, ctypes.byref(rkllm_input), ctypes.byref(rkllm_infer_params), userdata)
190
+ if status != 0:
191
+ raise RuntimeError(f"Failed to run RKLLM asynchronously: {status}")
192
+
193
+ def abort(handle: ctypes.c_void_p) -> None:
194
+ status = _lib.rkllm_abort(handle)
195
+ if status != 0:
196
+ raise RuntimeError(f"Failed to abort RKLLM: {status}")
197
+
198
+ def is_running(handle: ctypes.c_void_p) -> bool:
199
+ return _lib.rkllm_is_running(handle) == 0
200
+
201
+ # Helper function to convert numpy array to C array
202
+ def numpy_to_c_array(arr: np.ndarray, c_type):
203
+ return arr.ctypes.data_as(ctypes.POINTER(c_type))
204
+
205
+ # Helper function to create RKLLMInput
206
+ def create_rkllm_input(input_type: RKLLMInputType, **kwargs) -> RKLLMInput:
207
+ rkllm_input = RKLLMInput()
208
+ rkllm_input.input_type = input_type.value
209
+
210
+ if input_type == RKLLMInputType.RKLLM_INPUT_PROMPT:
211
+ rkllm_input._input.prompt_input = kwargs['prompt'].encode()
212
+ elif input_type == RKLLMInputType.RKLLM_INPUT_EMBED:
213
+ embed = kwargs['embed']
214
+ rkllm_input._input.embed_input.embed = numpy_to_c_array(embed, ctypes.c_float)
215
+ # rkllm_input._input.embed_input.n_tokens = embed.shape[1]
216
+ rkllm_input._input.embed_input.n_tokens = embed.shape[2]
217
+ elif input_type == RKLLMInputType.RKLLM_INPUT_TOKEN:
218
+ tokens = kwargs['tokens']
219
+ rkllm_input._input.token_input.input_ids = numpy_to_c_array(tokens, ctypes.c_int32)
220
+ rkllm_input._input.token_input.n_tokens = tokens.shape[1]
221
+ elif input_type == RKLLMInputType.RKLLM_INPUT_MULTIMODAL:
222
+ rkllm_input._input.multimodal_input.prompt = kwargs['prompt'].encode()
223
+ image_embed = kwargs['image_embed']
224
+ rkllm_input._input.multimodal_input.image_embed = numpy_to_c_array(image_embed, ctypes.c_float)
225
+ rkllm_input._input.multimodal_input.n_image_tokens = image_embed.shape[1]
226
+
227
+ return rkllm_input
run_rknn.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import numpy as np
4
+ from rkllm_binding import *
5
+ from rknnlite.api.rknn_lite import RKNNLite
6
+ import signal
7
+ import cv2
8
+
9
+ MODEL_PATH = "/home/firefly/qwen.rkllm"
10
+ VISION_ENCODER_PATH = "vision_transformer.rknn"
11
+ handle = None
12
+ img_size = 448
13
+
14
+ # exit on ctrl-c
15
+ def signal_handler(signal, frame):
16
+ print("Ctrl-C pressed, exiting...")
17
+ global handle
18
+ if handle:
19
+ abort(handle)
20
+ destroy(handle)
21
+ exit(0)
22
+
23
+ signal.signal(signal.SIGINT, signal_handler)
24
+
25
+ # export RKLLM_LOG_LEVEL=1
26
+ os.environ["RKLLM_LOG_LEVEL"] = "1"
27
+
28
+ inference_count = 0
29
+ inference_start_time = 0
30
+ def result_callback(result, userdata, state):
31
+ global inference_start_time
32
+ global inference_count
33
+ if state == LLMCallState.RKLLM_RUN_NORMAL:
34
+ if inference_count == 0:
35
+ first_token_time = time.time()
36
+ print(f"Time to first token: {first_token_time - inference_start_time:.2f} seconds")
37
+ inference_count += 1
38
+ print(result.contents.text.decode(), end="", flush=True)
39
+ elif state == LLMCallState.RKLLM_RUN_FINISH:
40
+ print("\n\n(finished)")
41
+ elif state == LLMCallState.RKLLM_RUN_ERROR:
42
+ print("\nError occurred during LLM call")
43
+
44
+ # Initialize vision encoder
45
+ vision_encoder = RKNNLite(verbose=False)
46
+ model_size = os.path.getsize(VISION_ENCODER_PATH)
47
+ print(f"Start loading vision encoder model (size: {model_size / 1024 / 1024:.2f} MB)")
48
+ start_time = time.time()
49
+ vision_encoder.load_rknn(VISION_ENCODER_PATH)
50
+ end_time = time.time()
51
+ print(f"Vision encoder loaded in {end_time - start_time:.2f} seconds (speed: {model_size / (end_time - start_time) / 1024 / 1024:.2f} MB/s)")
52
+ vision_encoder.init_runtime()
53
+
54
+ # image embedding
55
+ img_path = "test.jpg"
56
+
57
+ normalize_mean = 0.5
58
+ normalize_std = 0.5
59
+
60
+ img = cv2.imread(img_path)
61
+ img = cv2.resize(img, (img_size, img_size))
62
+ # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
63
+ img = img.astype(np.float32)
64
+ # img = img / 255.0
65
+ # img = (img - normalize_mean) / normalize_std
66
+ img = img[np.newaxis, :, :, :]
67
+ print(img.shape)
68
+ start_time = time.time()
69
+ image_embeddings = vision_encoder.inference(inputs=[img.astype(np.float32)], data_type="float32", data_format="nhwc")[0]
70
+ end_time = time.time()
71
+ print(f"Vision encoder inference time: {end_time - start_time:.2f} seconds")
72
+ print(image_embeddings.flags)
73
+ print(image_embeddings.shape)
74
+ np.save("image_embeddings_rknn.npy", image_embeddings)
75
+
76
+
77
+ vision_encoder.release() # free memory, rockchip plz fix this
78
+
79
+ # Initialize RKLLM
80
+ param = create_default_param()
81
+ param.model_path = MODEL_PATH.encode()
82
+ param.img_start = "<image>".encode()
83
+ param.img_end = "</image>".encode()
84
+ param.img_content = "<unk>".encode()
85
+ extend_param = RKLLMExtendParam()
86
+ extend_param.base_domain_id = 0 # iommu domain 0 for vision encoder
87
+ param.extend_param = extend_param
88
+ model_size = os.path.getsize(MODEL_PATH)
89
+ print(f"Start loading language model (size: {model_size / 1024 / 1024:.2f} MB)")
90
+ start_time = time.time()
91
+ handle = init(param, result_callback)
92
+ end_time = time.time()
93
+ print(f"Language model loaded in {end_time - start_time:.2f} seconds (speed: {model_size / (end_time - start_time) / 1024 / 1024:.2f} MB/s)")
94
+
95
+ # Create input
96
+ prompt = """<|im_start|>system
97
+ You are a helpful assistant.<|im_end|>
98
+ <|im_start|>user
99
+ <image>
100
+ 详细介绍一下这张图片: <|im_end|>
101
+ <|im_start|>assistant
102
+
103
+ """
104
+ # 2.56->3.25>2.41->10.2
105
+ # image_embeddings = np.load("image_embeddings_pth_orig.npy")
106
+ # print(image_embeddings.shape)
107
+ # rkllm_input = create_rkllm_input(RKLLMInputType.RKLLM_INPUT_EMBED, embed=image_embeddings.astype(np.float32))
108
+
109
+ rkllm_input = create_rkllm_input(RKLLMInputType.RKLLM_INPUT_MULTIMODAL, prompt=prompt, image_embed=image_embeddings.astype(np.float32))
110
+
111
+ # Create inference parameters
112
+ infer_param = RKLLMInferParam()
113
+ infer_param.mode = RKLLMInferMode.RKLLM_INFER_GENERATE.value
114
+
115
+ # Run RKLLM
116
+ print("Start inference...")
117
+ inference_start_time = time.time()
118
+ run(handle, rkllm_input, infer_param, None)
119
+
120
+ # Clean up
121
+ destroy(handle)
special_tokens_map.json ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ {
4
+ "content": "<image>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false
9
+ },
10
+ {
11
+ "content": "</image>",
12
+ "lstrip": false,
13
+ "normalized": false,
14
+ "rstrip": false,
15
+ "single_word": false
16
+ },
17
+ {
18
+ "content": "<ref>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ {
25
+ "content": "</ref>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ {
32
+ "content": "<box>",
33
+ "lstrip": false,
34
+ "normalized": false,
35
+ "rstrip": false,
36
+ "single_word": false
37
+ },
38
+ {
39
+ "content": "</box>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false
44
+ },
45
+ {
46
+ "content": "<quad>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false
51
+ },
52
+ {
53
+ "content": "</quad>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false
58
+ },
59
+ {
60
+ "content": "<point>",
61
+ "lstrip": false,
62
+ "normalized": false,
63
+ "rstrip": false,
64
+ "single_word": false
65
+ },
66
+ {
67
+ "content": "</point>",
68
+ "lstrip": false,
69
+ "normalized": false,
70
+ "rstrip": false,
71
+ "single_word": false
72
+ },
73
+ {
74
+ "content": "<slice>",
75
+ "lstrip": false,
76
+ "normalized": false,
77
+ "rstrip": false,
78
+ "single_word": false
79
+ },
80
+ {
81
+ "content": "</slice>",
82
+ "lstrip": false,
83
+ "normalized": false,
84
+ "rstrip": false,
85
+ "single_word": false
86
+ },
87
+ {
88
+ "content": "<image_id>",
89
+ "lstrip": false,
90
+ "normalized": false,
91
+ "rstrip": false,
92
+ "single_word": false
93
+ },
94
+ {
95
+ "content": "</image_id>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": false,
99
+ "single_word": false
100
+ },
101
+ {
102
+ "content": "<|reserved_special_token_0|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false
107
+ },
108
+ {
109
+ "content": "<|reserved_special_token_1|>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": false,
113
+ "single_word": false
114
+ },
115
+ {
116
+ "content": "<|reserved_special_token_2|>",
117
+ "lstrip": false,
118
+ "normalized": false,
119
+ "rstrip": false,
120
+ "single_word": false
121
+ },
122
+ {
123
+ "content": "<|reserved_special_token_3|>",
124
+ "lstrip": false,
125
+ "normalized": false,
126
+ "rstrip": false,
127
+ "single_word": false
128
+ },
129
+ {
130
+ "content": "<|reserved_special_token_4|>",
131
+ "lstrip": false,
132
+ "normalized": false,
133
+ "rstrip": false,
134
+ "single_word": false
135
+ },
136
+ {
137
+ "content": "<|reserved_special_token_5|>",
138
+ "lstrip": false,
139
+ "normalized": false,
140
+ "rstrip": false,
141
+ "single_word": false
142
+ }
143
+ ],
144
+ "bos_token": {
145
+ "content": "<|im_start|>",
146
+ "lstrip": false,
147
+ "normalized": false,
148
+ "rstrip": false,
149
+ "single_word": false
150
+ },
151
+ "eos_token": {
152
+ "content": "<|im_end|>",
153
+ "lstrip": false,
154
+ "normalized": false,
155
+ "rstrip": false,
156
+ "single_word": false
157
+ },
158
+ "pad_token": {
159
+ "content": "<|endoftext|>",
160
+ "lstrip": false,
161
+ "normalized": false,
162
+ "rstrip": false,
163
+ "single_word": false
164
+ },
165
+ "unk_token": {
166
+ "content": "<unk>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false
171
+ }
172
+ }
test.jpg ADDED
tokenization_minicpmv_fast.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.models.qwen2 import Qwen2TokenizerFast
2
+
3
+
4
+ class MiniCPMVTokenizerFast(Qwen2TokenizerFast):
5
+ def __init__(self, **kwargs):
6
+ super().__init__(**kwargs)
7
+ self.im_start = "<image>"
8
+ self.im_end = "</image>"
9
+ self.ref_start = "<ref>"
10
+ self.ref_end = "</ref>"
11
+ self.box_start = "<box>"
12
+ self.box_end = "</box>"
13
+ self.quad_start = "<quad>"
14
+ self.quad_end = "</quad>"
15
+ self.slice_start = "<slice>"
16
+ self.slice_end = "</slice>"
17
+ self.im_id_start = "<image_id>"
18
+ self.im_id_end = "</image_id>"
19
+
20
+ @property
21
+ def eos_id(self):
22
+ return self.eos_token_id
23
+
24
+ @property
25
+ def bos_id(self):
26
+ return self.bos_token_id
27
+
28
+ @property
29
+ def unk_id(self):
30
+ return self.unk_token_id
31
+
32
+ @property
33
+ def im_start_id(self):
34
+ return self.convert_tokens_to_ids(self.im_start)
35
+
36
+ @property
37
+ def im_end_id(self):
38
+ return self.convert_tokens_to_ids(self.im_end)
39
+
40
+ @property
41
+ def slice_start_id(self):
42
+ return self.convert_tokens_to_ids(self.slice_start)
43
+
44
+ @property
45
+ def slice_end_id(self):
46
+ return self.convert_tokens_to_ids(self.slice_end)
47
+
48
+ @property
49
+ def im_id_start_id(self):
50
+ return self.convert_tokens_to_ids(self.im_id_start)
51
+
52
+ @property
53
+ def im_id_end_id(self):
54
+ return self.convert_tokens_to_ids(self.im_id_end)
55
+
56
+ @property
57
+ def newline_id(self):
58
+ return self.convert_tokens_to_ids('\n')
59
+
60
+ @staticmethod
61
+ def escape(text: str) -> str:
62
+ return text
63
+
64
+ @staticmethod
65
+ def unescape(text: str) -> str:
66
+ return text
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "128244": {
5
+ "content": "<unk>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "151643": {
13
+ "content": "<|endoftext|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "151644": {
21
+ "content": "<|im_start|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "151645": {
29
+ "content": "<|im_end|>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "151646": {
37
+ "content": "<image>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "151647": {
45
+ "content": "</image>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "151648": {
53
+ "content": "<ref>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "151649": {
61
+ "content": "</ref>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "151650": {
69
+ "content": "<box>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": true
75
+ },
76
+ "151651": {
77
+ "content": "</box>",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": true
83
+ },
84
+ "151652": {
85
+ "content": "<quad>",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": true
91
+ },
92
+ "151653": {
93
+ "content": "</quad>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": true
99
+ },
100
+ "151654": {
101
+ "content": "<point>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": true
107
+ },
108
+ "151655": {
109
+ "content": "</point>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": false,
113
+ "single_word": false,
114
+ "special": true
115
+ },
116
+ "151656": {
117
+ "content": "<slice>",
118
+ "lstrip": false,
119
+ "normalized": false,
120
+ "rstrip": false,
121
+ "single_word": false,
122
+ "special": true
123
+ },
124
+ "151657": {
125
+ "content": "</slice>",
126
+ "lstrip": false,
127
+ "normalized": false,
128
+ "rstrip": false,
129
+ "single_word": false,
130
+ "special": true
131
+ },
132
+ "151658": {
133
+ "content": "<image_id>",
134
+ "lstrip": false,
135
+ "normalized": false,
136
+ "rstrip": false,
137
+ "single_word": false,
138
+ "special": true
139
+ },
140
+ "151659": {
141
+ "content": "</image_id>",
142
+ "lstrip": false,
143
+ "normalized": false,
144
+ "rstrip": false,
145
+ "single_word": false,
146
+ "special": true
147
+ },
148
+ "151660": {
149
+ "content": "<|reserved_special_token_0|>",
150
+ "lstrip": false,
151
+ "normalized": false,
152
+ "rstrip": false,
153
+ "single_word": false,
154
+ "special": true
155
+ },
156
+ "151661": {
157
+ "content": "<|reserved_special_token_1|>",
158
+ "lstrip": false,
159
+ "normalized": false,
160
+ "rstrip": false,
161
+ "single_word": false,
162
+ "special": true
163
+ },
164
+ "151662": {
165
+ "content": "<|reserved_special_token_2|>",
166
+ "lstrip": false,
167
+ "normalized": false,
168
+ "rstrip": false,
169
+ "single_word": false,
170
+ "special": true
171
+ },
172
+ "151663": {
173
+ "content": "<|reserved_special_token_3|>",
174
+ "lstrip": false,
175
+ "normalized": false,
176
+ "rstrip": false,
177
+ "single_word": false,
178
+ "special": true
179
+ },
180
+ "151664": {
181
+ "content": "<|reserved_special_token_4|>",
182
+ "lstrip": false,
183
+ "normalized": false,
184
+ "rstrip": false,
185
+ "single_word": false,
186
+ "special": true
187
+ },
188
+ "151665": {
189
+ "content": "<|reserved_special_token_5|>",
190
+ "lstrip": false,
191
+ "normalized": false,
192
+ "rstrip": false,
193
+ "single_word": false,
194
+ "special": true
195
+ }
196
+ },
197
+ "additional_special_tokens": [
198
+ "<image>",
199
+ "</image>",
200
+ "<ref>",
201
+ "</ref>",
202
+ "<box>",
203
+ "</box>",
204
+ "<quad>",
205
+ "</quad>",
206
+ "<point>",
207
+ "</point>",
208
+ "<slice>",
209
+ "</slice>",
210
+ "<image_id>",
211
+ "</image_id>",
212
+ "<|reserved_special_token_0|>",
213
+ "<|reserved_special_token_1|>",
214
+ "<|reserved_special_token_2|>",
215
+ "<|reserved_special_token_3|>",
216
+ "<|reserved_special_token_4|>",
217
+ "<|reserved_special_token_5|>"
218
+ ],
219
+ "bos_token": "<|im_start|>",
220
+ "chat_template": "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
221
+ "clean_up_tokenization_spaces": false,
222
+ "eos_token": "<|im_end|>",
223
+ "errors": "replace",
224
+ "model_max_length": 1000000000000000019884624838656,
225
+ "pad_token": "<|endoftext|>",
226
+ "split_special_tokens": false,
227
+ "auto_map": {
228
+ "AutoTokenizer": [
229
+ "tokenization_minicpmv_fast.MiniCPMVTokenizerFast",
230
+ null
231
+ ]
232
+ },
233
+ "tokenizer_class": "MiniCPMVTokenizerFast",
234
+ "unk_token": "<unk>"
235
+ }
vision_convert_rknn.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding: utf-8
3
+
4
+ import os
5
+ from rknn.api import RKNN
6
+ from sys import exit
7
+ import argparse
8
+ import cv2
9
+ import numpy as np
10
+ os.chdir(os.path.dirname(os.path.abspath(__file__)))
11
+
12
+ image_sizes= [[448, 448]]
13
+ batch_sizes = [1]
14
+
15
+ def convert_encoder():
16
+ rknn = RKNN(verbose=True)
17
+
18
+ ONNX_MODEL=f"vision_transformer.onnx"
19
+ RKNN_MODEL=ONNX_MODEL.replace(".onnx",".rknn")
20
+ DATASET="dataset.txt"
21
+ QUANTIZE=False
22
+ input_shapes = [[[batch_size, 3, image_size[0], image_size[1]]] for batch_size in batch_sizes for image_size in image_sizes]
23
+ print(input_shapes)
24
+
25
+ # pre-process config
26
+ print('--> Config model')
27
+ rknn.config(quantized_algorithm='normal', quantized_method='channel', target_platform='rk3588', optimization_level=3,
28
+ mean_values=[128, 128, 128], std_values=[128, 128, 128], dynamic_input=input_shapes) # mean_values=[0.5, 0.5, 0.5], std_values=[0.5, 0.5, 0.5],
29
+ print('done')
30
+
31
+ # Load ONNX model
32
+ print("--> Loading model")
33
+ ret = rknn.load_onnx(
34
+ model=ONNX_MODEL,
35
+ )
36
+
37
+ if ret != 0:
38
+ print('Load model failed!')
39
+ exit(ret)
40
+ print('done')
41
+
42
+ # Build model
43
+ print('--> Building model')
44
+ ret = rknn.build(do_quantization=QUANTIZE, dataset=DATASET, rknn_batch_size=None)
45
+ if ret != 0:
46
+ print('Build model failed!')
47
+ exit(ret)
48
+ print('done')
49
+
50
+ # export
51
+ print('--> Export RKNN model')
52
+ ret = rknn.export_rknn(RKNN_MODEL)
53
+ if ret != 0:
54
+ print('Export RKNN model failed!')
55
+ exit(ret)
56
+ print('done')
57
+ rknn.init_runtime(target='rk3588')
58
+ # # image embedding
59
+ # img_path = "test.jpg"
60
+
61
+ # normalize_mean = [0.5, 0.5, 0.5]
62
+ # normalize_std = [0.5, 0.5, 0.5]
63
+
64
+ # img = cv2.imread(img_path)
65
+ # img = cv2.resize(img, (448, 448))
66
+ # # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
67
+ # img = img.astype(np.float32)
68
+ # # img = (img - normalize_mean) / normalize_std
69
+ # img = img[np.newaxis, :, :, :]
70
+ # img = img.transpose(0, 3, 1, 2)
71
+ # np.save("img.npy", img)
72
+ # rknn.accuracy_analysis(inputs=["img.npy"], target='rk3588')
73
+ # usage: python convert_rknn.py encoder|all
74
+
75
+ if __name__ == "__main__":
76
+ parser = argparse.ArgumentParser()
77
+ parser.add_argument("model", type=str, help="model to convert", choices=["encoder", "all"], nargs='?')
78
+ args = parser.parse_args()
79
+ if args.model is None:
80
+ args.model = "all"
81
+ if args.model == "encoder":
82
+ convert_encoder()
83
+ elif args.model == "all":
84
+ convert_encoder()
85
+ else:
86
+ print(f"Unknown model: {args.model}")
87
+ exit(1)
vision_export_onnx.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
+
5
+ MODEL_PATH = "../MiniCPM-V-2_6/"
6
+ DEVICE_MAP = "cpu"
7
+
8
+ origin_model = AutoModelForCausalLM.from_pretrained(
9
+ MODEL_PATH, trust_remote_code=True, attn_implementation='eager', device_map=DEVICE_MAP).eval()
10
+
11
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)
12
+
13
+ for param in origin_model.parameters():
14
+ param.requires_grad = False
15
+
16
+ class VisionTransformer(torch.nn.Module):
17
+ def __init__(self):
18
+ super().__init__()
19
+ self.vpm = origin_model.vpm
20
+ self.resampler = origin_model.resampler
21
+ self.tgt_sizes = torch.Tensor([[32, 32]]).type(torch.int32)
22
+
23
+ def forward(self, pixel_values):
24
+ vit_embeds = self.vpm(pixel_values).last_hidden_state
25
+ vit_embeds = self.resampler(vit_embeds, self.tgt_sizes)
26
+ return vit_embeds
27
+
28
+
29
+ def convert_vision_transformer():
30
+ model = VisionTransformer()
31
+ IMAGE_SIZE = 448
32
+ pixel_values = torch.randn(
33
+ (1, 3, IMAGE_SIZE, IMAGE_SIZE))
34
+
35
+ # test first
36
+ vit_embeds = model(pixel_values)
37
+ print(vit_embeds.shape) #1x64x3584
38
+ if vit_embeds.shape != (1, 64, 3584):
39
+ raise ValueError("vit_embeds shape is not correct, something is wrong")
40
+
41
+
42
+ torch.onnx.export(model, pixel_values,
43
+ f'vision_transformer.onnx',
44
+ verbose=False,
45
+ input_names=['pixel_values'],
46
+ output_names=['vit_embeds'],
47
+ dynamic_axes={'pixel_values': {0: 'batch_size', 2: 'height', 3: 'width'},
48
+ 'vit_embeds': {0: 'batch_size', 1: 'seq_len'}},
49
+ do_constant_folding=True,
50
+ opset_version=17)
51
+
52
+ if __name__ == "__main__":
53
+ convert_vision_transformer()
vision_transformer.rknn ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d470c9d9b2c2b60fba30fb962a737ca578eb09f3d9d379e0a76684afd300984
3
+ size 988060799
vocab.json ADDED
The diff for this file is too large to render. See raw diff