Upload folder using huggingface_hub (#1)
Browse files- 36e2b847d0531957a4e971a9acdc5318f1a84d6cda625619418d3a1768443313 (3fe15d8830ddfdaf0b60ada92cd8e0c22e168d2d)
- README.md +85 -0
- config.json +165 -0
- configuration.py +116 -0
- generation_config.json +7 -0
- model.safetensors +3 -0
- modeling_tinyllava_elm.py +1917 -0
- smash_config.json +31 -0
- special_tokens_map.json +30 -0
- tokenizer.json +0 -0
- tokenizer.model +3 -0
- tokenizer_config.json +43 -0
README.md
ADDED
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
thumbnail: "https://assets-global.website-files.com/646b351987a8d8ce158d1940/64ec9e96b4334c0e1ac41504_Logo%20with%20white%20text.svg"
|
3 |
+
base_model: jiajunlong/TinyLLaVA-OpenELM-450M-CLIP-0.55B
|
4 |
+
metrics:
|
5 |
+
- memory_disk
|
6 |
+
- memory_inference
|
7 |
+
- inference_latency
|
8 |
+
- inference_throughput
|
9 |
+
- inference_CO2_emissions
|
10 |
+
- inference_energy_consumption
|
11 |
+
tags:
|
12 |
+
- pruna-ai
|
13 |
+
---
|
14 |
+
<!-- header start -->
|
15 |
+
<!-- 200823 -->
|
16 |
+
<div style="width: auto; margin-left: auto; margin-right: auto">
|
17 |
+
<a href="https://www.pruna.ai/" target="_blank" rel="noopener noreferrer">
|
18 |
+
<img src="https://i.imgur.com/eDAlcgk.png" alt="PrunaAI" style="width: 100%; min-width: 400px; display: block; margin: auto;">
|
19 |
+
</a>
|
20 |
+
</div>
|
21 |
+
<!-- header end -->
|
22 |
+
|
23 |
+
[![Twitter](https://img.shields.io/twitter/follow/PrunaAI?style=social)](https://twitter.com/PrunaAI)
|
24 |
+
[![GitHub](https://img.shields.io/github/followers/PrunaAI?label=Follow%20%40PrunaAI&style=social)](https://github.com/PrunaAI)
|
25 |
+
[![LinkedIn](https://img.shields.io/badge/LinkedIn-Connect-blue)](https://www.linkedin.com/company/93832878/admin/feed/posts/?feedType=following)
|
26 |
+
[![Discord](https://img.shields.io/badge/Discord-Join%20Us-blue?style=social&logo=discord)](https://discord.gg/rskEr4BZJx)
|
27 |
+
|
28 |
+
# Simply make AI models cheaper, smaller, faster, and greener!
|
29 |
+
|
30 |
+
- Give a thumbs up if you like this model!
|
31 |
+
- Contact us and tell us which model to compress next [here](https://www.pruna.ai/contact).
|
32 |
+
- Request access to easily compress your *own* AI models [here](https://z0halsaff74.typeform.com/pruna-access?typeform-source=www.pruna.ai).
|
33 |
+
- Read the documentations to know more [here](https://pruna-ai-pruna.readthedocs-hosted.com/en/latest/)
|
34 |
+
- Join Pruna AI community on Discord [here](https://discord.gg/CP4VSgck) to share feedback/suggestions or get help.
|
35 |
+
|
36 |
+
## Results
|
37 |
+
|
38 |
+
![image info](./plots.png)
|
39 |
+
|
40 |
+
**Frequently Asked Questions**
|
41 |
+
- ***How does the compression work?*** The model is compressed with llm-int8.
|
42 |
+
- ***How does the model quality change?*** The quality of the model output might vary compared to the base model.
|
43 |
+
- ***How is the model efficiency evaluated?*** These results were obtained on HARDWARE_NAME with configuration described in `model/smash_config.json` and are obtained after a hardware warmup. The smashed model is directly compared to the original base model. Efficiency results may vary in other settings (e.g. other hardware, image size, batch size, ...). We recommend to directly run them in the use-case conditions to know if the smashed model can benefit you.
|
44 |
+
- ***What is the model format?*** We use safetensors.
|
45 |
+
- ***What calibration data has been used?*** If needed by the compression method, we used WikiText as the calibration data.
|
46 |
+
- ***What is the naming convention for Pruna Huggingface models?*** We take the original model name and append "turbo", "tiny", or "green" if the smashed model has a measured inference speed, inference memory, or inference energy consumption which is less than 90% of the original base model.
|
47 |
+
- ***How to compress my own models?*** You can request premium access to more compression methods and tech support for your specific use-cases [here](https://z0halsaff74.typeform.com/pruna-access?typeform-source=www.pruna.ai).
|
48 |
+
- ***What are "first" metrics?*** Results mentioning "first" are obtained after the first run of the model. The first run might take more memory or be slower than the subsequent runs due cuda overheads.
|
49 |
+
- ***What are "Sync" and "Async" metrics?*** "Sync" metrics are obtained by syncing all GPU processes and stop measurement when all of them are executed. "Async" metrics are obtained without syncing all GPU processes and stop when the model output can be used by the CPU. We provide both metrics since both could be relevant depending on the use-case. We recommend to test the efficiency gains directly in your use-cases.
|
50 |
+
|
51 |
+
## Setup
|
52 |
+
|
53 |
+
You can run the smashed model with these steps:
|
54 |
+
|
55 |
+
0. Check requirements from the original repo jiajunlong/TinyLLaVA-OpenELM-450M-CLIP-0.55B installed. In particular, check python, cuda, and transformers versions.
|
56 |
+
1. Make sure that you have installed quantization related packages.
|
57 |
+
```bash
|
58 |
+
pip install transformers accelerate bitsandbytes>0.37.0
|
59 |
+
```
|
60 |
+
2. Load & run the model.
|
61 |
+
```python
|
62 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
63 |
+
|
64 |
+
|
65 |
+
model = AutoModelForCausalLM.from_pretrained("PrunaAI/jiajunlong-TinyLLaVA-OpenELM-450M-CLIP-0.55B-bnb-4bit-smashed", trust_remote_code=True, device_map='auto')
|
66 |
+
tokenizer = AutoTokenizer.from_pretrained("jiajunlong/TinyLLaVA-OpenELM-450M-CLIP-0.55B")
|
67 |
+
|
68 |
+
input_ids = tokenizer("What is the color of prunes?,", return_tensors='pt').to(model.device)["input_ids"]
|
69 |
+
|
70 |
+
outputs = model.generate(input_ids, max_new_tokens=216)
|
71 |
+
tokenizer.decode(outputs[0])
|
72 |
+
```
|
73 |
+
|
74 |
+
## Configurations
|
75 |
+
|
76 |
+
The configuration info are in `smash_config.json`.
|
77 |
+
|
78 |
+
## Credits & License
|
79 |
+
|
80 |
+
The license of the smashed model follows the license of the original model. Please check the license of the original model jiajunlong/TinyLLaVA-OpenELM-450M-CLIP-0.55B before using this model which provided the base model. The license of the `pruna-engine` is [here](https://pypi.org/project/pruna-engine/) on Pypi.
|
81 |
+
|
82 |
+
## Want to compress other models?
|
83 |
+
|
84 |
+
- Contact us and tell us which model to compress next [here](https://www.pruna.ai/contact).
|
85 |
+
- Request access to easily compress your own AI models [here](https://z0halsaff74.typeform.com/pruna-access?typeform-source=www.pruna.ai).
|
config.json
ADDED
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "/ceph/hdd/staff/charpent/.cache/modelsftw71kavjcm_8tgh",
|
3 |
+
"architectures": [
|
4 |
+
"TinyLlavaForConditionalGeneration"
|
5 |
+
],
|
6 |
+
"auto_map": {
|
7 |
+
"AutoConfig": "configuration.TinyLlavaConfig",
|
8 |
+
"AutoModelForCausalLM": "modeling_tinyllava_elm.TinyLlavaForConditionalGeneration"
|
9 |
+
},
|
10 |
+
"cache_dir": null,
|
11 |
+
"connector_type": "mlp2x_gelu",
|
12 |
+
"hidden_size": 1536,
|
13 |
+
"ignore_index": -100,
|
14 |
+
"image_aspect_ratio": "square",
|
15 |
+
"image_token_index": -200,
|
16 |
+
"llm_model_name_or_path": "apple/OpenELM-450M-Instruct",
|
17 |
+
"model_type": "tinyllava",
|
18 |
+
"num_queries": 128,
|
19 |
+
"num_resampler_layers": 3,
|
20 |
+
"pad_token": "<unk>",
|
21 |
+
"quantization_config": {
|
22 |
+
"_load_in_4bit": true,
|
23 |
+
"_load_in_8bit": false,
|
24 |
+
"bnb_4bit_compute_dtype": "bfloat16",
|
25 |
+
"bnb_4bit_quant_storage": "uint8",
|
26 |
+
"bnb_4bit_quant_type": "fp4",
|
27 |
+
"bnb_4bit_use_double_quant": false,
|
28 |
+
"llm_int8_enable_fp32_cpu_offload": false,
|
29 |
+
"llm_int8_has_fp16_weight": false,
|
30 |
+
"llm_int8_skip_modules": [
|
31 |
+
"lm_head"
|
32 |
+
],
|
33 |
+
"llm_int8_threshold": 6.0,
|
34 |
+
"load_in_4bit": true,
|
35 |
+
"load_in_8bit": false,
|
36 |
+
"quant_method": "bitsandbytes"
|
37 |
+
},
|
38 |
+
"resampler_hidden_size": 768,
|
39 |
+
"text_config": {
|
40 |
+
"_name_or_path": "apple/OpenELM-450M-Instruct",
|
41 |
+
"activation_fn_name": "swish",
|
42 |
+
"architectures": [
|
43 |
+
"OpenELMForCausalLM"
|
44 |
+
],
|
45 |
+
"auto_map": {
|
46 |
+
"AutoConfig": "apple/OpenELM-450M-Instruct--configuration_openelm.OpenELMConfig",
|
47 |
+
"AutoModelForCausalLM": "apple/OpenELM-450M-Instruct--modeling_openelm.OpenELMForCausalLM"
|
48 |
+
},
|
49 |
+
"ffn_dim_divisor": 256,
|
50 |
+
"ffn_multipliers": [
|
51 |
+
0.5,
|
52 |
+
0.68,
|
53 |
+
0.87,
|
54 |
+
1.05,
|
55 |
+
1.24,
|
56 |
+
1.42,
|
57 |
+
1.61,
|
58 |
+
1.79,
|
59 |
+
1.97,
|
60 |
+
2.16,
|
61 |
+
2.34,
|
62 |
+
2.53,
|
63 |
+
2.71,
|
64 |
+
2.89,
|
65 |
+
3.08,
|
66 |
+
3.26,
|
67 |
+
3.45,
|
68 |
+
3.63,
|
69 |
+
3.82,
|
70 |
+
4.0
|
71 |
+
],
|
72 |
+
"ffn_with_glu": true,
|
73 |
+
"head_dim": 64,
|
74 |
+
"max_context_length": 2048,
|
75 |
+
"model_dim": 1536,
|
76 |
+
"model_type": "openelm",
|
77 |
+
"normalization_layer_name": "rms_norm",
|
78 |
+
"normalize_qk_projections": true,
|
79 |
+
"num_gqa_groups": 4,
|
80 |
+
"num_kv_heads": [
|
81 |
+
3,
|
82 |
+
3,
|
83 |
+
3,
|
84 |
+
4,
|
85 |
+
4,
|
86 |
+
4,
|
87 |
+
4,
|
88 |
+
4,
|
89 |
+
4,
|
90 |
+
4,
|
91 |
+
5,
|
92 |
+
5,
|
93 |
+
5,
|
94 |
+
5,
|
95 |
+
5,
|
96 |
+
5,
|
97 |
+
6,
|
98 |
+
6,
|
99 |
+
6,
|
100 |
+
6
|
101 |
+
],
|
102 |
+
"num_query_heads": [
|
103 |
+
12,
|
104 |
+
12,
|
105 |
+
12,
|
106 |
+
16,
|
107 |
+
16,
|
108 |
+
16,
|
109 |
+
16,
|
110 |
+
16,
|
111 |
+
16,
|
112 |
+
16,
|
113 |
+
20,
|
114 |
+
20,
|
115 |
+
20,
|
116 |
+
20,
|
117 |
+
20,
|
118 |
+
20,
|
119 |
+
24,
|
120 |
+
24,
|
121 |
+
24,
|
122 |
+
24
|
123 |
+
],
|
124 |
+
"num_transformer_layers": 20,
|
125 |
+
"qkv_multipliers": [
|
126 |
+
0.5,
|
127 |
+
1.0
|
128 |
+
],
|
129 |
+
"rope_freq_constant": 10000,
|
130 |
+
"rope_max_length": 4096,
|
131 |
+
"share_input_output_layers": true,
|
132 |
+
"tie_word_embeddings": true,
|
133 |
+
"torch_dtype": "float16"
|
134 |
+
},
|
135 |
+
"tokenizer_model_max_length": 2048,
|
136 |
+
"tokenizer_name_or_path": "meta-llama/Llama-2-7b-hf",
|
137 |
+
"tokenizer_padding_side": "right",
|
138 |
+
"tokenizer_use_fast": false,
|
139 |
+
"torch_dtype": "float16",
|
140 |
+
"transformers_version": "4.42.4",
|
141 |
+
"tune_type_connector": "full",
|
142 |
+
"tune_type_llm": "full",
|
143 |
+
"tune_type_vision_tower": "frozen",
|
144 |
+
"tune_vision_tower_from_layer": 0,
|
145 |
+
"use_cache": true,
|
146 |
+
"vision_config": {
|
147 |
+
"dropout": 0.0,
|
148 |
+
"hidden_size": 768,
|
149 |
+
"image_size": 224,
|
150 |
+
"intermediate_size": 3072,
|
151 |
+
"model_name_or_path": "openai/clip-vit-base-patch16",
|
152 |
+
"model_name_or_path2": "",
|
153 |
+
"model_type": "clip_vision_model",
|
154 |
+
"num_attention_heads": 12,
|
155 |
+
"num_hidden_layers": 12,
|
156 |
+
"patch_size": 16,
|
157 |
+
"projection_dim": 512
|
158 |
+
},
|
159 |
+
"vision_feature_layer": -2,
|
160 |
+
"vision_feature_select_strategy": "patch",
|
161 |
+
"vision_hidden_size": 768,
|
162 |
+
"vision_model_name_or_path": "openai/clip-vit-base-patch16",
|
163 |
+
"vision_model_name_or_path2": "",
|
164 |
+
"vocab_size": 32000
|
165 |
+
}
|
configuration.py
ADDED
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PretrainedConfig
|
2 |
+
from transformers import CONFIG_MAPPING
|
3 |
+
from transformers import AutoConfig
|
4 |
+
|
5 |
+
IGNORE_INDEX = -100
|
6 |
+
IMAGE_TOKEN_INDEX = -200
|
7 |
+
DEFAULT_IMAGE_TOKEN = "<image>"
|
8 |
+
|
9 |
+
|
10 |
+
class TinyLlavaConfig(PretrainedConfig):
|
11 |
+
|
12 |
+
model_type = "tinyllava"
|
13 |
+
def __init__(
|
14 |
+
self,
|
15 |
+
llm_model_name_or_path = '',
|
16 |
+
tokenizer_name_or_path = None,
|
17 |
+
vision_model_name_or_path = '',
|
18 |
+
vision_model_name_or_path2 = '',
|
19 |
+
connector_type = None,
|
20 |
+
text_config=None,
|
21 |
+
hidden_size=2048,
|
22 |
+
vocab_size=32000,
|
23 |
+
ignore_index=-100,
|
24 |
+
image_token_index=32000,
|
25 |
+
pad_token = None,
|
26 |
+
pad_token_id = None,
|
27 |
+
tokenizer_padding_side = 'right',
|
28 |
+
tokenizer_model_max_length = 2048,
|
29 |
+
vision_config = None,
|
30 |
+
vision_hidden_size = None,
|
31 |
+
vision_feature_layer = -2,
|
32 |
+
vision_feature_select_strategy = 'patch',
|
33 |
+
image_aspect_ratio = 'square',
|
34 |
+
resampler_hidden_size = None,
|
35 |
+
num_queries = None,
|
36 |
+
num_resampler_layers = None,
|
37 |
+
use_cache = False,
|
38 |
+
cache_dir = None,
|
39 |
+
tokenizer_use_fast = False,
|
40 |
+
tune_type_llm = 'frozen',
|
41 |
+
tune_type_connector = 'frozen',
|
42 |
+
tune_type_vision_tower = 'frozen',
|
43 |
+
tune_vision_tower_from_layer = -1,
|
44 |
+
|
45 |
+
**kwargs
|
46 |
+
|
47 |
+
):
|
48 |
+
self.llm_model_name_or_path = llm_model_name_or_path
|
49 |
+
self.tokenizer_name_or_path = tokenizer_name_or_path or self.llm_model_name_or_path
|
50 |
+
self.vision_model_name_or_path = vision_model_name_or_path
|
51 |
+
self.vision_model_name_or_path2 = vision_model_name_or_path2
|
52 |
+
self.connector_type = connector_type
|
53 |
+
self.tune_type_llm = tune_type_llm
|
54 |
+
self.tune_type_connector = tune_type_connector
|
55 |
+
self.tune_type_vision_tower = tune_type_vision_tower
|
56 |
+
self.tune_vision_tower_from_layer = tune_vision_tower_from_layer
|
57 |
+
|
58 |
+
self.ignore_index = IGNORE_INDEX
|
59 |
+
self.image_token_index = IMAGE_TOKEN_INDEX
|
60 |
+
self.pad_token = pad_token
|
61 |
+
self.pad_token_id = pad_token_id
|
62 |
+
self.tokenizer_padding_side = tokenizer_padding_side
|
63 |
+
self.tokenizer_model_max_length = tokenizer_model_max_length
|
64 |
+
self.vision_feature_layer = vision_feature_layer
|
65 |
+
self.vision_feature_select_strategy = vision_feature_select_strategy
|
66 |
+
self.image_aspect_ratio = image_aspect_ratio
|
67 |
+
self.resampler_hidden_size = resampler_hidden_size
|
68 |
+
self.num_queries = num_queries
|
69 |
+
self.num_resampler_layers = num_resampler_layers
|
70 |
+
self.use_cache = use_cache
|
71 |
+
self.cache_dir = cache_dir
|
72 |
+
self.tokenizer_use_fast = tokenizer_use_fast
|
73 |
+
self._load_text_config(text_config)
|
74 |
+
self._load_vision_config(vision_config)
|
75 |
+
|
76 |
+
super().__init__(**kwargs)
|
77 |
+
|
78 |
+
|
79 |
+
def _load_text_config(self, text_config=None):
|
80 |
+
if self.llm_model_name_or_path is None or self.llm_model_name_or_path == '':
|
81 |
+
self.text_config = CONFIG_MAPPING['llama']()
|
82 |
+
|
83 |
+
else:
|
84 |
+
self.text_config = AutoConfig.from_pretrained(self.llm_model_name_or_path, trust_remote_code=True)
|
85 |
+
if text_config is not None:
|
86 |
+
self.text_config = self.text_config.from_dict(text_config)
|
87 |
+
|
88 |
+
self.hidden_size = getattr(self.text_config, 'hidden_size', getattr(self.text_config, 'model_dim', None))
|
89 |
+
self.vocab_size = getattr(self.text_config, 'vocab_size', None)
|
90 |
+
|
91 |
+
|
92 |
+
|
93 |
+
def _load_vision_config(self, vision_config=None):
|
94 |
+
if self.vision_model_name_or_path is None or self.vision_model_name_or_path == '':
|
95 |
+
self.vision_config = CONFIG_MAPPING['clip_vision_model'](
|
96 |
+
intermediate_size=4096,
|
97 |
+
hidden_size=1024,
|
98 |
+
patch_size=14,
|
99 |
+
image_size=336,
|
100 |
+
num_hidden_layers=24,
|
101 |
+
num_attention_heads=16,
|
102 |
+
vocab_size=32000,
|
103 |
+
projection_dim=768,
|
104 |
+
)
|
105 |
+
|
106 |
+
else:
|
107 |
+
self.vision_config = AutoConfig.from_pretrained(self.vision_model_name_or_path.split(':')[-1])
|
108 |
+
self.vision_config = getattr(self.vision_config, 'vision_config', self.vision_config)
|
109 |
+
if vision_config is not None:
|
110 |
+
self.vision_config = self.vision_config.from_dict(vision_config)
|
111 |
+
|
112 |
+
self.vision_config.model_name_or_path = self.vision_model_name_or_path.split(':')[-1]
|
113 |
+
self.vision_config.model_name_or_path2 = self.vision_model_name_or_path2.split(':')[-1]
|
114 |
+
self.vision_hidden_size = getattr(self.vision_config, 'hidden_size', None)
|
115 |
+
|
116 |
+
|
generation_config.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 1,
|
4 |
+
"eos_token_id": 2,
|
5 |
+
"transformers_version": "4.42.4",
|
6 |
+
"use_cache": false
|
7 |
+
}
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:3be933c7c77431e642ec1165d7f80d7797c013f4110ae1dedc988a06903401ce
|
3 |
+
size 379556530
|
modeling_tinyllava_elm.py
ADDED
@@ -0,0 +1,1917 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dataclasses import dataclass
|
2 |
+
import dataclasses
|
3 |
+
from typing import List, Optional, Tuple, Union
|
4 |
+
import ast
|
5 |
+
import re
|
6 |
+
from enum import auto, Enum
|
7 |
+
import requests
|
8 |
+
from PIL import Image
|
9 |
+
from io import BytesIO
|
10 |
+
import base64
|
11 |
+
import time
|
12 |
+
|
13 |
+
import torch
|
14 |
+
import torch.utils.checkpoint
|
15 |
+
from torch import nn, Tensor
|
16 |
+
from torch.nn import functional as F
|
17 |
+
|
18 |
+
from transformers import PreTrainedModel
|
19 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
20 |
+
from transformers.generation.utils import GenerateOutput
|
21 |
+
from transformers import CLIPVisionModel, CLIPImageProcessor,SiglipVisionModel, SiglipImageProcessor
|
22 |
+
from transformers import AutoConfig, AutoModelForCausalLM
|
23 |
+
|
24 |
+
from .configuration import TinyLlavaConfig, IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
|
25 |
+
|
26 |
+
# from tinyllava.utils.data_utils import get_value_from_kwargs
|
27 |
+
CONTROLLER_HEART_BEAT_EXPIRATION = 30
|
28 |
+
WORKER_HEART_BEAT_INTERVAL = 15
|
29 |
+
|
30 |
+
LOGDIR = "."
|
31 |
+
import os
|
32 |
+
#
|
33 |
+
# For licensing see accompanying LICENSE file.
|
34 |
+
# Copyright (C) 2024 Apple Inc. All Rights Reserved.
|
35 |
+
#
|
36 |
+
|
37 |
+
from torch.nn import CrossEntropyLoss
|
38 |
+
from transformers.activations import ACT2FN
|
39 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
40 |
+
from transformers.modeling_outputs import (
|
41 |
+
BaseModelOutputWithPast,
|
42 |
+
)
|
43 |
+
from transformers.utils import logging
|
44 |
+
|
45 |
+
logger = logging.get_logger(__name__)
|
46 |
+
|
47 |
+
# this import has to be relative, otherwise, when setting trust_remote_code=True
|
48 |
+
# huggingface transformers won't be able to load the module correctly
|
49 |
+
from numbers import Number
|
50 |
+
from typing import List, Optional, Union
|
51 |
+
|
52 |
+
import numpy as np
|
53 |
+
from transformers import PretrainedConfig, AutoTokenizer
|
54 |
+
|
55 |
+
|
56 |
+
|
57 |
+
logger = logging.get_logger(__name__)
|
58 |
+
|
59 |
+
# Model Constants
|
60 |
+
IGNORE_INDEX = -100
|
61 |
+
IMAGE_TOKEN_INDEX = -200
|
62 |
+
DEFAULT_IMAGE_TOKEN = "<image>"
|
63 |
+
DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
|
64 |
+
DEFAULT_IM_START_TOKEN = "<im_start>"
|
65 |
+
DEFAULT_IM_END_TOKEN = "<im_end>"
|
66 |
+
IMAGE_PLACEHOLDER = "<image-placeholder>"
|
67 |
+
|
68 |
+
CONTROLLER_HEART_BEAT_EXPIRATION = 30
|
69 |
+
WORKER_HEART_BEAT_INTERVAL = 15
|
70 |
+
LOGDIR = "."
|
71 |
+
|
72 |
+
|
73 |
+
class SeparatorStyle(Enum):
|
74 |
+
"""Different separator style."""
|
75 |
+
SINGLE = auto()
|
76 |
+
TWO = auto()
|
77 |
+
MPT = auto()
|
78 |
+
PLAIN = auto()
|
79 |
+
LLAMA_2 = auto()
|
80 |
+
TINY_LLAMA = auto()
|
81 |
+
QWEN_2 = auto()
|
82 |
+
|
83 |
+
|
84 |
+
@dataclasses.dataclass
|
85 |
+
class Conversation:
|
86 |
+
"""A class that keeps all conversation history."""
|
87 |
+
system: str
|
88 |
+
roles: List[str]
|
89 |
+
messages: List[List[str]]
|
90 |
+
offset: int
|
91 |
+
sep_style: SeparatorStyle = SeparatorStyle.SINGLE
|
92 |
+
sep: str = "###"
|
93 |
+
sep2: str = None
|
94 |
+
version: str = "Unknown"
|
95 |
+
|
96 |
+
skip_next: bool = False
|
97 |
+
|
98 |
+
def get_prompt(self):
|
99 |
+
messages = self.messages
|
100 |
+
if len(messages) > 0 and type(messages[0][1]) is tuple:
|
101 |
+
messages = self.messages.copy()
|
102 |
+
init_role, init_msg = messages[0].copy()
|
103 |
+
init_msg = init_msg[0].replace("<image>", "").strip()
|
104 |
+
if 'mmtag' in self.version:
|
105 |
+
messages[0] = (init_role, init_msg)
|
106 |
+
messages.insert(0, (self.roles[0], "<Image><image></Image>"))
|
107 |
+
messages.insert(1, (self.roles[1], "Received."))
|
108 |
+
else:
|
109 |
+
messages[0] = (init_role, "<image>\n" + init_msg)
|
110 |
+
|
111 |
+
if self.sep_style == SeparatorStyle.TWO:
|
112 |
+
seps = [self.sep, self.sep2]
|
113 |
+
ret = self.system + seps[0]
|
114 |
+
for i, (role, message) in enumerate(messages):
|
115 |
+
if message:
|
116 |
+
if type(message) is tuple:
|
117 |
+
message, _, _ = message
|
118 |
+
ret += role + ": " + message + seps[i % 2]
|
119 |
+
else:
|
120 |
+
ret += role + ":"
|
121 |
+
else:
|
122 |
+
raise ValueError(f"Invalid style: {self.sep_style}")
|
123 |
+
|
124 |
+
return ret
|
125 |
+
|
126 |
+
def append_message(self, role, message):
|
127 |
+
self.messages.append([role, message])
|
128 |
+
|
129 |
+
def copy(self):
|
130 |
+
return Conversation(
|
131 |
+
system=self.system,
|
132 |
+
roles=self.roles,
|
133 |
+
messages=[[x, y] for x, y in self.messages],
|
134 |
+
offset=self.offset,
|
135 |
+
sep_style=self.sep_style,
|
136 |
+
sep=self.sep,
|
137 |
+
sep2=self.sep2,
|
138 |
+
version=self.version)
|
139 |
+
|
140 |
+
|
141 |
+
|
142 |
+
|
143 |
+
conv_phi_v0 = Conversation(
|
144 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
145 |
+
"The assistant gives helpful, detailed, and polite answers to the user's questions.",
|
146 |
+
roles=("USER", "ASSISTANT"),
|
147 |
+
version="phi",
|
148 |
+
messages=(),
|
149 |
+
offset=0,
|
150 |
+
sep_style=SeparatorStyle.TWO,
|
151 |
+
sep=" ",
|
152 |
+
sep2="<|endoftext|>",
|
153 |
+
)
|
154 |
+
|
155 |
+
|
156 |
+
def load_image_from_base64(image):
|
157 |
+
return Image.open(BytesIO(base64.b64decode(image)))
|
158 |
+
|
159 |
+
|
160 |
+
def expand2square(pil_img, background_color):
|
161 |
+
width, height = pil_img.size
|
162 |
+
if width == height:
|
163 |
+
return pil_img
|
164 |
+
elif width > height:
|
165 |
+
result = Image.new(pil_img.mode, (width, width), background_color)
|
166 |
+
result.paste(pil_img, (0, (width - height) // 2))
|
167 |
+
return result
|
168 |
+
else:
|
169 |
+
result = Image.new(pil_img.mode, (height, height), background_color)
|
170 |
+
result.paste(pil_img, ((height - width) // 2, 0))
|
171 |
+
return result
|
172 |
+
|
173 |
+
|
174 |
+
def process_images(images, image_processor, model_cfg):
|
175 |
+
image_aspect_ratio = getattr(model_cfg, "image_aspect_ratio", None)
|
176 |
+
new_images = []
|
177 |
+
if image_aspect_ratio == 'pad':
|
178 |
+
for image in images:
|
179 |
+
image = expand2square(image, tuple(int(x*255) for x in image_processor.image_mean))
|
180 |
+
image = image_processor.preprocess(image, return_tensors='pt')['pixel_values'][0]
|
181 |
+
new_images.append(image)
|
182 |
+
else:
|
183 |
+
return image_processor(images, return_tensors='pt')['pixel_values']
|
184 |
+
if all(x.shape == new_images[0].shape for x in new_images):
|
185 |
+
new_images = torch.stack(new_images, dim=0)
|
186 |
+
return new_images
|
187 |
+
|
188 |
+
|
189 |
+
def tokenizer_image_token(prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None):
|
190 |
+
prompt_chunks = [tokenizer(chunk).input_ids for chunk in prompt.split('<image>')]
|
191 |
+
|
192 |
+
def insert_separator(X, sep):
|
193 |
+
return [ele for sublist in zip(X, [sep]*len(X)) for ele in sublist][:-1]
|
194 |
+
|
195 |
+
input_ids = []
|
196 |
+
offset = 0
|
197 |
+
if len(prompt_chunks) > 0 and len(prompt_chunks[0]) > 0 and prompt_chunks[0][0] == tokenizer.bos_token_id:
|
198 |
+
offset = 1
|
199 |
+
input_ids.append(prompt_chunks[0][0])
|
200 |
+
|
201 |
+
for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
|
202 |
+
input_ids.extend(x[offset:])
|
203 |
+
|
204 |
+
if return_tensors is not None:
|
205 |
+
if return_tensors == 'pt':
|
206 |
+
return torch.tensor(input_ids, dtype=torch.long)
|
207 |
+
raise ValueError(f'Unsupported tensor type: {return_tensors}')
|
208 |
+
return input_ids
|
209 |
+
|
210 |
+
def load_image(image_file):
|
211 |
+
if image_file.startswith("http") or image_file.startswith("https"):
|
212 |
+
response = requests.get(image_file)
|
213 |
+
image = Image.open(BytesIO(response.content)).convert("RGB")
|
214 |
+
else:
|
215 |
+
image = Image.open(image_file).convert("RGB")
|
216 |
+
return image
|
217 |
+
|
218 |
+
|
219 |
+
def make_divisible(
|
220 |
+
v: Union[float, int],
|
221 |
+
divisor: Optional[int] = 8,
|
222 |
+
min_value: Optional[Union[float, int]] = None,
|
223 |
+
) -> Union[float, int]:
|
224 |
+
"""
|
225 |
+
This function is taken from the original tf repo.
|
226 |
+
It ensures that all layers have a channel number that is divisible by the divisor
|
227 |
+
It can be seen at:
|
228 |
+
https://github.com/tensorflow/models/blob/2cfc99eff5e5eb729c6793d2f3d03aa1c9be2b15/research/slim/nets/mobilenet/mobilenet.py#L62
|
229 |
+
Args:
|
230 |
+
v: input value
|
231 |
+
divisor: default to 8
|
232 |
+
min_value: minimum divisor value
|
233 |
+
Returns:
|
234 |
+
new_v: new divisible value
|
235 |
+
"""
|
236 |
+
if min_value is None:
|
237 |
+
min_value = divisor
|
238 |
+
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
|
239 |
+
# Make sure that round down does not go down by more than 10%.
|
240 |
+
if new_v < 0.9 * v:
|
241 |
+
new_v += divisor
|
242 |
+
return new_v
|
243 |
+
|
244 |
+
|
245 |
+
def compute_heads(model_dim: int, head_dim: int) -> int:
|
246 |
+
"""Compute the number of heads.
|
247 |
+
Args:
|
248 |
+
model_dim: Model dimension.
|
249 |
+
head_dim: Head dimension.
|
250 |
+
Returns:
|
251 |
+
An integer denoting number of heads in multi-head attention is returned.
|
252 |
+
Raises:
|
253 |
+
ValueError: if model dimension is not divisible by head dimension.
|
254 |
+
"""
|
255 |
+
if model_dim % head_dim == 0:
|
256 |
+
return model_dim // head_dim
|
257 |
+
else:
|
258 |
+
raise ValueError(
|
259 |
+
f"Model dimension should be divisible by head dimension. Got: {model_dim} and {head_dim}."
|
260 |
+
)
|
261 |
+
|
262 |
+
|
263 |
+
OpenELM_CONFIGS = {
|
264 |
+
"OpenELM-270M": dict(
|
265 |
+
num_transformer_layers=16,
|
266 |
+
model_dim=1280,
|
267 |
+
head_dim=64,
|
268 |
+
num_gqa_groups=4,
|
269 |
+
normalize_qk_projections=True,
|
270 |
+
share_input_output_layers=True,
|
271 |
+
# Vary the FFN and QKV multipliers to create variable FFN and attention layers respectively.
|
272 |
+
ffn_multipliers=(0.5, 4.0),
|
273 |
+
qkv_multipliers=(0.5, 1.0),
|
274 |
+
),
|
275 |
+
"OpenELM-450M": dict(
|
276 |
+
num_transformer_layers=20,
|
277 |
+
model_dim=1536,
|
278 |
+
head_dim=64,
|
279 |
+
num_gqa_groups=4,
|
280 |
+
normalize_qk_projections=True,
|
281 |
+
share_input_output_layers=True,
|
282 |
+
# Vary the FFN and QKV multipliers to create variable FFN and attention layers respectively.
|
283 |
+
ffn_multipliers=(0.5, 4.0),
|
284 |
+
qkv_multipliers=(0.5, 1.0),
|
285 |
+
),
|
286 |
+
"OpenELM-1_1B": dict(
|
287 |
+
num_transformer_layers=28,
|
288 |
+
model_dim=2048,
|
289 |
+
head_dim=64,
|
290 |
+
num_gqa_groups=4,
|
291 |
+
normalize_qk_projections=True,
|
292 |
+
share_input_output_layers=True,
|
293 |
+
# Vary the FFN and QKV multipliers to create variable FFN and attention layers respectively.
|
294 |
+
ffn_multipliers=(0.5, 4.0),
|
295 |
+
qkv_multipliers=(0.5, 1.0),
|
296 |
+
),
|
297 |
+
"OpenELM-3B": dict(
|
298 |
+
num_transformer_layers=36,
|
299 |
+
model_dim=3072,
|
300 |
+
head_dim=128,
|
301 |
+
num_gqa_groups=4,
|
302 |
+
normalize_qk_projections=True,
|
303 |
+
share_input_output_layers=True,
|
304 |
+
# Vary the FFN and QKV multipliers to create variable FFN and attention layers respectively.
|
305 |
+
ffn_multipliers=(0.5, 4.0),
|
306 |
+
qkv_multipliers=(0.5, 1.0),
|
307 |
+
),
|
308 |
+
}
|
309 |
+
|
310 |
+
|
311 |
+
class OpenELMConfig(PretrainedConfig):
|
312 |
+
r"""
|
313 |
+
This is the configuration class to store the configuration of a [`OpenELMModel`]. It is used to instantiate an OpenELM model according to the specified arguments, defining the model architecture.
|
314 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
315 |
+
documentation from [`PretrainedConfig`] for more information.
|
316 |
+
Args:
|
317 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
318 |
+
Vocabulary size of the OpenELM model.
|
319 |
+
max_context_length (`int`, *optional*, defaults to 2048):
|
320 |
+
Maximum number of input tokens.
|
321 |
+
num_transformer_layers (`int`, *optional*, defaults to 12):
|
322 |
+
Number of hidden layers in the Transformer decoder.
|
323 |
+
model_dim (`int`, *optional*, defaults to 2048):
|
324 |
+
Dimension of the hidden representations.
|
325 |
+
head_dim (`int`, *optional*, defaults to 128):
|
326 |
+
The attention head dimension.
|
327 |
+
qkv_multipliers (`Union[Number, List[Number]]`, *optional*, defaults to 1.0):
|
328 |
+
If the qkv_multipliers is a Number, then all attention layers have the same latent dimensions,
|
329 |
+
resulting in uniform allocation of parameters.
|
330 |
+
If the qkv_multipliers is a List of Number, then each attention layer have different latent dimensions
|
331 |
+
assuming qkv_multipliers[0] != qkv_multipliers[1]. This results in variable allocation of parameters in attention layer.
|
332 |
+
This scaling is known as layer-wise or block-wise scaling: https://arxiv.org/abs/2008.00623
|
333 |
+
num_query_heads (`Union[int, None]`, *optional*, defaults to None):
|
334 |
+
The number of query heads, computed from `compute_heads(model_dim=model_dim, head_dim=head_dim)`.
|
335 |
+
num_gqa_groups (`int`, *optional*, defaults to 1):
|
336 |
+
This variable allows to switch between multi-head attention, group query attention, and multi-query attention.
|
337 |
+
When num_gqa_groups == 1, then it is multi-head attention.
|
338 |
+
When 1 < num_gqa_groups < num_heads and num_heads is divisible by num_gqa_groups, then it is group query attention
|
339 |
+
When num_gqa_groups == num_heads, then it is multi-query attention
|
340 |
+
ffn_multipliers (`Union[Number, List[Number]]`, *optional*, defaults to 4.0):
|
341 |
+
Feed-forward network (FFN) multipliers.
|
342 |
+
If the ffn_multipliers is a Number, then all FFN layers have the same latent dimensions,
|
343 |
+
resulting in uniform allocation of parameters.
|
344 |
+
If the ffn_multipliers is a List of Number, then each FFN layer have different latent dimensions
|
345 |
+
assuming ffn_multipliers[0] != ffn_multipliers[1]. This results in variable allocation of parameters in FFN layer.
|
346 |
+
This scaling is known as layer-wise or block-wise scaling: https://arxiv.org/abs/2008.00623
|
347 |
+
ffn_with_glu (`bool`, *optional*, defaults to True):
|
348 |
+
Whether to use FFN with Gated Linear Unit (GLU)
|
349 |
+
ffn_dim_divisor (`int`, *optional*, defaults to 256):
|
350 |
+
The ffn layer dimension divisor.
|
351 |
+
activation_fn_name (`str` or `function`, *optional*, defaults to `"swish"`):
|
352 |
+
The non-linear activation function (function or string) in the decoder.
|
353 |
+
normalization_layer_name (`str` or `function`, *optional*, defaults to `"rms_norm"`):
|
354 |
+
Type of normalization layer.
|
355 |
+
normalize_qk_projections (`bool`, *optional*, defaults to False):
|
356 |
+
Whether to normalize queries and keys after projections
|
357 |
+
share_input_output_layers (`bool`, *optional*, defaults to False):
|
358 |
+
Whether to share the embedding between input and output linear layer
|
359 |
+
rope_freq_constant (`int`, *optional*, defaults to 10000):
|
360 |
+
The base period of the RoPE embeddings.
|
361 |
+
rope_max_length (`int`, *optional*, defaults to 4096):
|
362 |
+
That rope_max_length is set to twice of max_context_length.
|
363 |
+
This allows flexibility in token lengths during training or fine-tuning.
|
364 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
365 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
366 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
367 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
368 |
+
relevant if `config.is_decoder=True`.
|
369 |
+
bos_token_id (`int`, *optional*, defaults to 2):
|
370 |
+
Beginning of stream token id.
|
371 |
+
eos_token_id (`int`, *optional*, defaults to 1):
|
372 |
+
End of stream token id.
|
373 |
+
"""
|
374 |
+
|
375 |
+
model_type = "openelm"
|
376 |
+
|
377 |
+
def __init__(
|
378 |
+
self,
|
379 |
+
vocab_size: int = 32000,
|
380 |
+
max_context_length: int = 2048,
|
381 |
+
num_transformer_layers: int = 12,
|
382 |
+
model_dim: int = 2048,
|
383 |
+
head_dim: int = 128,
|
384 |
+
qkv_multipliers: Union[Number, List[Number]] = 1.0,
|
385 |
+
num_query_heads: Union[int, None] = None,
|
386 |
+
num_gqa_groups: int = 1,
|
387 |
+
ffn_multipliers: Union[Number, List[Number]] = 4.0,
|
388 |
+
ffn_with_glu: bool = True,
|
389 |
+
ffn_dim_divisor: int = 256,
|
390 |
+
activation_fn_name: str = "swish",
|
391 |
+
normalization_layer_name: str = "rms_norm",
|
392 |
+
normalize_qk_projections: bool = False,
|
393 |
+
share_input_output_layers: bool = False,
|
394 |
+
rope_freq_constant: int = 10000,
|
395 |
+
rope_max_length: int = 4096,
|
396 |
+
initializer_range: float = 0.02,
|
397 |
+
use_cache: bool = True,
|
398 |
+
bos_token_id: int = 1,
|
399 |
+
eos_token_id: int = 2,
|
400 |
+
**kwargs,
|
401 |
+
) -> None:
|
402 |
+
self.vocab_size = vocab_size
|
403 |
+
self.max_context_length = max_context_length
|
404 |
+
self.num_transformer_layers = num_transformer_layers
|
405 |
+
self.model_dim = model_dim
|
406 |
+
self.head_dim = head_dim
|
407 |
+
self.qkv_multipliers = qkv_multipliers
|
408 |
+
self.num_query_heads = num_query_heads
|
409 |
+
self.num_gqa_groups = num_gqa_groups
|
410 |
+
self.ffn_multipliers = ffn_multipliers
|
411 |
+
self.ffn_with_glu = ffn_with_glu
|
412 |
+
self.ffn_dim_divisor = ffn_dim_divisor
|
413 |
+
self.activation_fn_name = activation_fn_name
|
414 |
+
self.normalization_layer_name = normalization_layer_name
|
415 |
+
self.normalize_qk_projections = normalize_qk_projections
|
416 |
+
self.share_input_output_layers = share_input_output_layers
|
417 |
+
self.rope_freq_constant = rope_freq_constant
|
418 |
+
self.rope_max_length = rope_max_length
|
419 |
+
self.num_query_heads = (
|
420 |
+
compute_heads(model_dim=model_dim, head_dim=head_dim)
|
421 |
+
if num_query_heads is None
|
422 |
+
else num_query_heads
|
423 |
+
)
|
424 |
+
self.initializer_range = initializer_range
|
425 |
+
|
426 |
+
self.__post_init__()
|
427 |
+
super().__init__(
|
428 |
+
use_cache=use_cache,
|
429 |
+
bos_token_id=bos_token_id,
|
430 |
+
eos_token_id=eos_token_id,
|
431 |
+
**kwargs,
|
432 |
+
)
|
433 |
+
|
434 |
+
def __post_init__(self) -> None:
|
435 |
+
if self.num_gqa_groups is not None:
|
436 |
+
head_multiple_of = self.num_gqa_groups
|
437 |
+
else:
|
438 |
+
head_multiple_of = 2
|
439 |
+
|
440 |
+
if isinstance(self.qkv_multipliers, Number):
|
441 |
+
# All attention layers have the same latent dimensions, resulting in uniform allocation of parameters.
|
442 |
+
qkv_dim = make_divisible(
|
443 |
+
self.model_dim * self.qkv_multipliers,
|
444 |
+
divisor=self.head_dim * head_multiple_of,
|
445 |
+
)
|
446 |
+
query_dims = [int(qkv_dim)] * self.num_transformer_layers
|
447 |
+
|
448 |
+
elif (
|
449 |
+
isinstance(self.qkv_multipliers, (tuple, list))
|
450 |
+
and len(self.qkv_multipliers) == 2
|
451 |
+
):
|
452 |
+
# Each attention layer have different latent dimensions assuming qkv_multipliers[0] != qkv_multipliers[1].
|
453 |
+
# This results in variable allocation of parameters in attention layer.
|
454 |
+
# This scaling is known as layer-wise or block-wise scaling: https://arxiv.org/abs/2008.00623
|
455 |
+
qkv_multipliers = [
|
456 |
+
round(v, 2)
|
457 |
+
for v in np.linspace(
|
458 |
+
self.qkv_multipliers[0],
|
459 |
+
self.qkv_multipliers[1],
|
460 |
+
num=self.num_transformer_layers,
|
461 |
+
dtype=float,
|
462 |
+
)
|
463 |
+
]
|
464 |
+
# Make sure that scaled model dimension is divisible by scaled head dimension.
|
465 |
+
query_dims = [
|
466 |
+
int(
|
467 |
+
make_divisible(
|
468 |
+
self.model_dim * m, divisor=self.head_dim * head_multiple_of
|
469 |
+
)
|
470 |
+
)
|
471 |
+
for m in qkv_multipliers
|
472 |
+
]
|
473 |
+
else:
|
474 |
+
raise NotImplementedError(
|
475 |
+
f"QKV multipliers should be a single number or a list containing exactly two numbers. Got: {qkv_multipliers}."
|
476 |
+
)
|
477 |
+
|
478 |
+
# compute the number of query, key, and value heads
|
479 |
+
# For multi-head and multi-query attention, the number of heads for query, key, and value are the same.
|
480 |
+
# For group query attention, the number of key and value heads are the same.
|
481 |
+
self.num_query_heads = [
|
482 |
+
int(compute_heads(q_dim, self.head_dim)) for q_dim in query_dims
|
483 |
+
]
|
484 |
+
self.num_kv_heads = [
|
485 |
+
q_heads // self.num_gqa_groups for q_heads in self.num_query_heads
|
486 |
+
]
|
487 |
+
|
488 |
+
# Feed-forward network (FFN) multipliers
|
489 |
+
if isinstance(self.ffn_multipliers, Number):
|
490 |
+
# All FFN layers have the same latent dimensions, resulting in uniform allocation of parameters.
|
491 |
+
self.ffn_multipliers = [self.ffn_multipliers] * self.num_transformer_layers
|
492 |
+
elif isinstance(self.ffn_multipliers, (tuple, list)):
|
493 |
+
# Each FFN layer have different latent dimensions assuming ffn_multipliers[0] != ffn_multipliers[1].
|
494 |
+
# This results in variable allocation of parameters in FFN layer.
|
495 |
+
# This scaling is known as layer-wise or block-wise scaling: https://arxiv.org/abs/2008.00623
|
496 |
+
if len(self.ffn_multipliers) == 2:
|
497 |
+
self.ffn_multipliers = [
|
498 |
+
round(v, 2)
|
499 |
+
for v in np.linspace(
|
500 |
+
self.ffn_multipliers[0],
|
501 |
+
self.ffn_multipliers[1],
|
502 |
+
num=self.num_transformer_layers,
|
503 |
+
dtype=float,
|
504 |
+
)
|
505 |
+
]
|
506 |
+
else:
|
507 |
+
assert (
|
508 |
+
len(self.ffn_multipliers) == self.num_transformer_layers
|
509 |
+
), f"{len(self.ffn_multipliers)=}!={self.num_transformer_layers=}"
|
510 |
+
else:
|
511 |
+
raise NotImplementedError(
|
512 |
+
f"FFN multipliers should be a single number or a list containing exactly two numbers. Got: {qkv_multipliers}."
|
513 |
+
)
|
514 |
+
|
515 |
+
# check num_query_heads divisible by num_kv_heads for every layer
|
516 |
+
for layer_idx in range(len(query_dims)):
|
517 |
+
assert self.num_query_heads[layer_idx] % self.num_kv_heads[layer_idx] == 0
|
518 |
+
|
519 |
+
class OpenELMRMSNorm(nn.Module):
|
520 |
+
def __init__(self, num_features: int, eps: float = 1e-6):
|
521 |
+
"""
|
522 |
+
Initialize the OpenELMRMSNorm normalization layer.
|
523 |
+
Args:
|
524 |
+
dim (int): The dimension of the input tensor.
|
525 |
+
eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6.
|
526 |
+
Attributes:
|
527 |
+
eps (float): A small value added to the denominator for numerical stability.
|
528 |
+
weight (nn.Parameter): Learnable scaling parameter.
|
529 |
+
"""
|
530 |
+
super().__init__()
|
531 |
+
self.eps = eps
|
532 |
+
self.weight = nn.Parameter(torch.ones(num_features))
|
533 |
+
self.num_features = num_features
|
534 |
+
|
535 |
+
def _norm(self, x: Tensor) -> Tensor:
|
536 |
+
"""
|
537 |
+
Apply the OpenELMRMSNorm normalization to the input tensor.
|
538 |
+
Args:
|
539 |
+
x (torch.Tensor): The input tensor.
|
540 |
+
Returns:
|
541 |
+
torch.Tensor: The normalized tensor.
|
542 |
+
"""
|
543 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
544 |
+
|
545 |
+
def forward(self, x: Tensor) -> Tensor:
|
546 |
+
"""
|
547 |
+
Forward pass through the OpenELMRMSNorm layer.
|
548 |
+
Args:
|
549 |
+
x (torch.Tensor): The input tensor.
|
550 |
+
Returns:
|
551 |
+
torch.Tensor: The output tensor after applying OpenELMRMSNorm.
|
552 |
+
"""
|
553 |
+
output = self._norm(x.float()).type_as(x)
|
554 |
+
return output * self.weight
|
555 |
+
|
556 |
+
def extra_repr(self) -> str:
|
557 |
+
return (
|
558 |
+
super().extra_repr() + f"num_features={self.num_features}, eps={self.eps}"
|
559 |
+
)
|
560 |
+
|
561 |
+
|
562 |
+
class OpenELMPreTrainedModel(PreTrainedModel):
|
563 |
+
config_class = OpenELMConfig
|
564 |
+
base_model_prefix = "transformer"
|
565 |
+
supports_gradient_checkpointing = True
|
566 |
+
_no_split_modules = ["OpenELMDecoderLayer"]
|
567 |
+
_skip_keys_device_placement = "past_key_values"
|
568 |
+
|
569 |
+
def __init__(self, *inputs, **kwargs) -> None:
|
570 |
+
super().__init__(*inputs, **kwargs)
|
571 |
+
|
572 |
+
def _init_weights(self, module: nn.Module) -> None:
|
573 |
+
"""Initialize the weights."""
|
574 |
+
if isinstance(module, nn.Linear):
|
575 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
576 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
577 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
578 |
+
if module.bias is not None:
|
579 |
+
module.bias.data.zero_()
|
580 |
+
elif isinstance(module, nn.Embedding):
|
581 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
582 |
+
if module.padding_idx is not None:
|
583 |
+
module.weight.data[module.padding_idx].zero_()
|
584 |
+
elif isinstance(module, OpenELMRMSNorm):
|
585 |
+
module.weight.data.fill_(1.0)
|
586 |
+
|
587 |
+
|
588 |
+
def _rotate_half(x: Tensor) -> Tensor:
|
589 |
+
x1, x2 = x.chunk(2, dim=-1)
|
590 |
+
return torch.cat((-x2, x1), dim=-1)
|
591 |
+
|
592 |
+
|
593 |
+
def _apply_rotary_pos_emb(x: Tensor, pos_sin: Tensor, pos_cos: Tensor) -> Tensor:
|
594 |
+
return (x * pos_cos) + (_rotate_half(x) * pos_sin)
|
595 |
+
|
596 |
+
|
597 |
+
class OpenELMRotaryEmbedding(torch.nn.Module):
|
598 |
+
"""
|
599 |
+
The rotary position embeddings (aka RoPE) from `RoFormer <https://arxiv.org/abs/2104.09864>`_.
|
600 |
+
RoPE encodes the position information of tokens using a rotation matrix, and is able to capture
|
601 |
+
explicit relative positional dependencies.
|
602 |
+
Args:
|
603 |
+
model_dim: The dimensionality of the model's hidden state.
|
604 |
+
max_seq_length: Maximum sequence length.
|
605 |
+
freq_constant: A constant used for computing frequencies.
|
606 |
+
"""
|
607 |
+
|
608 |
+
def __init__(
|
609 |
+
self, model_dim: int, max_seq_length: int, freq_constant: int = 10000
|
610 |
+
) -> None:
|
611 |
+
inv_freq = 1.0 / (
|
612 |
+
freq_constant
|
613 |
+
** (torch.arange(0, model_dim, 2, dtype=torch.float32) / model_dim)
|
614 |
+
)
|
615 |
+
super().__init__()
|
616 |
+
|
617 |
+
self.model_dim = model_dim
|
618 |
+
self.freq_constant = freq_constant
|
619 |
+
self.max_seq_length = max_seq_length
|
620 |
+
|
621 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
622 |
+
self._cached_cos = None
|
623 |
+
self._cached_sin = None
|
624 |
+
self._cached_seq_length = max_seq_length
|
625 |
+
self._compute_sin_cos_embeddings(max_seq_length)
|
626 |
+
|
627 |
+
def extra_repr(self) -> str:
|
628 |
+
return f"\tmodel_dim={self.model_dim}, max_seq_length={self.max_seq_length}, freq_constant={self.freq_constant}"
|
629 |
+
|
630 |
+
def _compute_sin_cos_embeddings(
|
631 |
+
self,
|
632 |
+
key_len: int,
|
633 |
+
key_device: torch.device = torch.device("cpu"),
|
634 |
+
key_dtype: torch.dtype = torch.float32,
|
635 |
+
) -> None:
|
636 |
+
"""
|
637 |
+
Compute sine and cos embeddings.
|
638 |
+
Args:
|
639 |
+
key_len: Number of tokens in the key embeddings in the transformer model.
|
640 |
+
device: Device where the key embeddings are stored.
|
641 |
+
key_dtype: Data type of the key embeddings.
|
642 |
+
Returns:
|
643 |
+
None
|
644 |
+
...note:
|
645 |
+
We recalculate the sine and cosine embeddings if any of the following conditions are met:
|
646 |
+
1. The number of tokens in key embeddings are greater than the cached sequence length.
|
647 |
+
2. Sine and cosine caches are empty.
|
648 |
+
3. The device and data type of sine and cosine embeddings does not match with the key embeddings.
|
649 |
+
"""
|
650 |
+
if (
|
651 |
+
key_len > self._cached_seq_length
|
652 |
+
or self._cached_cos is None
|
653 |
+
or (self._cached_cos is not None and self._cached_cos.device != key_device)
|
654 |
+
or (self._cached_cos is not None and self._cached_cos.dtype != key_dtype)
|
655 |
+
or self._cached_sin is None
|
656 |
+
or (self._cached_sin is not None and self._cached_sin.device != key_device)
|
657 |
+
or (self._cached_sin is not None and self._cached_sin.dtype != key_dtype)
|
658 |
+
):
|
659 |
+
self._cached_seq_length = max(key_len, self._cached_seq_length)
|
660 |
+
|
661 |
+
# The shape of 'pos_index' is [number of key tokens]
|
662 |
+
pos_index = torch.arange(
|
663 |
+
self._cached_seq_length,
|
664 |
+
dtype=torch.float32,
|
665 |
+
device=self.inv_freq.device,
|
666 |
+
)
|
667 |
+
# The shape of 'pos_index_theta' is [number of key tokens, model dimension]
|
668 |
+
pos_index_theta = torch.einsum("i,j->ij", pos_index, self.inv_freq)
|
669 |
+
# The shape of 'emb' is [number of key tokens, model dimension]
|
670 |
+
emb = torch.cat((pos_index_theta, pos_index_theta), dim=-1)
|
671 |
+
|
672 |
+
# the shape of cos and sin embeddings is [number of key tokens, model_dim]
|
673 |
+
cos_emb = emb.cos().to(dtype=key_dtype, device=key_device)
|
674 |
+
sin_emb = emb.sin().to(dtype=key_dtype, device=key_device)
|
675 |
+
|
676 |
+
# the shape of cached cos and sin embeddings is [1, 1, number of key tokens, model_dim]
|
677 |
+
self._cached_cos = cos_emb[None, None, :, :]
|
678 |
+
self._cached_sin = sin_emb[None, None, :, :]
|
679 |
+
|
680 |
+
def forward(
|
681 |
+
self,
|
682 |
+
query: torch.Tensor,
|
683 |
+
key: torch.Tensor,
|
684 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
685 |
+
"""
|
686 |
+
The forward function of RoPE embeddings.
|
687 |
+
Args:
|
688 |
+
query: Query embeddings in the transformer model. The shape of query embeddings is
|
689 |
+
[Batch, number of query heads, number of query tokens, model dimension].
|
690 |
+
key: Key embeddings in the transformer model. The shape of key embeddings is
|
691 |
+
[Batch, number of key heads, number of key tokens, model dimension].
|
692 |
+
Returns:
|
693 |
+
A tuple containing the query and key embeddings with positional information. The shape of the returned query
|
694 |
+
and key embeddings is the same as the input query and key embeddings respectively.
|
695 |
+
...note:
|
696 |
+
The RoPE embedding computation is done in full-precision. After the computation, input query and key tensors
|
697 |
+
are casted to original input datatype.
|
698 |
+
"""
|
699 |
+
dim = key.shape[-1]
|
700 |
+
key_len = key.shape[2]
|
701 |
+
query_len = query.shape[2]
|
702 |
+
|
703 |
+
assert dim == self.model_dim
|
704 |
+
assert key.device == query.device
|
705 |
+
assert key.dtype == query.dtype
|
706 |
+
|
707 |
+
# In the context of self-attention, the lengths of keys and queries are equal.
|
708 |
+
# However, in generation tasks, such as predicting the next token in a sequence, the lengths of keys and queries
|
709 |
+
# can differ. For instance, when employing key-value (KV) caching for sequence prediction, the keys
|
710 |
+
# represent embeddings of previous tokens and the current token, while the query corresponds
|
711 |
+
# to the embedding of the current token only.
|
712 |
+
assert (
|
713 |
+
key_len >= query_len
|
714 |
+
), "Number of keys has to be greater than or equal to number of queries."
|
715 |
+
|
716 |
+
query_float = query.float()
|
717 |
+
key_float = key.float()
|
718 |
+
|
719 |
+
self._compute_sin_cos_embeddings(
|
720 |
+
key_len, key_device=key_float.device, key_dtype=key_float.dtype
|
721 |
+
)
|
722 |
+
query_float = _apply_rotary_pos_emb(
|
723 |
+
x=query_float,
|
724 |
+
pos_sin=self._cached_sin[..., key_len - query_len : key_len, :],
|
725 |
+
pos_cos=self._cached_cos[..., key_len - query_len : key_len, :],
|
726 |
+
)
|
727 |
+
key_float = _apply_rotary_pos_emb(
|
728 |
+
x=key_float,
|
729 |
+
pos_sin=self._cached_sin[..., :key_len, :],
|
730 |
+
pos_cos=self._cached_cos[..., :key_len, :],
|
731 |
+
)
|
732 |
+
|
733 |
+
return query_float.type_as(query), key_float.type_as(key)
|
734 |
+
|
735 |
+
|
736 |
+
class OpenELMMultiHeadCausalAttention(nn.Module):
|
737 |
+
def __init__(self, config: OpenELMConfig, layer_idx: int) -> None:
|
738 |
+
super().__init__()
|
739 |
+
self.layer_idx = layer_idx
|
740 |
+
head_dim = config.head_dim
|
741 |
+
q_heads = config.num_query_heads[layer_idx]
|
742 |
+
k_heads = config.num_kv_heads[layer_idx]
|
743 |
+
v_heads = config.num_kv_heads[layer_idx]
|
744 |
+
|
745 |
+
self.qkv_proj = nn.Linear(
|
746 |
+
in_features=config.model_dim,
|
747 |
+
out_features=(q_heads + k_heads + v_heads) * head_dim,
|
748 |
+
bias=False,
|
749 |
+
)
|
750 |
+
|
751 |
+
self.pos_embedding = OpenELMRotaryEmbedding(
|
752 |
+
model_dim=config.head_dim,
|
753 |
+
max_seq_length=config.rope_max_length,
|
754 |
+
freq_constant=config.rope_freq_constant,
|
755 |
+
)
|
756 |
+
|
757 |
+
if config.normalize_qk_projections:
|
758 |
+
self.q_norm = OpenELMRMSNorm(
|
759 |
+
num_features=config.head_dim,
|
760 |
+
)
|
761 |
+
self.k_norm = OpenELMRMSNorm(
|
762 |
+
num_features=config.head_dim,
|
763 |
+
)
|
764 |
+
else:
|
765 |
+
self.q_norm = None
|
766 |
+
self.k_norm = None
|
767 |
+
|
768 |
+
self.out_proj = nn.Linear(
|
769 |
+
in_features=q_heads * head_dim,
|
770 |
+
out_features=config.model_dim,
|
771 |
+
bias=False,
|
772 |
+
)
|
773 |
+
|
774 |
+
self.head_dim = config.head_dim
|
775 |
+
self.num_q_heads = q_heads
|
776 |
+
self.num_k_heads = k_heads
|
777 |
+
self.num_v_heads = v_heads
|
778 |
+
self.transformer_dim = config.model_dim
|
779 |
+
self.num_groups = self.num_q_heads // self.num_k_heads
|
780 |
+
|
781 |
+
def extra_repr(self) -> str:
|
782 |
+
return (
|
783 |
+
super().extra_repr()
|
784 |
+
+ f"query_heads={self.num_q_heads}, key_heads={self.num_k_heads}, value_heads={self.num_v_heads}"
|
785 |
+
)
|
786 |
+
|
787 |
+
def forward(
|
788 |
+
self,
|
789 |
+
hidden_states: torch.Tensor,
|
790 |
+
attention_mask: Optional[torch.Tensor] = None,
|
791 |
+
past_key_value: Optional[Cache] = None,
|
792 |
+
output_attentions: bool = False,
|
793 |
+
use_cache: bool = False,
|
794 |
+
cache_position: Optional[torch.LongTensor] = None,
|
795 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
796 |
+
"""
|
797 |
+
Forward pass of multi-head self-attention.
|
798 |
+
Args:
|
799 |
+
hidden_states: Input tensor of the shape [batch size, sequence length, model dimension].
|
800 |
+
past_key_value: Tensor storing the cached keys and values.
|
801 |
+
output_attentions: output attention weights.
|
802 |
+
use_cache: Specifies whether to use kv-cache for generation.
|
803 |
+
cache_position: used for updating the kv-cache.
|
804 |
+
Returns:
|
805 |
+
The output of the same shape as the input, optionally with a tensor containing cached keys and values.
|
806 |
+
"""
|
807 |
+
|
808 |
+
# scaled_dot_product_attention does not return attention weights, set output_attentions to False
|
809 |
+
output_attentions = False
|
810 |
+
batch_size, seq_length, d_model = hidden_states.size()
|
811 |
+
|
812 |
+
# [B, S, d] --> [B, S, (q_h + k_h + v_h) * h]
|
813 |
+
qkv = self.qkv_proj(hidden_states)
|
814 |
+
# [B, S, (q_h + k_h + v_h) * h] --> [B, S, (q_h + k_h + v_h), h]
|
815 |
+
qkv = qkv.reshape(
|
816 |
+
batch_size,
|
817 |
+
seq_length,
|
818 |
+
self.num_q_heads + self.num_k_heads + self.num_v_heads,
|
819 |
+
self.head_dim,
|
820 |
+
)
|
821 |
+
# [B, S, (q_h + k_h + v_h), h] --> [B, (q_h + k_h + v_h), S, h]
|
822 |
+
qkv = qkv.transpose(1, 2)
|
823 |
+
# [B, (q_h + k_h + v_h), S, h] --> [B, q_h, S h], [B, k_h, S, h], [B, v_h, S, h]
|
824 |
+
queries, keys, values = qkv.split(
|
825 |
+
[self.num_q_heads, self.num_k_heads, self.num_v_heads], dim=1
|
826 |
+
)
|
827 |
+
|
828 |
+
if self.q_norm is not None:
|
829 |
+
queries = self.q_norm(queries)
|
830 |
+
|
831 |
+
if self.k_norm is not None:
|
832 |
+
keys = self.k_norm(keys)
|
833 |
+
|
834 |
+
past_key_value = getattr(self, "past_key_value", past_key_value)
|
835 |
+
|
836 |
+
if past_key_value is not None:
|
837 |
+
# sin and cos are specific to RoPE models; position_ids needed for the static cache
|
838 |
+
# cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
839 |
+
cache_kwargs = {"cache_position": cache_position}
|
840 |
+
keys, values = past_key_value.update(
|
841 |
+
keys, values, self.layer_idx, cache_kwargs
|
842 |
+
)
|
843 |
+
|
844 |
+
# Add positional embedding
|
845 |
+
queries, keys = self.pos_embedding(queries, keys)
|
846 |
+
|
847 |
+
if self.num_groups != 1:
|
848 |
+
# GQA
|
849 |
+
# [B, k_h, S, h] --> [B, q_h, S, h]
|
850 |
+
keys = keys.repeat_interleave(self.num_groups, dim=1)
|
851 |
+
# [B, v_h, S, h] --> [B, q_h, S, h]
|
852 |
+
values = values.repeat_interleave(self.num_groups, dim=1)
|
853 |
+
|
854 |
+
causal_mask = attention_mask
|
855 |
+
if attention_mask is not None and cache_position is not None:
|
856 |
+
causal_mask = causal_mask[:, :, cache_position, : keys.shape[-2]]
|
857 |
+
|
858 |
+
attn_output = F.scaled_dot_product_attention(
|
859 |
+
queries,
|
860 |
+
keys,
|
861 |
+
values,
|
862 |
+
attn_mask=causal_mask,
|
863 |
+
dropout_p=0,
|
864 |
+
)
|
865 |
+
|
866 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
867 |
+
attn_output = attn_output.reshape(
|
868 |
+
batch_size, seq_length, self.num_q_heads * self.head_dim
|
869 |
+
)
|
870 |
+
attn_output = self.out_proj(attn_output)
|
871 |
+
if not output_attentions:
|
872 |
+
attn_weights = None
|
873 |
+
return attn_output, attn_weights, past_key_value
|
874 |
+
|
875 |
+
|
876 |
+
class OpenELMFeedForwardNetwork(nn.Module):
|
877 |
+
def __init__(self, config: OpenELMConfig, layer_idx: int) -> None:
|
878 |
+
super().__init__()
|
879 |
+
ffn_multiplier = config.ffn_multipliers[layer_idx]
|
880 |
+
intermediate_dim = int(
|
881 |
+
make_divisible(
|
882 |
+
ffn_multiplier * config.model_dim,
|
883 |
+
divisor=config.ffn_dim_divisor,
|
884 |
+
)
|
885 |
+
)
|
886 |
+
if config.ffn_with_glu:
|
887 |
+
# FFN with Gated linear unit, as described in https://arxiv.org/abs/2002.05202v1.
|
888 |
+
self.proj_1 = nn.Linear(
|
889 |
+
in_features=config.model_dim,
|
890 |
+
out_features=2 * intermediate_dim,
|
891 |
+
bias=False,
|
892 |
+
)
|
893 |
+
self.proj_2 = nn.Linear(
|
894 |
+
in_features=intermediate_dim,
|
895 |
+
out_features=config.model_dim,
|
896 |
+
bias=False,
|
897 |
+
)
|
898 |
+
self.ffn_with_glu = True
|
899 |
+
else:
|
900 |
+
# Standard FFN, as described in https://arxiv.org/abs/1706.03762
|
901 |
+
self.proj_1 = nn.Linear(
|
902 |
+
in_features=config.model_dim,
|
903 |
+
out_features=intermediate_dim,
|
904 |
+
bias=False,
|
905 |
+
)
|
906 |
+
self.proj_2 = nn.Linear(
|
907 |
+
in_features=intermediate_dim,
|
908 |
+
out_features=config.model_dim,
|
909 |
+
bias=False,
|
910 |
+
)
|
911 |
+
self.ffn_with_glu = False
|
912 |
+
|
913 |
+
self.act = ACT2FN[config.activation_fn_name]
|
914 |
+
|
915 |
+
def extra_repr(self) -> str:
|
916 |
+
return super().extra_repr() + f"(ffn_with_glu) : {self.ffn_with_glu}"
|
917 |
+
|
918 |
+
def forward(self, x: Tensor) -> Tensor:
|
919 |
+
"""Forward function of FFN layer.
|
920 |
+
Args:
|
921 |
+
x: Input tensor of the shape [batch size, sequence length, model dimension].
|
922 |
+
Returns:
|
923 |
+
A tensor of the same shape as the input.
|
924 |
+
"""
|
925 |
+
if self.ffn_with_glu:
|
926 |
+
y_12 = self.proj_1(x)
|
927 |
+
y_1, y_2 = y_12.chunk(2, dim=-1)
|
928 |
+
y = self.act(y_1) * y_2
|
929 |
+
return self.proj_2(y)
|
930 |
+
else:
|
931 |
+
return self.proj_2(self.act(self.proj_1(x)))
|
932 |
+
|
933 |
+
|
934 |
+
class OpenELMDecoderLayer(nn.Module):
|
935 |
+
def __init__(self, config: OpenELMConfig, layer_idx: int) -> None:
|
936 |
+
super().__init__()
|
937 |
+
self.attn = OpenELMMultiHeadCausalAttention(config=config, layer_idx=layer_idx)
|
938 |
+
self.ffn = OpenELMFeedForwardNetwork(config=config, layer_idx=layer_idx)
|
939 |
+
self.ffn_norm = OpenELMRMSNorm(
|
940 |
+
num_features=config.model_dim,
|
941 |
+
)
|
942 |
+
self.attn_norm = OpenELMRMSNorm(
|
943 |
+
num_features=config.model_dim,
|
944 |
+
)
|
945 |
+
|
946 |
+
def forward(
|
947 |
+
self,
|
948 |
+
hidden_states: torch.Tensor,
|
949 |
+
attention_mask: Optional[torch.Tensor] = None,
|
950 |
+
position_ids: Optional[torch.LongTensor] = None,
|
951 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
952 |
+
output_attentions: Optional[bool] = False,
|
953 |
+
use_cache: Optional[bool] = False,
|
954 |
+
cache_position: Optional[torch.LongTensor] = None,
|
955 |
+
**kwargs,
|
956 |
+
) -> Tuple[
|
957 |
+
torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
|
958 |
+
]:
|
959 |
+
"""
|
960 |
+
Args:
|
961 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
962 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
963 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
964 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
965 |
+
output_attentions (`bool`, *optional*):
|
966 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
967 |
+
returned tensors for more detail.
|
968 |
+
use_cache (`bool`, *optional*):
|
969 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
970 |
+
(see `past_key_values`).
|
971 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
972 |
+
"""
|
973 |
+
residual = hidden_states
|
974 |
+
hidden_states = self.attn_norm(hidden_states)
|
975 |
+
|
976 |
+
# Self Attention
|
977 |
+
hidden_states, self_attn_weights, present_key_value = self.attn(
|
978 |
+
hidden_states=hidden_states,
|
979 |
+
attention_mask=attention_mask,
|
980 |
+
past_key_value=past_key_value,
|
981 |
+
output_attentions=output_attentions,
|
982 |
+
use_cache=use_cache,
|
983 |
+
cache_position=cache_position,
|
984 |
+
**kwargs,
|
985 |
+
)
|
986 |
+
hidden_states = residual + hidden_states
|
987 |
+
|
988 |
+
# Fully Connected
|
989 |
+
residual = hidden_states
|
990 |
+
hidden_states = self.ffn_norm(hidden_states)
|
991 |
+
hidden_states = self.ffn(hidden_states)
|
992 |
+
hidden_states = residual + hidden_states
|
993 |
+
|
994 |
+
outputs = (hidden_states,)
|
995 |
+
|
996 |
+
if output_attentions:
|
997 |
+
outputs += (self_attn_weights,)
|
998 |
+
|
999 |
+
if use_cache:
|
1000 |
+
outputs += (present_key_value,)
|
1001 |
+
|
1002 |
+
return outputs
|
1003 |
+
|
1004 |
+
|
1005 |
+
class OpenELMModel(OpenELMPreTrainedModel):
|
1006 |
+
config_class = OpenELMConfig
|
1007 |
+
|
1008 |
+
def __init__(self, config: OpenELMConfig):
|
1009 |
+
super().__init__(config)
|
1010 |
+
self.config = config
|
1011 |
+
|
1012 |
+
self.token_embeddings = nn.Embedding(
|
1013 |
+
embedding_dim=config.model_dim,
|
1014 |
+
num_embeddings=config.vocab_size,
|
1015 |
+
)
|
1016 |
+
|
1017 |
+
self.layers = nn.ModuleList(
|
1018 |
+
OpenELMDecoderLayer(config=config, layer_idx=layer_idx)
|
1019 |
+
for layer_idx in range(config.num_transformer_layers)
|
1020 |
+
)
|
1021 |
+
self.norm = OpenELMRMSNorm(num_features=config.model_dim)
|
1022 |
+
if config.share_input_output_layers:
|
1023 |
+
self.classifier = None
|
1024 |
+
else:
|
1025 |
+
self.classifier = nn.Linear(
|
1026 |
+
in_features=config.model_dim,
|
1027 |
+
out_features=config.vocab_size,
|
1028 |
+
bias=False,
|
1029 |
+
)
|
1030 |
+
self.num_transformer_layers = config.num_transformer_layers
|
1031 |
+
self.gradient_checkpointing = False
|
1032 |
+
|
1033 |
+
# Register a causal mask to separate causal and padding mask creation. Merging happens in the attention class.
|
1034 |
+
# NOTE: This is not friendly with TorchScript, ONNX, ExportedProgram serialization for very large `max_context_length`.
|
1035 |
+
causal_mask = torch.full(
|
1036 |
+
(config.max_context_length, config.max_context_length),
|
1037 |
+
fill_value=True,
|
1038 |
+
dtype=torch.bool,
|
1039 |
+
)
|
1040 |
+
self.register_buffer(
|
1041 |
+
"causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False
|
1042 |
+
)
|
1043 |
+
|
1044 |
+
# Initialize weights and apply final processing
|
1045 |
+
self.post_init()
|
1046 |
+
self.reset_parameters(config=config)
|
1047 |
+
|
1048 |
+
def get_input_embeddings(self):
|
1049 |
+
return self.token_embeddings
|
1050 |
+
|
1051 |
+
def set_input_embeddings(self, new_embeddings: torch.Tensor):
|
1052 |
+
self.token_embeddings = new_embeddings
|
1053 |
+
|
1054 |
+
def reset_parameters(self, config: OpenELMConfig) -> None:
|
1055 |
+
"""Initialize the layers in Language Model
|
1056 |
+
The initialization scheme is followed, following `OPT <https://arxiv.org/pdf/2205.01068.pdf>`_.
|
1057 |
+
Args:
|
1058 |
+
use_megatron_std: Use standard deviation as described in Megatron-LM.
|
1059 |
+
Returns:
|
1060 |
+
None
|
1061 |
+
"""
|
1062 |
+
for module in self.modules():
|
1063 |
+
if isinstance(module, nn.Linear):
|
1064 |
+
std = module.in_features**-0.5
|
1065 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=std)
|
1066 |
+
if module.bias is not None:
|
1067 |
+
torch.nn.init.zeros_(module.bias)
|
1068 |
+
elif isinstance(module, nn.Embedding):
|
1069 |
+
std = module.embedding_dim**-0.5
|
1070 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=std)
|
1071 |
+
elif isinstance(module, OpenELMRMSNorm):
|
1072 |
+
if module.weight is not None:
|
1073 |
+
torch.nn.init.ones_(module.weight)
|
1074 |
+
if hasattr(module, "bias") and module.bias is not None:
|
1075 |
+
torch.nn.init.zeros_(module.bias)
|
1076 |
+
|
1077 |
+
model_dim = config.model_dim
|
1078 |
+
n_layers = config.num_transformer_layers
|
1079 |
+
std = (model_dim**-0.5) * ((2 * n_layers) ** -0.5)
|
1080 |
+
for param_name, param in self.named_parameters():
|
1081 |
+
if param_name.endswith("out_proj.weight") or param_name.endswith(
|
1082 |
+
"ffn.proj_2.weight"
|
1083 |
+
):
|
1084 |
+
torch.nn.init.normal_(param, mean=0.0, std=std)
|
1085 |
+
|
1086 |
+
def forward(
|
1087 |
+
self,
|
1088 |
+
input_ids: torch.LongTensor = None,
|
1089 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1090 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1091 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1092 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1093 |
+
use_cache: Optional[bool] = None,
|
1094 |
+
output_attentions: Optional[bool] = None,
|
1095 |
+
output_hidden_states: Optional[bool] = None,
|
1096 |
+
return_dict: Optional[bool] = None,
|
1097 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1098 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
1099 |
+
output_attentions = (
|
1100 |
+
output_attentions
|
1101 |
+
if output_attentions is not None
|
1102 |
+
else self.config.output_attentions
|
1103 |
+
)
|
1104 |
+
output_hidden_states = (
|
1105 |
+
output_hidden_states
|
1106 |
+
if output_hidden_states is not None
|
1107 |
+
else self.config.output_hidden_states
|
1108 |
+
)
|
1109 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1110 |
+
return_dict = (
|
1111 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1112 |
+
)
|
1113 |
+
|
1114 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
1115 |
+
raise ValueError(
|
1116 |
+
"You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
|
1117 |
+
)
|
1118 |
+
|
1119 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
1120 |
+
logger.warning_once(
|
1121 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
1122 |
+
)
|
1123 |
+
use_cache = False
|
1124 |
+
|
1125 |
+
if inputs_embeds is None:
|
1126 |
+
inputs_embeds = self.token_embeddings(input_ids)
|
1127 |
+
|
1128 |
+
past_seen_tokens = 0
|
1129 |
+
if use_cache: # kept for BC (cache positions)
|
1130 |
+
if not isinstance(past_key_values, StaticCache):
|
1131 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
1132 |
+
past_seen_tokens = past_key_values.get_seq_length()
|
1133 |
+
|
1134 |
+
if cache_position is None:
|
1135 |
+
cache_position = torch.arange(
|
1136 |
+
past_seen_tokens,
|
1137 |
+
past_seen_tokens + inputs_embeds.shape[1],
|
1138 |
+
device=inputs_embeds.device,
|
1139 |
+
)
|
1140 |
+
|
1141 |
+
if position_ids is None:
|
1142 |
+
position_ids = cache_position.unsqueeze(0)
|
1143 |
+
|
1144 |
+
causal_mask = self._update_causal_mask(attention_mask, inputs_embeds)
|
1145 |
+
|
1146 |
+
# embed positions
|
1147 |
+
hidden_states = inputs_embeds
|
1148 |
+
|
1149 |
+
# decoder layers
|
1150 |
+
all_hidden_states = () if output_hidden_states else None
|
1151 |
+
all_self_attns = () if output_attentions else None
|
1152 |
+
next_decoder_cache = None
|
1153 |
+
|
1154 |
+
for decoder_layer in self.layers:
|
1155 |
+
if output_hidden_states:
|
1156 |
+
all_hidden_states += (hidden_states,)
|
1157 |
+
|
1158 |
+
if self.gradient_checkpointing and self.training:
|
1159 |
+
layer_outputs = self._gradient_checkpointing_func(
|
1160 |
+
decoder_layer.__call__,
|
1161 |
+
hidden_states,
|
1162 |
+
causal_mask,
|
1163 |
+
position_ids,
|
1164 |
+
past_key_values,
|
1165 |
+
output_attentions,
|
1166 |
+
use_cache,
|
1167 |
+
cache_position,
|
1168 |
+
)
|
1169 |
+
else:
|
1170 |
+
layer_outputs = decoder_layer(
|
1171 |
+
hidden_states,
|
1172 |
+
attention_mask=causal_mask,
|
1173 |
+
position_ids=position_ids,
|
1174 |
+
past_key_value=past_key_values,
|
1175 |
+
output_attentions=output_attentions,
|
1176 |
+
use_cache=use_cache,
|
1177 |
+
cache_position=cache_position,
|
1178 |
+
)
|
1179 |
+
|
1180 |
+
hidden_states = layer_outputs[0]
|
1181 |
+
|
1182 |
+
if use_cache:
|
1183 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
1184 |
+
|
1185 |
+
if output_attentions:
|
1186 |
+
all_self_attns += (layer_outputs[1],)
|
1187 |
+
|
1188 |
+
hidden_states = self.norm(hidden_states)
|
1189 |
+
|
1190 |
+
# add hidden states from the last decoder layer
|
1191 |
+
if output_hidden_states:
|
1192 |
+
all_hidden_states += (hidden_states,)
|
1193 |
+
|
1194 |
+
next_cache = None
|
1195 |
+
if use_cache:
|
1196 |
+
next_cache = (
|
1197 |
+
next_decoder_cache.to_legacy_cache()
|
1198 |
+
if isinstance(next_decoder_cache, Cache)
|
1199 |
+
else next_decoder_cache
|
1200 |
+
)
|
1201 |
+
if not return_dict:
|
1202 |
+
return tuple(
|
1203 |
+
v
|
1204 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
|
1205 |
+
if v is not None
|
1206 |
+
)
|
1207 |
+
return BaseModelOutputWithPast(
|
1208 |
+
last_hidden_state=hidden_states,
|
1209 |
+
past_key_values=next_cache,
|
1210 |
+
hidden_states=all_hidden_states,
|
1211 |
+
attentions=all_self_attns,
|
1212 |
+
)
|
1213 |
+
|
1214 |
+
def _update_causal_mask(self, attention_mask, input_tensor):
|
1215 |
+
if self.config._attn_implementation == "flash_attention_2":
|
1216 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
1217 |
+
return attention_mask
|
1218 |
+
return None
|
1219 |
+
|
1220 |
+
batch_size, seq_length = input_tensor.shape[:2]
|
1221 |
+
dtype = input_tensor.dtype
|
1222 |
+
device = input_tensor.device
|
1223 |
+
|
1224 |
+
# support going beyond cached `max_position_embedding`
|
1225 |
+
if seq_length > self.causal_mask.shape[-1]:
|
1226 |
+
causal_mask = torch.full(
|
1227 |
+
(2 * self.causal_mask.shape[-1], 2 * self.causal_mask.shape[-1]),
|
1228 |
+
fill_value=1,
|
1229 |
+
)
|
1230 |
+
self.register_buffer(
|
1231 |
+
"causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False
|
1232 |
+
)
|
1233 |
+
|
1234 |
+
# We use the current dtype to avoid any overflows
|
1235 |
+
min_dtype = torch.finfo(dtype).min
|
1236 |
+
causal_mask = (
|
1237 |
+
self.causal_mask[None, None, :, :].repeat(batch_size, 1, 1, 1).to(dtype)
|
1238 |
+
* min_dtype
|
1239 |
+
)
|
1240 |
+
|
1241 |
+
causal_mask = causal_mask.to(dtype=dtype, device=device)
|
1242 |
+
if attention_mask is not None and attention_mask.dim() == 2:
|
1243 |
+
mask_length = attention_mask.shape[-1]
|
1244 |
+
padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[
|
1245 |
+
:, None, None, :
|
1246 |
+
].eq(0.0)
|
1247 |
+
causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(
|
1248 |
+
padding_mask, min_dtype
|
1249 |
+
)
|
1250 |
+
|
1251 |
+
if self.config._attn_implementation == "sdpa" and attention_mask is not None:
|
1252 |
+
# For dynamo, rather use a check on fullgraph=True once this is possible (https://github.com/pytorch/pytorch/pull/120400).
|
1253 |
+
is_tracing = (
|
1254 |
+
torch.jit.is_tracing()
|
1255 |
+
or isinstance(input_tensor, torch.fx.Proxy)
|
1256 |
+
or (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling())
|
1257 |
+
)
|
1258 |
+
if not is_tracing and torch.any(attention_mask != 1):
|
1259 |
+
# Attend to all tokens in masked rows from the causal_mask, for example the relevant first rows when
|
1260 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
1261 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
1262 |
+
causal_mask = causal_mask.mul(
|
1263 |
+
~torch.all(causal_mask == min_dtype, dim=-1, keepdim=True)
|
1264 |
+
).to(dtype)
|
1265 |
+
|
1266 |
+
return causal_mask
|
1267 |
+
|
1268 |
+
|
1269 |
+
class OpenELMForCausalLM(OpenELMPreTrainedModel):
|
1270 |
+
_tied_weights_keys = ["lm_head.weight"]
|
1271 |
+
|
1272 |
+
def __init__(self, config: OpenELMConfig):
|
1273 |
+
super().__init__(config)
|
1274 |
+
self.transformer = OpenELMModel(config)
|
1275 |
+
self.vocab_size = config.vocab_size
|
1276 |
+
if config.share_input_output_layers:
|
1277 |
+
self.lm_head = None
|
1278 |
+
else:
|
1279 |
+
self.lm_head = nn.Linear(config.model_dim, config.vocab_size, bias=False)
|
1280 |
+
|
1281 |
+
# Initialize weights and apply final processing
|
1282 |
+
self.post_init()
|
1283 |
+
|
1284 |
+
def get_input_embeddings(self):
|
1285 |
+
return self.transformer.token_embeddings
|
1286 |
+
|
1287 |
+
def set_input_embeddings(self, value):
|
1288 |
+
self.transformer.token_embeddings = value
|
1289 |
+
|
1290 |
+
def get_output_embeddings(self):
|
1291 |
+
return self.lm_head
|
1292 |
+
|
1293 |
+
def set_output_embeddings(self, new_embeddings):
|
1294 |
+
self.lm_head = new_embeddings
|
1295 |
+
|
1296 |
+
def set_decoder(self, decoder):
|
1297 |
+
self.transformer = decoder
|
1298 |
+
|
1299 |
+
def get_decoder(self):
|
1300 |
+
return self.transformer
|
1301 |
+
|
1302 |
+
def forward(
|
1303 |
+
self,
|
1304 |
+
input_ids: torch.LongTensor = None,
|
1305 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1306 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1307 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1308 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1309 |
+
labels: Optional[torch.LongTensor] = None,
|
1310 |
+
use_cache: Optional[bool] = None,
|
1311 |
+
output_attentions: Optional[bool] = None,
|
1312 |
+
output_hidden_states: Optional[bool] = None,
|
1313 |
+
return_dict: Optional[bool] = None,
|
1314 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1315 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1316 |
+
output_attentions = (
|
1317 |
+
output_attentions
|
1318 |
+
if output_attentions is not None
|
1319 |
+
else self.config.output_attentions
|
1320 |
+
)
|
1321 |
+
output_hidden_states = (
|
1322 |
+
output_hidden_states
|
1323 |
+
if output_hidden_states is not None
|
1324 |
+
else self.config.output_hidden_states
|
1325 |
+
)
|
1326 |
+
return_dict = (
|
1327 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1328 |
+
)
|
1329 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1330 |
+
outputs = self.transformer(
|
1331 |
+
input_ids=input_ids,
|
1332 |
+
attention_mask=attention_mask,
|
1333 |
+
position_ids=position_ids,
|
1334 |
+
past_key_values=past_key_values,
|
1335 |
+
inputs_embeds=inputs_embeds,
|
1336 |
+
use_cache=use_cache,
|
1337 |
+
output_attentions=output_attentions,
|
1338 |
+
output_hidden_states=output_hidden_states,
|
1339 |
+
return_dict=return_dict,
|
1340 |
+
cache_position=cache_position,
|
1341 |
+
)
|
1342 |
+
|
1343 |
+
hidden_states = outputs[0]
|
1344 |
+
if self.lm_head is None:
|
1345 |
+
# shared
|
1346 |
+
logits = F.linear(
|
1347 |
+
hidden_states, weight=self.transformer.token_embeddings.weight
|
1348 |
+
)
|
1349 |
+
else:
|
1350 |
+
logits = self.lm_head(hidden_states)
|
1351 |
+
logits = logits[:, : self.config.vocab_size]
|
1352 |
+
loss = None
|
1353 |
+
if labels is not None:
|
1354 |
+
# Shift so that tokens < n predict n
|
1355 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1356 |
+
shift_labels = labels[..., 1:].contiguous()
|
1357 |
+
# Flatten the tokens
|
1358 |
+
loss_fct = CrossEntropyLoss()
|
1359 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1360 |
+
shift_labels = shift_labels.view(-1)
|
1361 |
+
# Enable model parallelism
|
1362 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1363 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1364 |
+
|
1365 |
+
if not return_dict:
|
1366 |
+
output = (logits,) + outputs[1:]
|
1367 |
+
return (loss,) + output if loss is not None else output
|
1368 |
+
|
1369 |
+
return CausalLMOutputWithPast(
|
1370 |
+
loss=loss,
|
1371 |
+
logits=logits,
|
1372 |
+
past_key_values=outputs.past_key_values,
|
1373 |
+
hidden_states=outputs.hidden_states,
|
1374 |
+
attentions=outputs.attentions,
|
1375 |
+
)
|
1376 |
+
|
1377 |
+
def prepare_inputs_for_generation(
|
1378 |
+
self,
|
1379 |
+
input_ids,
|
1380 |
+
past_key_values=None,
|
1381 |
+
attention_mask=None,
|
1382 |
+
inputs_embeds=None,
|
1383 |
+
**kwargs,
|
1384 |
+
):
|
1385 |
+
past_length = 0
|
1386 |
+
if past_key_values is not None:
|
1387 |
+
if isinstance(past_key_values, Cache):
|
1388 |
+
cache_length = past_key_values.get_seq_length()
|
1389 |
+
past_length = past_key_values.seen_tokens
|
1390 |
+
max_cache_length = past_key_values.get_max_length()
|
1391 |
+
else:
|
1392 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
1393 |
+
max_cache_length = None
|
1394 |
+
|
1395 |
+
# Keep only the unprocessed tokens:
|
1396 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
1397 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
1398 |
+
# input)
|
1399 |
+
if (
|
1400 |
+
attention_mask is not None
|
1401 |
+
and attention_mask.shape[1] > input_ids.shape[1]
|
1402 |
+
):
|
1403 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
1404 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
1405 |
+
# input_ids based on the past_length.
|
1406 |
+
elif past_length < input_ids.shape[1]:
|
1407 |
+
input_ids = input_ids[:, past_length:]
|
1408 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
1409 |
+
|
1410 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
1411 |
+
if (
|
1412 |
+
max_cache_length is not None
|
1413 |
+
and attention_mask is not None
|
1414 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
1415 |
+
):
|
1416 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
1417 |
+
|
1418 |
+
position_ids = kwargs.get("position_ids", None)
|
1419 |
+
if attention_mask is not None and position_ids is None:
|
1420 |
+
# create position_ids on the fly for batch generation
|
1421 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1422 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1423 |
+
if past_key_values:
|
1424 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1425 |
+
|
1426 |
+
if self.generation_config.cache_implementation == "static":
|
1427 |
+
# generation with static cache
|
1428 |
+
cache_position = kwargs.get("cache_position", None)
|
1429 |
+
if cache_position is None:
|
1430 |
+
past_length = 0
|
1431 |
+
else:
|
1432 |
+
past_length = cache_position[-1] + 1
|
1433 |
+
input_ids = input_ids[:, past_length:]
|
1434 |
+
position_ids = position_ids[:, past_length:]
|
1435 |
+
|
1436 |
+
# we should only keep a `cache_position` in generate, and do +=1.
|
1437 |
+
# same goes for position ids. Could also help with continued generation.
|
1438 |
+
cache_position = torch.arange(
|
1439 |
+
past_length,
|
1440 |
+
past_length + position_ids.shape[-1],
|
1441 |
+
device=position_ids.device,
|
1442 |
+
)
|
1443 |
+
|
1444 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1445 |
+
if inputs_embeds is not None and past_key_values is None:
|
1446 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1447 |
+
else:
|
1448 |
+
# The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
|
1449 |
+
# recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
|
1450 |
+
# We could use `next_tokens` directly instead.
|
1451 |
+
model_inputs = {"input_ids": input_ids.contiguous()}
|
1452 |
+
|
1453 |
+
model_inputs.update(
|
1454 |
+
{
|
1455 |
+
"position_ids": position_ids.contiguous(),
|
1456 |
+
"cache_position": cache_position,
|
1457 |
+
"past_key_values": past_key_values,
|
1458 |
+
"use_cache": kwargs.get("use_cache"),
|
1459 |
+
"attention_mask": attention_mask,
|
1460 |
+
}
|
1461 |
+
)
|
1462 |
+
return model_inputs
|
1463 |
+
|
1464 |
+
@staticmethod
|
1465 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1466 |
+
reordered_past = ()
|
1467 |
+
for layer_past in past_key_values:
|
1468 |
+
reordered_past += (
|
1469 |
+
tuple(
|
1470 |
+
past_state.index_select(0, beam_idx.to(past_state.device))
|
1471 |
+
for past_state in layer_past
|
1472 |
+
),
|
1473 |
+
)
|
1474 |
+
return reordered_past
|
1475 |
+
|
1476 |
+
|
1477 |
+
ACT_TYPE = {
|
1478 |
+
'relu': nn.ReLU,
|
1479 |
+
'gelu': nn.GELU
|
1480 |
+
}
|
1481 |
+
|
1482 |
+
class Connector(nn.Module):
|
1483 |
+
def __init__(self, config=None):
|
1484 |
+
super().__init__()
|
1485 |
+
mlp_gelu_match = re.match(r'^mlp(\d+)x_gelu$', config.connector_type)
|
1486 |
+
act_type = config.connector_type.split('_')[-1]
|
1487 |
+
mlp_depth = int(mlp_gelu_match.group(1))
|
1488 |
+
modules = [nn.Linear(config.vision_hidden_size, config.hidden_size)]
|
1489 |
+
for _ in range(1, mlp_depth):
|
1490 |
+
modules.append(ACT_TYPE[act_type]())
|
1491 |
+
modules.append(nn.Linear(config.hidden_size, config.hidden_size))
|
1492 |
+
|
1493 |
+
self._connector = nn.Sequential(*modules)
|
1494 |
+
|
1495 |
+
def forward(self, x):
|
1496 |
+
return self._connector(x)
|
1497 |
+
|
1498 |
+
class VisionTower(nn.Module):
|
1499 |
+
def __init__(self, cfg, model_name_or_path = 'clip'):
|
1500 |
+
super().__init__()
|
1501 |
+
if 'clip' in model_name_or_path:
|
1502 |
+
self._vision_tower = CLIPVisionModel(cfg)
|
1503 |
+
self._image_processor = CLIPImageProcessor.from_pretrained(cfg.model_name_or_path)
|
1504 |
+
else:
|
1505 |
+
self._vision_tower = SiglipVisionModel(cfg)
|
1506 |
+
self._image_processor = SiglipImageProcessor.from_pretrained(cfg.model_name_or_path)
|
1507 |
+
|
1508 |
+
self.config = cfg
|
1509 |
+
|
1510 |
+
|
1511 |
+
|
1512 |
+
def forward(self, x, **kwargs):
|
1513 |
+
image_features = self._vision_tower(x, output_hidden_states=True)
|
1514 |
+
image_features = image_features.hidden_states[kwargs.get('vision_feature_layer', -2)]
|
1515 |
+
|
1516 |
+
if kwargs.get('vision_feature_select_strategy', 'patch') == 'patch':
|
1517 |
+
image_features = image_features[:, 1:]
|
1518 |
+
elif kwargs.get('vision_feature_select_strategy', 'patch') == 'cls_patch':
|
1519 |
+
image_features = image_features
|
1520 |
+
else:
|
1521 |
+
raise ValueError(f"Unexpected select feature: {kwargs.get('vision_feature_select_strategy')}")
|
1522 |
+
|
1523 |
+
return image_features
|
1524 |
+
|
1525 |
+
|
1526 |
+
|
1527 |
+
@property
|
1528 |
+
def vision_tower(self):
|
1529 |
+
return self._vision_tower
|
1530 |
+
|
1531 |
+
@vision_tower.setter
|
1532 |
+
def vision_tower(self, vision_tower):
|
1533 |
+
self._vision_tower = vision_tower
|
1534 |
+
|
1535 |
+
def get_value_from_kwargs(kwargs, name):
|
1536 |
+
if name in kwargs:
|
1537 |
+
return kwargs.pop(name)
|
1538 |
+
else:
|
1539 |
+
return None
|
1540 |
+
|
1541 |
+
|
1542 |
+
|
1543 |
+
class TinyLlavaPreTrainedModel(PreTrainedModel):
|
1544 |
+
config_class = TinyLlavaConfig
|
1545 |
+
base_model_prefix = "model"
|
1546 |
+
supports_gradient_checkpointing = True
|
1547 |
+
_no_split_modules = ["LlavaVisionAttention"]
|
1548 |
+
_skip_keys_device_placement = "past_key_values"
|
1549 |
+
_supports_flash_attn_2 = True
|
1550 |
+
|
1551 |
+
def _init_weights(self, module):
|
1552 |
+
std = (
|
1553 |
+
self.config.initializer_range
|
1554 |
+
if hasattr(self.config, "initializer_range")
|
1555 |
+
else self.config.text_config.initializer_range
|
1556 |
+
)
|
1557 |
+
|
1558 |
+
if hasattr(module, "class_embedding"):
|
1559 |
+
module.class_embedding.data.normal_(mean=0.0, std=std)
|
1560 |
+
|
1561 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
1562 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
1563 |
+
if module.bias is not None:
|
1564 |
+
module.bias.data.zero_()
|
1565 |
+
elif isinstance(module, nn.Embedding):
|
1566 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
1567 |
+
if module.padding_idx is not None:
|
1568 |
+
module.weight.data[module.padding_idx].zero_()
|
1569 |
+
|
1570 |
+
@property
|
1571 |
+
def _supports_sdpa(self):
|
1572 |
+
return self.language_model._supports_sdpa
|
1573 |
+
|
1574 |
+
|
1575 |
+
class TinyLlavaForConditionalGeneration(TinyLlavaPreTrainedModel):
|
1576 |
+
def __init__(self, config: TinyLlavaConfig):
|
1577 |
+
|
1578 |
+
super().__init__(config)
|
1579 |
+
|
1580 |
+
self.language_model = OpenELMForCausalLM(config.text_config)
|
1581 |
+
self.vision_tower = VisionTower(config.vision_config, config.vision_model_name_or_path)
|
1582 |
+
self.connector = Connector(config)
|
1583 |
+
self.post_init()
|
1584 |
+
|
1585 |
+
|
1586 |
+
def get_input_embeddings(self):
|
1587 |
+
return self.language_model.get_input_embeddings()
|
1588 |
+
|
1589 |
+
def set_input_embeddings(self, value):
|
1590 |
+
self.language_model.set_input_embeddings(value)
|
1591 |
+
|
1592 |
+
def get_output_embeddings(self):
|
1593 |
+
return self.language_model.get_output_embeddings()
|
1594 |
+
|
1595 |
+
def set_output_embeddings(self, new_embeddings):
|
1596 |
+
self.language_model.set_output_embeddings(new_embeddings)
|
1597 |
+
|
1598 |
+
def set_decoder(self, decoder):
|
1599 |
+
self.language_model.set_decoder(decoder)
|
1600 |
+
|
1601 |
+
def get_decoder(self):
|
1602 |
+
return self.language_model.get_decoder()
|
1603 |
+
|
1604 |
+
def tie_weights(self):
|
1605 |
+
return self.language_model.tie_weights()
|
1606 |
+
|
1607 |
+
def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, pad_to_multiple_of=None) -> nn.Embedding:
|
1608 |
+
model_embeds = self.language_model.resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
|
1609 |
+
# update vocab size
|
1610 |
+
self.config.text_config.vocab_size = model_embeds.num_embeddings
|
1611 |
+
self.config.vocab_size = model_embeds.num_embeddings
|
1612 |
+
self.vocab_size = model_embeds.num_embeddings
|
1613 |
+
return model_embeds
|
1614 |
+
|
1615 |
+
|
1616 |
+
def forward(
|
1617 |
+
self,
|
1618 |
+
input_ids: torch.LongTensor = None,
|
1619 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1620 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1621 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1622 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1623 |
+
labels: Optional[torch.LongTensor] = None,
|
1624 |
+
use_cache: Optional[bool] = None,
|
1625 |
+
output_attentions: Optional[bool] = None,
|
1626 |
+
output_hidden_states: Optional[bool] = None,
|
1627 |
+
images: Optional[torch.FloatTensor] = None,
|
1628 |
+
image_sizes: Optional[List[List[int]]] = None,
|
1629 |
+
return_dict: Optional[bool] = None,
|
1630 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1631 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1632 |
+
if inputs_embeds is None:
|
1633 |
+
(
|
1634 |
+
input_ids,
|
1635 |
+
position_ids,
|
1636 |
+
attention_mask,
|
1637 |
+
past_key_values,
|
1638 |
+
inputs_embeds,
|
1639 |
+
labels
|
1640 |
+
) = self.prepare_inputs_labels_for_multimodal(
|
1641 |
+
input_ids,
|
1642 |
+
position_ids,
|
1643 |
+
attention_mask,
|
1644 |
+
past_key_values,
|
1645 |
+
labels,
|
1646 |
+
images,
|
1647 |
+
image_sizes
|
1648 |
+
)
|
1649 |
+
return self.language_model.forward(
|
1650 |
+
input_ids=input_ids,
|
1651 |
+
attention_mask=attention_mask,
|
1652 |
+
position_ids=position_ids,
|
1653 |
+
past_key_values=past_key_values,
|
1654 |
+
inputs_embeds=inputs_embeds,
|
1655 |
+
labels=labels,
|
1656 |
+
use_cache=use_cache,
|
1657 |
+
output_attentions=output_attentions,
|
1658 |
+
output_hidden_states=output_hidden_states,
|
1659 |
+
return_dict=return_dict
|
1660 |
+
)
|
1661 |
+
|
1662 |
+
@torch.no_grad()
|
1663 |
+
def generate(
|
1664 |
+
self,
|
1665 |
+
inputs: Optional[torch.Tensor] = None,
|
1666 |
+
images: Optional[torch.Tensor] = None,
|
1667 |
+
image_sizes: Optional[torch.Tensor] = None,
|
1668 |
+
**kwargs,
|
1669 |
+
) -> Union[GenerateOutput, torch.LongTensor]:
|
1670 |
+
position_ids = kwargs.pop("position_ids", None)
|
1671 |
+
attention_mask = kwargs.pop("attention_mask", None)
|
1672 |
+
if "inputs_embeds" in kwargs:
|
1673 |
+
raise NotImplementedError("`inputs_embeds` is not supported")
|
1674 |
+
|
1675 |
+
if images is not None:
|
1676 |
+
(
|
1677 |
+
inputs,
|
1678 |
+
position_ids,
|
1679 |
+
attention_mask,
|
1680 |
+
_,
|
1681 |
+
inputs_embeds,
|
1682 |
+
_
|
1683 |
+
) = self.prepare_inputs_labels_for_multimodal(
|
1684 |
+
inputs,
|
1685 |
+
position_ids,
|
1686 |
+
attention_mask,
|
1687 |
+
None,
|
1688 |
+
None,
|
1689 |
+
images,
|
1690 |
+
image_sizes=image_sizes
|
1691 |
+
)
|
1692 |
+
else:
|
1693 |
+
inputs_embeds = self.language_model.get_input_embeddings()(inputs)
|
1694 |
+
|
1695 |
+
return self.language_model.generate(
|
1696 |
+
position_ids=position_ids,
|
1697 |
+
attention_mask=attention_mask,
|
1698 |
+
inputs_embeds=inputs_embeds,
|
1699 |
+
**kwargs
|
1700 |
+
)
|
1701 |
+
|
1702 |
+
def encode_images(self, images):
|
1703 |
+
kwargs = {}
|
1704 |
+
kwargs['vision_feature_layer'] = self.config.vision_feature_layer
|
1705 |
+
kwargs['vision_feature_select_strategy'] = self.config.vision_feature_select_strategy
|
1706 |
+
images = images.to(device=self.device, dtype=self.dtype)
|
1707 |
+
image_features = self.vision_tower(images, **kwargs)
|
1708 |
+
image_features = self.connector(image_features)
|
1709 |
+
return image_features
|
1710 |
+
|
1711 |
+
|
1712 |
+
|
1713 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None,
|
1714 |
+
inputs_embeds=None, **kwargs):
|
1715 |
+
images = kwargs.pop("images", None)
|
1716 |
+
image_sizes = kwargs.pop("image_sizes", None)
|
1717 |
+
inputs = self.language_model.prepare_inputs_for_generation(
|
1718 |
+
input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
|
1719 |
+
)
|
1720 |
+
if images is not None:
|
1721 |
+
inputs['images'] = images
|
1722 |
+
if image_sizes is not None:
|
1723 |
+
inputs['image_sizes'] = image_sizes
|
1724 |
+
return inputs
|
1725 |
+
|
1726 |
+
def prepare_inputs_labels_for_multimodal(
|
1727 |
+
self, input_ids, position_ids, attention_mask, past_key_values, labels,
|
1728 |
+
images, image_sizes=None
|
1729 |
+
):
|
1730 |
+
vision_tower = self.vision_tower
|
1731 |
+
if vision_tower is None or images is None or input_ids.shape[1] == 1:
|
1732 |
+
return input_ids, position_ids, attention_mask, past_key_values, None, labels
|
1733 |
+
|
1734 |
+
|
1735 |
+
image_features = self.encode_images(images)
|
1736 |
+
|
1737 |
+
# TODO: image start / end is not implemented here to support pretraining.
|
1738 |
+
if getattr(self.config, 'tune_mm_mlp_adapter', False):
|
1739 |
+
raise NotImplementedError
|
1740 |
+
|
1741 |
+
# Let's just add dummy tensors if they do not exist,
|
1742 |
+
# it is a headache to deal with None all the time.
|
1743 |
+
# But it is not ideal, and if you have a better idea,
|
1744 |
+
# please open an issue / submit a PR, thanks.
|
1745 |
+
_labels = labels
|
1746 |
+
_position_ids = position_ids
|
1747 |
+
_attention_mask = attention_mask
|
1748 |
+
if attention_mask is None:
|
1749 |
+
attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
|
1750 |
+
else:
|
1751 |
+
attention_mask = attention_mask.bool()
|
1752 |
+
if position_ids is None:
|
1753 |
+
position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
|
1754 |
+
if labels is None:
|
1755 |
+
labels = torch.full_like(input_ids, IGNORE_INDEX)
|
1756 |
+
|
1757 |
+
# remove the padding using attention_mask -- FIXME
|
1758 |
+
_input_ids = input_ids
|
1759 |
+
input_ids = [cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)]
|
1760 |
+
labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
|
1761 |
+
|
1762 |
+
new_input_embeds = []
|
1763 |
+
new_labels = []
|
1764 |
+
cur_image_idx = 0
|
1765 |
+
for batch_idx, cur_input_ids in enumerate(input_ids):
|
1766 |
+
num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
|
1767 |
+
if num_images == 0:
|
1768 |
+
cur_image_features = image_features[cur_image_idx]
|
1769 |
+
cur_input_embeds_1 = self.language_model.get_input_embeddings()(cur_input_ids)
|
1770 |
+
cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
|
1771 |
+
new_input_embeds.append(cur_input_embeds)
|
1772 |
+
new_labels.append(labels[batch_idx])
|
1773 |
+
cur_image_idx += 1
|
1774 |
+
continue
|
1775 |
+
|
1776 |
+
image_token_indices = [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
|
1777 |
+
cur_input_ids_noim = []
|
1778 |
+
cur_labels = labels[batch_idx]
|
1779 |
+
cur_labels_noim = []
|
1780 |
+
for i in range(len(image_token_indices) - 1):
|
1781 |
+
cur_input_ids_noim.append(cur_input_ids[image_token_indices[i]+1:image_token_indices[i+1]])
|
1782 |
+
cur_labels_noim.append(cur_labels[image_token_indices[i]+1:image_token_indices[i+1]])
|
1783 |
+
split_sizes = [x.shape[0] for x in cur_labels_noim]
|
1784 |
+
cur_input_embeds = self.language_model.get_input_embeddings()(torch.cat(cur_input_ids_noim))
|
1785 |
+
cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
|
1786 |
+
cur_new_input_embeds = []
|
1787 |
+
cur_new_labels = []
|
1788 |
+
|
1789 |
+
for i in range(num_images + 1):
|
1790 |
+
cur_new_input_embeds.append(cur_input_embeds_no_im[i])
|
1791 |
+
cur_new_labels.append(cur_labels_noim[i])
|
1792 |
+
if i < num_images:
|
1793 |
+
cur_image_features = image_features[cur_image_idx]
|
1794 |
+
cur_image_idx += 1
|
1795 |
+
cur_new_input_embeds.append(cur_image_features)
|
1796 |
+
cur_new_labels.append(torch.full((cur_image_features.shape[0],), IGNORE_INDEX, device=cur_labels.device, dtype=cur_labels.dtype))
|
1797 |
+
|
1798 |
+
cur_new_input_embeds = [x.to(self.device) for x in cur_new_input_embeds]
|
1799 |
+
|
1800 |
+
cur_new_input_embeds = torch.cat(cur_new_input_embeds)
|
1801 |
+
cur_new_labels = torch.cat(cur_new_labels)
|
1802 |
+
|
1803 |
+
new_input_embeds.append(cur_new_input_embeds)
|
1804 |
+
new_labels.append(cur_new_labels)
|
1805 |
+
|
1806 |
+
# Truncate sequences to max length as image embeddings can make the sequence longer
|
1807 |
+
tokenizer_model_max_length = getattr(self.config, 'tokenizer_model_max_length', None)
|
1808 |
+
if tokenizer_model_max_length is not None:
|
1809 |
+
new_input_embeds = [x[:tokenizer_model_max_length] for x in new_input_embeds]
|
1810 |
+
new_labels = [x[:tokenizer_model_max_length] for x in new_labels]
|
1811 |
+
|
1812 |
+
# Combine them
|
1813 |
+
max_len = max(x.shape[0] for x in new_input_embeds)
|
1814 |
+
batch_size = len(new_input_embeds)
|
1815 |
+
|
1816 |
+
new_input_embeds_padded = []
|
1817 |
+
new_labels_padded = torch.full((batch_size, max_len), IGNORE_INDEX, dtype=new_labels[0].dtype, device=new_labels[0].device)
|
1818 |
+
attention_mask = torch.zeros((batch_size, max_len), dtype=attention_mask.dtype, device=attention_mask.device)
|
1819 |
+
position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
|
1820 |
+
|
1821 |
+
for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
|
1822 |
+
cur_len = cur_new_embed.shape[0]
|
1823 |
+
if getattr(self.config, 'tokenizer_padding_side', 'right') == "left":
|
1824 |
+
new_input_embeds_padded.append(torch.cat((
|
1825 |
+
torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device),
|
1826 |
+
cur_new_embed
|
1827 |
+
), dim=0))
|
1828 |
+
if cur_len > 0:
|
1829 |
+
new_labels_padded[i, -cur_len:] = cur_new_labels
|
1830 |
+
attention_mask[i, -cur_len:] = True
|
1831 |
+
position_ids[i, -cur_len:] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
|
1832 |
+
else:
|
1833 |
+
new_input_embeds_padded.append(torch.cat((
|
1834 |
+
cur_new_embed,
|
1835 |
+
torch.zeros((max_len - cur_len, cur_new_embed.shape[1]), dtype=cur_new_embed.dtype, device=cur_new_embed.device)
|
1836 |
+
), dim=0))
|
1837 |
+
if cur_len > 0:
|
1838 |
+
new_labels_padded[i, :cur_len] = cur_new_labels
|
1839 |
+
attention_mask[i, :cur_len] = True
|
1840 |
+
position_ids[i, :cur_len] = torch.arange(0, cur_len, dtype=position_ids.dtype, device=position_ids.device)
|
1841 |
+
|
1842 |
+
new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
|
1843 |
+
|
1844 |
+
if _labels is None:
|
1845 |
+
new_labels = None
|
1846 |
+
else:
|
1847 |
+
new_labels = new_labels_padded
|
1848 |
+
|
1849 |
+
if _attention_mask is None:
|
1850 |
+
attention_mask = None
|
1851 |
+
else:
|
1852 |
+
attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
|
1853 |
+
|
1854 |
+
if _position_ids is None:
|
1855 |
+
position_ids = None
|
1856 |
+
|
1857 |
+
return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
|
1858 |
+
|
1859 |
+
def chat(
|
1860 |
+
self,
|
1861 |
+
prompt: str,
|
1862 |
+
tokenizer = None,
|
1863 |
+
image: str = None,
|
1864 |
+
max_new_tokens: int = 512,
|
1865 |
+
num_beams = 1,
|
1866 |
+
top_p=None,
|
1867 |
+
temperature=0
|
1868 |
+
):
|
1869 |
+
image_processor = self.vision_tower._image_processor
|
1870 |
+
|
1871 |
+
if image is not None:
|
1872 |
+
prompt = DEFAULT_IMAGE_TOKEN + '\n' + prompt
|
1873 |
+
conv = conv_phi_v0.copy()
|
1874 |
+
conv.append_message(conv.roles[0], prompt)
|
1875 |
+
conv.append_message(conv.roles[1], None)
|
1876 |
+
prompt = conv.get_prompt()
|
1877 |
+
if image is not None:
|
1878 |
+
image = load_image(image)
|
1879 |
+
image_tensor = process_images(image, image_processor, self.config).to(self.device)
|
1880 |
+
|
1881 |
+
input_ids = (
|
1882 |
+
tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt")
|
1883 |
+
.unsqueeze(0).to(self.device)
|
1884 |
+
)
|
1885 |
+
# Generate
|
1886 |
+
stime = time.time()
|
1887 |
+
|
1888 |
+
with torch.inference_mode():
|
1889 |
+
output_ids = self.generate(
|
1890 |
+
input_ids,
|
1891 |
+
images=image_tensor,
|
1892 |
+
do_sample=True if temperature > 0 else False,
|
1893 |
+
temperature=temperature,
|
1894 |
+
top_p=top_p,
|
1895 |
+
num_beams=num_beams,
|
1896 |
+
pad_token_id=tokenizer.pad_token_id,
|
1897 |
+
max_new_tokens=max_new_tokens,
|
1898 |
+
use_cache=True,
|
1899 |
+
# stopping_criteria=[stopping_criteria],
|
1900 |
+
)
|
1901 |
+
|
1902 |
+
# print('inference over')
|
1903 |
+
generation_time = time.time() - stime
|
1904 |
+
outputs = tokenizer.batch_decode(
|
1905 |
+
output_ids, skip_special_tokens=True
|
1906 |
+
)[0]
|
1907 |
+
|
1908 |
+
outputs = outputs.strip()
|
1909 |
+
|
1910 |
+
return outputs, generation_time
|
1911 |
+
|
1912 |
+
|
1913 |
+
|
1914 |
+
|
1915 |
+
|
1916 |
+
AutoConfig.register("tinyllava", TinyLlavaConfig)
|
1917 |
+
AutoModelForCausalLM.register(TinyLlavaConfig, TinyLlavaForConditionalGeneration)
|
smash_config.json
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"api_key": null,
|
3 |
+
"verify_url": "http://johnrachwan.pythonanywhere.com",
|
4 |
+
"smash_config": {
|
5 |
+
"pruners": "None",
|
6 |
+
"pruning_ratio": 0.0,
|
7 |
+
"factorizers": "None",
|
8 |
+
"quantizers": "['llm-int8']",
|
9 |
+
"weight_quantization_bits": 4,
|
10 |
+
"output_deviation": 0.005,
|
11 |
+
"compilers": "None",
|
12 |
+
"static_batch": true,
|
13 |
+
"static_shape": true,
|
14 |
+
"controlnet": "None",
|
15 |
+
"unet_dim": 4,
|
16 |
+
"device": "cuda",
|
17 |
+
"cache_dir": "/ceph/hdd/staff/charpent/.cache/modelsftw71kav",
|
18 |
+
"batch_size": 1,
|
19 |
+
"model_name": "jiajunlong/TinyLLaVA-OpenELM-450M-CLIP-0.55B",
|
20 |
+
"task": "text_text_generation",
|
21 |
+
"max_batch_size": 1,
|
22 |
+
"qtype_weight": "torch.qint8",
|
23 |
+
"qtype_activation": "torch.quint8",
|
24 |
+
"qobserver": "<class 'torch.ao.quantization.observer.MinMaxObserver'>",
|
25 |
+
"qscheme": "torch.per_tensor_symmetric",
|
26 |
+
"qconfig": "x86",
|
27 |
+
"group_size": 128,
|
28 |
+
"damp_percent": 0.1,
|
29 |
+
"save_load_fn": "bitsandbytes"
|
30 |
+
}
|
31 |
+
}
|
special_tokens_map.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<s>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": false,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"eos_token": {
|
10 |
+
"content": "</s>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": {
|
17 |
+
"content": "<unk>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": false,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
},
|
23 |
+
"unk_token": {
|
24 |
+
"content": "<unk>",
|
25 |
+
"lstrip": false,
|
26 |
+
"normalized": false,
|
27 |
+
"rstrip": false,
|
28 |
+
"single_word": false
|
29 |
+
}
|
30 |
+
}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
|
3 |
+
size 499723
|
tokenizer_config.json
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": true,
|
3 |
+
"add_eos_token": false,
|
4 |
+
"add_prefix_space": true,
|
5 |
+
"added_tokens_decoder": {
|
6 |
+
"0": {
|
7 |
+
"content": "<unk>",
|
8 |
+
"lstrip": false,
|
9 |
+
"normalized": false,
|
10 |
+
"rstrip": false,
|
11 |
+
"single_word": false,
|
12 |
+
"special": true
|
13 |
+
},
|
14 |
+
"1": {
|
15 |
+
"content": "<s>",
|
16 |
+
"lstrip": false,
|
17 |
+
"normalized": false,
|
18 |
+
"rstrip": false,
|
19 |
+
"single_word": false,
|
20 |
+
"special": true
|
21 |
+
},
|
22 |
+
"2": {
|
23 |
+
"content": "</s>",
|
24 |
+
"lstrip": false,
|
25 |
+
"normalized": false,
|
26 |
+
"rstrip": false,
|
27 |
+
"single_word": false,
|
28 |
+
"special": true
|
29 |
+
}
|
30 |
+
},
|
31 |
+
"bos_token": "<s>",
|
32 |
+
"clean_up_tokenization_spaces": false,
|
33 |
+
"eos_token": "</s>",
|
34 |
+
"legacy": false,
|
35 |
+
"model_max_length": 2048,
|
36 |
+
"pad_token": "<unk>",
|
37 |
+
"padding_side": "right",
|
38 |
+
"sp_model_kwargs": {},
|
39 |
+
"spaces_between_special_tokens": false,
|
40 |
+
"tokenizer_class": "LlamaTokenizer",
|
41 |
+
"unk_token": "<unk>",
|
42 |
+
"use_default_system_prompt": false
|
43 |
+
}
|