npvinHnivqn
commited on
Commit
•
01d9133
1
Parent(s):
74cf8ae
bug
Browse files- LICENSE +42 -0
- README.md +154 -0
- config.json +31 -0
- configuration_stablelm_epoch.py +116 -0
- generation_config.json +6 -0
- model.safetensors +3 -0
- modeling_stablelm_epoch.py +949 -0
- special_tokens_map.json +30 -0
- tokenizer.json +0 -0
- tokenizer_config.json +213 -0
LICENSE
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
STABILITY AI NON-COMMERCIAL RESEARCH COMMUNITY LICENSE AGREEMENT
|
2 |
+
Dated: December 06, 2023
|
3 |
+
|
4 |
+
By using or distributing any portion or element of the Models, Software, Software Products or Derivative Works, you agree to be bound by this Agreement.
|
5 |
+
|
6 |
+
"Agreement" means this Stable Non-Commercial Research Community License Agreement.
|
7 |
+
|
8 |
+
“AUP” means the Stability AI Acceptable Use Policy available at https://stability.ai/use-policy, as may be updated from time to time.
|
9 |
+
|
10 |
+
"Derivative Work(s)” means (a) any derivative work of the Software Products as recognized by U.S. copyright laws and (b) any modifications to a Model, and any other model created which is based on or derived from the Model or the Model’s output. For clarity, Derivative Works do not include the output of any Model.
|
11 |
+
|
12 |
+
“Documentation” means any specifications, manuals, documentation, and other written information provided by Stability AI related to the Software.
|
13 |
+
|
14 |
+
"Licensee" or "you" means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity's behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf.
|
15 |
+
|
16 |
+
“Model(s)" means, collectively, Stability AI’s proprietary models and algorithms, including machine-learning models, trained model weights and other elements of the foregoing, made available under this Agreement.
|
17 |
+
|
18 |
+
“Non-Commercial Uses” means exercising any of the rights granted herein for the purpose of research or non-commercial purposes. Non-Commercial Uses does not include any production use of the Software Products or any Derivative Works.
|
19 |
+
|
20 |
+
"Stability AI" or "we" means Stability AI Ltd. and its affiliates.
|
21 |
+
|
22 |
+
|
23 |
+
"Software" means Stability AI’s proprietary software made available under this Agreement.
|
24 |
+
|
25 |
+
“Software Products” means the Models, Software and Documentation, individually or in any combination.
|
26 |
+
|
27 |
+
|
28 |
+
|
29 |
+
1. License Rights and Redistribution.
|
30 |
+
a. Subject to your compliance with this Agreement, the AUP (which is hereby incorporated herein by reference), and the Documentation, Stability AI grants you a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable, royalty free and limited license under Stability AI’s intellectual property or other rights owned or controlled by Stability AI embodied in the Software Products to use, reproduce, distribute, and create Derivative Works of, the Software Products, in each case for Non-Commercial Uses only.
|
31 |
+
b. You may not use the Software Products or Derivative Works to enable third parties to use the Software Products or Derivative Works as part of your hosted service or via your APIs, whether you are adding substantial additional functionality thereto or not. Merely distributing the Software Products or Derivative Works for download online without offering any related service (ex. by distributing the Models on HuggingFace) is not a violation of this subsection. If you wish to use the Software Products or any Derivative Works for commercial or production use or you wish to make the Software Products or any Derivative Works available to third parties via your hosted service or your APIs, contact Stability AI at https://stability.ai/contact.
|
32 |
+
c. If you distribute or make the Software Products, or any Derivative Works thereof, available to a third party, the Software Products, Derivative Works, or any portion thereof, respectively, will remain subject to this Agreement and you must (i) provide a copy of this Agreement to such third party, and (ii) retain the following attribution notice within a "Notice" text file distributed as a part of such copies: "This Stability AI Model is licensed under the Stability AI Non-Commercial Research Community License, Copyright (c) Stability AI Ltd. All Rights Reserved.” If you create a Derivative Work of a Software Product, you may add your own attribution notices to the Notice file included with the Software Product, provided that you clearly indicate which attributions apply to the Software Product and you must state in the NOTICE file that you changed the Software Product and how it was modified.
|
33 |
+
2. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE SOFTWARE PRODUCTS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE SOFTWARE PRODUCTS, DERIVATIVE WORKS OR ANY OUTPUT OR RESULTS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE SOFTWARE PRODUCTS, DERIVATIVE WORKS AND ANY OUTPUT AND RESULTS.
|
34 |
+
3. Limitation of Liability. IN NO EVENT WILL STABILITY AI OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF STABILITY AI OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
|
35 |
+
4. Intellectual Property.
|
36 |
+
a. No trademark licenses are granted under this Agreement, and in connection with the Software Products or Derivative Works, neither Stability AI nor Licensee may use any name or mark owned by or associated with the other or any of its affiliates, except as required for reasonable and customary use in describing and redistributing the Software Products or Derivative Works.
|
37 |
+
b. Subject to Stability AI’s ownership of the Software Products and Derivative Works made by or for Stability AI, with respect to any Derivative Works that are made by you, as between you and Stability AI, you are and will be the owner of such Derivative Works
|
38 |
+
c. If you institute litigation or other proceedings against Stability AI (including a cross-claim or counterclaim in a lawsuit) alleging that the Software Products, Derivative Works or associated outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Stability AI from and against any claim by any third party arising out of or related to your use or distribution of the Software Products or Derivative Works in violation of this Agreement.
|
39 |
+
5. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access to the Software Products and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Stability AI may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of any Software Products or Derivative Works. Sections 2-4 shall survive the termination of this Agreement.
|
40 |
+
|
41 |
+
6. Governing Law. This Agreement will be governed by and construed in accordance with the laws of the United States and the State of California without regard to choice of law
|
42 |
+
principles.
|
README.md
ADDED
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
datasets:
|
3 |
+
- HuggingFaceH4/ultrachat_200k
|
4 |
+
- HuggingFaceH4/ultrafeedback_binarized
|
5 |
+
- meta-math/MetaMathQA
|
6 |
+
- WizardLM/WizardLM_evol_instruct_V2_196k
|
7 |
+
- Intel/orca_dpo_pairs
|
8 |
+
language:
|
9 |
+
- en
|
10 |
+
tags:
|
11 |
+
- causal-lm
|
12 |
+
extra_gated_fields:
|
13 |
+
Name: text
|
14 |
+
Email: text
|
15 |
+
Country: text
|
16 |
+
Organization or Affiliation: text
|
17 |
+
I ALLOW Stability AI to email me about new model releases: checkbox
|
18 |
+
license: other
|
19 |
+
---
|
20 |
+
# `StableLM Zephyr 3B`
|
21 |
+
|
22 |
+
## Model Description
|
23 |
+
|
24 |
+
`StableLM Zephyr 3B` is a 3 billion parameter instruction tuned inspired by [HugginFaceH4's Zephyr 7B](https://huggingface.co/HuggingFaceH4/zephyr-7b-beta) training pipeline this model was trained on a mix of publicly available datasets, synthetic datasets using [Direct Preference Optimization (DPO)](https://arxiv.org/abs/2305.18290), evaluation for this model based on
|
25 |
+
[MT Bench](https://tatsu-lab.github.io/alpaca_eval/) and [Alpaca Benchmark](https://tatsu-lab.github.io/alpaca_eval/)
|
26 |
+
|
27 |
+
## Usage
|
28 |
+
|
29 |
+
`StableLM Zephyr 3B` uses the following instruction format:
|
30 |
+
```
|
31 |
+
<|user|>
|
32 |
+
List 3 synonyms for the word "tiny"<|endoftext|>
|
33 |
+
<|assistant|>
|
34 |
+
1. Dwarf
|
35 |
+
2. Little
|
36 |
+
3. Petite<|endoftext|>
|
37 |
+
```
|
38 |
+
|
39 |
+
This format is also available through the tokenizer's `apply_chat_template` method:
|
40 |
+
|
41 |
+
```python
|
42 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
43 |
+
|
44 |
+
tokenizer = AutoTokenizer.from_pretrained('stabilityai/stablelm-zephyr-3b')
|
45 |
+
model = AutoModelForCausalLM.from_pretrained(
|
46 |
+
'stabilityai/stablelm-zephyr-3b',
|
47 |
+
trust_remote_code=True,
|
48 |
+
device_map="auto"
|
49 |
+
)
|
50 |
+
|
51 |
+
prompt = [{'role': 'user', 'content': 'List 3 synonyms for the word "tiny"'}]
|
52 |
+
inputs = tokenizer.apply_chat_template(
|
53 |
+
prompt,
|
54 |
+
add_generation_prompt=True,
|
55 |
+
return_tensors='pt'
|
56 |
+
)
|
57 |
+
|
58 |
+
tokens = model.generate(
|
59 |
+
inputs.to(model.device),
|
60 |
+
max_new_tokens=1024,
|
61 |
+
temperature=0.8,
|
62 |
+
do_sample=True
|
63 |
+
)
|
64 |
+
|
65 |
+
print(tokenizer.decode(tokens[0], skip_special_tokens=False))
|
66 |
+
```
|
67 |
+
|
68 |
+
You can also see how to run a performance optimized version of this model [here](https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/273-stable-zephyr-3b-chatbot/273-stable-zephyr-3b-chatbot.ipynb) using [OpenVINO](https://docs.openvino.ai/2023.2/home.html) from Intel.
|
69 |
+
|
70 |
+
## Model Details
|
71 |
+
|
72 |
+
* **Developed by**: [Stability AI](https://stability.ai/)
|
73 |
+
* **Model type**: `StableLM Zephyr 3B` model is an auto-regressive language model based on the transformer decoder architecture.
|
74 |
+
* **Language(s)**: English
|
75 |
+
* **Library**: [Alignment Handbook](https://github.com/huggingface/alignment-handbook.git)
|
76 |
+
* **Finetuned from model**: [stabilityai/stablelm-3b-4e1t](https://huggingface.co/stabilityai/stablelm-3b-4e1t)
|
77 |
+
* **License**: [StabilityAI Non-Commercial Research Community License](https://huggingface.co/stabilityai/stablelm-zephyr-3b/raw/main/LICENSE). If you want to use this model for your commercial products or purposes, please contact us [here](https://stability.ai/contact) to learn more.
|
78 |
+
* **Contact**: For questions and comments about the model, please email `lm@stability.ai`
|
79 |
+
|
80 |
+
### Training Dataset
|
81 |
+
|
82 |
+
The dataset is comprised of a mixture of open datasets large-scale datasets available on the [HuggingFace Hub](https://huggingface.co/datasets):
|
83 |
+
1. SFT Datasets
|
84 |
+
- HuggingFaceH4/ultrachat_200k
|
85 |
+
- meta-math/MetaMathQA
|
86 |
+
- WizardLM/WizardLM_evol_instruct_V2_196k
|
87 |
+
- Open-Orca/SlimOrca
|
88 |
+
2. Preference Datasets:
|
89 |
+
- HuggingFaceH4/ultrafeedback_binarized
|
90 |
+
- Intel/orca_dpo_pairs
|
91 |
+
|
92 |
+
## Performance
|
93 |
+
|
94 |
+
### MT-Bench and Alpaca Bench
|
95 |
+
|
96 |
+
|
97 |
+
<img src="https://cdn-uploads.huggingface.co/production/uploads/6310474ca119d49bc1eb0d80/8WIZS6dAlu5kSH-382pMl.png" alt="mt_bench_plot" width="600"/>
|
98 |
+
|
99 |
+
| Model | Size | Alignment | MT-Bench (score) | AlpacaEval (win rate %) |
|
100 |
+
|-------------|-----|----|---------------|--------------|
|
101 |
+
| **StableLM Zephyr 3B** 🪁 | 3B | DPO | 6.64 | 76.00 |
|
102 |
+
| StableLM Zephyr (SFT only) | 3B | SFT | 6.04 | 71.15 |
|
103 |
+
| Capybara v1.9 | 3B | dSFT | 5.94 | - |
|
104 |
+
| MPT-Chat | 7B |dSFT |5.42| -|
|
105 |
+
| Xwin-LM v0.1 | 7B| dPPO| 6.19| 87.83|
|
106 |
+
| Mistral-Instruct v0.1 | 7B| - | 6.84 |-|
|
107 |
+
| Zephyr-7b-α |7B| dDPO| 6.88| -|
|
108 |
+
| Zephyr-7b-β| 7B | dDPO | 7.34 | 90.60 |
|
109 |
+
| Falcon-Instruct | 40B |dSFT |5.17 |45.71|
|
110 |
+
| Guanaco | 65B | SFT |6.41| 71.80|
|
111 |
+
| Llama2-Chat | 70B |RLHF |6.86| 92.66|
|
112 |
+
| Vicuna v1.3 | 33B |dSFT |7.12 |88.99|
|
113 |
+
| WizardLM v1.0 | 70B |dSFT |7.71 |-|
|
114 |
+
| Xwin-LM v0.1 | 70B |dPPO |- |95.57|
|
115 |
+
| GPT-3.5-turbo | - |RLHF |7.94 |89.37|
|
116 |
+
| Claude 2 | - |RLHF |8.06| 91.36|
|
117 |
+
| GPT-4 | -| RLHF |8.99| 95.28|
|
118 |
+
|
119 |
+
## Other benchmarks:
|
120 |
+
| Task | Value |
|
121 |
+
|-----------------------|---------------------------|
|
122 |
+
| ARC (25-shot) | 47.0 |
|
123 |
+
| HellaSwag (10-shot) | 74.2 |
|
124 |
+
| MMLU (5-shot) | 46.3 |
|
125 |
+
| TruthfulQA (0-shot) | 46.5 |
|
126 |
+
| Winogrande (5-shot) | 65.5 |
|
127 |
+
| GSM8K (5-shot) | 42.3 |
|
128 |
+
| BigBench (Avg) | 35.26 |
|
129 |
+
| AGI Benchmark (Avg) | 33.23 |
|
130 |
+
|
131 |
+
### Training Infrastructure
|
132 |
+
|
133 |
+
* **Hardware**: `StableLM Zephyr 3B` was trained on the Stability AI cluster across 8 nodes with 8 A100 80GBs GPUs for each nodes.
|
134 |
+
* **Code Base**: We use our internal script for SFT steps and used [HuggingFace Alignment Handbook script](https://github.com/huggingface/alignment-handbook) for DPO training.
|
135 |
+
|
136 |
+
## Commitment to Ethical AI
|
137 |
+
In line with our responsibility towards ethical AI development, `StableLM Zephyr 3B` is released with a focus on ensuring safety, reliability, and appropriateness in its applications. To this end, we have evaluated `StableLM Zephyr 3B` on 488 malicious prompts and used standard protocols to assess the harmfulness of its outputs. Compared to Zephyr-7b-β, `StableLM Zephyr 3B` reduces the number of harmful outputs as assessed by GPT-4 by 55. Additionally, we performed an internal red teaming event targeting the following abuse areas:
|
138 |
+
* **Self-Harm Methods**: (Suicide Methods, Encouragement of Self-Harm, Methods and encouragement of Eating Disorders)
|
139 |
+
* **Misinformation**: (Health, Conspiracy Theories, Social Unrest/Conflict, Political Misinformation, & Climate change)
|
140 |
+
* **Hate Speech**: (Race, Stereotypes, Immigrants, Gender, Personally Identifiable Information such as Social security numbers, Full names, ID numbers, Email addresses, and telephone numbers)
|
141 |
+
|
142 |
+
We have incorporated the findings of our malicious prompts evaluation and red teaming event into our release. Users are encouraged to fine-tune and evaluate the model to suit their specific needs, considering the potential biases and limitations found in `StableLM Zephyr 3B` and inherent in other LLM models.
|
143 |
+
|
144 |
+
## Use and Limitations
|
145 |
+
|
146 |
+
### Intended Use
|
147 |
+
|
148 |
+
The model is intended to be used as a foundational base model for application-specific fine-tuning. Developers must evaluate and fine-tune the model for safe performance in downstream applications.
|
149 |
+
|
150 |
+
### Limitations and Bias
|
151 |
+
|
152 |
+
This model is not trained against adversarial inputs. We strongly recommend pairing this model with an input and output classifier to prevent harmful responses.
|
153 |
+
|
154 |
+
Through our internal red teaming, we discovered that while the model will not output harmful information if not prompted to do so, it is willing to output potentially harmful outputs or misinformation when the user requests it. Using this model will require guardrails around your inputs and outputs to ensure that any outputs returned are not misinformation or harmful. Additionally, as each use case is unique, we recommend running your own suite of tests to ensure proper performance of this model. Finally, do not use the models if they are unsuitable for your application, or for any applications that may cause deliberate or unintentional harm to others.
|
config.json
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "stabilityai/stablelm-zephyr-3b",
|
3 |
+
"architectures": [
|
4 |
+
"StableLMEpochForCausalLM"
|
5 |
+
],
|
6 |
+
"auto_map": {
|
7 |
+
"AutoConfig": "configuration_stablelm_epoch.StableLMEpochConfig",
|
8 |
+
"AutoModelForCausalLM": "modeling_stablelm_epoch.StableLMEpochForCausalLM"
|
9 |
+
},
|
10 |
+
"bos_token_id": 0,
|
11 |
+
"eos_token_id": 0,
|
12 |
+
"hidden_act": "silu",
|
13 |
+
"hidden_size": 2560,
|
14 |
+
"initializer_range": 0.02,
|
15 |
+
"intermediate_size": 6912,
|
16 |
+
"max_position_embeddings": 4096,
|
17 |
+
"model_type": "stablelm_epoch",
|
18 |
+
"norm_eps": 1e-05,
|
19 |
+
"num_attention_heads": 32,
|
20 |
+
"num_heads": 32,
|
21 |
+
"num_hidden_layers": 32,
|
22 |
+
"num_key_value_heads": 32,
|
23 |
+
"rope_pct": 0.25,
|
24 |
+
"rope_theta": 10000,
|
25 |
+
"rotary_scaling_factor": 1.0,
|
26 |
+
"tie_word_embeddings": false,
|
27 |
+
"torch_dtype": "bfloat16",
|
28 |
+
"transformers_version": "4.35.2",
|
29 |
+
"use_cache": true,
|
30 |
+
"vocab_size": 50304
|
31 |
+
}
|
configuration_stablelm_epoch.py
ADDED
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 Stability and The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
""" StableLM Epoch model configuration"""
|
16 |
+
from transformers import PretrainedConfig
|
17 |
+
from transformers.utils import logging
|
18 |
+
import sys
|
19 |
+
sys.path.append("./")
|
20 |
+
|
21 |
+
|
22 |
+
logger = logging.get_logger(__name__)
|
23 |
+
|
24 |
+
|
25 |
+
class StableLMEpochConfig(PretrainedConfig):
|
26 |
+
r"""
|
27 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
28 |
+
documentation from [`PretrainedConfig`] for more information.
|
29 |
+
|
30 |
+
Args:
|
31 |
+
vocab_size (`int`, *optional*, defaults to 50_304):
|
32 |
+
Vocabulary size of the StableLM model. Defines the number of different tokens that
|
33 |
+
can be represented by the `inputs_ids` passed when calling [`StableLMEpochModel`].
|
34 |
+
intermediate_size (`int`, *optional*, defaults to 6912):
|
35 |
+
Dimension of the MLP representations.
|
36 |
+
hidden_size (`int`, *optional*, defaults to 2560):
|
37 |
+
Dimension of the decoder layers and the pooler layer.
|
38 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
39 |
+
Number of hidden layers in the Transformer decoder.
|
40 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
41 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
42 |
+
num_key_value_heads (`int`, *optional*):
|
43 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
44 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
45 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
46 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
47 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
48 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
49 |
+
`num_attention_heads`.
|
50 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
51 |
+
The non-linear activation function (function or string).
|
52 |
+
rope_pct (`float`, *optional*, defaults to 1.0):
|
53 |
+
Percentage of hidden dimensions to allocate to rotary embeddings.
|
54 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
55 |
+
The base period of the RoPE embeddings.
|
56 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
57 |
+
The maximum sequence length that this model might ever be used with.
|
58 |
+
Typically set this to something large just in case (e.g., 512 or 1024 or 2048).
|
59 |
+
initializer_range (`float`, *optional*, defaults to 1e-5):
|
60 |
+
The standard deviation of the truncated_normal_initializer for initializing
|
61 |
+
all weight matrices.
|
62 |
+
norm_eps (`float`, *optional*, defaults to 1e-8):
|
63 |
+
The epsilon used by the normalization layers.
|
64 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
65 |
+
Whether or not the model should return the last key/values attentions
|
66 |
+
(not used by all models). Only relevant if `config.is_decoder=True`.
|
67 |
+
tie_word_embeddings(`bool`, *optional*, defaults to `False`):
|
68 |
+
Whether to tie weight embeddings
|
69 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
70 |
+
The dropout ratio for the attention probabilities.
|
71 |
+
"""
|
72 |
+
model_type = "stablelm_epoch"
|
73 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
74 |
+
|
75 |
+
def __init__(
|
76 |
+
self,
|
77 |
+
vocab_size=50_304,
|
78 |
+
intermediate_size=6912,
|
79 |
+
hidden_size=2560,
|
80 |
+
num_hidden_layers=32,
|
81 |
+
num_attention_heads=32,
|
82 |
+
num_key_value_heads=32,
|
83 |
+
hidden_act="silu",
|
84 |
+
rope_pct=0.25,
|
85 |
+
rope_theta=10_000,
|
86 |
+
max_position_embeddings=4096,
|
87 |
+
initializer_range=0.02,
|
88 |
+
norm_eps=1.0e-5,
|
89 |
+
use_cache=True,
|
90 |
+
bos_token_id=0,
|
91 |
+
eos_token_id=2,
|
92 |
+
tie_word_embeddings=False,
|
93 |
+
attention_dropout: float = 0.0,
|
94 |
+
**kwargs,
|
95 |
+
):
|
96 |
+
self.vocab_size = vocab_size
|
97 |
+
self.max_position_embeddings = max_position_embeddings
|
98 |
+
self.intermediate_size = intermediate_size
|
99 |
+
self.hidden_size = hidden_size
|
100 |
+
self.num_hidden_layers = num_hidden_layers
|
101 |
+
self.num_attention_heads = num_attention_heads
|
102 |
+
self.num_key_value_heads = num_key_value_heads
|
103 |
+
self.hidden_act = hidden_act
|
104 |
+
self.rope_pct = rope_pct
|
105 |
+
self.rope_theta = rope_theta
|
106 |
+
self.initializer_range = initializer_range
|
107 |
+
self.norm_eps = norm_eps
|
108 |
+
self.use_cache = use_cache
|
109 |
+
self.tie_word_embeddings = tie_word_embeddings
|
110 |
+
self.attention_dropout = attention_dropout
|
111 |
+
super().__init__(
|
112 |
+
bos_token_id=bos_token_id,
|
113 |
+
eos_token_id=eos_token_id,
|
114 |
+
tie_word_embeddings=tie_word_embeddings,
|
115 |
+
**kwargs,
|
116 |
+
)
|
generation_config.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 0,
|
4 |
+
"eos_token_id": 0,
|
5 |
+
"transformers_version": "4.35.2"
|
6 |
+
}
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a64e61de38fb07678572b0d9ef3e5ae29e7555bfade2f1e61fd02c978052cd18
|
3 |
+
size 5590927496
|
modeling_stablelm_epoch.py
ADDED
@@ -0,0 +1,949 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2023 Stability AI, EleutherAI, and The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
#
|
16 |
+
# This code is based off the following work:
|
17 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py
|
18 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt_neox/modeling_gpt_neox.py
|
19 |
+
""" PyTorch StableLM Epoch model. """
|
20 |
+
from typing import Optional, Tuple, Union
|
21 |
+
import math
|
22 |
+
import warnings
|
23 |
+
|
24 |
+
import torch
|
25 |
+
import torch.nn.functional as F
|
26 |
+
import torch.utils.checkpoint
|
27 |
+
from torch import nn
|
28 |
+
from torch.nn import CrossEntropyLoss
|
29 |
+
|
30 |
+
from transformers.cache_utils import Cache
|
31 |
+
from transformers.modeling_outputs import (
|
32 |
+
BaseModelOutputWithPast,
|
33 |
+
CausalLMOutputWithPast,
|
34 |
+
)
|
35 |
+
from transformers.modeling_utils import PreTrainedModel
|
36 |
+
from transformers.utils import logging, is_flash_attn_greater_or_equal_2_10
|
37 |
+
|
38 |
+
from .configuration_stablelm_epoch import StableLMEpochConfig
|
39 |
+
|
40 |
+
try:
|
41 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
42 |
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
|
43 |
+
except:
|
44 |
+
flash_attn_func, flash_attn_varlen_func = None, None
|
45 |
+
index_first_axis, pad_input, unpad_input = None, None, None
|
46 |
+
|
47 |
+
|
48 |
+
logger = logging.get_logger(__name__)
|
49 |
+
|
50 |
+
|
51 |
+
# Copied from transformers.models.llama.modeling_llama._get_unpad_data
|
52 |
+
def _get_unpad_data(attention_mask):
|
53 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
54 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
55 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
56 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
|
57 |
+
return (
|
58 |
+
indices,
|
59 |
+
cu_seqlens,
|
60 |
+
max_seqlen_in_batch,
|
61 |
+
)
|
62 |
+
|
63 |
+
|
64 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
65 |
+
def _make_causal_mask(
|
66 |
+
input_ids_shape: torch.Size,
|
67 |
+
dtype: torch.dtype,
|
68 |
+
device: torch.device,
|
69 |
+
past_key_values_length: int = 0,
|
70 |
+
):
|
71 |
+
"""Make causal mask used for bi-directional self-attention."""
|
72 |
+
batch_size, tgt_len = input_ids_shape
|
73 |
+
mask = torch.full((tgt_len, tgt_len), torch.finfo(torch.float16).min, device=device)
|
74 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
75 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
76 |
+
mask = mask.to(dtype)
|
77 |
+
if past_key_values_length > 0:
|
78 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
79 |
+
return mask[None, None, :, :].expand(batch_size, 1, tgt_len, tgt_len + past_key_values_length)
|
80 |
+
|
81 |
+
|
82 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
83 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
84 |
+
"""Expands attention_mask from `[batch_size, seq_len]` to `[batch_size, 1, tgt_seq_len, src_seq_len]`."""
|
85 |
+
batch_size, src_len = mask.size()
|
86 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
87 |
+
|
88 |
+
expanded_mask = mask[:, None, None, :].expand(batch_size, 1, tgt_len, src_len).to(dtype)
|
89 |
+
inverted_mask = 1.0 - expanded_mask
|
90 |
+
|
91 |
+
return inverted_mask.masked_fill(
|
92 |
+
inverted_mask.to(torch.bool), torch.finfo(dtype).min
|
93 |
+
)
|
94 |
+
|
95 |
+
|
96 |
+
class RotaryEmbedding(nn.Module):
|
97 |
+
def __init__(
|
98 |
+
self,
|
99 |
+
dim: int,
|
100 |
+
max_position_embeddings: int,
|
101 |
+
base: int = 10_000,
|
102 |
+
device: Optional[torch.device] = None,
|
103 |
+
):
|
104 |
+
super().__init__()
|
105 |
+
|
106 |
+
self.dim = dim
|
107 |
+
self.max_position_embeddings = max_position_embeddings
|
108 |
+
self.base = base
|
109 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim))
|
110 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
111 |
+
|
112 |
+
# Build here to make `torch.jit.trace` work.
|
113 |
+
self._set_cos_sin_cache(
|
114 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype(),
|
115 |
+
)
|
116 |
+
|
117 |
+
def _set_cos_sin_cache(self, seq_len: int, device: torch.device, dtype: torch.dtype):
|
118 |
+
self.max_seq_len_cached = seq_len
|
119 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)
|
120 |
+
|
121 |
+
# Don't do einsum, it converts fp32 to fp16 under AMP
|
122 |
+
# freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
123 |
+
freqs = torch.outer(t, self.inv_freq)
|
124 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
125 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
126 |
+
self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
|
127 |
+
self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
|
128 |
+
|
129 |
+
def forward(self, x: torch.Tensor, seq_len: Optional[int] = None):
|
130 |
+
# x: [batch_size, num_heads, seq_len, head_size]
|
131 |
+
if seq_len > self.max_seq_len_cached:
|
132 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=torch.get_default_dtype())
|
133 |
+
return (
|
134 |
+
self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
135 |
+
self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
136 |
+
)
|
137 |
+
|
138 |
+
|
139 |
+
def rotate_half(x: torch.Tensor):
|
140 |
+
"""Rotates half the hidden dims of the input."""
|
141 |
+
x1, x2 = torch.chunk(x, 2, dim=-1)
|
142 |
+
return torch.cat((-x2, x1), dim=-1)
|
143 |
+
|
144 |
+
|
145 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
|
146 |
+
# The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
|
147 |
+
cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
|
148 |
+
sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
|
149 |
+
cos = cos[position_ids].unsqueeze(1) # [batch_size, 1, seq_len, dim]
|
150 |
+
sin = sin[position_ids].unsqueeze(1) # [batch_size, 1, seq_len, dim]
|
151 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
152 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
153 |
+
return q_embed, k_embed
|
154 |
+
|
155 |
+
|
156 |
+
class MLP(nn.Module):
|
157 |
+
def __init__(self, config: StableLMEpochConfig):
|
158 |
+
super().__init__()
|
159 |
+
self.config = config
|
160 |
+
self.hidden_size = config.hidden_size
|
161 |
+
self.intermediate_size = config.intermediate_size
|
162 |
+
self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
163 |
+
self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
164 |
+
self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
|
165 |
+
self.act_fn = nn.SiLU()
|
166 |
+
|
167 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
168 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
169 |
+
|
170 |
+
|
171 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
172 |
+
"""
|
173 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
174 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
175 |
+
"""
|
176 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
177 |
+
if n_rep == 1:
|
178 |
+
return hidden_states
|
179 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
180 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
181 |
+
|
182 |
+
|
183 |
+
class Attention(nn.Module):
|
184 |
+
def __init__(self, config: StableLMEpochConfig):
|
185 |
+
super().__init__()
|
186 |
+
self.config = config
|
187 |
+
self.hidden_size = config.hidden_size
|
188 |
+
self.num_heads = config.num_attention_heads
|
189 |
+
self.head_dim = self.hidden_size // self.num_heads
|
190 |
+
self.num_key_value_heads = config.num_key_value_heads
|
191 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
192 |
+
self.max_position_embeddings = config.max_position_embeddings
|
193 |
+
self.is_causal = True
|
194 |
+
self.attention_dropout = config.attention_dropout
|
195 |
+
|
196 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
197 |
+
raise ValueError(
|
198 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
199 |
+
f" and `num_heads`: {self.num_heads})."
|
200 |
+
)
|
201 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
202 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
203 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
204 |
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
205 |
+
self.o_proj.weight.data.fill_(0) # Zero initial, contribute nothing the the final result
|
206 |
+
|
207 |
+
self._init_rope()
|
208 |
+
|
209 |
+
def _init_rope(self):
|
210 |
+
self.rotary_ndims = int(self.head_dim * self.config.rope_pct)
|
211 |
+
self.rotary_emb = RotaryEmbedding(
|
212 |
+
self.rotary_ndims,
|
213 |
+
max_position_embeddings=self.config.max_position_embeddings,
|
214 |
+
base=self.config.rope_theta,
|
215 |
+
)
|
216 |
+
|
217 |
+
def forward(
|
218 |
+
self,
|
219 |
+
hidden_states: torch.FloatTensor,
|
220 |
+
cross_states: torch.FloatTensor,
|
221 |
+
attention_mask: torch.FloatTensor,
|
222 |
+
position_ids: torch.LongTensor,
|
223 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
224 |
+
output_attentions: Optional[bool] = False,
|
225 |
+
use_cache: Optional[bool] = False,
|
226 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
227 |
+
bsz, q_len, _ = hidden_states.size()
|
228 |
+
_, kv_len, _ = cross_states.size()
|
229 |
+
|
230 |
+
query_states = self.q_proj(hidden_states)
|
231 |
+
key_states = self.k_proj(cross_states)
|
232 |
+
value_states = self.v_proj(cross_states)
|
233 |
+
|
234 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
235 |
+
key_states = key_states.view(bsz, kv_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
236 |
+
value_states = value_states.view(bsz, kv_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
237 |
+
|
238 |
+
query_rot = query_states[..., : self.rotary_ndims]
|
239 |
+
query_pass = query_states[..., self.rotary_ndims :]
|
240 |
+
key_rot = key_states[..., : self.rotary_ndims]
|
241 |
+
key_pass = key_states[..., self.rotary_ndims :]
|
242 |
+
|
243 |
+
kv_seq_len = key_states.shape[-2]
|
244 |
+
|
245 |
+
if past_key_value is not None:
|
246 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
247 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
248 |
+
query_states, key_states = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
|
249 |
+
|
250 |
+
# [batch_size, num_heads, seq_len, head_dim]
|
251 |
+
query_states = torch.cat((query_states, query_pass), dim=-1)
|
252 |
+
key_states = torch.cat((key_states, key_pass), dim=-1)
|
253 |
+
|
254 |
+
if past_key_value is not None:
|
255 |
+
# Reuse k, v, self_attention
|
256 |
+
key_states = torch.cat((past_key_value[0], key_states), dim=2)
|
257 |
+
value_states = torch.cat((past_key_value[1], value_states), dim=2)
|
258 |
+
|
259 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
260 |
+
|
261 |
+
# Repeat k/v heads if n_kv_heads < n_heads
|
262 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
263 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
264 |
+
|
265 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
266 |
+
|
267 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
268 |
+
raise ValueError(
|
269 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
270 |
+
f" {attn_weights.size()}"
|
271 |
+
)
|
272 |
+
|
273 |
+
if attention_mask is not None:
|
274 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
275 |
+
raise ValueError(
|
276 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
277 |
+
)
|
278 |
+
attn_weights = attn_weights + attention_mask
|
279 |
+
|
280 |
+
# Upcast attention to fp32
|
281 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
282 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
283 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
284 |
+
|
285 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
286 |
+
raise ValueError(
|
287 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
288 |
+
f" {attn_output.size()}"
|
289 |
+
)
|
290 |
+
|
291 |
+
# Merge heads
|
292 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
293 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
294 |
+
|
295 |
+
# Final linear projection
|
296 |
+
attn_output = self.o_proj(attn_output)
|
297 |
+
|
298 |
+
if not output_attentions:
|
299 |
+
attn_weights = None
|
300 |
+
|
301 |
+
return attn_output, attn_weights, past_key_value
|
302 |
+
|
303 |
+
|
304 |
+
class FlashAttention2(Attention):
|
305 |
+
"""
|
306 |
+
Reference: https://github.com/huggingface/transformers/blob/5d36025ca13d05151b7a0c761e90d429c4644a30/src/transformers/models/llama/modeling_llama.py#L456
|
307 |
+
"""
|
308 |
+
|
309 |
+
def __init__(self, *args, **kwargs):
|
310 |
+
super().__init__(*args, **kwargs)
|
311 |
+
|
312 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
313 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
314 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
315 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
316 |
+
|
317 |
+
def forward(
|
318 |
+
self,
|
319 |
+
hidden_states: torch.Tensor,
|
320 |
+
cross_states: torch.Tensor,
|
321 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
322 |
+
position_ids: Optional[torch.LongTensor] = None,
|
323 |
+
past_key_value: Optional[Cache] = None,
|
324 |
+
output_attentions: bool = False,
|
325 |
+
use_cache: bool = False,
|
326 |
+
**kwargs,
|
327 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
328 |
+
# FlashAttention2 attention does not support output_attentions
|
329 |
+
if "padding_mask" in kwargs:
|
330 |
+
warnings.warn(
|
331 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
332 |
+
)
|
333 |
+
|
334 |
+
# overwrite attention_mask with padding_mask
|
335 |
+
attention_mask = kwargs.pop("padding_mask")
|
336 |
+
|
337 |
+
output_attentions = False
|
338 |
+
|
339 |
+
bsz, q_len, _ = hidden_states.size()
|
340 |
+
|
341 |
+
query_states = self.q_proj(hidden_states)
|
342 |
+
key_states = self.k_proj(cross_states)
|
343 |
+
value_states = self.v_proj(cross_states)
|
344 |
+
|
345 |
+
# Flash attention requires the input to have the shape
|
346 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
347 |
+
# therefore we just need to keep the original shape
|
348 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
349 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
350 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
351 |
+
|
352 |
+
query_rot = query_states[..., : self.rotary_ndims]
|
353 |
+
query_pass = query_states[..., self.rotary_ndims :]
|
354 |
+
key_rot = key_states[..., : self.rotary_ndims]
|
355 |
+
key_pass = key_states[..., self.rotary_ndims :]
|
356 |
+
|
357 |
+
kv_seq_len = key_states.shape[-2]
|
358 |
+
if past_key_value is not None:
|
359 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
360 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
361 |
+
query_states, key_states = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, position_ids)
|
362 |
+
|
363 |
+
# [batch_size, num_heads, seq_len, head_dim]
|
364 |
+
query_states = torch.cat((query_states, query_pass), dim=-1)
|
365 |
+
key_states = torch.cat((key_states, key_pass), dim=-1)
|
366 |
+
|
367 |
+
if past_key_value is not None:
|
368 |
+
# Reuse k, v, self_attention
|
369 |
+
key_states = torch.cat((past_key_value[0], key_states), dim=2)
|
370 |
+
value_states = torch.cat((past_key_value[1], value_states), dim=2)
|
371 |
+
|
372 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
373 |
+
|
374 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
375 |
+
# to be able to avoid many of these transpose/reshape/view.
|
376 |
+
query_states = query_states.transpose(1, 2)
|
377 |
+
key_states = key_states.transpose(1, 2)
|
378 |
+
value_states = value_states.transpose(1, 2)
|
379 |
+
|
380 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
381 |
+
|
382 |
+
attn_output = self._flash_attention_forward(
|
383 |
+
query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
|
384 |
+
)
|
385 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
386 |
+
attn_output = self.o_proj(attn_output)
|
387 |
+
|
388 |
+
if not output_attentions:
|
389 |
+
attn_weights = None
|
390 |
+
|
391 |
+
return attn_output, attn_weights, past_key_value
|
392 |
+
|
393 |
+
def _flash_attention_forward(
|
394 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
395 |
+
):
|
396 |
+
"""
|
397 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
398 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
399 |
+
|
400 |
+
Args:
|
401 |
+
query_states (`torch.Tensor`):
|
402 |
+
Input query states to be passed to Flash Attention API
|
403 |
+
key_states (`torch.Tensor`):
|
404 |
+
Input key states to be passed to Flash Attention API
|
405 |
+
value_states (`torch.Tensor`):
|
406 |
+
Input value states to be passed to Flash Attention API
|
407 |
+
attention_mask (`torch.Tensor`):
|
408 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
409 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
410 |
+
dropout (`int`, *optional*):
|
411 |
+
Attention dropout
|
412 |
+
softmax_scale (`float`, *optional*):
|
413 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
414 |
+
"""
|
415 |
+
if not self._flash_attn_uses_top_left_mask:
|
416 |
+
causal = self.is_causal
|
417 |
+
else:
|
418 |
+
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in FlashAttention2 __init__.
|
419 |
+
causal = self.is_causal and query_length != 1
|
420 |
+
|
421 |
+
# Contains at least one padding token in the sequence
|
422 |
+
if attention_mask is not None:
|
423 |
+
batch_size = query_states.shape[0]
|
424 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
425 |
+
query_states, key_states, value_states, attention_mask, query_length
|
426 |
+
)
|
427 |
+
|
428 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
429 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
430 |
+
|
431 |
+
attn_output_unpad = flash_attn_varlen_func(
|
432 |
+
query_states,
|
433 |
+
key_states,
|
434 |
+
value_states,
|
435 |
+
cu_seqlens_q=cu_seqlens_q,
|
436 |
+
cu_seqlens_k=cu_seqlens_k,
|
437 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
438 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
439 |
+
dropout_p=dropout,
|
440 |
+
softmax_scale=softmax_scale,
|
441 |
+
causal=causal,
|
442 |
+
)
|
443 |
+
|
444 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
445 |
+
else:
|
446 |
+
attn_output = flash_attn_func(
|
447 |
+
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
|
448 |
+
)
|
449 |
+
|
450 |
+
return attn_output
|
451 |
+
|
452 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
453 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
454 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
455 |
+
|
456 |
+
key_layer = index_first_axis(
|
457 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
458 |
+
)
|
459 |
+
value_layer = index_first_axis(
|
460 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
461 |
+
)
|
462 |
+
if query_length == kv_seq_len:
|
463 |
+
query_layer = index_first_axis(
|
464 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
465 |
+
)
|
466 |
+
cu_seqlens_q = cu_seqlens_k
|
467 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
468 |
+
indices_q = indices_k
|
469 |
+
elif query_length == 1:
|
470 |
+
max_seqlen_in_batch_q = 1
|
471 |
+
cu_seqlens_q = torch.arange(
|
472 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
473 |
+
) # There is a memcpy here, that is very bad.
|
474 |
+
indices_q = cu_seqlens_q[:-1]
|
475 |
+
query_layer = query_layer.squeeze(1)
|
476 |
+
else:
|
477 |
+
# The -q_len: slice assumes left padding.
|
478 |
+
attention_mask = attention_mask[:, -query_length:]
|
479 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
480 |
+
|
481 |
+
return (
|
482 |
+
query_layer,
|
483 |
+
key_layer,
|
484 |
+
value_layer,
|
485 |
+
indices_q,
|
486 |
+
(cu_seqlens_q, cu_seqlens_k),
|
487 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
488 |
+
)
|
489 |
+
|
490 |
+
|
491 |
+
ATTENTION_CLASSES = {
|
492 |
+
"eager": Attention,
|
493 |
+
"flash_attention_2": FlashAttention2,
|
494 |
+
}
|
495 |
+
|
496 |
+
|
497 |
+
class DecoderLayer(nn.Module):
|
498 |
+
def __init__(self, config: StableLMEpochConfig):
|
499 |
+
super().__init__()
|
500 |
+
self.self_attn = ATTENTION_CLASSES[config._attn_implementation](config=config)
|
501 |
+
self.cross_attn = ATTENTION_CLASSES[config._attn_implementation](config=config)
|
502 |
+
self.mlp = MLP(config)
|
503 |
+
self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps)
|
504 |
+
self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps)
|
505 |
+
|
506 |
+
def forward(
|
507 |
+
self,
|
508 |
+
hidden_states: Optional[torch.FloatTensor],
|
509 |
+
cross_states: Optional[torch.FloatTensor],
|
510 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
511 |
+
position_ids: Optional[torch.LongTensor] = None,
|
512 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
513 |
+
output_attentions: Optional[bool] = False,
|
514 |
+
use_cache: Optional[bool] = False,
|
515 |
+
) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
|
516 |
+
residual = hidden_states
|
517 |
+
|
518 |
+
hidden_states = self.input_layernorm(hidden_states)
|
519 |
+
|
520 |
+
# Self Attention
|
521 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
522 |
+
hidden_states=hidden_states,
|
523 |
+
cross_states=hidden_states,
|
524 |
+
attention_mask=attention_mask,
|
525 |
+
position_ids=position_ids,
|
526 |
+
past_key_value=past_key_value,
|
527 |
+
output_attentions=output_attentions,
|
528 |
+
use_cache=use_cache,
|
529 |
+
)
|
530 |
+
hidden_states = residual + hidden_states
|
531 |
+
|
532 |
+
# Cross Attention
|
533 |
+
residual = hidden_states
|
534 |
+
|
535 |
+
bsz, q_len, _ = hidden_states.size()
|
536 |
+
_, kv_len, _ = cross_states.size()
|
537 |
+
|
538 |
+
cross_attn_mask = torch.ones((bsz, 1, kv_len, q_len), device=hidden_states.device)
|
539 |
+
hidden_states, cross_attn_weights, _ = self.cross_attn(
|
540 |
+
hidden_states=hidden_states,
|
541 |
+
cross_states=cross_states,
|
542 |
+
attention_mask=cross_attn_mask,
|
543 |
+
position_ids=position_ids,
|
544 |
+
past_key_value=past_key_value,
|
545 |
+
output_attentions=output_attentions,
|
546 |
+
use_cache=use_cache,
|
547 |
+
)
|
548 |
+
hidden_states = residual + hidden_states
|
549 |
+
|
550 |
+
# Fully Connected
|
551 |
+
residual = hidden_states
|
552 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
553 |
+
hidden_states = self.mlp(hidden_states)
|
554 |
+
hidden_states = residual + hidden_states
|
555 |
+
|
556 |
+
outputs = (hidden_states,)
|
557 |
+
|
558 |
+
if output_attentions:
|
559 |
+
outputs += (self_attn_weights,)
|
560 |
+
|
561 |
+
if use_cache:
|
562 |
+
outputs += (present_key_value,)
|
563 |
+
|
564 |
+
return outputs
|
565 |
+
|
566 |
+
|
567 |
+
class StableLMEpochPreTrainedModel(PreTrainedModel):
|
568 |
+
"""An abstract class to handle weights initialization and a simple interface
|
569 |
+
for downloading and loading pretrained models.
|
570 |
+
"""
|
571 |
+
|
572 |
+
config_class = StableLMEpochConfig
|
573 |
+
base_model_prefix = "model"
|
574 |
+
supports_gradient_checkpointing = True
|
575 |
+
_no_split_modules = ["DecoderLayer"]
|
576 |
+
_skip_keys_device_placement = "past_key_values"
|
577 |
+
_supports_flash_attn_2 = True
|
578 |
+
|
579 |
+
def _init_weights(self, module: nn.Module):
|
580 |
+
"""Initialize the weights"""
|
581 |
+
if isinstance(module, nn.Linear):
|
582 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
583 |
+
if module.bias is not None:
|
584 |
+
module.bias.data.zero_()
|
585 |
+
elif isinstance(module, nn.Embedding):
|
586 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
587 |
+
if module.padding_idx is not None:
|
588 |
+
module.weight.data[module.padding_idx].zero_()
|
589 |
+
elif isinstance(module, nn.LayerNorm):
|
590 |
+
module.bias.data.zero_()
|
591 |
+
module.weight.data.fill_(1.0)
|
592 |
+
|
593 |
+
def _set_gradient_checkpointing(self, module: nn.Module, value=False):
|
594 |
+
if isinstance(module, StableLMEpochModel):
|
595 |
+
module.gradient_checkpointing = value
|
596 |
+
|
597 |
+
|
598 |
+
class StableLMEpochModel(StableLMEpochPreTrainedModel):
|
599 |
+
def __init__(self, config: StableLMEpochConfig):
|
600 |
+
super().__init__(config)
|
601 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
|
602 |
+
self.layers = nn.ModuleList([DecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
603 |
+
self.norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps)
|
604 |
+
|
605 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
606 |
+
self.gradient_checkpointing = False
|
607 |
+
# Initialize weights and apply final processing
|
608 |
+
self.post_init()
|
609 |
+
|
610 |
+
def get_input_embeddings(self):
|
611 |
+
return self.embed_tokens
|
612 |
+
|
613 |
+
def set_input_embeddings(self, value: nn.Module):
|
614 |
+
self.embed_tokens = value
|
615 |
+
|
616 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
617 |
+
def _prepare_decoder_attention_mask(
|
618 |
+
self,
|
619 |
+
attention_mask: torch.Tensor,
|
620 |
+
input_shape: torch.Size,
|
621 |
+
inputs_embeds: torch.Tensor,
|
622 |
+
past_key_values_length: int,
|
623 |
+
):
|
624 |
+
# Create causal mask
|
625 |
+
# [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]
|
626 |
+
combined_attention_mask = None
|
627 |
+
if input_shape[-1] > 1:
|
628 |
+
combined_attention_mask = _make_causal_mask(
|
629 |
+
input_shape,
|
630 |
+
inputs_embeds.dtype,
|
631 |
+
device=inputs_embeds.device,
|
632 |
+
past_key_values_length=past_key_values_length,
|
633 |
+
)
|
634 |
+
|
635 |
+
if attention_mask is not None:
|
636 |
+
# [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]
|
637 |
+
expanded_attn_mask = _expand_mask(
|
638 |
+
attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
|
639 |
+
).to(inputs_embeds.device)
|
640 |
+
combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
641 |
+
|
642 |
+
return combined_attention_mask
|
643 |
+
|
644 |
+
def forward(
|
645 |
+
self,
|
646 |
+
input_ids: Optional[torch.LongTensor] = None,
|
647 |
+
cross_states: Optional[torch.FloatTensor] = None,
|
648 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
649 |
+
position_ids: Optional[torch.LongTensor] = None,
|
650 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
651 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
652 |
+
use_cache: Optional[bool] = None,
|
653 |
+
output_attentions: Optional[bool] = None,
|
654 |
+
output_hidden_states: Optional[bool] = None,
|
655 |
+
return_dict: Optional[bool] = None,
|
656 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
657 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
658 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
659 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
660 |
+
|
661 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
662 |
+
|
663 |
+
# Retrieve input_ids and inputs_embeds
|
664 |
+
if input_ids is not None and inputs_embeds is not None:
|
665 |
+
raise ValueError(
|
666 |
+
"You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time"
|
667 |
+
)
|
668 |
+
elif input_ids is not None:
|
669 |
+
batch_size, seq_length = input_ids.shape
|
670 |
+
elif inputs_embeds is not None:
|
671 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
672 |
+
else:
|
673 |
+
raise ValueError(
|
674 |
+
"You have to specify either decoder_input_ids or decoder_inputs_embeds"
|
675 |
+
)
|
676 |
+
|
677 |
+
seq_length_with_past = seq_length
|
678 |
+
past_key_values_length = 0
|
679 |
+
|
680 |
+
if position_ids is None:
|
681 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
682 |
+
position_ids = torch.arange(
|
683 |
+
past_key_values_length,
|
684 |
+
seq_length + past_key_values_length,
|
685 |
+
dtype=torch.long,
|
686 |
+
device=device,
|
687 |
+
)
|
688 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
689 |
+
else:
|
690 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
691 |
+
|
692 |
+
if inputs_embeds is None:
|
693 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
694 |
+
|
695 |
+
# Embed positions
|
696 |
+
if self._use_flash_attention_2:
|
697 |
+
# 2d mask is passed through the layers
|
698 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
699 |
+
else:
|
700 |
+
if attention_mask is None:
|
701 |
+
attention_mask = torch.ones(
|
702 |
+
(batch_size, seq_length_with_past),
|
703 |
+
dtype=torch.bool,
|
704 |
+
device=inputs_embeds.device,
|
705 |
+
)
|
706 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
707 |
+
attention_mask,
|
708 |
+
(batch_size, seq_length),
|
709 |
+
inputs_embeds,
|
710 |
+
past_key_values_length,
|
711 |
+
)
|
712 |
+
|
713 |
+
hidden_states = inputs_embeds
|
714 |
+
|
715 |
+
if self.gradient_checkpointing and self.training:
|
716 |
+
if use_cache:
|
717 |
+
logger.warning(
|
718 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
719 |
+
)
|
720 |
+
use_cache = False
|
721 |
+
|
722 |
+
# Decoder layers
|
723 |
+
all_hidden_states = () if output_hidden_states else None
|
724 |
+
all_self_attns = () if output_attentions else None
|
725 |
+
next_decoder_cache = () if use_cache else None
|
726 |
+
|
727 |
+
for idx, decoder_layer in enumerate(self.layers):
|
728 |
+
if output_hidden_states:
|
729 |
+
all_hidden_states += (hidden_states,)
|
730 |
+
|
731 |
+
past_key_value = (
|
732 |
+
past_key_values[idx] if past_key_values is not None else None
|
733 |
+
)
|
734 |
+
|
735 |
+
if self.gradient_checkpointing and self.training:
|
736 |
+
|
737 |
+
def create_custom_forward(module):
|
738 |
+
def custom_forward(*inputs):
|
739 |
+
# None for past_key_value
|
740 |
+
return module(*inputs, past_key_value, output_attentions)
|
741 |
+
|
742 |
+
return custom_forward
|
743 |
+
|
744 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
745 |
+
create_custom_forward(decoder_layer),
|
746 |
+
hidden_states,
|
747 |
+
attention_mask,
|
748 |
+
position_ids,
|
749 |
+
)
|
750 |
+
else:
|
751 |
+
layer_outputs = decoder_layer(
|
752 |
+
hidden_states,
|
753 |
+
cross_states,
|
754 |
+
attention_mask=attention_mask,
|
755 |
+
position_ids=position_ids,
|
756 |
+
past_key_value=past_key_value,
|
757 |
+
output_attentions=output_attentions,
|
758 |
+
use_cache=use_cache,
|
759 |
+
)
|
760 |
+
|
761 |
+
hidden_states = layer_outputs[0]
|
762 |
+
|
763 |
+
if use_cache:
|
764 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
765 |
+
|
766 |
+
if output_attentions:
|
767 |
+
all_self_attns += (layer_outputs[1],)
|
768 |
+
|
769 |
+
hidden_states = self.norm(hidden_states)
|
770 |
+
|
771 |
+
# Add hidden states from the last decoder layer
|
772 |
+
if output_hidden_states:
|
773 |
+
all_hidden_states += (hidden_states,)
|
774 |
+
|
775 |
+
next_cache = next_decoder_cache if use_cache else None
|
776 |
+
if not return_dict:
|
777 |
+
return tuple(
|
778 |
+
v
|
779 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
|
780 |
+
if v is not None
|
781 |
+
)
|
782 |
+
return BaseModelOutputWithPast(
|
783 |
+
last_hidden_state=hidden_states,
|
784 |
+
past_key_values=next_cache,
|
785 |
+
hidden_states=all_hidden_states,
|
786 |
+
attentions=all_self_attns,
|
787 |
+
)
|
788 |
+
|
789 |
+
|
790 |
+
class StableLMEpochForCausalLM(StableLMEpochPreTrainedModel):
|
791 |
+
_tied_weights_keys = ["lm_head.weight"]
|
792 |
+
|
793 |
+
def __init__(self, config: StableLMEpochConfig):
|
794 |
+
super().__init__(config)
|
795 |
+
|
796 |
+
self.model = StableLMEpochModel(config)
|
797 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
798 |
+
|
799 |
+
# Initialize weights and apply final processing
|
800 |
+
self.post_init()
|
801 |
+
|
802 |
+
def get_input_embeddings(self):
|
803 |
+
return self.model.embed_tokens
|
804 |
+
|
805 |
+
def set_input_embeddings(self, value):
|
806 |
+
self.model.embed_tokens = value
|
807 |
+
|
808 |
+
def get_output_embeddings(self):
|
809 |
+
return self.lm_head
|
810 |
+
|
811 |
+
def set_output_embeddings(self, new_embeddings: nn.Module):
|
812 |
+
self.lm_head = new_embeddings
|
813 |
+
|
814 |
+
def get_decoder(self):
|
815 |
+
return self.model
|
816 |
+
|
817 |
+
def set_decoder(self, decoder):
|
818 |
+
self.model = decoder
|
819 |
+
|
820 |
+
def forward(
|
821 |
+
self,
|
822 |
+
input_ids: Optional[torch.LongTensor] = None,
|
823 |
+
cross_states: Optional[torch.FloatTensor] = None,
|
824 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
825 |
+
position_ids: Optional[torch.LongTensor] = None,
|
826 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
827 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
828 |
+
labels: Optional[torch.LongTensor] = None,
|
829 |
+
use_cache: Optional[bool] = None,
|
830 |
+
output_attentions: Optional[bool] = None,
|
831 |
+
output_hidden_states: Optional[bool] = None,
|
832 |
+
return_dict: Optional[bool] = None,
|
833 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
834 |
+
output_attentions = (
|
835 |
+
output_attentions
|
836 |
+
if output_attentions is not None
|
837 |
+
else self.config.output_attentions
|
838 |
+
)
|
839 |
+
output_hidden_states = (
|
840 |
+
output_hidden_states
|
841 |
+
if output_hidden_states is not None
|
842 |
+
else self.config.output_hidden_states
|
843 |
+
)
|
844 |
+
return_dict = (
|
845 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
846 |
+
)
|
847 |
+
|
848 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
849 |
+
outputs = self.model(
|
850 |
+
input_ids,
|
851 |
+
cross_states,
|
852 |
+
attention_mask=attention_mask,
|
853 |
+
position_ids=position_ids,
|
854 |
+
past_key_values=past_key_values,
|
855 |
+
inputs_embeds=inputs_embeds,
|
856 |
+
use_cache=use_cache,
|
857 |
+
output_attentions=output_attentions,
|
858 |
+
output_hidden_states=output_hidden_states,
|
859 |
+
return_dict=return_dict,
|
860 |
+
)
|
861 |
+
|
862 |
+
hidden_states = outputs[0]
|
863 |
+
logits = self.lm_head(hidden_states).float()
|
864 |
+
|
865 |
+
loss = None
|
866 |
+
if labels is not None:
|
867 |
+
# Shift so that tokens < n predict n
|
868 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
869 |
+
shift_labels = labels[..., 1:].contiguous()
|
870 |
+
# Flatten the tokens
|
871 |
+
loss_fct = CrossEntropyLoss()
|
872 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
873 |
+
shift_labels = shift_labels.view(-1)
|
874 |
+
# Enable model parallelism
|
875 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
876 |
+
loss = loss_fct(shift_logits, shift_labels)
|
877 |
+
|
878 |
+
if not return_dict:
|
879 |
+
output = (logits,) + outputs[1:]
|
880 |
+
return (loss,) + output if loss is not None else output
|
881 |
+
|
882 |
+
return CausalLMOutputWithPast(
|
883 |
+
loss=loss,
|
884 |
+
logits=logits,
|
885 |
+
past_key_values=outputs.past_key_values,
|
886 |
+
hidden_states=outputs.hidden_states,
|
887 |
+
attentions=outputs.attentions,
|
888 |
+
)
|
889 |
+
|
890 |
+
def prepare_inputs_for_generation(
|
891 |
+
self,
|
892 |
+
input_ids,
|
893 |
+
past_key_values: Optional[torch.Tensor] = None,
|
894 |
+
attention_mask: Optional[torch.Tensor] = None,
|
895 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
896 |
+
**kwargs,
|
897 |
+
):
|
898 |
+
# Trim decoder_input_ids if past is used
|
899 |
+
if past_key_values is not None:
|
900 |
+
past_length = past_key_values[0][0].shape[2]
|
901 |
+
|
902 |
+
# Some generation methods already pass only the last input ID
|
903 |
+
if input_ids.shape[1] > past_length:
|
904 |
+
remove_prefix_length = past_length
|
905 |
+
else:
|
906 |
+
# Default to old behavior: keep only final ID
|
907 |
+
remove_prefix_length = input_ids.shape[1] - 1
|
908 |
+
|
909 |
+
input_ids = input_ids[:, remove_prefix_length:]
|
910 |
+
|
911 |
+
position_ids = kwargs.get("position_ids", None)
|
912 |
+
if attention_mask is not None and position_ids is None:
|
913 |
+
# Create position_ids on the fly for batch generation
|
914 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
915 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
916 |
+
if past_key_values:
|
917 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
918 |
+
|
919 |
+
# If `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
920 |
+
if inputs_embeds is not None and past_key_values is None:
|
921 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
922 |
+
else:
|
923 |
+
model_inputs = {"input_ids": input_ids}
|
924 |
+
|
925 |
+
model_inputs.update(
|
926 |
+
{
|
927 |
+
"attention_mask": attention_mask,
|
928 |
+
"past_key_values": past_key_values,
|
929 |
+
"use_cache": kwargs.get("use_cache"),
|
930 |
+
"position_ids": position_ids,
|
931 |
+
}
|
932 |
+
)
|
933 |
+
return model_inputs
|
934 |
+
|
935 |
+
@staticmethod
|
936 |
+
def _reorder_cache(past_key_values, beam_idx):
|
937 |
+
reordered_past = ()
|
938 |
+
for layer_past in past_key_values:
|
939 |
+
reordered_past += (
|
940 |
+
tuple(
|
941 |
+
past_state.index_select(0, beam_idx.to(past_state.device))
|
942 |
+
for past_state in layer_past
|
943 |
+
),
|
944 |
+
)
|
945 |
+
return reordered_past
|
946 |
+
|
947 |
+
|
948 |
+
StableLMEpochConfig.register_for_auto_class()
|
949 |
+
StableLMEpochForCausalLM.register_for_auto_class("AutoModelForSeq2SeqLM")
|
special_tokens_map.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<|endoftext|>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": false,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"eos_token": {
|
10 |
+
"content": "<|endoftext|>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": {
|
17 |
+
"content": "<|endoftext|>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": false,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
},
|
23 |
+
"unk_token": {
|
24 |
+
"content": "<|endoftext|>",
|
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_config.json
ADDED
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_prefix_space": false,
|
3 |
+
"added_tokens_decoder": {
|
4 |
+
"0": {
|
5 |
+
"content": "<|endoftext|>",
|
6 |
+
"lstrip": false,
|
7 |
+
"normalized": false,
|
8 |
+
"rstrip": false,
|
9 |
+
"single_word": false,
|
10 |
+
"special": true
|
11 |
+
},
|
12 |
+
"1": {
|
13 |
+
"content": "<|padding|>",
|
14 |
+
"lstrip": false,
|
15 |
+
"normalized": false,
|
16 |
+
"rstrip": false,
|
17 |
+
"single_word": false,
|
18 |
+
"special": true
|
19 |
+
},
|
20 |
+
"50254": {
|
21 |
+
"content": " ",
|
22 |
+
"lstrip": false,
|
23 |
+
"normalized": true,
|
24 |
+
"rstrip": false,
|
25 |
+
"single_word": false,
|
26 |
+
"special": false
|
27 |
+
},
|
28 |
+
"50255": {
|
29 |
+
"content": " ",
|
30 |
+
"lstrip": false,
|
31 |
+
"normalized": true,
|
32 |
+
"rstrip": false,
|
33 |
+
"single_word": false,
|
34 |
+
"special": false
|
35 |
+
},
|
36 |
+
"50256": {
|
37 |
+
"content": " ",
|
38 |
+
"lstrip": false,
|
39 |
+
"normalized": true,
|
40 |
+
"rstrip": false,
|
41 |
+
"single_word": false,
|
42 |
+
"special": false
|
43 |
+
},
|
44 |
+
"50257": {
|
45 |
+
"content": " ",
|
46 |
+
"lstrip": false,
|
47 |
+
"normalized": true,
|
48 |
+
"rstrip": false,
|
49 |
+
"single_word": false,
|
50 |
+
"special": false
|
51 |
+
},
|
52 |
+
"50258": {
|
53 |
+
"content": " ",
|
54 |
+
"lstrip": false,
|
55 |
+
"normalized": true,
|
56 |
+
"rstrip": false,
|
57 |
+
"single_word": false,
|
58 |
+
"special": false
|
59 |
+
},
|
60 |
+
"50259": {
|
61 |
+
"content": " ",
|
62 |
+
"lstrip": false,
|
63 |
+
"normalized": true,
|
64 |
+
"rstrip": false,
|
65 |
+
"single_word": false,
|
66 |
+
"special": false
|
67 |
+
},
|
68 |
+
"50260": {
|
69 |
+
"content": " ",
|
70 |
+
"lstrip": false,
|
71 |
+
"normalized": true,
|
72 |
+
"rstrip": false,
|
73 |
+
"single_word": false,
|
74 |
+
"special": false
|
75 |
+
},
|
76 |
+
"50261": {
|
77 |
+
"content": " ",
|
78 |
+
"lstrip": false,
|
79 |
+
"normalized": true,
|
80 |
+
"rstrip": false,
|
81 |
+
"single_word": false,
|
82 |
+
"special": false
|
83 |
+
},
|
84 |
+
"50262": {
|
85 |
+
"content": " ",
|
86 |
+
"lstrip": false,
|
87 |
+
"normalized": true,
|
88 |
+
"rstrip": false,
|
89 |
+
"single_word": false,
|
90 |
+
"special": false
|
91 |
+
},
|
92 |
+
"50263": {
|
93 |
+
"content": " ",
|
94 |
+
"lstrip": false,
|
95 |
+
"normalized": true,
|
96 |
+
"rstrip": false,
|
97 |
+
"single_word": false,
|
98 |
+
"special": false
|
99 |
+
},
|
100 |
+
"50264": {
|
101 |
+
"content": " ",
|
102 |
+
"lstrip": false,
|
103 |
+
"normalized": true,
|
104 |
+
"rstrip": false,
|
105 |
+
"single_word": false,
|
106 |
+
"special": false
|
107 |
+
},
|
108 |
+
"50265": {
|
109 |
+
"content": " ",
|
110 |
+
"lstrip": false,
|
111 |
+
"normalized": true,
|
112 |
+
"rstrip": false,
|
113 |
+
"single_word": false,
|
114 |
+
"special": false
|
115 |
+
},
|
116 |
+
"50266": {
|
117 |
+
"content": " ",
|
118 |
+
"lstrip": false,
|
119 |
+
"normalized": true,
|
120 |
+
"rstrip": false,
|
121 |
+
"single_word": false,
|
122 |
+
"special": false
|
123 |
+
},
|
124 |
+
"50267": {
|
125 |
+
"content": " ",
|
126 |
+
"lstrip": false,
|
127 |
+
"normalized": true,
|
128 |
+
"rstrip": false,
|
129 |
+
"single_word": false,
|
130 |
+
"special": false
|
131 |
+
},
|
132 |
+
"50268": {
|
133 |
+
"content": " ",
|
134 |
+
"lstrip": false,
|
135 |
+
"normalized": true,
|
136 |
+
"rstrip": false,
|
137 |
+
"single_word": false,
|
138 |
+
"special": false
|
139 |
+
},
|
140 |
+
"50269": {
|
141 |
+
"content": " ",
|
142 |
+
"lstrip": false,
|
143 |
+
"normalized": true,
|
144 |
+
"rstrip": false,
|
145 |
+
"single_word": false,
|
146 |
+
"special": false
|
147 |
+
},
|
148 |
+
"50270": {
|
149 |
+
"content": " ",
|
150 |
+
"lstrip": false,
|
151 |
+
"normalized": true,
|
152 |
+
"rstrip": false,
|
153 |
+
"single_word": false,
|
154 |
+
"special": false
|
155 |
+
},
|
156 |
+
"50271": {
|
157 |
+
"content": " ",
|
158 |
+
"lstrip": false,
|
159 |
+
"normalized": true,
|
160 |
+
"rstrip": false,
|
161 |
+
"single_word": false,
|
162 |
+
"special": false
|
163 |
+
},
|
164 |
+
"50272": {
|
165 |
+
"content": " ",
|
166 |
+
"lstrip": false,
|
167 |
+
"normalized": true,
|
168 |
+
"rstrip": false,
|
169 |
+
"single_word": false,
|
170 |
+
"special": false
|
171 |
+
},
|
172 |
+
"50273": {
|
173 |
+
"content": " ",
|
174 |
+
"lstrip": false,
|
175 |
+
"normalized": true,
|
176 |
+
"rstrip": false,
|
177 |
+
"single_word": false,
|
178 |
+
"special": false
|
179 |
+
},
|
180 |
+
"50274": {
|
181 |
+
"content": " ",
|
182 |
+
"lstrip": false,
|
183 |
+
"normalized": true,
|
184 |
+
"rstrip": false,
|
185 |
+
"single_word": false,
|
186 |
+
"special": false
|
187 |
+
},
|
188 |
+
"50275": {
|
189 |
+
"content": " ",
|
190 |
+
"lstrip": false,
|
191 |
+
"normalized": true,
|
192 |
+
"rstrip": false,
|
193 |
+
"single_word": false,
|
194 |
+
"special": false
|
195 |
+
},
|
196 |
+
"50276": {
|
197 |
+
"content": " ",
|
198 |
+
"lstrip": false,
|
199 |
+
"normalized": true,
|
200 |
+
"rstrip": false,
|
201 |
+
"single_word": false,
|
202 |
+
"special": false
|
203 |
+
}
|
204 |
+
},
|
205 |
+
"bos_token": "<|endoftext|>",
|
206 |
+
"chat_template": "{% for message in messages %}\n{% if message['role'] == 'user' %}\n{{ '<|user|>\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'system' %}\n{{ '<|system|>\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'assistant' %}\n{{ '<|assistant|>\n' + message['content'] + eos_token }}\n{% endif %}\n{% if loop.last and add_generation_prompt %}\n{{ '<|assistant|>' }}\n{% endif %}\n{% endfor %}",
|
207 |
+
"clean_up_tokenization_spaces": true,
|
208 |
+
"eos_token": "<|endoftext|>",
|
209 |
+
"model_max_length": 2048,
|
210 |
+
"pad_token": "<|endoftext|>",
|
211 |
+
"tokenizer_class": "GPTNeoXTokenizer",
|
212 |
+
"unk_token": "<|endoftext|>"
|
213 |
+
}
|