Track large files with Git LFS
Browse files- README.md +203 -0
- config.json +36 -0
- configuration_hawk.py +71 -0
- merges.txt +0 -0
- modelling_hawk.py +723 -0
- pytorch_model-00001-of-00002.bin +3 -0
- pytorch_model-00002-of-00002.bin +3 -0
- pytorch_model.bin.index.json +171 -0
- special_tokens_map.json +30 -0
- tokenization_hawk.py +306 -0
- tokenizer_config.json +46 -0
- vocab.json +0 -0
README.md
CHANGED
@@ -1,3 +1,206 @@
|
|
1 |
---
|
2 |
license: apache-2.0
|
|
|
|
|
|
|
|
|
|
|
3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
---
|
2 |
license: apache-2.0
|
3 |
+
language:
|
4 |
+
- en
|
5 |
+
tags:
|
6 |
+
- hawk
|
7 |
+
pipeline_tag: text-generation
|
8 |
---
|
9 |
+
# HawkLM-Chat-demo
|
10 |
+
|
11 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
12 |
+
|
13 |
+
This modelcard aims to be a base template for new models. It has been generated using [this raw template](https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/modelcard_template.md?plain=1).
|
14 |
+
|
15 |
+
## Model Details
|
16 |
+
|
17 |
+
### Model Description
|
18 |
+
|
19 |
+
<!-- Provide a longer summary of what this model is. -->
|
20 |
+
|
21 |
+
|
22 |
+
|
23 |
+
- **Developed by:** Rexopia
|
24 |
+
- **Reach me:** [email protected]
|
25 |
+
- **Language(s) (NLP):** English
|
26 |
+
- **License:** Apache license 2.0
|
27 |
+
- **Pretrained model:** False
|
28 |
+
|
29 |
+
### Model Sources
|
30 |
+
|
31 |
+
<!-- Provide the basic links for the model. -->
|
32 |
+
|
33 |
+
- **Github Repository:** Coming soon
|
34 |
+
- **Demo version:** True
|
35 |
+
|
36 |
+
## Uses
|
37 |
+
|
38 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
39 |
+
|
40 |
+
### Direct Use
|
41 |
+
|
42 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
43 |
+
|
44 |
+
[More Information Needed]
|
45 |
+
|
46 |
+
### Downstream Use [optional]
|
47 |
+
|
48 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
49 |
+
|
50 |
+
[More Information Needed]
|
51 |
+
|
52 |
+
### Out-of-Scope Use
|
53 |
+
|
54 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
55 |
+
|
56 |
+
[More Information Needed]
|
57 |
+
|
58 |
+
## Bias, Risks, and Limitations
|
59 |
+
|
60 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
61 |
+
|
62 |
+
[More Information Needed]
|
63 |
+
|
64 |
+
### Recommendations
|
65 |
+
|
66 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
67 |
+
|
68 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
69 |
+
|
70 |
+
## How to Get Started with the Model
|
71 |
+
|
72 |
+
Use the code below to get started with the model.
|
73 |
+
|
74 |
+
```python
|
75 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
76 |
+
|
77 |
+
tokenizer = AutoTokenizer.from_pretrained("Rexopia/HawkLM-Chat-demo", trust_remote_code=True)
|
78 |
+
model = AutoModelForCausalLM.from_pretrained("Rexopia/HawkLM-Chat-demo", device_map="auto", trust_remote_code=True)
|
79 |
+
```
|
80 |
+
|
81 |
+
## Training Details
|
82 |
+
|
83 |
+
### Training Data
|
84 |
+
|
85 |
+
<!-- This should link to a Data Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
86 |
+
|
87 |
+
We sampled from Redpajama 1T datasets without any Arxiv and GitHub tags.
|
88 |
+
|
89 |
+
### Training Procedure
|
90 |
+
|
91 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
92 |
+
|
93 |
+
#### Preprocessing [optional]
|
94 |
+
|
95 |
+
[More Information Needed]
|
96 |
+
|
97 |
+
|
98 |
+
#### Training Hyperparameters
|
99 |
+
|
100 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
101 |
+
|
102 |
+
#### Speeds, Sizes, Times [optional]
|
103 |
+
|
104 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
105 |
+
|
106 |
+
[More Information Needed]
|
107 |
+
|
108 |
+
## Evaluation
|
109 |
+
|
110 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
111 |
+
|
112 |
+
### Testing Data, Factors & Metrics
|
113 |
+
|
114 |
+
#### Testing Data
|
115 |
+
|
116 |
+
<!-- This should link to a Data Card if possible. -->
|
117 |
+
|
118 |
+
[More Information Needed]
|
119 |
+
|
120 |
+
#### Factors
|
121 |
+
|
122 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
123 |
+
|
124 |
+
[More Information Needed]
|
125 |
+
|
126 |
+
#### Metrics
|
127 |
+
|
128 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
129 |
+
|
130 |
+
[More Information Needed]
|
131 |
+
|
132 |
+
### Results
|
133 |
+
|
134 |
+
[More Information Needed]
|
135 |
+
|
136 |
+
#### Summary
|
137 |
+
|
138 |
+
|
139 |
+
|
140 |
+
## Model Examination [optional]
|
141 |
+
|
142 |
+
<!-- Relevant interpretability work for the model goes here -->
|
143 |
+
|
144 |
+
[More Information Needed]
|
145 |
+
|
146 |
+
## Environmental Impact
|
147 |
+
|
148 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
149 |
+
|
150 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
151 |
+
|
152 |
+
- **Hardware Type:** [More Information Needed]
|
153 |
+
- **Hours used:** [More Information Needed]
|
154 |
+
- **Cloud Provider:** [More Information Needed]
|
155 |
+
- **Compute Region:** [More Information Needed]
|
156 |
+
- **Carbon Emitted:** [More Information Needed]
|
157 |
+
|
158 |
+
## Technical Specifications [optional]
|
159 |
+
|
160 |
+
### Model Architecture and Objective
|
161 |
+
|
162 |
+
[More Information Needed]
|
163 |
+
|
164 |
+
### Compute Infrastructure
|
165 |
+
|
166 |
+
[More Information Needed]
|
167 |
+
|
168 |
+
#### Hardware
|
169 |
+
|
170 |
+
[More Information Needed]
|
171 |
+
|
172 |
+
#### Software
|
173 |
+
|
174 |
+
[More Information Needed]
|
175 |
+
|
176 |
+
## Citation [optional]
|
177 |
+
|
178 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
179 |
+
|
180 |
+
**BibTeX:**
|
181 |
+
|
182 |
+
[More Information Needed]
|
183 |
+
|
184 |
+
**APA:**
|
185 |
+
|
186 |
+
[More Information Needed]
|
187 |
+
|
188 |
+
## Glossary [optional]
|
189 |
+
|
190 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
191 |
+
|
192 |
+
[More Information Needed]
|
193 |
+
|
194 |
+
## More Information [optional]
|
195 |
+
|
196 |
+
[More Information Needed]
|
197 |
+
|
198 |
+
## Model Card Authors [optional]
|
199 |
+
|
200 |
+
[More Information Needed]
|
201 |
+
|
202 |
+
## Model Card Contact
|
203 |
+
|
204 |
+
[More Information Needed]
|
205 |
+
|
206 |
+
|
config.json
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"activation_function": "silu",
|
3 |
+
"architectures": [
|
4 |
+
"HawkForCausalLM"
|
5 |
+
],
|
6 |
+
"auto_map": {
|
7 |
+
"AutoConfig": "configuration_hawk.HawkConfig",
|
8 |
+
"AutoModelForCausalLM": "modelling_hawk.HawkForCausalLM"
|
9 |
+
},
|
10 |
+
"attn_pdrop": 0.0,
|
11 |
+
"bos_token_id": 65535,
|
12 |
+
"embd_pdrop": 0.0,
|
13 |
+
"eos_token_id": 65535,
|
14 |
+
"initializer_range": 0.02,
|
15 |
+
"layer_norm_epsilon": 1e-06,
|
16 |
+
"model_type": "hawk",
|
17 |
+
"n_embd": 1024,
|
18 |
+
"n_head": 16,
|
19 |
+
"n_inner": 2688,
|
20 |
+
"n_layer": 20,
|
21 |
+
"n_positions": 1024,
|
22 |
+
"reorder_and_upcast_attn": false,
|
23 |
+
"resid_pdrop": 0.0,
|
24 |
+
"rotary_dim": 64,
|
25 |
+
"scale_attn_by_inverse_layer_idx": false,
|
26 |
+
"scale_attn_weights": true,
|
27 |
+
"summary_activation": null,
|
28 |
+
"summary_first_dropout": 0.0,
|
29 |
+
"summary_proj_to_labels": true,
|
30 |
+
"summary_type": "cls_index",
|
31 |
+
"summary_use_proj": true,
|
32 |
+
"tokenizer_class": "HawkTokenizer",
|
33 |
+
"transformers_version": "4.31.0",
|
34 |
+
"use_cache": true,
|
35 |
+
"vocab_size": 65536
|
36 |
+
}
|
configuration_hawk.py
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers.configuration_utils import PretrainedConfig
|
2 |
+
|
3 |
+
class HawkConfig(PretrainedConfig):
|
4 |
+
"""
|
5 |
+
# TODO Need to Expand More!
|
6 |
+
"""
|
7 |
+
|
8 |
+
model_type = "hawk"
|
9 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
10 |
+
attribute_map = {
|
11 |
+
"hidden_size": "n_embd",
|
12 |
+
"max_position_embeddings": "n_positions",
|
13 |
+
"num_attention_heads": "n_head",
|
14 |
+
"num_hidden_layers": "n_layer",
|
15 |
+
}
|
16 |
+
|
17 |
+
def __init__(
|
18 |
+
self,
|
19 |
+
vocab_size=65536,
|
20 |
+
n_positions=1024,
|
21 |
+
n_embd=1024,
|
22 |
+
n_layer=24,
|
23 |
+
n_head=16,
|
24 |
+
n_inner=None,
|
25 |
+
activation_function="silu",
|
26 |
+
resid_pdrop=0.0,
|
27 |
+
embd_pdrop=0.0,
|
28 |
+
attn_pdrop=0.0,
|
29 |
+
layer_norm_epsilon=1e-6,
|
30 |
+
initializer_range=0.02,
|
31 |
+
summary_type="cls_index",
|
32 |
+
summary_use_proj=True,
|
33 |
+
summary_activation=None,
|
34 |
+
summary_proj_to_labels=True,
|
35 |
+
summary_first_dropout=0.0,
|
36 |
+
scale_attn_weights=True,
|
37 |
+
use_cache=True,
|
38 |
+
bos_token_id=1,
|
39 |
+
eos_token_id=2,
|
40 |
+
scale_attn_by_inverse_layer_idx=False,
|
41 |
+
reorder_and_upcast_attn=False,
|
42 |
+
**kwargs,
|
43 |
+
):
|
44 |
+
self.vocab_size = vocab_size
|
45 |
+
self.n_positions = n_positions
|
46 |
+
self.n_embd = n_embd
|
47 |
+
self.n_layer = n_layer
|
48 |
+
self.n_head = n_head
|
49 |
+
self.n_inner = n_inner
|
50 |
+
self.activation_function = activation_function
|
51 |
+
self.resid_pdrop = resid_pdrop
|
52 |
+
self.embd_pdrop = embd_pdrop
|
53 |
+
self.attn_pdrop = attn_pdrop
|
54 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
55 |
+
self.initializer_range = initializer_range
|
56 |
+
self.summary_type = summary_type
|
57 |
+
self.summary_use_proj = summary_use_proj
|
58 |
+
self.summary_activation = summary_activation
|
59 |
+
self.summary_first_dropout = summary_first_dropout
|
60 |
+
self.summary_proj_to_labels = summary_proj_to_labels
|
61 |
+
self.scale_attn_weights = scale_attn_weights
|
62 |
+
self.use_cache = use_cache
|
63 |
+
self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx
|
64 |
+
self.reorder_and_upcast_attn = reorder_and_upcast_attn
|
65 |
+
|
66 |
+
self.bos_token_id = bos_token_id
|
67 |
+
self.eos_token_id = eos_token_id
|
68 |
+
|
69 |
+
self.rotary_dim = 32 # TODO Need to modify
|
70 |
+
|
71 |
+
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
modelling_hawk.py
ADDED
@@ -0,0 +1,723 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
from typing import List, Optional, Tuple, Union
|
3 |
+
|
4 |
+
import torch
|
5 |
+
|
6 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, CausalLMOutputWithCrossAttentions
|
7 |
+
from transformers.modeling_utils import PreTrainedModel
|
8 |
+
from transformers.utils import logging
|
9 |
+
from transformers.activations import ACT2FN
|
10 |
+
|
11 |
+
logger = logging.get_logger(__name__)
|
12 |
+
|
13 |
+
from .configuration_hawk import HawkConfig
|
14 |
+
|
15 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
16 |
+
def _make_causal_mask(
|
17 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
18 |
+
):
|
19 |
+
"""
|
20 |
+
Make causal mask used for bi-directional self-attention.
|
21 |
+
"""
|
22 |
+
bsz, tgt_len = input_ids_shape
|
23 |
+
mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
|
24 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
25 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
26 |
+
mask = mask.to(dtype)
|
27 |
+
|
28 |
+
if past_key_values_length > 0:
|
29 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
30 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
31 |
+
|
32 |
+
|
33 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
34 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
35 |
+
"""
|
36 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
37 |
+
"""
|
38 |
+
bsz, src_len = mask.size()
|
39 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
40 |
+
|
41 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
42 |
+
|
43 |
+
inverted_mask = 1.0 - expanded_mask
|
44 |
+
|
45 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
46 |
+
|
47 |
+
|
48 |
+
class RotaryEmbedding(torch.nn.Module):
|
49 |
+
def __init__(self, dim, max_position_embeddings, base=10000, device=None):
|
50 |
+
super().__init__()
|
51 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
|
52 |
+
self.register_buffer("inv_freq", inv_freq)
|
53 |
+
|
54 |
+
# Build here to make `torch.jit.trace` work.
|
55 |
+
self.max_seq_len_cached = max_position_embeddings
|
56 |
+
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
|
57 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
58 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
59 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
60 |
+
self.cos_cached = emb.cos()[None, None, :, :]
|
61 |
+
self.sin_cached = emb.sin()[None, None, :, :]
|
62 |
+
|
63 |
+
def forward(self, x, seq_len=None):
|
64 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
65 |
+
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
|
66 |
+
if seq_len > self.max_seq_len_cached:
|
67 |
+
self.max_seq_len_cached = seq_len
|
68 |
+
t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
|
69 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
70 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
71 |
+
emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
|
72 |
+
self.cos_cached = emb.cos()[None, None, :, :]
|
73 |
+
self.sin_cached = emb.sin()[None, None, :, :]
|
74 |
+
return self.cos_cached[:seq_len, ...].to(x.device), self.sin_cached[:seq_len, ...].to(x.device)
|
75 |
+
|
76 |
+
|
77 |
+
def rotate_half(x):
|
78 |
+
"""Rotates half the hidden dims of the input."""
|
79 |
+
x1 = x[..., : x.shape[-1] // 2]
|
80 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
81 |
+
return torch.cat((-x2, x1), dim=-1)
|
82 |
+
|
83 |
+
|
84 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
|
85 |
+
gather_indices = position_ids[:, None, :, None] # [bs, 1, seq_len, 1]
|
86 |
+
gather_indices = gather_indices.repeat(1, cos.shape[1], 1, cos.shape[3])
|
87 |
+
cos = torch.gather(cos.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
|
88 |
+
sin = torch.gather(sin.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
|
89 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
90 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
91 |
+
return q_embed, k_embed
|
92 |
+
|
93 |
+
try:
|
94 |
+
from flash_attn.flash_attn_interface import flash_attn_unpadded_func
|
95 |
+
except ImportError:
|
96 |
+
flash_attn_unpadded_func = None
|
97 |
+
|
98 |
+
try:
|
99 |
+
from einops import rearrange
|
100 |
+
except ImportError:
|
101 |
+
rearrange = None
|
102 |
+
|
103 |
+
class FlashSelfAttention(torch.nn.Module):
|
104 |
+
"""Implement the scaled dot product attention with softmax.
|
105 |
+
Arguments
|
106 |
+
---------
|
107 |
+
softmax_scale: The temperature to use for the softmax attention.do
|
108 |
+
(default: 1/sqrt(d_keys) where d_keys is computed at
|
109 |
+
runtime)
|
110 |
+
attention_dropout: The dropout rate to apply to the attention
|
111 |
+
(default: 0.0)
|
112 |
+
"""
|
113 |
+
def __init__(self, causal=False, softmax_scale=None, attention_dropout=0.0,
|
114 |
+
device=None, dtype=None):
|
115 |
+
super().__init__()
|
116 |
+
assert flash_attn_unpadded_func is not None, ('Please install FlashAttention first, '
|
117 |
+
'e.g., with pip install flash-attn')
|
118 |
+
assert rearrange is not None, 'Please install einops first, e.g., with pip install einops'
|
119 |
+
self.causal = causal
|
120 |
+
self.softmax_scale = softmax_scale
|
121 |
+
self.dropout_p = attention_dropout
|
122 |
+
|
123 |
+
def forward(self, q, k, v):
|
124 |
+
"""Implements the multihead softmax attention.
|
125 |
+
Arguments
|
126 |
+
---------
|
127 |
+
q, k, v: The tensor containing the query, key, and value. (B, S, H, D)
|
128 |
+
"""
|
129 |
+
|
130 |
+
assert all((i.dtype in [torch.float16, torch.bfloat16] for i in (q,k,v)))
|
131 |
+
assert all((i.is_cuda for i in (q,k,v)))
|
132 |
+
|
133 |
+
batch_size, seqlen_q = q.shape[0], q.shape[1]
|
134 |
+
seqlen_k = k.shape[1]
|
135 |
+
|
136 |
+
q, k, v = [rearrange(x, 'b s ... -> (b s) ...') for x in [q, k, v]]
|
137 |
+
cu_seqlens_q = torch.arange(0, (batch_size + 1) * seqlen_q, step=seqlen_q, dtype=torch.int32,
|
138 |
+
device=q.device)
|
139 |
+
|
140 |
+
if self.training:
|
141 |
+
# during training q,k,v always have same seqlen
|
142 |
+
assert seqlen_k == seqlen_q
|
143 |
+
|
144 |
+
is_causal = self.causal
|
145 |
+
cu_seqlens_k = cu_seqlens_q
|
146 |
+
dropout_p = self.dropout_p
|
147 |
+
else:
|
148 |
+
# turn off FA causal mask after first inference autoregressive iteration
|
149 |
+
# only on first autoregressive step q,k,v have same seqlen
|
150 |
+
is_causal = seqlen_q == seqlen_k
|
151 |
+
cu_seqlens_k = torch.arange(0, (batch_size + 1) * seqlen_k, step=seqlen_k, dtype=torch.int32,
|
152 |
+
device=q.device)
|
153 |
+
dropout_p = 0
|
154 |
+
|
155 |
+
output = flash_attn_unpadded_func(
|
156 |
+
q, k, v, cu_seqlens_q, cu_seqlens_k, seqlen_q, seqlen_k,
|
157 |
+
dropout_p,
|
158 |
+
softmax_scale=self.softmax_scale, causal=is_causal
|
159 |
+
)
|
160 |
+
|
161 |
+
output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
|
162 |
+
return output
|
163 |
+
|
164 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaAttention
|
165 |
+
class Attention(torch.nn.Module):
|
166 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
167 |
+
|
168 |
+
def __init__(self, config: HawkConfig):
|
169 |
+
super().__init__()
|
170 |
+
self.config = config
|
171 |
+
self.hidden_size = config.n_embd
|
172 |
+
self.num_heads = config.n_head
|
173 |
+
self.head_dim = self.hidden_size // self.num_heads
|
174 |
+
self.max_position_embeddings = config.n_positions
|
175 |
+
self.rotary_ndims = config.rotary_dim
|
176 |
+
|
177 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
178 |
+
raise ValueError(
|
179 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
180 |
+
f" and `num_heads`: {self.num_heads})."
|
181 |
+
)
|
182 |
+
self.qkv_proj = torch.nn.Linear(self.hidden_size, 3 * self.num_heads * self.head_dim, bias=False)
|
183 |
+
#self.core_attention_flash = FlashSelfAttention(
|
184 |
+
# causal=True, attention_dropout=config.attn_pdrop
|
185 |
+
# )
|
186 |
+
self.c_proj = torch.nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
187 |
+
|
188 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
189 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
190 |
+
|
191 |
+
def _split_heads(self, tensor, num_heads, attn_head_size):
|
192 |
+
"""
|
193 |
+
Splits hidden_size dim into attn_head_size and num_heads
|
194 |
+
"""
|
195 |
+
new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
|
196 |
+
tensor = tensor.view(new_shape)
|
197 |
+
return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
|
198 |
+
|
199 |
+
def forward(
|
200 |
+
self,
|
201 |
+
hidden_states: torch.Tensor,
|
202 |
+
attention_mask: Optional[torch.Tensor] = None,
|
203 |
+
position_ids: Optional[torch.LongTensor] = None,
|
204 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
205 |
+
output_attentions: bool = False,
|
206 |
+
use_cache: bool = False,
|
207 |
+
rotary_pos_emb = None,
|
208 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
209 |
+
|
210 |
+
bsz, q_len, _ = hidden_states.size() # ruji modified
|
211 |
+
qkv_states = self.qkv_proj(hidden_states)
|
212 |
+
|
213 |
+
query_states, key_states, value_states = qkv_states.chunk(3, dim=-1)
|
214 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).permute(0,2,1,3)
|
215 |
+
key_states = key_states.view(bsz, q_len, self.num_heads, self.head_dim).permute(0,2,1,3)
|
216 |
+
value_states = value_states.view(bsz, q_len, self.num_heads, self.head_dim).permute(0,2,1,3)
|
217 |
+
|
218 |
+
# Compute rotary embeddings on rotary_ndims
|
219 |
+
query_rot = query_states[..., : self.rotary_ndims]
|
220 |
+
query_pass = query_states[..., self.rotary_ndims :]
|
221 |
+
key_rot = key_states[..., : self.rotary_ndims]
|
222 |
+
key_pass = key_states[..., self.rotary_ndims :]
|
223 |
+
|
224 |
+
# Compute token offset for rotary embeddings (when decoding)
|
225 |
+
kv_seq_len = key_states.shape[-2]
|
226 |
+
if past_key_value:
|
227 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
228 |
+
cos, sin = rotary_pos_emb(value_states, seq_len=kv_seq_len)
|
229 |
+
query, key = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
|
230 |
+
query_states = torch.cat((query, query_pass), dim=-1)
|
231 |
+
key_states = torch.cat((key, key_pass), dim=-1)
|
232 |
+
|
233 |
+
if past_key_value is not None:
|
234 |
+
# reuse k, v, self_attention
|
235 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
236 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
237 |
+
|
238 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
239 |
+
|
240 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
241 |
+
|
242 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
243 |
+
raise ValueError(
|
244 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
245 |
+
f" {attn_weights.size()}"
|
246 |
+
)
|
247 |
+
|
248 |
+
if attention_mask is not None:
|
249 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
250 |
+
raise ValueError(
|
251 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
252 |
+
)
|
253 |
+
attn_weights = attn_weights + attention_mask
|
254 |
+
attn_weights = torch.max(
|
255 |
+
attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min, device=attn_weights.device)
|
256 |
+
)
|
257 |
+
|
258 |
+
# upcast attention to fp32
|
259 |
+
attn_weights = torch.nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
|
260 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
261 |
+
|
262 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
263 |
+
raise ValueError(
|
264 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
265 |
+
f" {attn_output.size()}"
|
266 |
+
)
|
267 |
+
|
268 |
+
attn_output = attn_output.transpose(1, 2)
|
269 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
270 |
+
|
271 |
+
attn_output = self.c_proj(attn_output)
|
272 |
+
|
273 |
+
if not output_attentions:
|
274 |
+
attn_weights = None
|
275 |
+
|
276 |
+
return attn_output, attn_weights, past_key_value
|
277 |
+
|
278 |
+
class MLP(torch.nn.Module):
|
279 |
+
def __init__(self, hidden_size, intermediate_size, hidden_act):
|
280 |
+
super().__init__()
|
281 |
+
self.c_fc = torch.nn.Linear(hidden_size, intermediate_size*2, bias=False)
|
282 |
+
self.c_proj = torch.nn.Linear(intermediate_size, hidden_size, bias=False)
|
283 |
+
def swiglu(x):
|
284 |
+
x = torch.chunk(x, 2, dim=-1)
|
285 |
+
return torch.nn.functional.silu(x[0]) * x[1]
|
286 |
+
self.activation_func = swiglu
|
287 |
+
|
288 |
+
def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor:
|
289 |
+
intermediate_parallel = self.c_fc(hidden_states)
|
290 |
+
intermediate_parallel = self.activation_func(intermediate_parallel)
|
291 |
+
output = self.c_proj(intermediate_parallel)
|
292 |
+
return output
|
293 |
+
|
294 |
+
class HawkBlock(torch.nn.Module):
|
295 |
+
def __init__(self, config: HawkConfig):
|
296 |
+
super().__init__()
|
297 |
+
self.hidden_size = config.n_embd
|
298 |
+
self.input_layernorm = torch.nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
299 |
+
self.attn = Attention(config=config)
|
300 |
+
self.post_attention_layernorm = torch.nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
301 |
+
self.mlp = MLP(
|
302 |
+
hidden_size=self.hidden_size,
|
303 |
+
intermediate_size=config.n_inner,
|
304 |
+
hidden_act=config.activation_function,
|
305 |
+
)
|
306 |
+
|
307 |
+
def forward(
|
308 |
+
self,
|
309 |
+
hidden_states: torch.Tensor,
|
310 |
+
attention_mask: Optional[torch.Tensor] = None,
|
311 |
+
position_ids: Optional[torch.LongTensor] = None,
|
312 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
313 |
+
output_attentions: Optional[bool] = False,
|
314 |
+
use_cache: Optional[bool] = False,
|
315 |
+
rotary_pos_emb = None,
|
316 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
317 |
+
"""
|
318 |
+
Args:
|
319 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
320 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
321 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
322 |
+
output_attentions (`bool`, *optional*):
|
323 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
324 |
+
returned tensors for more detail.
|
325 |
+
use_cache (`bool`, *optional*):
|
326 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
327 |
+
(see `past_key_values`).
|
328 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
329 |
+
"""
|
330 |
+
|
331 |
+
residual = hidden_states
|
332 |
+
hidden_states = self.input_layernorm(hidden_states)
|
333 |
+
|
334 |
+
# Self Attention
|
335 |
+
hidden_states, self_attn_weights, present_key_value = self.attn(
|
336 |
+
hidden_states=hidden_states,
|
337 |
+
attention_mask=attention_mask,
|
338 |
+
position_ids=position_ids,
|
339 |
+
past_key_value=past_key_value,
|
340 |
+
output_attentions=output_attentions,
|
341 |
+
use_cache=use_cache,
|
342 |
+
rotary_pos_emb=rotary_pos_emb,
|
343 |
+
)
|
344 |
+
|
345 |
+
hidden_states = residual + hidden_states
|
346 |
+
|
347 |
+
# Fully Connected
|
348 |
+
residual = hidden_states
|
349 |
+
|
350 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
351 |
+
hidden_states = self.mlp(hidden_states)
|
352 |
+
hidden_states = residual + hidden_states
|
353 |
+
|
354 |
+
outputs = (hidden_states,)
|
355 |
+
|
356 |
+
if output_attentions:
|
357 |
+
outputs += (self_attn_weights,)
|
358 |
+
|
359 |
+
if use_cache:
|
360 |
+
outputs += (present_key_value,)
|
361 |
+
|
362 |
+
return outputs
|
363 |
+
|
364 |
+
class HawkPreTrainedModel(PreTrainedModel):
|
365 |
+
config_class = HawkConfig
|
366 |
+
base_model_prefix = "model"
|
367 |
+
supports_gradient_checkpointing = True
|
368 |
+
_no_split_modules = ["HawkBlock"]
|
369 |
+
_skip_keys_device_placement = "past_key_values"
|
370 |
+
_keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
|
371 |
+
|
372 |
+
def _init_weights(self, module):
|
373 |
+
std = self.config.initializer_range
|
374 |
+
if isinstance(module, torch.nn.Linear):
|
375 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
376 |
+
if module.bias is not None:
|
377 |
+
module.bias.data.zero_()
|
378 |
+
elif isinstance(module, torch.nn.Embedding):
|
379 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
380 |
+
if module.padding_idx is not None:
|
381 |
+
module.weight.data[module.padding_idx].zero_()
|
382 |
+
|
383 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
384 |
+
if isinstance(module, HawkModel):
|
385 |
+
module.gradient_checkpointing = value
|
386 |
+
|
387 |
+
class HawkModel(HawkPreTrainedModel):
|
388 |
+
"""
|
389 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`HawkBlock`]
|
390 |
+
|
391 |
+
Args:
|
392 |
+
config: HawkConfig
|
393 |
+
"""
|
394 |
+
|
395 |
+
def __init__(self, config: HawkConfig):
|
396 |
+
super().__init__(config)
|
397 |
+
self.vocab_size = config.vocab_size
|
398 |
+
|
399 |
+
self.word_embeddings = torch.nn.Embedding(config.vocab_size, config.n_embd)
|
400 |
+
self.rotary_pos_emb = RotaryEmbedding(config.rotary_dim, config.n_positions)
|
401 |
+
self.layers = torch.nn.ModuleList([HawkBlock(config) for _ in range(config.n_layer)])
|
402 |
+
self.final_layernorm = torch.nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
403 |
+
|
404 |
+
self.gradient_checkpointing = False
|
405 |
+
# Initialize weights and apply final processing
|
406 |
+
self.post_init()
|
407 |
+
|
408 |
+
def get_input_embeddings(self):
|
409 |
+
return self.word_embeddings
|
410 |
+
|
411 |
+
def set_input_embeddings(self, value):
|
412 |
+
self.word_embeddings = value
|
413 |
+
|
414 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
415 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
416 |
+
# create causal mask
|
417 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
418 |
+
combined_attention_mask = None
|
419 |
+
if input_shape[-1] > 1:
|
420 |
+
combined_attention_mask = _make_causal_mask(
|
421 |
+
input_shape,
|
422 |
+
inputs_embeds.dtype,
|
423 |
+
device=inputs_embeds.device,
|
424 |
+
past_key_values_length=past_key_values_length,
|
425 |
+
)
|
426 |
+
|
427 |
+
if attention_mask is not None:
|
428 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
429 |
+
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
|
430 |
+
inputs_embeds.device
|
431 |
+
)
|
432 |
+
combined_attention_mask = (
|
433 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
434 |
+
)
|
435 |
+
|
436 |
+
return combined_attention_mask
|
437 |
+
|
438 |
+
def forward(
|
439 |
+
self,
|
440 |
+
input_ids: torch.LongTensor = None,
|
441 |
+
attention_mask: Optional[torch.Tensor] = None,
|
442 |
+
position_ids: Optional[torch.LongTensor] = None,
|
443 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
444 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
445 |
+
use_cache: Optional[bool] = None,
|
446 |
+
output_attentions: Optional[bool] = None,
|
447 |
+
output_hidden_states: Optional[bool] = None,
|
448 |
+
return_dict: Optional[bool] = None,
|
449 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
450 |
+
|
451 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
452 |
+
output_hidden_states = (
|
453 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
454 |
+
)
|
455 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
456 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
457 |
+
|
458 |
+
# retrieve input_ids and inputs_embeds
|
459 |
+
if input_ids is not None and inputs_embeds is not None:
|
460 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
461 |
+
elif input_ids is not None:
|
462 |
+
batch_size, seq_length = input_ids.shape
|
463 |
+
elif inputs_embeds is not None:
|
464 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
465 |
+
else:
|
466 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
467 |
+
|
468 |
+
seq_length_with_past = seq_length
|
469 |
+
past_key_values_length = 0
|
470 |
+
|
471 |
+
if past_key_values is not None:
|
472 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
473 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
474 |
+
|
475 |
+
if position_ids is None:
|
476 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
477 |
+
position_ids = torch.arange(
|
478 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
479 |
+
)
|
480 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
481 |
+
else:
|
482 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
483 |
+
|
484 |
+
if inputs_embeds is None:
|
485 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
486 |
+
# embed positions
|
487 |
+
if attention_mask is None:
|
488 |
+
attention_mask = torch.ones(
|
489 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
490 |
+
)
|
491 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
492 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
493 |
+
)
|
494 |
+
|
495 |
+
# Rotary positional embeddings
|
496 |
+
rotary_pos_emb = self.rotary_pos_emb
|
497 |
+
|
498 |
+
hidden_states = inputs_embeds
|
499 |
+
|
500 |
+
if self.gradient_checkpointing and self.training:
|
501 |
+
if use_cache:
|
502 |
+
logger.warning_once(
|
503 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
504 |
+
)
|
505 |
+
use_cache = False
|
506 |
+
|
507 |
+
# decoder layers
|
508 |
+
all_hidden_states = () if output_hidden_states else None
|
509 |
+
all_self_attns = () if output_attentions else None
|
510 |
+
next_decoder_cache = () if use_cache else None
|
511 |
+
|
512 |
+
for idx, decoder_layer in enumerate(self.layers):
|
513 |
+
# print(f'idx: {idx}')
|
514 |
+
if output_hidden_states:
|
515 |
+
all_hidden_states += (hidden_states,)
|
516 |
+
|
517 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
518 |
+
|
519 |
+
if self.gradient_checkpointing and self.training:
|
520 |
+
|
521 |
+
def create_custom_forward(module):
|
522 |
+
def custom_forward(*inputs):
|
523 |
+
# None for past_key_value
|
524 |
+
return module(*inputs, output_attentions, None)
|
525 |
+
|
526 |
+
return custom_forward
|
527 |
+
|
528 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
529 |
+
create_custom_forward(decoder_layer),
|
530 |
+
hidden_states,
|
531 |
+
attention_mask,
|
532 |
+
position_ids,
|
533 |
+
None,
|
534 |
+
)
|
535 |
+
else:
|
536 |
+
layer_outputs = decoder_layer(
|
537 |
+
hidden_states,
|
538 |
+
attention_mask=attention_mask,
|
539 |
+
position_ids=position_ids,
|
540 |
+
past_key_value=past_key_value,
|
541 |
+
output_attentions=output_attentions,
|
542 |
+
use_cache=use_cache,
|
543 |
+
rotary_pos_emb=rotary_pos_emb,
|
544 |
+
)
|
545 |
+
|
546 |
+
hidden_states = layer_outputs[0]
|
547 |
+
|
548 |
+
if use_cache:
|
549 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
550 |
+
|
551 |
+
if output_attentions:
|
552 |
+
all_self_attns += (layer_outputs[1],)
|
553 |
+
|
554 |
+
hidden_states = self.final_layernorm(hidden_states)
|
555 |
+
|
556 |
+
# add hidden states from the last decoder layer
|
557 |
+
if output_hidden_states:
|
558 |
+
all_hidden_states += (hidden_states,)
|
559 |
+
|
560 |
+
next_cache = next_decoder_cache if use_cache else None
|
561 |
+
if not return_dict:
|
562 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
563 |
+
return BaseModelOutputWithPast(
|
564 |
+
last_hidden_state=hidden_states,
|
565 |
+
past_key_values=next_cache,
|
566 |
+
hidden_states=all_hidden_states,
|
567 |
+
attentions=all_self_attns,
|
568 |
+
)
|
569 |
+
|
570 |
+
|
571 |
+
class HawkForCausalLM(HawkPreTrainedModel):
|
572 |
+
_keys_to_ignore_on_load_missing = [r"model.rotary_pos_emb.inv_freq"]
|
573 |
+
|
574 |
+
def __init__(self, config):
|
575 |
+
super().__init__(config)
|
576 |
+
self.model = HawkModel(config)
|
577 |
+
|
578 |
+
self.lm_head = torch.nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
579 |
+
|
580 |
+
# Initialize weights and apply final processing
|
581 |
+
self.post_init()
|
582 |
+
|
583 |
+
def get_input_embeddings(self):
|
584 |
+
return self.model.word_embeddings
|
585 |
+
|
586 |
+
def set_input_embeddings(self, value):
|
587 |
+
self.model.word_embeddings = value
|
588 |
+
|
589 |
+
def get_output_embeddings(self):
|
590 |
+
return self.lm_head
|
591 |
+
|
592 |
+
def set_output_embeddings(self, new_embeddings):
|
593 |
+
self.lm_head = new_embeddings
|
594 |
+
|
595 |
+
def set_decoder(self, decoder):
|
596 |
+
self.model = decoder
|
597 |
+
|
598 |
+
def get_decoder(self):
|
599 |
+
return self.model
|
600 |
+
|
601 |
+
def forward(
|
602 |
+
self,
|
603 |
+
input_ids: torch.LongTensor = None,
|
604 |
+
attention_mask: Optional[torch.Tensor] = None,
|
605 |
+
position_ids: Optional[torch.LongTensor] = None,
|
606 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
607 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
608 |
+
labels: Optional[torch.LongTensor] = None,
|
609 |
+
use_cache: Optional[bool] = None,
|
610 |
+
output_attentions: Optional[bool] = None,
|
611 |
+
output_hidden_states: Optional[bool] = None,
|
612 |
+
return_dict: Optional[bool] = None,
|
613 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
614 |
+
r"""
|
615 |
+
Args:
|
616 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
617 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
618 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
619 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
620 |
+
|
621 |
+
Returns:
|
622 |
+
|
623 |
+
Example:
|
624 |
+
|
625 |
+
```python
|
626 |
+
>>> from transformers import AutoTokenizer, LlamaForCausalLM
|
627 |
+
|
628 |
+
>>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
629 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
630 |
+
|
631 |
+
>>> prompt = "Hey, are you consciours? Can you talk to me?"
|
632 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
633 |
+
|
634 |
+
>>> # Generate
|
635 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
636 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
637 |
+
"Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
|
638 |
+
```"""
|
639 |
+
|
640 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
641 |
+
output_hidden_states = (
|
642 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
643 |
+
)
|
644 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
645 |
+
|
646 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
647 |
+
outputs = self.model(
|
648 |
+
input_ids=input_ids,
|
649 |
+
attention_mask=attention_mask,
|
650 |
+
position_ids=position_ids,
|
651 |
+
past_key_values=past_key_values,
|
652 |
+
inputs_embeds=inputs_embeds,
|
653 |
+
use_cache=use_cache,
|
654 |
+
output_attentions=output_attentions,
|
655 |
+
output_hidden_states=output_hidden_states,
|
656 |
+
return_dict=return_dict,
|
657 |
+
)
|
658 |
+
|
659 |
+
hidden_states = outputs[0]
|
660 |
+
|
661 |
+
logits = self.lm_head(hidden_states)
|
662 |
+
|
663 |
+
loss = None
|
664 |
+
if labels is not None:
|
665 |
+
# Shift so that tokens < n predict n
|
666 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
667 |
+
shift_labels = labels[..., 1:].contiguous()
|
668 |
+
# Flatten the tokens
|
669 |
+
loss_fct = torch.nn.CrossEntropyLoss()
|
670 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
671 |
+
shift_labels = shift_labels.view(-1)
|
672 |
+
# Enable model parallelism
|
673 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
674 |
+
loss = loss_fct(shift_logits, shift_labels)
|
675 |
+
|
676 |
+
if not return_dict:
|
677 |
+
output = (logits,) + outputs[1:]
|
678 |
+
return (loss,) + output if loss is not None else output
|
679 |
+
|
680 |
+
return CausalLMOutputWithPast(
|
681 |
+
loss=loss,
|
682 |
+
logits=logits,
|
683 |
+
past_key_values=outputs.past_key_values,
|
684 |
+
hidden_states=outputs.hidden_states,
|
685 |
+
attentions=outputs.attentions,
|
686 |
+
)
|
687 |
+
|
688 |
+
def prepare_inputs_for_generation(
|
689 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
690 |
+
):
|
691 |
+
if past_key_values:
|
692 |
+
input_ids = input_ids[:, -1:]
|
693 |
+
|
694 |
+
position_ids = kwargs.get("position_ids", None)
|
695 |
+
if attention_mask is not None and position_ids is None:
|
696 |
+
# create position_ids on the fly for batch generation
|
697 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
698 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
699 |
+
if past_key_values:
|
700 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
701 |
+
|
702 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
703 |
+
if inputs_embeds is not None and past_key_values is None:
|
704 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
705 |
+
else:
|
706 |
+
model_inputs = {"input_ids": input_ids}
|
707 |
+
|
708 |
+
model_inputs.update(
|
709 |
+
{
|
710 |
+
"position_ids": position_ids,
|
711 |
+
"past_key_values": past_key_values,
|
712 |
+
"use_cache": kwargs.get("use_cache"),
|
713 |
+
"attention_mask": attention_mask,
|
714 |
+
}
|
715 |
+
)
|
716 |
+
return model_inputs
|
717 |
+
|
718 |
+
@staticmethod
|
719 |
+
def _reorder_cache(past_key_values, beam_idx):
|
720 |
+
reordered_past = ()
|
721 |
+
for layer_past in past_key_values:
|
722 |
+
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
|
723 |
+
return reordered_past
|
pytorch_model-00001-of-00002.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:11981b114885657fdb57dad152c13a735a01d748dccb4786e0055979c5e27081
|
3 |
+
size 982801364
|
pytorch_model-00002-of-00002.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:88dd68d61e4d84ce93c8498992d45aa0afe58c07ff3efb8c8a3f058435f11625
|
3 |
+
size 282171835
|
pytorch_model.bin.index.json
ADDED
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"metadata": {
|
3 |
+
"total_size": 1264918528
|
4 |
+
},
|
5 |
+
"weight_map": {
|
6 |
+
"lm_head.weight": "pytorch_model-00001-of-00002.bin",
|
7 |
+
"model.final_layernorm.bias": "pytorch_model-00002-of-00002.bin",
|
8 |
+
"model.final_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
9 |
+
"model.layers.0.attn.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
10 |
+
"model.layers.0.attn.qkv_proj.weight": "pytorch_model-00001-of-00002.bin",
|
11 |
+
"model.layers.0.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
12 |
+
"model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
13 |
+
"model.layers.0.mlp.c_fc.weight": "pytorch_model-00001-of-00002.bin",
|
14 |
+
"model.layers.0.mlp.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
15 |
+
"model.layers.0.post_attention_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
16 |
+
"model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
17 |
+
"model.layers.1.attn.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
18 |
+
"model.layers.1.attn.qkv_proj.weight": "pytorch_model-00001-of-00002.bin",
|
19 |
+
"model.layers.1.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
20 |
+
"model.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
21 |
+
"model.layers.1.mlp.c_fc.weight": "pytorch_model-00001-of-00002.bin",
|
22 |
+
"model.layers.1.mlp.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
23 |
+
"model.layers.1.post_attention_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
24 |
+
"model.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
25 |
+
"model.layers.10.attn.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
26 |
+
"model.layers.10.attn.qkv_proj.weight": "pytorch_model-00001-of-00002.bin",
|
27 |
+
"model.layers.10.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
28 |
+
"model.layers.10.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
29 |
+
"model.layers.10.mlp.c_fc.weight": "pytorch_model-00001-of-00002.bin",
|
30 |
+
"model.layers.10.mlp.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
31 |
+
"model.layers.10.post_attention_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
32 |
+
"model.layers.10.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
33 |
+
"model.layers.11.attn.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
34 |
+
"model.layers.11.attn.qkv_proj.weight": "pytorch_model-00001-of-00002.bin",
|
35 |
+
"model.layers.11.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
36 |
+
"model.layers.11.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
37 |
+
"model.layers.11.mlp.c_fc.weight": "pytorch_model-00001-of-00002.bin",
|
38 |
+
"model.layers.11.mlp.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
39 |
+
"model.layers.11.post_attention_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
40 |
+
"model.layers.11.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
41 |
+
"model.layers.12.attn.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
42 |
+
"model.layers.12.attn.qkv_proj.weight": "pytorch_model-00001-of-00002.bin",
|
43 |
+
"model.layers.12.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
44 |
+
"model.layers.12.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
45 |
+
"model.layers.12.mlp.c_fc.weight": "pytorch_model-00001-of-00002.bin",
|
46 |
+
"model.layers.12.mlp.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
47 |
+
"model.layers.12.post_attention_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
48 |
+
"model.layers.12.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
49 |
+
"model.layers.13.attn.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
50 |
+
"model.layers.13.attn.qkv_proj.weight": "pytorch_model-00001-of-00002.bin",
|
51 |
+
"model.layers.13.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
52 |
+
"model.layers.13.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
53 |
+
"model.layers.13.mlp.c_fc.weight": "pytorch_model-00001-of-00002.bin",
|
54 |
+
"model.layers.13.mlp.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
55 |
+
"model.layers.13.post_attention_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
56 |
+
"model.layers.13.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
57 |
+
"model.layers.14.attn.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
58 |
+
"model.layers.14.attn.qkv_proj.weight": "pytorch_model-00001-of-00002.bin",
|
59 |
+
"model.layers.14.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
60 |
+
"model.layers.14.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
61 |
+
"model.layers.14.mlp.c_fc.weight": "pytorch_model-00002-of-00002.bin",
|
62 |
+
"model.layers.14.mlp.c_proj.weight": "pytorch_model-00002-of-00002.bin",
|
63 |
+
"model.layers.14.post_attention_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
64 |
+
"model.layers.14.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
65 |
+
"model.layers.15.attn.c_proj.weight": "pytorch_model-00002-of-00002.bin",
|
66 |
+
"model.layers.15.attn.qkv_proj.weight": "pytorch_model-00002-of-00002.bin",
|
67 |
+
"model.layers.15.input_layernorm.bias": "pytorch_model-00002-of-00002.bin",
|
68 |
+
"model.layers.15.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
69 |
+
"model.layers.15.mlp.c_fc.weight": "pytorch_model-00002-of-00002.bin",
|
70 |
+
"model.layers.15.mlp.c_proj.weight": "pytorch_model-00002-of-00002.bin",
|
71 |
+
"model.layers.15.post_attention_layernorm.bias": "pytorch_model-00002-of-00002.bin",
|
72 |
+
"model.layers.15.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
73 |
+
"model.layers.16.attn.c_proj.weight": "pytorch_model-00002-of-00002.bin",
|
74 |
+
"model.layers.16.attn.qkv_proj.weight": "pytorch_model-00002-of-00002.bin",
|
75 |
+
"model.layers.16.input_layernorm.bias": "pytorch_model-00002-of-00002.bin",
|
76 |
+
"model.layers.16.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
77 |
+
"model.layers.16.mlp.c_fc.weight": "pytorch_model-00002-of-00002.bin",
|
78 |
+
"model.layers.16.mlp.c_proj.weight": "pytorch_model-00002-of-00002.bin",
|
79 |
+
"model.layers.16.post_attention_layernorm.bias": "pytorch_model-00002-of-00002.bin",
|
80 |
+
"model.layers.16.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
81 |
+
"model.layers.17.attn.c_proj.weight": "pytorch_model-00002-of-00002.bin",
|
82 |
+
"model.layers.17.attn.qkv_proj.weight": "pytorch_model-00002-of-00002.bin",
|
83 |
+
"model.layers.17.input_layernorm.bias": "pytorch_model-00002-of-00002.bin",
|
84 |
+
"model.layers.17.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
85 |
+
"model.layers.17.mlp.c_fc.weight": "pytorch_model-00002-of-00002.bin",
|
86 |
+
"model.layers.17.mlp.c_proj.weight": "pytorch_model-00002-of-00002.bin",
|
87 |
+
"model.layers.17.post_attention_layernorm.bias": "pytorch_model-00002-of-00002.bin",
|
88 |
+
"model.layers.17.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
89 |
+
"model.layers.18.attn.c_proj.weight": "pytorch_model-00002-of-00002.bin",
|
90 |
+
"model.layers.18.attn.qkv_proj.weight": "pytorch_model-00002-of-00002.bin",
|
91 |
+
"model.layers.18.input_layernorm.bias": "pytorch_model-00002-of-00002.bin",
|
92 |
+
"model.layers.18.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
93 |
+
"model.layers.18.mlp.c_fc.weight": "pytorch_model-00002-of-00002.bin",
|
94 |
+
"model.layers.18.mlp.c_proj.weight": "pytorch_model-00002-of-00002.bin",
|
95 |
+
"model.layers.18.post_attention_layernorm.bias": "pytorch_model-00002-of-00002.bin",
|
96 |
+
"model.layers.18.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
97 |
+
"model.layers.19.attn.c_proj.weight": "pytorch_model-00002-of-00002.bin",
|
98 |
+
"model.layers.19.attn.qkv_proj.weight": "pytorch_model-00002-of-00002.bin",
|
99 |
+
"model.layers.19.input_layernorm.bias": "pytorch_model-00002-of-00002.bin",
|
100 |
+
"model.layers.19.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
101 |
+
"model.layers.19.mlp.c_fc.weight": "pytorch_model-00002-of-00002.bin",
|
102 |
+
"model.layers.19.mlp.c_proj.weight": "pytorch_model-00002-of-00002.bin",
|
103 |
+
"model.layers.19.post_attention_layernorm.bias": "pytorch_model-00002-of-00002.bin",
|
104 |
+
"model.layers.19.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
105 |
+
"model.layers.2.attn.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
106 |
+
"model.layers.2.attn.qkv_proj.weight": "pytorch_model-00001-of-00002.bin",
|
107 |
+
"model.layers.2.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
108 |
+
"model.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
109 |
+
"model.layers.2.mlp.c_fc.weight": "pytorch_model-00001-of-00002.bin",
|
110 |
+
"model.layers.2.mlp.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
111 |
+
"model.layers.2.post_attention_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
112 |
+
"model.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
113 |
+
"model.layers.3.attn.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
114 |
+
"model.layers.3.attn.qkv_proj.weight": "pytorch_model-00001-of-00002.bin",
|
115 |
+
"model.layers.3.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
116 |
+
"model.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
117 |
+
"model.layers.3.mlp.c_fc.weight": "pytorch_model-00001-of-00002.bin",
|
118 |
+
"model.layers.3.mlp.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
119 |
+
"model.layers.3.post_attention_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
120 |
+
"model.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
121 |
+
"model.layers.4.attn.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
122 |
+
"model.layers.4.attn.qkv_proj.weight": "pytorch_model-00001-of-00002.bin",
|
123 |
+
"model.layers.4.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
124 |
+
"model.layers.4.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
125 |
+
"model.layers.4.mlp.c_fc.weight": "pytorch_model-00001-of-00002.bin",
|
126 |
+
"model.layers.4.mlp.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
127 |
+
"model.layers.4.post_attention_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
128 |
+
"model.layers.4.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
129 |
+
"model.layers.5.attn.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
130 |
+
"model.layers.5.attn.qkv_proj.weight": "pytorch_model-00001-of-00002.bin",
|
131 |
+
"model.layers.5.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
132 |
+
"model.layers.5.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
133 |
+
"model.layers.5.mlp.c_fc.weight": "pytorch_model-00001-of-00002.bin",
|
134 |
+
"model.layers.5.mlp.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
135 |
+
"model.layers.5.post_attention_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
136 |
+
"model.layers.5.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
137 |
+
"model.layers.6.attn.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
138 |
+
"model.layers.6.attn.qkv_proj.weight": "pytorch_model-00001-of-00002.bin",
|
139 |
+
"model.layers.6.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
140 |
+
"model.layers.6.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
141 |
+
"model.layers.6.mlp.c_fc.weight": "pytorch_model-00001-of-00002.bin",
|
142 |
+
"model.layers.6.mlp.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
143 |
+
"model.layers.6.post_attention_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
144 |
+
"model.layers.6.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
145 |
+
"model.layers.7.attn.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
146 |
+
"model.layers.7.attn.qkv_proj.weight": "pytorch_model-00001-of-00002.bin",
|
147 |
+
"model.layers.7.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
148 |
+
"model.layers.7.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
149 |
+
"model.layers.7.mlp.c_fc.weight": "pytorch_model-00001-of-00002.bin",
|
150 |
+
"model.layers.7.mlp.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
151 |
+
"model.layers.7.post_attention_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
152 |
+
"model.layers.7.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
153 |
+
"model.layers.8.attn.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
154 |
+
"model.layers.8.attn.qkv_proj.weight": "pytorch_model-00001-of-00002.bin",
|
155 |
+
"model.layers.8.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
156 |
+
"model.layers.8.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
157 |
+
"model.layers.8.mlp.c_fc.weight": "pytorch_model-00001-of-00002.bin",
|
158 |
+
"model.layers.8.mlp.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
159 |
+
"model.layers.8.post_attention_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
160 |
+
"model.layers.8.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
161 |
+
"model.layers.9.attn.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
162 |
+
"model.layers.9.attn.qkv_proj.weight": "pytorch_model-00001-of-00002.bin",
|
163 |
+
"model.layers.9.input_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
164 |
+
"model.layers.9.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
165 |
+
"model.layers.9.mlp.c_fc.weight": "pytorch_model-00001-of-00002.bin",
|
166 |
+
"model.layers.9.mlp.c_proj.weight": "pytorch_model-00001-of-00002.bin",
|
167 |
+
"model.layers.9.post_attention_layernorm.bias": "pytorch_model-00001-of-00002.bin",
|
168 |
+
"model.layers.9.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
169 |
+
"model.word_embeddings.weight": "pytorch_model-00001-of-00002.bin"
|
170 |
+
}
|
171 |
+
}
|
special_tokens_map.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<s>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": true,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"eos_token": {
|
10 |
+
"content": "</s>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": true,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": {
|
17 |
+
"content": "<pad>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": true,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
},
|
23 |
+
"unk_token": {
|
24 |
+
"content": "<unk>",
|
25 |
+
"lstrip": false,
|
26 |
+
"normalized": true,
|
27 |
+
"rstrip": false,
|
28 |
+
"single_word": false
|
29 |
+
}
|
30 |
+
}
|
tokenization_hawk.py
ADDED
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""Tokenization classes for OpenAI GPT."""
|
16 |
+
|
17 |
+
|
18 |
+
import json
|
19 |
+
import os
|
20 |
+
from functools import lru_cache
|
21 |
+
from typing import TYPE_CHECKING, List, Optional, Tuple
|
22 |
+
|
23 |
+
import regex as re
|
24 |
+
|
25 |
+
from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
|
26 |
+
from transformers.utils import logging
|
27 |
+
|
28 |
+
|
29 |
+
if TYPE_CHECKING:
|
30 |
+
from transformers.pipelines.conversational import Conversation
|
31 |
+
|
32 |
+
logger = logging.get_logger(__name__)
|
33 |
+
|
34 |
+
VOCAB_FILES_NAMES = {
|
35 |
+
"vocab_file": "vocab.json",
|
36 |
+
"merges_file": "merges.txt",
|
37 |
+
}
|
38 |
+
|
39 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
40 |
+
"vocab_file": {
|
41 |
+
"hawk-demo": "/path/to/hawk/vocab.json",
|
42 |
+
},
|
43 |
+
"merges_file": {
|
44 |
+
"hawk-demo": "/path/to/hawk/merges.txt",
|
45 |
+
},
|
46 |
+
}
|
47 |
+
|
48 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
|
49 |
+
"hawk-demo": 1024,
|
50 |
+
}
|
51 |
+
|
52 |
+
|
53 |
+
@lru_cache()
|
54 |
+
def bytes_to_unicode():
|
55 |
+
"""
|
56 |
+
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
|
57 |
+
characters the bpe code barfs on.
|
58 |
+
|
59 |
+
The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
|
60 |
+
if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
|
61 |
+
decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
|
62 |
+
tables between utf-8 bytes and unicode strings.
|
63 |
+
"""
|
64 |
+
bs = (
|
65 |
+
list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
|
66 |
+
)
|
67 |
+
cs = bs[:]
|
68 |
+
n = 0
|
69 |
+
for b in range(2**8):
|
70 |
+
if b not in bs:
|
71 |
+
bs.append(b)
|
72 |
+
cs.append(2**8 + n)
|
73 |
+
n += 1
|
74 |
+
cs = [chr(n) for n in cs]
|
75 |
+
return dict(zip(bs, cs))
|
76 |
+
|
77 |
+
|
78 |
+
def get_pairs(word):
|
79 |
+
"""
|
80 |
+
Return set of symbol pairs in a word.
|
81 |
+
|
82 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
83 |
+
"""
|
84 |
+
pairs = set()
|
85 |
+
prev_char = word[0]
|
86 |
+
for char in word[1:]:
|
87 |
+
pairs.add((prev_char, char))
|
88 |
+
prev_char = char
|
89 |
+
return pairs
|
90 |
+
|
91 |
+
|
92 |
+
class HawkTokenizer(PreTrainedTokenizer):
|
93 |
+
"""
|
94 |
+
TODO NEED TO EXPAND
|
95 |
+
"""
|
96 |
+
|
97 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
98 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
99 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
100 |
+
model_input_names = ["input_ids", "attention_mask"]
|
101 |
+
|
102 |
+
def __init__(
|
103 |
+
self,
|
104 |
+
vocab_file,
|
105 |
+
merges_file,
|
106 |
+
errors="replace",
|
107 |
+
unk_token="<unk>",
|
108 |
+
bos_token="<s>",
|
109 |
+
eos_token="</s>",
|
110 |
+
pad_token="<pad>",
|
111 |
+
add_prefix_space=False,
|
112 |
+
add_bos_token=False,
|
113 |
+
**kwargs,
|
114 |
+
):
|
115 |
+
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
|
116 |
+
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
|
117 |
+
unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
|
118 |
+
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
|
119 |
+
super().__init__(
|
120 |
+
errors=errors,
|
121 |
+
unk_token=unk_token,
|
122 |
+
bos_token=bos_token,
|
123 |
+
eos_token=eos_token,
|
124 |
+
pad_token=pad_token,
|
125 |
+
add_prefix_space=add_prefix_space,
|
126 |
+
add_bos_token=add_bos_token,
|
127 |
+
**kwargs,
|
128 |
+
)
|
129 |
+
self.add_bos_token = add_bos_token
|
130 |
+
|
131 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
132 |
+
self.encoder = json.load(vocab_handle)
|
133 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
134 |
+
self.errors = errors # how to handle errors in decoding
|
135 |
+
self.byte_encoder = bytes_to_unicode()
|
136 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
137 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
138 |
+
bpe_merges = merges_handle.read().split("\n")[1:-1]
|
139 |
+
bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
|
140 |
+
self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
|
141 |
+
self.cache = {}
|
142 |
+
self.add_prefix_space = add_prefix_space
|
143 |
+
|
144 |
+
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
|
145 |
+
self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
|
146 |
+
|
147 |
+
@property
|
148 |
+
def vocab_size(self):
|
149 |
+
return len(self.encoder)
|
150 |
+
|
151 |
+
def get_vocab(self):
|
152 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
153 |
+
|
154 |
+
def bpe(self, token):
|
155 |
+
if token in self.cache:
|
156 |
+
return self.cache[token]
|
157 |
+
word = tuple(token)
|
158 |
+
pairs = get_pairs(word)
|
159 |
+
|
160 |
+
if not pairs:
|
161 |
+
return token
|
162 |
+
|
163 |
+
while True:
|
164 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
165 |
+
if bigram not in self.bpe_ranks:
|
166 |
+
break
|
167 |
+
first, second = bigram
|
168 |
+
new_word = []
|
169 |
+
i = 0
|
170 |
+
while i < len(word):
|
171 |
+
try:
|
172 |
+
j = word.index(first, i)
|
173 |
+
except ValueError:
|
174 |
+
new_word.extend(word[i:])
|
175 |
+
break
|
176 |
+
else:
|
177 |
+
new_word.extend(word[i:j])
|
178 |
+
i = j
|
179 |
+
|
180 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
181 |
+
new_word.append(first + second)
|
182 |
+
i += 2
|
183 |
+
else:
|
184 |
+
new_word.append(word[i])
|
185 |
+
i += 1
|
186 |
+
new_word = tuple(new_word)
|
187 |
+
word = new_word
|
188 |
+
if len(word) == 1:
|
189 |
+
break
|
190 |
+
else:
|
191 |
+
pairs = get_pairs(word)
|
192 |
+
word = " ".join(word)
|
193 |
+
self.cache[token] = word
|
194 |
+
return word
|
195 |
+
|
196 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
197 |
+
if self.add_bos_token:
|
198 |
+
bos_token_ids = [self.bos_token_id]
|
199 |
+
else:
|
200 |
+
bos_token_ids = []
|
201 |
+
|
202 |
+
output = bos_token_ids + token_ids_0
|
203 |
+
|
204 |
+
if token_ids_1 is None:
|
205 |
+
return output
|
206 |
+
|
207 |
+
return output + bos_token_ids + token_ids_1
|
208 |
+
|
209 |
+
def get_special_tokens_mask(
|
210 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
211 |
+
) -> List[int]:
|
212 |
+
"""
|
213 |
+
Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
|
214 |
+
special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
|
215 |
+
|
216 |
+
Args:
|
217 |
+
token_ids_0 (`List[int]`):
|
218 |
+
List of IDs.
|
219 |
+
token_ids_1 (`List[int]`, *optional*):
|
220 |
+
Optional second list of IDs for sequence pairs.
|
221 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
222 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
223 |
+
|
224 |
+
Returns:
|
225 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
226 |
+
"""
|
227 |
+
if already_has_special_tokens:
|
228 |
+
return super().get_special_tokens_mask(
|
229 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
230 |
+
)
|
231 |
+
|
232 |
+
if not self.add_bos_token:
|
233 |
+
return super().get_special_tokens_mask(
|
234 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=False
|
235 |
+
)
|
236 |
+
|
237 |
+
if token_ids_1 is None:
|
238 |
+
return [1] + ([0] * len(token_ids_0))
|
239 |
+
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
|
240 |
+
|
241 |
+
def _tokenize(self, text):
|
242 |
+
"""Tokenize a string."""
|
243 |
+
bpe_tokens = []
|
244 |
+
for token in re.findall(self.pat, text):
|
245 |
+
token = "".join(
|
246 |
+
self.byte_encoder[b] for b in token.encode("utf-8")
|
247 |
+
) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
|
248 |
+
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
|
249 |
+
return bpe_tokens
|
250 |
+
|
251 |
+
def _convert_token_to_id(self, token):
|
252 |
+
"""Converts a token (str) in an id using the vocab."""
|
253 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
254 |
+
|
255 |
+
def _convert_id_to_token(self, index):
|
256 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
257 |
+
return self.decoder.get(index)
|
258 |
+
|
259 |
+
def convert_tokens_to_string(self, tokens):
|
260 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
261 |
+
text = "".join(tokens)
|
262 |
+
text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
|
263 |
+
return text
|
264 |
+
|
265 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
266 |
+
if not os.path.isdir(save_directory):
|
267 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
268 |
+
return
|
269 |
+
vocab_file = os.path.join(
|
270 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
271 |
+
)
|
272 |
+
merge_file = os.path.join(
|
273 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
274 |
+
)
|
275 |
+
|
276 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
277 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
278 |
+
|
279 |
+
index = 0
|
280 |
+
with open(merge_file, "w", encoding="utf-8") as writer:
|
281 |
+
writer.write("#version: 0.2\n")
|
282 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
|
283 |
+
if index != token_index:
|
284 |
+
logger.warning(
|
285 |
+
f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
|
286 |
+
" Please check that the tokenizer is not corrupted!"
|
287 |
+
)
|
288 |
+
index = token_index
|
289 |
+
writer.write(" ".join(bpe_tokens) + "\n")
|
290 |
+
index += 1
|
291 |
+
|
292 |
+
return vocab_file, merge_file
|
293 |
+
|
294 |
+
def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
|
295 |
+
add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
|
296 |
+
if is_split_into_words or add_prefix_space:
|
297 |
+
text = " " + text
|
298 |
+
return (text, kwargs)
|
299 |
+
|
300 |
+
def _build_conversation_input_ids(self, conversation: "Conversation") -> List[int]:
|
301 |
+
input_ids = []
|
302 |
+
for is_user, text in conversation.iter_texts():
|
303 |
+
input_ids.extend(self.encode(text, add_special_tokens=False) + [self.eos_token_id])
|
304 |
+
if len(input_ids) > self.model_max_length:
|
305 |
+
input_ids = input_ids[-self.model_max_length :]
|
306 |
+
return input_ids
|
tokenizer_config.json
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": false,
|
3 |
+
"add_prefix_space": false,
|
4 |
+
"auto_map": {
|
5 |
+
"AutoTokenizer": [
|
6 |
+
"tokenization_hawk.HawkTokenizer",
|
7 |
+
null
|
8 |
+
]
|
9 |
+
},
|
10 |
+
"bos_token": {
|
11 |
+
"__type": "AddedToken",
|
12 |
+
"content": "<s>",
|
13 |
+
"lstrip": false,
|
14 |
+
"normalized": true,
|
15 |
+
"rstrip": false,
|
16 |
+
"single_word": false
|
17 |
+
},
|
18 |
+
"clean_up_tokenization_spaces": true,
|
19 |
+
"eos_token": {
|
20 |
+
"__type": "AddedToken",
|
21 |
+
"content": "</s>",
|
22 |
+
"lstrip": false,
|
23 |
+
"normalized": true,
|
24 |
+
"rstrip": false,
|
25 |
+
"single_word": false
|
26 |
+
},
|
27 |
+
"errors": "replace",
|
28 |
+
"model_max_length": 1000000000000000019884624838656,
|
29 |
+
"pad_token": {
|
30 |
+
"__type": "AddedToken",
|
31 |
+
"content": "<pad>",
|
32 |
+
"lstrip": false,
|
33 |
+
"normalized": true,
|
34 |
+
"rstrip": false,
|
35 |
+
"single_word": false
|
36 |
+
},
|
37 |
+
"tokenizer_class": "HawkTokenizer",
|
38 |
+
"unk_token": {
|
39 |
+
"__type": "AddedToken",
|
40 |
+
"content": "<unk>",
|
41 |
+
"lstrip": false,
|
42 |
+
"normalized": true,
|
43 |
+
"rstrip": false,
|
44 |
+
"single_word": false
|
45 |
+
}
|
46 |
+
}
|
vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|