bj798 commited on
Commit
0ad3dd7
1 Parent(s): e9b52d6

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - ar
4
+ - en
5
+ thumbnail: null
6
+ tags:
7
+ - Arabic
8
+ - English
9
+ - LLM
10
+ - Decoder
11
+ - causal-lm
12
+ - jais-family
13
+ license: apache-2.0
14
+ pipeline_tag: text-generation
15
+ ---
16
+ # Jais Family Model Card
17
+
18
+
19
+ The Jais family of models is a comprehensive series of bilingual English-Arabic large language models (LLMs). These models are optimized to excel in Arabic while having strong English capabilities. We release two variants of foundation models that include:
20
+
21
+ - Models **pre-trained from scratch** (`jais-family-*`).
22
+ - Models **pre-trained adaptively from [Llama-2](https://arxiv.org/pdf/2307.09288)** (`jais-adapted-*`).
23
+
24
+ In this release, we introduce 20 models across 8 sizes, ranging from 590M to 70B parameters, trained on up to 1.6T tokens of Arabic, English, and code data. *All* pre-trained models in this series are instruction fine-tuned (`*-chat`) for dialog using a curated mix of Arabic and English instruction data.
25
+
26
+ We hope this extensive release will accelerate research in Arabic NLP, and enable numerous downstream applications for the Arabic speaking and bilingual community. The training and adaptation techniques we demonstrate successfully for Arabic models are extensible to other low and medium resource languages.
27
+
28
+ ## Jais Family Details
29
+
30
+ - **Developed by:** Core42 (Inception), Cerebras Systems.
31
+ - **Language(s):** (NLP): Arabic (MSA) and English.
32
+ - **Input:** Text only data.
33
+ - **Output:** Model generates text.
34
+ - **Model Sizes:** 590M, 1.3B, 2.7B, 6.7B, 7B, 13B, 30B, 70B.
35
+ - **Demo:** [Access the live demo here](https://arabic-gpt.ai/)
36
+ - **License:** Apache 2.0
37
+
38
+ | **Pre-trained Model** | **Fine-tuned Model** | **Size (Parameters)** | **Context length (Tokens)** |
39
+ |:---------------------|:--------|:-------|:-------|
40
+ | [jais-family-30b-16k](https://huggingface.co/core42/jais-family-30b-16k) | [Jais-family-30b-16k-chat](https://huggingface.co/core42/jais-family-30b-16k-chat) | 30B | 16,384 |
41
+ | [jais-family-30b-8k](https://huggingface.co/core42/jais-family-30b-8k) | [Jais-family-30b-8k-chat](https://huggingface.co/core42/jais-family-30b-8k-chat) | 30B | 8,192 |
42
+ | [jais-family-13b ](https://huggingface.co/core42/jais-family-13b) | [Jais-family-13b-chat](https://huggingface.co/core42/jais-family-13b-chat) | 13B | 2,048 |
43
+ | [jais-family-6p7b](https://huggingface.co/core42/jais-family-6p7b) | [Jais-family-6p7b-chat](https://huggingface.co/core42/jais-family-6p7b-chat) | 6.7B | 2,048 |
44
+ | [jais-family-2p7b](https://huggingface.co/core42/jais-family-2p7b) | [Jais-family-2p7b-chat](https://huggingface.co/core42/jais-family-2p7b-chat) | 2.7B | 2,048 |
45
+ | [jais-family-1p3b](https://huggingface.co/core42/jais-family-1p3b) | [Jais-family-1p3b-chat](https://huggingface.co/core42/jais-family-1p3b-chat) | 1.3B | 2,048 |
46
+ | [jais-family-590m](https://huggingface.co/core42/jais-family-590m) | [Jais-family-590m-chat](https://huggingface.co/core42/jais-family-590m-chat) | 590M | 2,048 |
47
+
48
+ | **Adapted pre-trained Model** | **Fine-tuned Model** | **Size (Parameters)** | **Context length (Tokens)** |
49
+ |:---------------------|:--------|:-------|:-------|
50
+ | [jais-adapted-70b](https://huggingface.co/core42/jais-adapted-70b) | [Jais-adapted-70b-chat](https://huggingface.co/core42/jais-adapted-70b-chat) | 70B | 4,096 |
51
+ | [jais-adapted-13b](https://huggingface.co/core42/jais-adapted-13b) | [Jais-adapted-13b-chat](https://huggingface.co/core42/jais-adapted-13b-chat) | 13B | 4,096 |
52
+ | [jais-adapted-7b](https://huggingface.co/core42/jais-adapted-7b) | [Jais-adapted-7b-chat](https://huggingface.co/core42/jais-adapted-7b-chat) | 7B | 4,096 |
53
+
54
+ ### Model Architecture:
55
+ <a name="model-architecture"></a>
56
+
57
+ All models in this family are auto-regressive language models that use a transformer-based, decoder-only architecture (GPT-3).
58
+
59
+ Jais models (`jais-family-*`) are *trained from scratch*, incorporating the SwiGLU non-linear activation function and ALiBi position encoding. These architectural enhancements allow the models to extrapolate at long sequence lengths, leading to improved context handling and precision.
60
+
61
+ Jais adapted models (`jais-adapted-*`) are *built on top of Llama-2*, which employs RoPE position embedding and Grouped Query Attention. We introduce tokenizer expansion with Arabic data, which improves fertility and compute efficiency by over 3x. In particular, we add `32,000` new Arabic tokens from the Jais-30b vocabulary into the Llama-2 tokenizer.
62
+ To initialize these new Arabic token embeddings we first learn a linear projection from the embedding space of Jais-30b to Llama's embedding space, using the set of shared English tokens present in both vocabularies. Next, this learned projection is applied to transform the existing Jais-30b Arabic embeddings into the Llama-2 embedding space.
63
+
64
+
65
+ ## Getting started
66
+
67
+ Below is sample code to use the model. Note that the model requires a custom model class, so users must enable `trust_remote_code=True` while loading the model.
68
+
69
+ ```python
70
+ # -*- coding: utf-8 -*-
71
+
72
+ import torch
73
+ from transformers import AutoTokenizer, AutoModelForCausalLM
74
+
75
+ model_path = "core42/jais-family-590m"
76
+
77
+ device = "cuda" if torch.cuda.is_available() else "cpu"
78
+
79
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
80
+ model = AutoModelForCausalLM.from_pretrained(model_path, device_map="auto", trust_remote_code=True)
81
+
82
+
83
+ def get_response(text, tokenizer=tokenizer, model=model):
84
+ input_ids = tokenizer(text, return_tensors="pt").input_ids
85
+ inputs = input_ids.to(device)
86
+ input_len = inputs.shape[-1]
87
+ generate_ids = model.generate(
88
+ inputs,
89
+ top_p=0.9,
90
+ temperature=0.3,
91
+ max_length=2048,
92
+ min_length=input_len + 4,
93
+ repetition_penalty=1.2,
94
+ do_sample=True,
95
+ )
96
+ response = tokenizer.batch_decode(
97
+ generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
98
+ )[0]
99
+ return response
100
+
101
+
102
+ text = "عاصمة دولة الإمارات العربية المتحدة ه"
103
+ print(get_response(text))
104
+
105
+ text = "The capital of UAE is"
106
+ print(get_response(text))
107
+ ```
108
+
109
+ ## Training Details
110
+
111
+ ### Pretraining Data
112
+
113
+ The Jais family of models are trained on up to 1.6 Trillion tokens of diverse English, Arabic and Code data. The data consists of the following sources:
114
+
115
+ - **Web:** We used publicly available web pages, wikipedia articles, news articles, and social network content in both Arabic and English.
116
+
117
+ - **Code:** To enhance the reasoning capability of our model, we include Code data in various programming languages.
118
+
119
+ - **Books:** We used a selection of publicly available Arabic and English books data, which improves long-range context modelling and coherent storytelling.
120
+
121
+ - **Scientific:** A subset of ArXiv papers were included to improve reasoning and long context abilities.
122
+
123
+ - **Synthetic:** We augment the volume of Arabic data by translating English to Arabic using an in-house machine translation system. We restrict this to high quality English resources such as English Wikipedia and English books.
124
+
125
+ We extensively preprocess and deduplicate the training data. For Arabic, we used a custom preprocessing pipeline to filter for data with high linguistic quality. More information on this pipeline can be found in the [Jais paper](https://arxiv.org/abs/2308.16149).
126
+
127
+ - **Jais pre-trained** (`jais-family-*`): Following our previous experimentation with language alignment mixing in [Jais](https://arxiv.org/abs/2308.16149), we used a ratio of 1:2:0.4 of Arabic:English:Code data. This recipe for <u>from scratch pre-training</u> addresses Arabic data scarcity while improving performance in both languages.
128
+ - **Jais adapted pre-trained** (`jais-adapted-*`): For the <u>adapted pre-training of Llama-2</u>, we utilized a larger Arabic dataset of ~334B Arabic tokens mixed with English and Code data. We vary the mixing ratio, at different model sizes, to introduce strong Arabic capabilities while maintaining performance in English.
129
+
130
+
131
+ | **Pre-trained model** | **English data (tokens)** | **Arabic data (tokens)** | **Code data (tokens)** | **Total data (tokens)** |
132
+ |-------------------------|---------------------------|--------------------------|------------------------|------------------------|
133
+ | [jais-family-30b-16k](https://huggingface.co/core42/jais-family-30b-16k) | 980B | 490B | 196B | 1666B |
134
+ | [jais-family-30b-8k](https://huggingface.co/core42/jais-family-30b-8k) | 882B | 441B | 177B | 1500B |
135
+ | [jais-family-13b ](https://huggingface.co/core42/jais-family-13b) | 283B | 141B | 56B | 480B |
136
+ | [jais-family-6p7b](https://huggingface.co/core42/jais-family-6p7b) | 283B | 141B | 56B | 480B |
137
+ | [jais-family-2p7b](https://huggingface.co/core42/jais-family-2p7b) | 283B | 141B | 56B | 480B |
138
+ | [jais-family-1p3b](https://huggingface.co/core42/jais-family-1p3b) | 283B | 141B | 56B | 480B |
139
+ | [jais-family-590m](https://huggingface.co/core42/jais-family-590m) | 283B | 141B | 56B | 480B |
140
+ | [jais-adapted-70b](https://huggingface.co/core42/jais-adapted-70b) | 33B | 334B | 4B | 371B |
141
+ | [jais-adapted-13b](https://huggingface.co/core42/jais-adapted-13b) | 127B | 140B | 13B | 280B |
142
+ | [jais-adapted-7b](https://huggingface.co/core42/jais-adapted-7b) | 18B | 19B | 2B | 39B |
143
+
144
+ ### Finetuning data
145
+
146
+ <!-- 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. -->
147
+
148
+ All chat models in the Jais family are fine-tuned using Arabic and English prompt-response pairs in both single-turn and multi-turn settings. Data sources include open-source fine-tuning datasets filtered for topic and style diversity. Additionally, internally curated human data is incorporated to enhance cultural adaptation. This data is supplemented with content generated using synthetic methods including machine translation, distillation, and model self-chat. Overall, our updated instruction-tuning dataset comprises ~10M and ~4M prompt-response pairs in English and Arabic respectively.
149
+
150
+ ### Training Procedure
151
+
152
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
153
+
154
+ During the pre-training of (`jais-family-*`) models, documents are packed into sequences separated by EOS tokens, and the model is trained autoregressively, applying the loss to all tokens. For jais-30b models, the context length is progressively expanded from 2k to 8K to 16K by incorporating curated long-context documents in training. This progressive expansion leverages faster initial training at shorter context lengths, while gradually extending support for larger context lengths towards the end of the training process.
155
+
156
+ During the adapted pre-training of the (`jais-adapted-*`) models, we first initialize the new tokenizer and Arabic embeddings as described in [Model Architecture](#model-architecture). In training, we implemented a two-stage approach to overcome observed higher norms of the new Arabic embeddings. In the first stage, the backbone of the model is frozen, and the embeddings are trained using approximately 15 billion tokens from a bilingual corpus of English and Arabic. In the second stage, the backbone is unfrozen, and continuous pretraining is conducted with all parameters.
157
+
158
+ During instruction tuning, each training example consists of a single-turn or multi-turn prompt and it's response. Instead of one example per sequence, examples are packed together while the loss is masked on the prompt tokens. This approach speeds up training by allowing more examples to be processed per batch.
159
+
160
+
161
+ ### Training Hyperparameters:
162
+
163
+ #### Jais-family-590m
164
+ | Hyperparameter | Value |
165
+ |----------------|-------------------------------------------|
166
+ | Precision | fp32 |
167
+ | Optimizer | AdamW |
168
+ | Learning rate | 0 to 0.01563(<=163 warmup steps)<br>0.01563 to 4.21e-05(>163 and <=209422 steps) |
169
+ | Weight decay | 0.1 |
170
+ | Batch size | 1120|
171
+ | Context Length | 2048|
172
+ | Steps | 209422 |
173
+
174
+ ### Compute Infrastructure
175
+
176
+ The training process was performed on the Condor Galaxy (CG) supercomputer platform. A CG contains 64 Cerebras CS-2 Wafer-Scale Engines (WSE-2) with 40 GB of SRAM, and achieves a total of 960 PetaFLOP/s.
177
+
178
+ ## Evaluation
179
+
180
+ <!-- This section describes the evaluation protocols and provides the results. -->
181
+
182
+ We conducted a comprehensive evaluation of Jais models focusing on both English and Arabic, using LM-harness in a zero-shot setting. The evaluation criteria spanned various dimensions, including:
183
+
184
+ - **Knowledge:** How well the model answers factual questions.
185
+ - **Reasoning:** The model's ability to answer questions requiring reasoning.
186
+ - **Misinformation/Bias:** Assessment of the model's susceptibility to generating false or misleading information, and its neutrality.
187
+
188
+ ### Arabic evaluation results:
189
+
190
+ <style>
191
+ .table-container {
192
+ overflow-x: auto;
193
+ white-space: nowrap;
194
+ }
195
+ </style>
196
+
197
+ <div class="table-container">
198
+
199
+ | **Models** | Avg | ArabicMMLU*| MMLU | EXAMS*| LitQA*| agqa | agrc | Hellaswag | PIQA | BoolQA | Situated QA | ARC-C | OpenBookQA | TruthfulQA | CrowS-Pairs |
200
+ |--------------------------|-------|------------|-------|-------|-------|------|------|------------|------|--------|-------------|-------|------------|------------|-------------|
201
+ | jais-family-30b-16k | 49.2 | 44.0 | 33.4 | 40.9 | 60 | 47.8 | 49.3 | 60.9 | 68.6 | 70.3 | 41.6 | 38.7 | 31.8 | 45.2 | 57 |
202
+ | jais-family-30b-8k | 49.7 | 46.0 | 34 | 42 | 60.6 | 47.6 | 50.4 | 60.4 | 69 | 67.7 | 42.2 | 39.2 | 33.8 | 45.1 | 57.3 |
203
+ | jais-family-13b | 46.1 | 34.0 | 30.3 | 42.7 | 58.3 | 40.5 | 45.5 | 57.3 | 68.1 | 63.1 | 41.6 | 35.3 | 31.4 | 41 | 56.1 |
204
+ | jais-family-6p7b | 44.6 | 32.2 | 29.9 | 39 | 50.3 | 39.2 | 44.1 | 54.3 | 66.8 | 66.5 | 40.9 | 33.5 | 30.4 | 41.2 | 55.4 |
205
+ | jais-family-2p7b | 41.0 | 29.5 | 28.5 | 36.1 | 45.7 | 32.4 | 40.8 | 44.2 | 62.5 | 62.2 | 39.2 | 27.4 | 28.2 | 43.6 | 53.6 |
206
+ | jais-family-1p3b | 40.8 | 28.9 | 28.5 | 34.2 | 45.7 | 32.4 | 40.8 | 44.2 | 62.5 | 62.2 | 39.2 | 27.4 | 28.2 | 43.6 | 53.6 |
207
+ | jais-family-590m | 39.7 | 31.2 | 27 | 33.1 | 41.7 | 33.8 | 38.8 | 38.2 | 60.7 | 62.2 | 37.9 | 25.5 | 27.4 | 44.7 | 53.3 |
208
+ | jais-family-30b-16k-chat | 51.6 | 59.9 | 34.6 | 40.2 | 58.9 | 46.8 | 54.7 | 56.2 | 64.4 | 76.7 | 55.9 | 40.8 | 30.8 | 49.5 | 52.9 |
209
+ | jais-family-30b-8k-chat | 51.4 | 61.2 | 34.2 | 40.2 | 54.3 | 47.3 | 53.6 | 60 | 63.4 | 76.8 | 54.7 | 39.5 | 30 | 50.7 | 54.3 |
210
+ | jais-family-13b-chat | 50.3 | 58.2 | 33.9 | 42.9 | 53.1 | 46.8 | 51.7 | 59.3 | 65.4 | 75.2 | 51.2 | 38.4 | 29.8 | 44.8 | 53.8 |
211
+ | jais-family-6p7b-chat | 48.7 | 55.7 | 32.8 | 37.7 | 49.7 | 40.5 | 50.1 | 56.2 | 62.9 | 79.4 | 52 | 38 | 30.4 | 44.7 | 52 |
212
+ | jais-family-2p7b-chat | 45.6 | 50.0 | 31.5 | 35.9 | 41.1 | 37.3 | 42.1 | 48.6 | 63.7 | 74.4 | 50.9 | 35.3 | 31.2 | 44.5 | 51.3 |
213
+ | jais-family-1p3b-chat | 42.7 | 42.2 | 30.1 | 33.6 | 40.6 | 34.1 | 41.2 | 43 | 63.6 | 69.3 | 44.9 | 31.6 | 28 | 45.6 | 50.4 |
214
+ | jais-family-590m-chat | 37.8 | 39.1 | 28 |29.5 | 33.1 | 30.8 | 36.4 | 30.3 | 57.8 | 57.2 | 40.5 | 25.9 | 26.8 | 44.5 | 49.3 |
215
+
216
+
217
+
218
+ | **Adapted Models** | Avg | ArabicMMLU*| MMLU | EXAMS*| LitQA*| agqa | agrc | Hellaswag | PIQA | BoolQA | Situated QA | ARC-C | OpenBookQA | TruthfulQA | CrowS-Pairs |
219
+ |--------------------------|-------|------------|-------|-------|-------|------|------|------------|------|--------|-------------|-------|------------|------------|-------------|
220
+ | jais-adapted-70b | 51.5 | 55.9 | 36.8 | 42.3 | 58.3 | 48.6 | 54 | 61.5 | 68.4 | 68.4 | 42.1 | 42.6 | 33 | 50.2 | 58.3 |
221
+ | jais-adapted-13b | 46.6 | 44.7 | 30.6 | 37.7 | 54.3 | 43.8 | 48.3 | 54.9 | 67.1 | 64.5 | 40.6 | 36.1 | 32 | 43.6 | 54.00 |
222
+ | jais-adapted-7b | 42.0 | 35.9 | 28.9 | 36.7 | 46.3 | 34.1 | 40.3 | 45 | 61.3 | 63.8 | 38.1 | 29.7 | 30.2 | 44.3 | 53.6 |
223
+ | jais-adapted-70b-chat | 52.9 | 66.8 | 34.6 | 42.5 | 62.9 | 36.8 | 48.6 | 64.5 | 69.7 | 82.8 | 49.3 | 44.2 | 32.2 | 53.3 | 52.4 |
224
+ | jais-adapted-13b-chat | 50.3 | 59.0 | 31.7 | 37.5 | 56.6 | 41.9 | 51.7 | 58.8 | 67.1 | 78.2 | 45.9 | 41 | 34.2 | 48.3 | 52.1 |
225
+ | jais-adapted-7b-chat | 46.1 | 51.3 | 30 | 37 | 48 | 36.8 | 48.6 | 51.1 | 62.9 | 72.4 | 41.3 | 34.6 | 30.4 | 48.6 | 51.8 |
226
+
227
+ </div>
228
+
229
+ Arabic benchmarks are translated using an in-house MT model and reviewed by Arabic linguists. Benchmarks labeled with an asterisk (*) are natively Arabic; for further details, see the [Jais paper](https://arxiv.org/abs/2308.16149). Additionally, we include [ArabicMMLU](https://arxiv.org/abs/2402.12840), a native Arabic benchmark based on regional knowledge.
230
+
231
+
232
+ ### English evaluation results:
233
+
234
+ <div class="table-container">
235
+
236
+ | **Models** | Avg | MMLU | RACE | Hellaswag | PIQA | BoolQA | SIQA | ARC-Challenge | OpenBookQA | Winogrande | TruthfulQA | CrowS-Pairs |
237
+ |--------------------------|----------|------|------|-----------|------|--------|------|---------------|------------|------------|----------------|-------------|
238
+ | jais-family-30b-16k | 59.3 | 42.2 | 40.5 | 79.7 | 80.6 | 78.7 | 48.8 | 50.3 | 44.2 | 71.6 | 43.5 | 72.6 |
239
+ | jais-family-30b-8k | 58.8 | 42.3 | 40.3 | 79.1 | 80.5 | 80.9 | 49.3 | 48.4 | 43.2 | 70.6 | 40.3 | 72.3 |
240
+ | jais-family-13b | 54.6 | 32.3 | 39 | 72 | 77.4 | 73.9 | 47.9 | 43.2 | 40 | 67.1 | 36.1 | 71.7 |
241
+ | jais-family-6p7b | 53.1 | 32 | 38 | 69.3 | 76 | 71.7 | 47.1 | 40.3 | 37.4 | 65.1 | 34.4 | 72.5 |
242
+ | jais-family-2p7b | 51 | 29.4 | 38 | 62.7 | 74.1 | 67.4 | 45.6 | 35.1 | 35.6 | 62.9 | 40.1 | 70.2 |
243
+ | jais-family-1p3b | 48.7 | 28.2 | 35.4 | 55.4 | 72 | 62.7 | 44.9 | 30.7 | 36.2 | 60.9 | 40.4 | 69 |
244
+ | jais-family-590m | 45.2 | 27.8 | 32.9 | 46.1 | 68.1 | 60.4 | 43.2 | 25.6 | 30.8 | 55.8 | 40.9 | 65.3 |
245
+ | jais-family-30b-16k-chat | 58.8 | 42 | 41.1 | 76.2 | 73.3 | 84.6 | 60.3 | 48.4 | 40.8 | 68.2 | 44.8 | 67 |
246
+ | jais-family-30b-8k-chat | 60.3 | 40.6 | 47.1 | 78.9 | 72.7 | 90.6 | 60 | 50.1 | 43.2 | 70.6 | 44.9 | 64.2 |
247
+ | jais-family-13b-chat | 57.5 | 36.6 | 42.6 | 75 | 75.8 | 87.6 | 54.4 | 47.9 | 42 | 65 | 40.6 | 64.5 |
248
+ | jais-family-6p7b-chat | 56 | 36.6 | 41.3 | 72 | 74 | 86.9 | 55.4 | 44.6 | 40 | 62.4 | 41 | 62.2 |
249
+ | jais-family-2p7b-chat | 52.8 | 32.7 | 40.4 | 62.2 | 71 | 84.1 | 54 | 37.2 | 36.8 | 61.4 | 40.9 | 59.8 |
250
+ | jais-family-1p3b-chat | 49.3 | 31.9 | 37.4 | 54.5 | 70.2 | 77.8 | 49.8 | 34.4 | 35.6 | 52.7 | 37.2 | 60.8 |
251
+ | jais-family-590m-chat | 42.6 | 27.9 | 33.4 | 33.1 | 63.7 | 60.1 | 45.3 | 26.7 | 25.8 | 50.5 | 44.5 | 57.7 |
252
+
253
+ </div>
254
+
255
+ <div class="table-container">
256
+
257
+ |**Adapted Models**| Avg | MMLU | RACE | Hellaswag | PIQA | BoolQA | SIQA | ARC-Challenge | OpenBookQA | Winogrande | TruthfulQA | CrowS-Pairs |
258
+ |--------------------------|----------|------|------|-----------|------|--------|------|---------------|------------|------------|----------------|-------------|
259
+ | jais-adapted-70b | 60.1 | 40.4 | 38.5 | 81.2 | 81.1 | 81.2 | 48.1 | 50.4 | 45 | 75.8 | 45.7 | 74 |
260
+ | jais-adapted-13b | 56 | 33.8 | 39.5 | 76.5 | 78.6 | 77.8 | 44.6 | 45.9 | 44.4 | 71.4 | 34.6 | 69 |
261
+ | jais-adapted-7b | 55.7 | 32.2 | 39.8 | 75.3 | 78.8 | 75.7 | 45.2 | 42.8 | 43 | 68 | 38.3 | 73.1 |
262
+ | jais-adapted-70b-chat | 61.4 | 38.7 | 42.9 | 82.7 | 81.2 | 89.6 | 52.9 | 54.9 | 44.4 | 75.7 | 44 | 68.8 |
263
+ | jais-adapted-13b-chat | 58.5 | 34.9 | 42.4 | 79.6 | 79.7 | 88.2 | 50.5 | 48.5 | 42.4 | 70.3 | 42.2 | 65.1 |
264
+ | jais-adapted-7b-chat | 58.5 | 33.8 | 43.9 | 77.8 | 79.4 | 87.1 | 47.3 | 46.9 | 43.4 | 69.9 | 42 | 72.4 |
265
+
266
+ </div>
267
+
268
+
269
+ ### GPT-4 evaluation
270
+
271
+
272
+ In addition to the LM-Harness evaluation, we conducted an open-ended generation evaluation using GPT-4-as-a-judge. We measured pairwise win-rates of model responses in both Arabic and English on a fixed set of 80 prompts from the Vicuna test set.
273
+ English prompts were translated to Arabic by our in-house linguists.
274
+ In the following, we compare the models in this release of the jais family against previously released versions:
275
+
276
+ <p align="center">
277
+ <img src="https://huggingface.co/core42/jais-family-30b-16k-chat/resolve/main/jais.png" alt="Jais-adapted GPT-4">
278
+ </p>
279
+ <p align="center">
280
+ <em>GPT-4-as-a-judge evaluation of Jais in Arabic and English. Jais family models are significantly better than previous Jais at generations in both languages. </em>
281
+ </p>
282
+
283
+ <p align="center">
284
+ <img src="https://huggingface.co/core42/jais-family-30b-16k-chat/resolve/main/jais-adapted.png" alt="Jais-adapted GPT-4">
285
+ </p>
286
+ <p align="center">
287
+ <em>GPT-4-as-a-judge evaluation of adapted Jais in Arabic and English. The generation quality of Arabic is significantly enhanced, while achieving improvement in English when compared to Llama-2 instruct. </em>
288
+ </p>
289
+
290
+ Besides pairwise comparison, we also perform MT-bench style single-answer grading on a scale of 1 to 10.
291
+
292
+ <p align="center">
293
+ <img src="https://huggingface.co/core42/jais-family-30b-16k-chat/resolve/main/mt_bench.png" alt="MT-bench">
294
+ </p>
295
+ <p align="center">
296
+ <em>MT-bench style single-answer grading evaluation of Jais and adapted Jais in Arabic and English. Comparisons are made between select corresponding models from earlier releases. The quality ratings of responses are generally improved, with significant enhancements in Arabic.</em>
297
+ </p>
298
+
299
+
300
+
301
+ ## Intended use
302
+
303
+ We release the Jais family of models under a full open-source license. We welcome all feedback and opportunities to collaborate. Spanning sizes from 590M to 70B parameters, this suite of bilingual models accommodates a wide range of use cases. Some potential downstream applications include:
304
+
305
+ - **Research**: The Jais family serves Arabic researchers and NLP practitioners, offering both compute-efficient and advanced model sizes
306
+ - Natural language understanding and generation tasks.
307
+ - Mechanistic interpretability analyses on cultural alignment in bilingual pre-trained and adapted pre-trained models.
308
+ - Quantitative studies of Arabic cultural and linguistic phenomena.
309
+
310
+ - **Commercial Use**: Jais 30B and 70B chat models are well-suited for direct use in chat applications with appropriate prompting or for further fine-tuning on specific tasks.
311
+ - Development of chat assistants for Arabic-speaking users.
312
+ - Sentiment analysis to gain insights into local markets and customer trends.
313
+ - Summarization of bilingual Arabic-English documents.
314
+
315
+ Audiences that we hope will benefit from our model:
316
+ - **Academics**: For those researching Arabic Natural Language Processing.
317
+ - **Businesses**: Companies targeting Arabic-speaking audiences.
318
+ - **Developers**: Those integrating Arabic language capabilities in applications.
319
+
320
+ ### Out-of-Scope Use
321
+
322
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
323
+
324
+ While the Jais family of models are powerful Arabic and English bilingual models, it's essential to understand their limitations
325
+ and the potential of misuse. It is prohibited to use the model in any manner that violates applicable laws or regulations.
326
+
327
+ The following are some example scenarios where the model should not be used.
328
+
329
+ - **Malicious Use**: The model should not be used to generate harmful, misleading, or inappropriate content. Thisincludes but is not limited to:
330
+ - Generating or promoting hate speech, violence, or discrimination.
331
+ - Spreading misinformation or fake news.
332
+ - Engaging in or promoting illegal activities.
333
+
334
+ - **Sensitive Information**: The model should not be used to handle or generate personal, confidential, or sensitive information.
335
+
336
+ - **Generalization Across All Languages**: Jais family of models are bilingual and optimized for Arabic and English. They should not be presumed to have equal proficiency in other languages or dialects.
337
+
338
+ - **High-Stakes Decisions**: The model should not be used to make high-stakes decisions without human oversight. This includes medical, legal, financial, or safety-critical decisions.
339
+
340
+ ## Bias, Risks, and Limitations
341
+
342
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
343
+
344
+ The Jais family is trained on publicly available data which was in part curated by Core42. We have employed different techniques to reduce bias in the model. While efforts have been made to minimize biases, it is likely that the model, as with all LLM models, will exhibit some bias.
345
+
346
+ The fine-tuned variants are trained as an AI assistant for Arabic and English speakers. Chat models are limited to produce responses for queries in these two languages and may not produce appropriate responses to other language queries.
347
+
348
+ By using Jais, you acknowledge and accept that, as with any large language model, it may generate incorrect, misleading, and/or offensive information or content. The information is not intended as advice and should not be relied upon in any way, nor are we responsible for any of the content or consequences resulting from its use.
349
+
350
+
351
+ #### Summary
352
+
353
+ We release the Jais family of Arabic and English bilingual models. The wide range of pre-trained model sizes, the recipe for adapting English-centric models to Arabic, and the fine-tuning of all sizes unlocks numerous use cases commercially and academically in the Arabic setting.
354
+
355
+ Through this release, we aim to make LLMs more accessible to Arabic NLP researchers and companies, offering native Arabic models that provide better cultural understanding than English centric ones. The strategies we employ for pre-training, fine-tuning and adaptation to Arabic are extensible to other low and medium resource languages, paving the way for language-focused and accessible models that cater to local contexts.
356
+
357
+ #### Citation info
358
+
359
+ ```bibtex
360
+ @misc{sengupta2023jais,
361
+ title={Jais and Jais-chat: Arabic-Centric Foundation and Instruction-Tuned Open Generative Large Language Models},
362
+ author={Neha Sengupta, Sunil Kumar Sahu, Bokang Jia, Satheesh Katipomu, Haonan Li, Fajri Koto, William Marshall, Gurpreet Gosal, Cynthia Liu, Zhiming Chen, Osama Mohammed Afzal, Samta Kamboj, Onkar Pandit, Rahul Pal, Lalit Pradhan, Zain Muhammad Mujahid, Massa Baali, Xudong Han, Sondos Mahmoud Bsharat, Alham Fikri Aji, Zhiqiang Shen, Zhengzhong Liu, Natalia Vassilieva, Joel Hestness, Andy Hock, Andrew Feldman, Jonathan Lee, Andrew Jackson, Hector Xuguang Ren, Preslav Nakov, Timothy Baldwin and Eric Xing},
363
+ year={2023},
364
+ eprint={2308.16149},
365
+ archivePrefix={arXiv},
366
+ primaryClass={cs.CL}
367
+ }
368
+
369
+ @article{jaisfamilymodelcard,
370
+ title={Jais Family Model Card},
371
+ author={Core42 (Inception)},
372
+ year={2024},
373
+ url = {https://huggingface.co/core42/jais-family-30b-16k-chat/blob/main/README.md}
374
+ }
375
+ ```
config.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "core42/jais-family-590m",
3
+ "activation_function": "swiglu",
4
+ "alibi_scaling": null,
5
+ "architectures": [
6
+ "JAISLMHeadModel"
7
+ ],
8
+ "attn_pdrop": 0.0,
9
+ "auto_map": {
10
+ "AutoConfig": "configuration_jais.JAISConfig",
11
+ "AutoModel": "modeling_jais.JAISModel",
12
+ "AutoModelForCausalLM": "modeling_jais.JAISLMHeadModel",
13
+ "AutoModelForQuestionAnswering": "modeling_jais.JAISForQuestionAnswering",
14
+ "AutoModelForSequenceClassification": "modeling_jais.JAISForSequenceClassification",
15
+ "AutoModelForTokenClassification": "modeling_jais.JAISForTokenClassification"
16
+ },
17
+ "bos_token_id": 0,
18
+ "embd_pdrop": 0.0,
19
+ "eos_token_id": 0,
20
+ "initializer_range": 0.02,
21
+ "layer_norm_epsilon": 1e-05,
22
+ "model_type": "jais",
23
+ "mup_embeddings_scale": 9.1705785388303,
24
+ "mup_output_alpha": 1.09518349815769,
25
+ "mup_scale_qk_dot_by_d": true,
26
+ "mup_width_scale": 0.16666666666666666,
27
+ "n_embd": 1536,
28
+ "n_head": 12,
29
+ "n_inner": 4096,
30
+ "n_layer": 18,
31
+ "n_positions": 2048,
32
+ "pad_token_id": 0,
33
+ "position_embedding_type": "alibi",
34
+ "reorder_and_upcast_attn": false,
35
+ "resid_pdrop": 0.0,
36
+ "scale_attn_by_inverse_layer_idx": false,
37
+ "scale_attn_weights": true,
38
+ "torch_dtype": "float32",
39
+ "transformers_version": "4.40.1",
40
+ "use_cache": true,
41
+ "vocab_size": 84992
42
+ }
configuration_jais.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The OpenAI Team Authors and HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ # Copyright 2023 Cerebras Systems.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """ JAIS configuration"""
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ class JAISConfig(PretrainedConfig):
26
+ """
27
+ This is the configuration class to store the configuration of a [`JAISModel`]. It is used to instantiate a JAIS
28
+ model according to the specified arguments, defining the model architecture.
29
+
30
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
31
+ documentation from [`PretrainedConfig`] for more information.
32
+
33
+
34
+ Args:
35
+ vocab_size (`int`, *optional*, defaults to 50257):
36
+ Vocabulary size of the JAIS model. Defines the number of different tokens that can be represented by the
37
+ `inputs_ids` passed when calling [`JAISModel`].
38
+ n_positions (`int`, *optional*, defaults to 1024):
39
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
40
+ just in case (e.g., 512 or 1024 or 2048).
41
+ n_embd (`int`, *optional*, defaults to 768):
42
+ Dimensionality of the embeddings and hidden states.
43
+ n_layer (`int`, *optional*, defaults to 12):
44
+ Number of hidden layers in the Transformer encoder.
45
+ n_head (`int`, *optional*, defaults to 12):
46
+ Number of attention heads for each attention layer in the Transformer encoder.
47
+ n_inner (`int`, *optional*, defaults to None):
48
+ Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
49
+ activation_function (`str`, *optional*, defaults to `"gelu"`):
50
+ Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new", "swiglu"]`.
51
+ resid_pdrop (`float`, *optional*, defaults to 0.1):
52
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
53
+ embd_pdrop (`float`, *optional*, defaults to 0.1):
54
+ The dropout ratio for the embeddings.
55
+ attn_pdrop (`float`, *optional*, defaults to 0.1):
56
+ The dropout ratio for the attention.
57
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
58
+ The epsilon to use in the layer normalization layers.
59
+ initializer_range (`float`, *optional*, defaults to 0.02):
60
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
61
+ scale_attn_weights (`bool`, *optional*, defaults to `True`):
62
+ Scale attention weights by dividing by sqrt(hidden_size)..
63
+ use_cache (`bool`, *optional*, defaults to `True`):
64
+ Whether or not the model should return the last key/values attentions (not used by all models).
65
+ scale_attn_by_inverse_layer_idx (`bool`, *optional*, defaults to `False`):
66
+ Whether to additionally scale attention weights by `1 / layer_idx + 1`.
67
+ reorder_and_upcast_attn (`bool`, *optional*, defaults to `False`):
68
+ Whether to scale keys (K) prior to computing attention (dot-product) and upcast attention
69
+ dot-product/softmax to float() when training with mixed precision.
70
+ position_embedding_type (`str`, *optional*, defaults to `"learned"`):
71
+ Positional embedding can be either `"alibi"` or `"learned"`.
72
+ mup_width_scale (`float`, *optional*, defaults to 1.0):
73
+ muP parameter to scale learning rate and initializers. Calculated as (`d_model,0 / d_model`), where
74
+ `d_model` is the model's width and `d_model,0` is the proxy model's width.
75
+ mup_embeddings_scale (`float`, *optional*, defaults to 1.0):
76
+ muP parameter to scale token and position embeddings.
77
+ mup_output_alpha (`float`, *optional*, defaults to 1.0):
78
+ muP parameter to scale output logits (`output_logits_scale = mup_output_alpha * mup_width_scale`).
79
+ mup_scale_qk_dot_by_d (`bool`, *optional*, defaults to `False`):
80
+ Scale attention weights by dividing by hidden_size instead of sqrt(hidden_size). Need to set
81
+ scale_attn_weights to `True` as well.
82
+ alibi_scaling (`Dict`, *optional*):
83
+ Dictionary containing the scaling configuration for ALiBi embeddings. Currently only supports linear
84
+ scaling strategy. Can specify either the scaling `factor` (must be a float greater than 1) for fixed scaling
85
+ or `train_seq_len` for dynamic scaling on input samples with sequence length > `train_seq_len`. The expected
86
+ formats are `{"type": strategy name, "factor": scaling factor}` or
87
+ `{"type": strategy name, "train_seq_len": training sequence length}`.
88
+
89
+ Example:
90
+
91
+ ```python
92
+ >>> from transformers import JAISConfig, JAISModel
93
+
94
+ >>> # Initializing a JAIS configuration
95
+ >>> configuration = JAISConfig()
96
+
97
+ >>> # Initializing a model (with random weights) from the configuration
98
+ >>> model = JAISModel(configuration)
99
+
100
+ >>> # Accessing the model configuration
101
+ >>> configuration = model.config
102
+ ```"""
103
+
104
+ model_type = "jais"
105
+ keys_to_ignore_at_inference = ["past_key_values"]
106
+ attribute_map = {
107
+ "hidden_size": "n_embd",
108
+ "max_position_embeddings": "n_positions",
109
+ "num_attention_heads": "n_head",
110
+ "num_hidden_layers": "n_layer",
111
+ }
112
+
113
+ def __init__(
114
+ self,
115
+ vocab_size=50257,
116
+ n_positions=1024,
117
+ n_embd=768,
118
+ n_layer=12,
119
+ n_head=12,
120
+ n_inner=None,
121
+ activation_function="gelu_new",
122
+ resid_pdrop=0.1,
123
+ embd_pdrop=0.1,
124
+ attn_pdrop=0.1,
125
+ layer_norm_epsilon=1e-5,
126
+ initializer_range=0.02,
127
+ scale_attn_weights=True,
128
+ use_cache=True,
129
+ bos_token_id=50256,
130
+ eos_token_id=50256,
131
+ scale_attn_by_inverse_layer_idx=False,
132
+ reorder_and_upcast_attn=False,
133
+ position_embedding_type="learned",
134
+ mup_width_scale=1.0,
135
+ mup_embeddings_scale=1.0,
136
+ mup_output_alpha=1.0,
137
+ mup_scale_qk_dot_by_d=False,
138
+ alibi_scaling=None,
139
+ **kwargs,
140
+ ):
141
+ self.vocab_size = vocab_size
142
+ self.n_positions = n_positions
143
+ self.n_embd = n_embd
144
+ self.n_layer = n_layer
145
+ self.n_head = n_head
146
+ self.n_inner = n_inner
147
+ self.activation_function = activation_function
148
+ self.resid_pdrop = resid_pdrop
149
+ self.embd_pdrop = embd_pdrop
150
+ self.attn_pdrop = attn_pdrop
151
+ self.layer_norm_epsilon = layer_norm_epsilon
152
+ self.initializer_range = initializer_range
153
+ self.scale_attn_weights = scale_attn_weights
154
+ self.use_cache = use_cache
155
+ self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx
156
+ self.reorder_and_upcast_attn = reorder_and_upcast_attn
157
+
158
+ self.bos_token_id = bos_token_id
159
+ self.eos_token_id = eos_token_id
160
+
161
+ self.position_embedding_type = position_embedding_type
162
+ self.mup_width_scale = mup_width_scale
163
+ self.mup_embeddings_scale = mup_embeddings_scale
164
+ self.mup_output_alpha = mup_output_alpha
165
+ self.mup_scale_qk_dot_by_d = mup_scale_qk_dot_by_d
166
+
167
+ self.alibi_scaling = alibi_scaling
168
+ self._alibi_scaling_validation()
169
+
170
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
171
+
172
+ def _alibi_scaling_validation(self):
173
+ """
174
+ Validate the `alibi_scaling` configuration.
175
+ """
176
+ if self.alibi_scaling is None:
177
+ return
178
+
179
+ if not isinstance(self.alibi_scaling, dict) or len(self.alibi_scaling) != 2:
180
+ raise ValueError(
181
+ "`alibi_scaling` must be a dictionary with two fields, `type` and `factor` or `type` and `train_seq_len`, "
182
+ f"got {self.alibi_scaling}"
183
+ )
184
+ alibi_scaling_type = self.alibi_scaling.get("type", None)
185
+ alibi_scaling_factor = self.alibi_scaling.get("factor", None)
186
+ alibi_dynamic_scaling = self.alibi_scaling.get("train_seq_len", None)
187
+ if alibi_scaling_type is None or alibi_scaling_type != "linear":
188
+ raise ValueError(
189
+ f"`alibi_scaling`'s type field must be 'linear', got {alibi_scaling_type}"
190
+ )
191
+ if alibi_scaling_factor is not None:
192
+ if not isinstance(alibi_scaling_factor, float) or alibi_scaling_factor <= 1.0:
193
+ raise ValueError(f"`alibi_scaling`'s factor field must be a float > 1.0, got {alibi_scaling_factor}")
194
+ if alibi_dynamic_scaling is not None:
195
+ if not isinstance(alibi_dynamic_scaling, int) or alibi_dynamic_scaling <= 1:
196
+ raise ValueError(f"`alibi_scaling`'s `train_seq_len` field must be an integer > 1, got {alibi_dynamic_scaling}")
model-00001-of-00001.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f270d82e0d07051bfb790c66102c3951b97c6fc91ce959b31c8fc99088383d56
3
+ size 3084437888
model.safetensors.index.json ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 3084410928
4
+ },
5
+ "weight_map": {
6
+ "transformer.wte.weight": "model-00001-of-00001.safetensors",
7
+ "transformer.relative_pe.slopes": "model-00001-of-00001.safetensors",
8
+ "transformer.h.0.attn.c_attn.weight": "model-00001-of-00001.safetensors",
9
+ "transformer.h.0.attn.c_attn.bias": "model-00001-of-00001.safetensors",
10
+ "transformer.h.0.attn.c_proj.weight": "model-00001-of-00001.safetensors",
11
+ "transformer.h.0.attn.c_proj.bias": "model-00001-of-00001.safetensors",
12
+ "transformer.h.0.ln_1.weight": "model-00001-of-00001.safetensors",
13
+ "transformer.h.0.ln_1.bias": "model-00001-of-00001.safetensors",
14
+ "transformer.h.0.ln_2.weight": "model-00001-of-00001.safetensors",
15
+ "transformer.h.0.ln_2.bias": "model-00001-of-00001.safetensors",
16
+ "transformer.h.0.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
17
+ "transformer.h.0.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
18
+ "transformer.h.0.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
19
+ "transformer.h.0.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
20
+ "transformer.h.0.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
21
+ "transformer.h.0.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
22
+ "transformer.h.1.attn.c_attn.weight": "model-00001-of-00001.safetensors",
23
+ "transformer.h.1.attn.c_attn.bias": "model-00001-of-00001.safetensors",
24
+ "transformer.h.1.attn.c_proj.weight": "model-00001-of-00001.safetensors",
25
+ "transformer.h.1.attn.c_proj.bias": "model-00001-of-00001.safetensors",
26
+ "transformer.h.1.ln_1.weight": "model-00001-of-00001.safetensors",
27
+ "transformer.h.1.ln_1.bias": "model-00001-of-00001.safetensors",
28
+ "transformer.h.1.ln_2.weight": "model-00001-of-00001.safetensors",
29
+ "transformer.h.1.ln_2.bias": "model-00001-of-00001.safetensors",
30
+ "transformer.h.1.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
31
+ "transformer.h.1.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
32
+ "transformer.h.1.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
33
+ "transformer.h.1.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
34
+ "transformer.h.1.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
35
+ "transformer.h.1.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
36
+ "transformer.h.2.attn.c_attn.weight": "model-00001-of-00001.safetensors",
37
+ "transformer.h.2.attn.c_attn.bias": "model-00001-of-00001.safetensors",
38
+ "transformer.h.2.attn.c_proj.weight": "model-00001-of-00001.safetensors",
39
+ "transformer.h.2.attn.c_proj.bias": "model-00001-of-00001.safetensors",
40
+ "transformer.h.2.ln_1.weight": "model-00001-of-00001.safetensors",
41
+ "transformer.h.2.ln_1.bias": "model-00001-of-00001.safetensors",
42
+ "transformer.h.2.ln_2.weight": "model-00001-of-00001.safetensors",
43
+ "transformer.h.2.ln_2.bias": "model-00001-of-00001.safetensors",
44
+ "transformer.h.2.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
45
+ "transformer.h.2.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
46
+ "transformer.h.2.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
47
+ "transformer.h.2.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
48
+ "transformer.h.2.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
49
+ "transformer.h.2.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
50
+ "transformer.h.3.attn.c_attn.weight": "model-00001-of-00001.safetensors",
51
+ "transformer.h.3.attn.c_attn.bias": "model-00001-of-00001.safetensors",
52
+ "transformer.h.3.attn.c_proj.weight": "model-00001-of-00001.safetensors",
53
+ "transformer.h.3.attn.c_proj.bias": "model-00001-of-00001.safetensors",
54
+ "transformer.h.3.ln_1.weight": "model-00001-of-00001.safetensors",
55
+ "transformer.h.3.ln_1.bias": "model-00001-of-00001.safetensors",
56
+ "transformer.h.3.ln_2.weight": "model-00001-of-00001.safetensors",
57
+ "transformer.h.3.ln_2.bias": "model-00001-of-00001.safetensors",
58
+ "transformer.h.3.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
59
+ "transformer.h.3.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
60
+ "transformer.h.3.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
61
+ "transformer.h.3.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
62
+ "transformer.h.3.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
63
+ "transformer.h.3.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
64
+ "transformer.h.4.attn.c_attn.weight": "model-00001-of-00001.safetensors",
65
+ "transformer.h.4.attn.c_attn.bias": "model-00001-of-00001.safetensors",
66
+ "transformer.h.4.attn.c_proj.weight": "model-00001-of-00001.safetensors",
67
+ "transformer.h.4.attn.c_proj.bias": "model-00001-of-00001.safetensors",
68
+ "transformer.h.4.ln_1.weight": "model-00001-of-00001.safetensors",
69
+ "transformer.h.4.ln_1.bias": "model-00001-of-00001.safetensors",
70
+ "transformer.h.4.ln_2.weight": "model-00001-of-00001.safetensors",
71
+ "transformer.h.4.ln_2.bias": "model-00001-of-00001.safetensors",
72
+ "transformer.h.4.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
73
+ "transformer.h.4.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
74
+ "transformer.h.4.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
75
+ "transformer.h.4.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
76
+ "transformer.h.4.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
77
+ "transformer.h.4.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
78
+ "transformer.h.5.attn.c_attn.weight": "model-00001-of-00001.safetensors",
79
+ "transformer.h.5.attn.c_attn.bias": "model-00001-of-00001.safetensors",
80
+ "transformer.h.5.attn.c_proj.weight": "model-00001-of-00001.safetensors",
81
+ "transformer.h.5.attn.c_proj.bias": "model-00001-of-00001.safetensors",
82
+ "transformer.h.5.ln_1.weight": "model-00001-of-00001.safetensors",
83
+ "transformer.h.5.ln_1.bias": "model-00001-of-00001.safetensors",
84
+ "transformer.h.5.ln_2.weight": "model-00001-of-00001.safetensors",
85
+ "transformer.h.5.ln_2.bias": "model-00001-of-00001.safetensors",
86
+ "transformer.h.5.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
87
+ "transformer.h.5.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
88
+ "transformer.h.5.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
89
+ "transformer.h.5.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
90
+ "transformer.h.5.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
91
+ "transformer.h.5.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
92
+ "transformer.h.6.attn.c_attn.weight": "model-00001-of-00001.safetensors",
93
+ "transformer.h.6.attn.c_attn.bias": "model-00001-of-00001.safetensors",
94
+ "transformer.h.6.attn.c_proj.weight": "model-00001-of-00001.safetensors",
95
+ "transformer.h.6.attn.c_proj.bias": "model-00001-of-00001.safetensors",
96
+ "transformer.h.6.ln_1.weight": "model-00001-of-00001.safetensors",
97
+ "transformer.h.6.ln_1.bias": "model-00001-of-00001.safetensors",
98
+ "transformer.h.6.ln_2.weight": "model-00001-of-00001.safetensors",
99
+ "transformer.h.6.ln_2.bias": "model-00001-of-00001.safetensors",
100
+ "transformer.h.6.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
101
+ "transformer.h.6.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
102
+ "transformer.h.6.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
103
+ "transformer.h.6.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
104
+ "transformer.h.6.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
105
+ "transformer.h.6.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
106
+ "transformer.h.7.attn.c_attn.weight": "model-00001-of-00001.safetensors",
107
+ "transformer.h.7.attn.c_attn.bias": "model-00001-of-00001.safetensors",
108
+ "transformer.h.7.attn.c_proj.weight": "model-00001-of-00001.safetensors",
109
+ "transformer.h.7.attn.c_proj.bias": "model-00001-of-00001.safetensors",
110
+ "transformer.h.7.ln_1.weight": "model-00001-of-00001.safetensors",
111
+ "transformer.h.7.ln_1.bias": "model-00001-of-00001.safetensors",
112
+ "transformer.h.7.ln_2.weight": "model-00001-of-00001.safetensors",
113
+ "transformer.h.7.ln_2.bias": "model-00001-of-00001.safetensors",
114
+ "transformer.h.7.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
115
+ "transformer.h.7.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
116
+ "transformer.h.7.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
117
+ "transformer.h.7.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
118
+ "transformer.h.7.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
119
+ "transformer.h.7.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
120
+ "transformer.h.8.attn.c_attn.weight": "model-00001-of-00001.safetensors",
121
+ "transformer.h.8.attn.c_attn.bias": "model-00001-of-00001.safetensors",
122
+ "transformer.h.8.attn.c_proj.weight": "model-00001-of-00001.safetensors",
123
+ "transformer.h.8.attn.c_proj.bias": "model-00001-of-00001.safetensors",
124
+ "transformer.h.8.ln_1.weight": "model-00001-of-00001.safetensors",
125
+ "transformer.h.8.ln_1.bias": "model-00001-of-00001.safetensors",
126
+ "transformer.h.8.ln_2.weight": "model-00001-of-00001.safetensors",
127
+ "transformer.h.8.ln_2.bias": "model-00001-of-00001.safetensors",
128
+ "transformer.h.8.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
129
+ "transformer.h.8.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
130
+ "transformer.h.8.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
131
+ "transformer.h.8.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
132
+ "transformer.h.8.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
133
+ "transformer.h.8.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
134
+ "transformer.h.9.attn.c_attn.weight": "model-00001-of-00001.safetensors",
135
+ "transformer.h.9.attn.c_attn.bias": "model-00001-of-00001.safetensors",
136
+ "transformer.h.9.attn.c_proj.weight": "model-00001-of-00001.safetensors",
137
+ "transformer.h.9.attn.c_proj.bias": "model-00001-of-00001.safetensors",
138
+ "transformer.h.9.ln_1.weight": "model-00001-of-00001.safetensors",
139
+ "transformer.h.9.ln_1.bias": "model-00001-of-00001.safetensors",
140
+ "transformer.h.9.ln_2.weight": "model-00001-of-00001.safetensors",
141
+ "transformer.h.9.ln_2.bias": "model-00001-of-00001.safetensors",
142
+ "transformer.h.9.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
143
+ "transformer.h.9.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
144
+ "transformer.h.9.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
145
+ "transformer.h.9.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
146
+ "transformer.h.9.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
147
+ "transformer.h.9.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
148
+ "transformer.h.10.attn.c_attn.weight": "model-00001-of-00001.safetensors",
149
+ "transformer.h.10.attn.c_attn.bias": "model-00001-of-00001.safetensors",
150
+ "transformer.h.10.attn.c_proj.weight": "model-00001-of-00001.safetensors",
151
+ "transformer.h.10.attn.c_proj.bias": "model-00001-of-00001.safetensors",
152
+ "transformer.h.10.ln_1.weight": "model-00001-of-00001.safetensors",
153
+ "transformer.h.10.ln_1.bias": "model-00001-of-00001.safetensors",
154
+ "transformer.h.10.ln_2.weight": "model-00001-of-00001.safetensors",
155
+ "transformer.h.10.ln_2.bias": "model-00001-of-00001.safetensors",
156
+ "transformer.h.10.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
157
+ "transformer.h.10.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
158
+ "transformer.h.10.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
159
+ "transformer.h.10.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
160
+ "transformer.h.10.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
161
+ "transformer.h.10.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
162
+ "transformer.h.11.attn.c_attn.weight": "model-00001-of-00001.safetensors",
163
+ "transformer.h.11.attn.c_attn.bias": "model-00001-of-00001.safetensors",
164
+ "transformer.h.11.attn.c_proj.weight": "model-00001-of-00001.safetensors",
165
+ "transformer.h.11.attn.c_proj.bias": "model-00001-of-00001.safetensors",
166
+ "transformer.h.11.ln_1.weight": "model-00001-of-00001.safetensors",
167
+ "transformer.h.11.ln_1.bias": "model-00001-of-00001.safetensors",
168
+ "transformer.h.11.ln_2.weight": "model-00001-of-00001.safetensors",
169
+ "transformer.h.11.ln_2.bias": "model-00001-of-00001.safetensors",
170
+ "transformer.h.11.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
171
+ "transformer.h.11.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
172
+ "transformer.h.11.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
173
+ "transformer.h.11.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
174
+ "transformer.h.11.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
175
+ "transformer.h.11.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
176
+ "transformer.h.12.attn.c_attn.weight": "model-00001-of-00001.safetensors",
177
+ "transformer.h.12.attn.c_attn.bias": "model-00001-of-00001.safetensors",
178
+ "transformer.h.12.attn.c_proj.weight": "model-00001-of-00001.safetensors",
179
+ "transformer.h.12.attn.c_proj.bias": "model-00001-of-00001.safetensors",
180
+ "transformer.h.12.ln_1.weight": "model-00001-of-00001.safetensors",
181
+ "transformer.h.12.ln_1.bias": "model-00001-of-00001.safetensors",
182
+ "transformer.h.12.ln_2.weight": "model-00001-of-00001.safetensors",
183
+ "transformer.h.12.ln_2.bias": "model-00001-of-00001.safetensors",
184
+ "transformer.h.12.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
185
+ "transformer.h.12.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
186
+ "transformer.h.12.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
187
+ "transformer.h.12.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
188
+ "transformer.h.12.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
189
+ "transformer.h.12.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
190
+ "transformer.h.13.attn.c_attn.weight": "model-00001-of-00001.safetensors",
191
+ "transformer.h.13.attn.c_attn.bias": "model-00001-of-00001.safetensors",
192
+ "transformer.h.13.attn.c_proj.weight": "model-00001-of-00001.safetensors",
193
+ "transformer.h.13.attn.c_proj.bias": "model-00001-of-00001.safetensors",
194
+ "transformer.h.13.ln_1.weight": "model-00001-of-00001.safetensors",
195
+ "transformer.h.13.ln_1.bias": "model-00001-of-00001.safetensors",
196
+ "transformer.h.13.ln_2.weight": "model-00001-of-00001.safetensors",
197
+ "transformer.h.13.ln_2.bias": "model-00001-of-00001.safetensors",
198
+ "transformer.h.13.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
199
+ "transformer.h.13.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
200
+ "transformer.h.13.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
201
+ "transformer.h.13.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
202
+ "transformer.h.13.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
203
+ "transformer.h.13.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
204
+ "transformer.h.14.attn.c_attn.weight": "model-00001-of-00001.safetensors",
205
+ "transformer.h.14.attn.c_attn.bias": "model-00001-of-00001.safetensors",
206
+ "transformer.h.14.attn.c_proj.weight": "model-00001-of-00001.safetensors",
207
+ "transformer.h.14.attn.c_proj.bias": "model-00001-of-00001.safetensors",
208
+ "transformer.h.14.ln_1.weight": "model-00001-of-00001.safetensors",
209
+ "transformer.h.14.ln_1.bias": "model-00001-of-00001.safetensors",
210
+ "transformer.h.14.ln_2.weight": "model-00001-of-00001.safetensors",
211
+ "transformer.h.14.ln_2.bias": "model-00001-of-00001.safetensors",
212
+ "transformer.h.14.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
213
+ "transformer.h.14.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
214
+ "transformer.h.14.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
215
+ "transformer.h.14.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
216
+ "transformer.h.14.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
217
+ "transformer.h.14.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
218
+ "transformer.h.15.attn.c_attn.weight": "model-00001-of-00001.safetensors",
219
+ "transformer.h.15.attn.c_attn.bias": "model-00001-of-00001.safetensors",
220
+ "transformer.h.15.attn.c_proj.weight": "model-00001-of-00001.safetensors",
221
+ "transformer.h.15.attn.c_proj.bias": "model-00001-of-00001.safetensors",
222
+ "transformer.h.15.ln_1.weight": "model-00001-of-00001.safetensors",
223
+ "transformer.h.15.ln_1.bias": "model-00001-of-00001.safetensors",
224
+ "transformer.h.15.ln_2.weight": "model-00001-of-00001.safetensors",
225
+ "transformer.h.15.ln_2.bias": "model-00001-of-00001.safetensors",
226
+ "transformer.h.15.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
227
+ "transformer.h.15.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
228
+ "transformer.h.15.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
229
+ "transformer.h.15.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
230
+ "transformer.h.15.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
231
+ "transformer.h.15.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
232
+ "transformer.h.16.attn.c_attn.weight": "model-00001-of-00001.safetensors",
233
+ "transformer.h.16.attn.c_attn.bias": "model-00001-of-00001.safetensors",
234
+ "transformer.h.16.attn.c_proj.weight": "model-00001-of-00001.safetensors",
235
+ "transformer.h.16.attn.c_proj.bias": "model-00001-of-00001.safetensors",
236
+ "transformer.h.16.ln_1.weight": "model-00001-of-00001.safetensors",
237
+ "transformer.h.16.ln_1.bias": "model-00001-of-00001.safetensors",
238
+ "transformer.h.16.ln_2.weight": "model-00001-of-00001.safetensors",
239
+ "transformer.h.16.ln_2.bias": "model-00001-of-00001.safetensors",
240
+ "transformer.h.16.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
241
+ "transformer.h.16.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
242
+ "transformer.h.16.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
243
+ "transformer.h.16.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
244
+ "transformer.h.16.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
245
+ "transformer.h.16.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
246
+ "transformer.h.17.attn.c_attn.weight": "model-00001-of-00001.safetensors",
247
+ "transformer.h.17.attn.c_attn.bias": "model-00001-of-00001.safetensors",
248
+ "transformer.h.17.attn.c_proj.weight": "model-00001-of-00001.safetensors",
249
+ "transformer.h.17.attn.c_proj.bias": "model-00001-of-00001.safetensors",
250
+ "transformer.h.17.ln_1.weight": "model-00001-of-00001.safetensors",
251
+ "transformer.h.17.ln_1.bias": "model-00001-of-00001.safetensors",
252
+ "transformer.h.17.ln_2.weight": "model-00001-of-00001.safetensors",
253
+ "transformer.h.17.ln_2.bias": "model-00001-of-00001.safetensors",
254
+ "transformer.h.17.mlp.c_fc.weight": "model-00001-of-00001.safetensors",
255
+ "transformer.h.17.mlp.c_fc.bias": "model-00001-of-00001.safetensors",
256
+ "transformer.h.17.mlp.c_fc2.weight": "model-00001-of-00001.safetensors",
257
+ "transformer.h.17.mlp.c_fc2.bias": "model-00001-of-00001.safetensors",
258
+ "transformer.h.17.mlp.c_proj.weight": "model-00001-of-00001.safetensors",
259
+ "transformer.h.17.mlp.c_proj.bias": "model-00001-of-00001.safetensors",
260
+ "transformer.ln_f.weight": "model-00001-of-00001.safetensors",
261
+ "transformer.ln_f.bias": "model-00001-of-00001.safetensors",
262
+ "lm_head.weight": "model-00001-of-00001.safetensors"
263
+ }
264
+ }
modeling_jais.py ADDED
@@ -0,0 +1,1600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The OpenAI Team Authors and HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ # Copyright 2023 Cerebras Systems.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """ PyTorch JAIS model."""
18
+
19
+ import math
20
+ import os
21
+ import warnings
22
+ from typing import Optional, Tuple, Union
23
+
24
+ import torch
25
+ from torch import Tensor, nn
26
+ from torch.cuda.amp import autocast
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import (
31
+ BaseModelOutputWithPastAndCrossAttentions,
32
+ CausalLMOutputWithCrossAttentions,
33
+ QuestionAnsweringModelOutput,
34
+ SequenceClassifierOutputWithPast,
35
+ TokenClassifierOutput,
36
+ )
37
+ from transformers.modeling_utils import PreTrainedModel
38
+ from transformers.pytorch_utils import Conv1D, find_pruneable_heads_and_indices, prune_conv1d_layer
39
+ from transformers.utils import (
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ logging,
44
+ )
45
+ from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
46
+ from .configuration_jais import JAISConfig
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+ _CHECKPOINT_FOR_DOC = "core42/jais-13b"
52
+ _CONFIG_FOR_DOC = "JAISConfig"
53
+
54
+
55
+ class SwiGLUActivation(nn.Module):
56
+ def forward(self, x1: Tensor, x2: Tensor) -> Tensor:
57
+ return x1 * nn.functional.silu(x2)
58
+
59
+
60
+ class AlibiPositionEmbeddingLayer(nn.Module):
61
+ def __init__(self, num_heads, alibi_scaling=None):
62
+ super(AlibiPositionEmbeddingLayer, self).__init__()
63
+
64
+ self.num_heads = num_heads
65
+ self.alibi_scaling = alibi_scaling
66
+ slopes = torch.tensor(AlibiPositionEmbeddingLayer._get_alibi_slopes(num_heads)).unsqueeze(-1)
67
+ self.slopes = nn.parameter.Parameter(slopes, requires_grad=False)
68
+
69
+ def forward(
70
+ self,
71
+ seq_length,
72
+ key_length,
73
+ cached_qk_len,
74
+ ):
75
+ context_position = torch.arange(
76
+ cached_qk_len, cached_qk_len + seq_length, device=self.slopes.device
77
+ )[:, None]
78
+ memory_position = torch.arange(
79
+ key_length + cached_qk_len, device=self.slopes.device
80
+ )[None, :]
81
+ relative_position = memory_position - context_position
82
+ relative_position = torch.abs(relative_position).unsqueeze(0).expand(self.num_heads, -1, -1)
83
+
84
+ if self.alibi_scaling is None:
85
+ scale = 1.0
86
+ elif self.alibi_scaling.get("factor") is not None:
87
+ scale = self.alibi_scaling["factor"]
88
+ elif relative_position.shape[-1] > self.alibi_scaling["train_seq_len"]:
89
+ scale = relative_position.shape[-1] / self.alibi_scaling["train_seq_len"]
90
+ else:
91
+ scale = 1.0
92
+
93
+ alibi = (self.slopes / -scale).unsqueeze(1) * relative_position
94
+ return alibi
95
+
96
+ @staticmethod
97
+ def _get_alibi_slopes(n):
98
+ def get_slopes_power_of_2(n):
99
+ start = 2 ** (-(2 ** -(math.log2(n) - 3)))
100
+ ratio = start
101
+ return [start * ratio**i for i in range(n)]
102
+
103
+ if math.log2(n).is_integer():
104
+ return get_slopes_power_of_2(
105
+ n
106
+ ) # In the paper, we only train models that have 2^a heads for some a. This function has
107
+ else: # some good properties that only occur when the input is a power of 2. To maintain that even
108
+ closest_power_of_2 = 2 ** math.floor(
109
+ math.log2(n)
110
+ ) # when the number of heads is not a power of 2, we use this workaround.
111
+ return (
112
+ get_slopes_power_of_2(closest_power_of_2)
113
+ + AlibiPositionEmbeddingLayer._get_alibi_slopes(2 * closest_power_of_2)[0::2][: n - closest_power_of_2]
114
+ )
115
+
116
+
117
+ def load_tf_weights_in_jais(model, config, jais_checkpoint_path):
118
+ """Load tf checkpoints in a pytorch model"""
119
+ try:
120
+ import re
121
+
122
+ import tensorflow as tf
123
+ except ImportError:
124
+ logger.error(
125
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
126
+ "https://www.tensorflow.org/install/ for installation instructions."
127
+ )
128
+ raise
129
+ tf_path = os.path.abspath(jais_checkpoint_path)
130
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
131
+ # Load weights from TF model
132
+ init_vars = tf.train.list_variables(tf_path)
133
+ names = []
134
+ arrays = []
135
+ for name, shape in init_vars:
136
+ logger.info(f"Loading TF weight {name} with shape {shape}")
137
+ array = tf.train.load_variable(tf_path, name)
138
+ names.append(name)
139
+ arrays.append(array.squeeze())
140
+
141
+ for name, array in zip(names, arrays):
142
+ name = name[6:] # skip "model/"
143
+ name = name.split("/")
144
+ pointer = model
145
+ for m_name in name:
146
+ if re.fullmatch(r"[A-Za-z]+\d+", m_name):
147
+ scope_names = re.split(r"(\d+)", m_name)
148
+ else:
149
+ scope_names = [m_name]
150
+ if scope_names[0] == "w" or scope_names[0] == "g":
151
+ pointer = getattr(pointer, "weight")
152
+ elif scope_names[0] == "b":
153
+ pointer = getattr(pointer, "bias")
154
+ elif scope_names[0] == "wpe" or scope_names[0] == "wte":
155
+ pointer = getattr(pointer, scope_names[0])
156
+ pointer = getattr(pointer, "weight")
157
+ else:
158
+ pointer = getattr(pointer, scope_names[0])
159
+ if len(scope_names) >= 2:
160
+ num = int(scope_names[1])
161
+ pointer = pointer[num]
162
+ try:
163
+ assert (
164
+ pointer.shape == array.shape
165
+ ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
166
+ except AssertionError as e:
167
+ e.args += (pointer.shape, array.shape)
168
+ raise
169
+ logger.info(f"Initialize PyTorch weight {name}")
170
+ pointer.data = torch.from_numpy(array)
171
+ return model
172
+
173
+
174
+ class JAISAttention(nn.Module):
175
+ def __init__(self, config, is_cross_attention=False, layer_idx=None):
176
+ super().__init__()
177
+
178
+ max_positions = config.max_position_embeddings
179
+ self.register_buffer(
180
+ "bias",
181
+ torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
182
+ 1, 1, max_positions, max_positions
183
+ ),
184
+ persistent=False,
185
+ )
186
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
187
+
188
+ self.embed_dim = config.hidden_size
189
+ self.num_heads = config.num_attention_heads
190
+ self.head_dim = self.embed_dim // self.num_heads
191
+ self.split_size = self.embed_dim
192
+ if self.head_dim * self.num_heads != self.embed_dim:
193
+ raise ValueError(
194
+ f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
195
+ f" {self.num_heads})."
196
+ )
197
+
198
+ self.scale_attn_weights = config.scale_attn_weights
199
+ self.is_cross_attention = is_cross_attention
200
+
201
+ # Layer-wise attention scaling, reordering, and upcasting
202
+ self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx
203
+ self.layer_idx = layer_idx
204
+ self.reorder_and_upcast_attn = config.reorder_and_upcast_attn
205
+
206
+ if self.is_cross_attention:
207
+ self.c_attn = Conv1D(2 * self.embed_dim, self.embed_dim)
208
+ self.q_attn = Conv1D(self.embed_dim, self.embed_dim)
209
+ else:
210
+ self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim)
211
+ self.c_proj = Conv1D(self.embed_dim, self.embed_dim)
212
+
213
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
214
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
215
+
216
+ self.pruned_heads = set()
217
+
218
+ self.attn_scale_power = 1.0 if config.mup_scale_qk_dot_by_d else 0.5
219
+
220
+ def prune_heads(self, heads):
221
+ if len(heads) == 0:
222
+ return
223
+ heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, self.head_dim, self.pruned_heads)
224
+ index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
225
+
226
+ # Prune conv1d layers
227
+ self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
228
+ self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
229
+
230
+ # Update hyper params
231
+ self.split_size = (self.split_size // self.num_heads) * (self.num_heads - len(heads))
232
+ self.num_heads = self.num_heads - len(heads)
233
+ self.pruned_heads = self.pruned_heads.union(heads)
234
+
235
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None, position_bias=None):
236
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
237
+
238
+ if self.scale_attn_weights:
239
+ attn_weights = attn_weights / torch.full(
240
+ [], value.size(-1) ** self.attn_scale_power, dtype=attn_weights.dtype, device=attn_weights.device
241
+ )
242
+
243
+ # Layer-wise attention scaling
244
+ if self.scale_attn_by_inverse_layer_idx:
245
+ attn_weights = attn_weights / float(self.layer_idx + 1)
246
+
247
+ if not self.is_cross_attention:
248
+ # if only "normal" attention layer implements causal mask
249
+ query_length, key_length = query.size(-2), key.size(-2)
250
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
251
+ mask_value = torch.finfo(attn_weights.dtype).min
252
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
253
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
254
+ mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
255
+ attn_weights = torch.where(causal_mask, attn_weights.to(attn_weights.dtype), mask_value)
256
+
257
+ if attention_mask is not None:
258
+ # Apply the attention mask
259
+ attn_weights = attn_weights + attention_mask
260
+
261
+ if position_bias is not None:
262
+ attn_weights += position_bias.type_as(attn_weights).unsqueeze(0)
263
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
264
+
265
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
266
+ attn_weights = attn_weights.type(value.dtype)
267
+ attn_weights = self.attn_dropout(attn_weights)
268
+
269
+ # Mask heads if we want to
270
+ if head_mask is not None:
271
+ attn_weights = attn_weights * head_mask
272
+
273
+ attn_output = torch.matmul(attn_weights, value)
274
+
275
+ return attn_output, attn_weights
276
+
277
+ def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None, head_mask=None, position_bias=None):
278
+ # Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM)
279
+ bsz, num_heads, q_seq_len, dk = query.size()
280
+ _, _, k_seq_len, _ = key.size()
281
+
282
+ # Preallocate attn_weights for `baddbmm`
283
+ attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device)
284
+
285
+ # Compute Scale Factor
286
+ scale_factor = 1.0
287
+ if self.scale_attn_weights:
288
+ scale_factor /= float(value.size(-1)) ** self.attn_scale_power
289
+
290
+ if self.scale_attn_by_inverse_layer_idx:
291
+ scale_factor /= float(self.layer_idx + 1)
292
+
293
+ # Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk))
294
+ with autocast(enabled=False):
295
+ q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
296
+ attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor)
297
+ attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
298
+
299
+ if not self.is_cross_attention:
300
+ # if only "normal" attention layer implements causal mask
301
+ query_length, key_length = query.size(-2), key.size(-2)
302
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
303
+ mask_value = torch.finfo(attn_weights.dtype).min
304
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
305
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
306
+ mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
307
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
308
+
309
+ if attention_mask is not None:
310
+ # Apply the attention mask
311
+ attn_weights = attn_weights + attention_mask
312
+
313
+ if position_bias is not None:
314
+ attn_weights += position_bias.type_as(attn_weights).unsqueeze(0)
315
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
316
+
317
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise
318
+ if attn_weights.dtype != torch.float32:
319
+ raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32")
320
+ attn_weights = attn_weights.type(value.dtype)
321
+ attn_weights = self.attn_dropout(attn_weights)
322
+
323
+ # Mask heads if we want to
324
+ if head_mask is not None:
325
+ attn_weights = attn_weights * head_mask
326
+
327
+ attn_output = torch.matmul(attn_weights, value)
328
+
329
+ return attn_output, attn_weights
330
+
331
+ def _split_heads(self, tensor, num_heads, attn_head_size):
332
+ """
333
+ Splits hidden_size dim into attn_head_size and num_heads
334
+ """
335
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
336
+ tensor = tensor.view(new_shape)
337
+ return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
338
+
339
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
340
+ """
341
+ Merges attn_head_size dim and num_attn_heads dim into hidden_size
342
+ """
343
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
344
+ new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
345
+ return tensor.view(new_shape)
346
+
347
+ def forward(
348
+ self,
349
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
350
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
351
+ attention_mask: Optional[torch.FloatTensor] = None,
352
+ head_mask: Optional[torch.FloatTensor] = None,
353
+ encoder_hidden_states: Optional[torch.Tensor] = None,
354
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
355
+ use_cache: Optional[bool] = False,
356
+ output_attentions: Optional[bool] = False,
357
+ position_bias: Optional[torch.FloatTensor] = None,
358
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
359
+ if encoder_hidden_states is not None:
360
+ if not hasattr(self, "q_attn"):
361
+ raise ValueError(
362
+ "If class is used as cross attention, the weights `q_attn` have to be defined. "
363
+ "Please make sure to instantiate class with `JAISAttention(..., is_cross_attention=True)`."
364
+ )
365
+
366
+ query = self.q_attn(hidden_states)
367
+ key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
368
+ attention_mask = encoder_attention_mask
369
+ else:
370
+ query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
371
+
372
+ query = self._split_heads(query, self.num_heads, self.head_dim)
373
+ key = self._split_heads(key, self.num_heads, self.head_dim)
374
+ value = self._split_heads(value, self.num_heads, self.head_dim)
375
+
376
+ if layer_past is not None:
377
+ past_key, past_value = layer_past
378
+ key = torch.cat((past_key, key), dim=-2)
379
+ value = torch.cat((past_value, value), dim=-2)
380
+
381
+ if use_cache is True:
382
+ present = (key, value)
383
+ else:
384
+ present = None
385
+
386
+ if self.reorder_and_upcast_attn:
387
+ attn_output, attn_weights = self._upcast_and_reordered_attn(
388
+ query, key, value, attention_mask, head_mask, position_bias
389
+ )
390
+ else:
391
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask, position_bias)
392
+
393
+ attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
394
+ attn_output = self.c_proj(attn_output)
395
+ attn_output = self.resid_dropout(attn_output)
396
+
397
+ outputs = (attn_output, present)
398
+ if output_attentions:
399
+ outputs += (attn_weights,)
400
+
401
+ return outputs # a, present, (attentions)
402
+
403
+
404
+ class JAISMLP(nn.Module):
405
+ def __init__(self, intermediate_size, config):
406
+ super().__init__()
407
+ embed_dim = config.hidden_size
408
+ self.swiglu = config.activation_function == "swiglu"
409
+ self.c_fc = Conv1D(intermediate_size, embed_dim)
410
+ self.c_fc2 = Conv1D(intermediate_size, embed_dim) if self.swiglu else None
411
+ self.c_proj = Conv1D(embed_dim, intermediate_size)
412
+ self.act = SwiGLUActivation() if self.swiglu else ACT2FN[config.activation_function]
413
+ self.dropout = nn.Dropout(config.resid_pdrop)
414
+
415
+ def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor:
416
+ if self.swiglu:
417
+ hidden_states2 = self.c_fc2(hidden_states)
418
+ hidden_states = self.c_fc(hidden_states)
419
+ hidden_states = self.act(hidden_states, hidden_states2) if self.swiglu else self.act(hidden_states)
420
+ hidden_states = self.c_proj(hidden_states)
421
+ hidden_states = self.dropout(hidden_states)
422
+ return hidden_states
423
+
424
+
425
+ class JAISBlock(nn.Module):
426
+ def __init__(self, config, layer_idx=None):
427
+ super().__init__()
428
+ hidden_size = config.hidden_size
429
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
430
+
431
+ self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
432
+ self.attn = JAISAttention(config, layer_idx=layer_idx)
433
+ self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
434
+
435
+ if config.add_cross_attention:
436
+ self.crossattention = JAISAttention(config, is_cross_attention=True, layer_idx=layer_idx)
437
+ self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
438
+
439
+ self.mlp = JAISMLP(inner_dim, config)
440
+
441
+ def forward(
442
+ self,
443
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
444
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
445
+ attention_mask: Optional[torch.FloatTensor] = None,
446
+ head_mask: Optional[torch.FloatTensor] = None,
447
+ encoder_hidden_states: Optional[torch.Tensor] = None,
448
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
449
+ use_cache: Optional[bool] = False,
450
+ output_attentions: Optional[bool] = False,
451
+ position_bias: Optional[torch.FloatTensor] = None,
452
+ ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
453
+ residual = hidden_states
454
+ hidden_states = self.ln_1(hidden_states)
455
+ attn_outputs = self.attn(
456
+ hidden_states,
457
+ layer_past=layer_past,
458
+ attention_mask=attention_mask,
459
+ head_mask=head_mask,
460
+ use_cache=use_cache,
461
+ output_attentions=output_attentions,
462
+ position_bias=position_bias,
463
+ )
464
+ attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
465
+ outputs = attn_outputs[1:]
466
+ # residual connection
467
+ hidden_states = attn_output + residual
468
+
469
+ if encoder_hidden_states is not None:
470
+ # add one self-attention block for cross-attention
471
+ if not hasattr(self, "crossattention"):
472
+ raise ValueError(
473
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
474
+ "cross-attention layers by setting `config.add_cross_attention=True`"
475
+ )
476
+ residual = hidden_states
477
+ hidden_states = self.ln_cross_attn(hidden_states)
478
+ cross_attn_outputs = self.crossattention(
479
+ hidden_states,
480
+ attention_mask=attention_mask,
481
+ head_mask=head_mask,
482
+ encoder_hidden_states=encoder_hidden_states,
483
+ encoder_attention_mask=encoder_attention_mask,
484
+ output_attentions=output_attentions,
485
+ position_bias=position_bias,
486
+ )
487
+ attn_output = cross_attn_outputs[0]
488
+ # residual connection
489
+ hidden_states = residual + attn_output
490
+ outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
491
+
492
+ residual = hidden_states
493
+ hidden_states = self.ln_2(hidden_states)
494
+ feed_forward_hidden_states = self.mlp(hidden_states)
495
+ # residual connection
496
+ hidden_states = residual + feed_forward_hidden_states
497
+
498
+ if use_cache:
499
+ outputs = (hidden_states,) + outputs
500
+ else:
501
+ outputs = (hidden_states,) + outputs[1:]
502
+
503
+ return outputs # hidden_states, present, (attentions, cross_attentions)
504
+
505
+
506
+ class JAISPreTrainedModel(PreTrainedModel):
507
+ """
508
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
509
+ models.
510
+ """
511
+
512
+ config_class = JAISConfig
513
+ load_tf_weights = load_tf_weights_in_jais
514
+ base_model_prefix = "transformer"
515
+ is_parallelizable = True
516
+ supports_gradient_checkpointing = True
517
+ _no_split_modules = ["JAISBlock"]
518
+ _skip_keys_device_placement = "past_key_values"
519
+
520
+ def __init__(self, *inputs, **kwargs):
521
+ super().__init__(*inputs, **kwargs)
522
+
523
+ def _init_weights(self, module):
524
+ """Initialize the weights."""
525
+ mup_init_scale = math.sqrt(self.config.mup_width_scale)
526
+ if isinstance(module, (nn.Linear, Conv1D)):
527
+ # Slightly different from the TF version which uses truncated_normal for initialization
528
+ # cf https://github.com/pytorch/pytorch/pull/5617
529
+ module.weight.data.normal_(mean=0.0, std=(self.config.initializer_range * mup_init_scale))
530
+ if module.bias is not None:
531
+ module.bias.data.zero_()
532
+ elif isinstance(module, nn.Embedding):
533
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
534
+ if module.padding_idx is not None:
535
+ module.weight.data[module.padding_idx].zero_()
536
+ elif isinstance(module, nn.LayerNorm):
537
+ module.bias.data.zero_()
538
+ module.weight.data.fill_(1.0)
539
+
540
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
541
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
542
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
543
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
544
+ #
545
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
546
+ for name, p in module.named_parameters():
547
+ if name == "c_proj.weight":
548
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
549
+ stddev = self.config.initializer_range * mup_init_scale / math.sqrt(2 * self.config.n_layer)
550
+ p.data.normal_(mean=0.0, std=stddev)
551
+
552
+ def _set_gradient_checkpointing(self, module, value=False):
553
+ if isinstance(module, JAISModel):
554
+ module.gradient_checkpointing = value
555
+
556
+ def get_mup_param_groups(self, lr, weight_decay=0.0, decoupled_wd=True):
557
+ """
558
+ Returns list of dicts defining parameter groups for muP:
559
+ group 0: most model params get scaled learning rate and weight decay.
560
+ group 1: embedding layer gets non-scaled learning rate and weight decay.
561
+ group 2: normalization layers and biases get non-scaled learning rate only.
562
+
563
+ The output can be passed to Adam-base optimizers
564
+ e.g.
565
+ param_groups = model.get_mup_param_groups(lr=1e-3, weight_decay=0.1)
566
+ torch.optim.AdamW(param_groups, betas=(0.9, 0.95), eps=1e-8)
567
+ """
568
+ norm_modules = (
569
+ torch.nn.LayerNorm,
570
+ torch.nn.BatchNorm1d,
571
+ torch.nn.BatchNorm2d,
572
+ torch.nn.BatchNorm3d,
573
+ torch.nn.InstanceNorm1d,
574
+ torch.nn.InstanceNorm2d,
575
+ torch.nn.InstanceNorm3d,
576
+ torch.nn.GroupNorm,
577
+ torch.nn.SyncBatchNorm,
578
+ torch.nn.LocalResponseNorm,
579
+ )
580
+
581
+ def get_group_index(param_name):
582
+ for name, module in self.named_modules():
583
+ if name in param_name:
584
+ if isinstance(module, norm_modules):
585
+ return 2
586
+ elif isinstance(module, torch.nn.Embedding):
587
+ return 1
588
+ return 0
589
+
590
+ width_scale = self.config.mup_width_scale
591
+ new_param_groups = []
592
+ new_param_groups.append({"params": [], "lr": lr * width_scale, "weight_decay": weight_decay})
593
+ if not decoupled_wd:
594
+ new_param_groups[0]["weight_decay"] /= width_scale
595
+ new_param_groups.append({"params": [], "lr": lr, "weight_decay": weight_decay})
596
+ new_param_groups.append({"params": [], "lr": lr, "weight_decay": 0.0})
597
+
598
+ for name, param in self.named_parameters():
599
+ if not param.requires_grad:
600
+ continue
601
+
602
+ if name.endswith("bias"):
603
+ new_param_groups[2]["params"].append(param)
604
+ else:
605
+ new_param_groups[get_group_index(name)]["params"].append(param)
606
+
607
+ for idx, param_group in enumerate(new_param_groups):
608
+ if len(param_group["params"]) == 0:
609
+ del new_param_groups[idx]
610
+
611
+ return new_param_groups
612
+
613
+
614
+ JAIS_START_DOCSTRING = r"""
615
+
616
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
617
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
618
+ etc.)
619
+
620
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
621
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
622
+ and behavior.
623
+
624
+ Parameters:
625
+ config ([`JAISConfig`]): Model configuration class with all the parameters of the model.
626
+ Initializing with a config file does not load the weights associated with the model, only the
627
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
628
+ """
629
+
630
+ JAIS_INPUTS_DOCSTRING = r"""
631
+ Args:
632
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
633
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
634
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
635
+ sequence tokens in the vocabulary.
636
+
637
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
638
+ `input_ids`.
639
+
640
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
641
+ [`PreTrainedTokenizer.__call__`] for details.
642
+
643
+ [What are input IDs?](../glossary#input-ids)
644
+ past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
645
+ Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
646
+ `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
647
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
648
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
649
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
650
+
651
+ - 1 for tokens that are **not masked**,
652
+ - 0 for tokens that are **masked**.
653
+
654
+ If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
655
+ `past_key_values`. In other words, the `attention_mask` always has to have the length:
656
+ `len(past_key_values) + len(input_ids)`
657
+
658
+ [What are attention masks?](../glossary#attention-mask)
659
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
660
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
661
+ 1]`:
662
+
663
+ - 0 corresponds to a *sentence A* token,
664
+ - 1 corresponds to a *sentence B* token.
665
+
666
+ [What are token type IDs?](../glossary#token-type-ids)
667
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
668
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
669
+ config.max_position_embeddings - 1]`.
670
+
671
+ [What are position IDs?](../glossary#position-ids)
672
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
673
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
674
+
675
+ - 1 indicates the head is **not masked**,
676
+ - 0 indicates the head is **masked**.
677
+
678
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
679
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
680
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
681
+ model's internal embedding lookup matrix.
682
+
683
+ If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
684
+ `past_key_values`).
685
+ use_cache (`bool`, *optional*):
686
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
687
+ `past_key_values`).
688
+ output_attentions (`bool`, *optional*):
689
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
690
+ tensors for more detail.
691
+ output_hidden_states (`bool`, *optional*):
692
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
693
+ more detail.
694
+ return_dict (`bool`, *optional*):
695
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
696
+ """
697
+ PARALLELIZE_DOCSTRING = r"""
698
+ This is an experimental feature and is a subject to change at a moment's notice.
699
+
700
+ Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
701
+ it will evenly distribute blocks across all devices.
702
+
703
+ Args:
704
+ device_map (`Dict[int, list]`, optional, defaults to None):
705
+ A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
706
+ automatically mapped to the first device (for esoteric reasons). That means that the first device should
707
+ have fewer attention modules mapped to it than other devices. For reference, the gpt2 models have the
708
+ following number of attention modules:
709
+
710
+ - gpt2: 12
711
+ - gpt2-medium: 24
712
+ - gpt2-large: 36
713
+ - gpt2-xl: 48
714
+
715
+ Example:
716
+
717
+ ```python
718
+ # Here is an example of a device map on a machine with 4 GPUs using gpt2-xl, which has a total of 48 attention modules:
719
+ model = GPT2LMHeadModel.from_pretrained("gpt2-xl")
720
+ device_map = {
721
+ 0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
722
+ 1: [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
723
+ 2: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34],
724
+ 3: [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],
725
+ }
726
+ model.parallelize(device_map)
727
+ ```
728
+ """
729
+ DEPARALLELIZE_DOCSTRING = r"""
730
+ Moves the model to cpu from a model parallel state.
731
+
732
+ Example:
733
+
734
+ ```python
735
+ # On a 4 GPU machine with gpt2-large:
736
+ model = GPT2LMHeadModel.from_pretrained("gpt2-large")
737
+ device_map = {
738
+ 0: [0, 1, 2, 3, 4, 5, 6, 7],
739
+ 1: [8, 9, 10, 11, 12, 13, 14, 15],
740
+ 2: [16, 17, 18, 19, 20, 21, 22, 23],
741
+ 3: [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],
742
+ }
743
+ model.parallelize(device_map) # Splits the model across several devices
744
+ model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
745
+ ```
746
+ """
747
+
748
+
749
+ @add_start_docstrings(
750
+ "The bare JAIS Model transformer outputting raw hidden-states without any specific head on top.",
751
+ JAIS_START_DOCSTRING,
752
+ )
753
+ class JAISModel(JAISPreTrainedModel):
754
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
755
+ _keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias"]
756
+
757
+ def __init__(self, config):
758
+ super().__init__(config)
759
+
760
+ self.embed_dim = config.hidden_size
761
+
762
+ self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
763
+ self.wpe = (
764
+ nn.Embedding(config.max_position_embeddings, self.embed_dim)
765
+ if config.position_embedding_type != "alibi"
766
+ else None
767
+ )
768
+ self.embeddings_scale = config.mup_embeddings_scale
769
+
770
+ self.drop = nn.Dropout(config.embd_pdrop)
771
+ self.h = nn.ModuleList([JAISBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
772
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
773
+
774
+ self.relative_pe = (
775
+ AlibiPositionEmbeddingLayer(config.num_attention_heads, config.alibi_scaling)
776
+ if config.position_embedding_type == "alibi"
777
+ else None
778
+ )
779
+
780
+ # Model parallel
781
+ self.model_parallel = False
782
+ self.device_map = None
783
+ self.gradient_checkpointing = False
784
+
785
+ # Initialize weights and apply final processing
786
+ self.post_init()
787
+
788
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
789
+ def parallelize(self, device_map=None):
790
+ # Check validity of device_map
791
+ warnings.warn(
792
+ "`JAISModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load your"
793
+ " model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
794
+ " `device_map` but it needs to be a dictionary module_name to device, so for instance {'h.0': 0, 'h.1': 1,"
795
+ " ...}",
796
+ FutureWarning,
797
+ )
798
+ self.device_map = (
799
+ get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map
800
+ )
801
+ assert_device_map(self.device_map, len(self.h))
802
+ self.model_parallel = True
803
+ self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys()))
804
+ self.last_device = "cuda:" + str(max(self.device_map.keys()))
805
+ self.wte = self.wte.to(self.first_device)
806
+ if self.wpe is not None:
807
+ self.wpe = self.wpe.to(self.first_device)
808
+ # Load onto devices
809
+ for k, v in self.device_map.items():
810
+ for block in v:
811
+ cuda_device = "cuda:" + str(k)
812
+ self.h[block] = self.h[block].to(cuda_device)
813
+ # ln_f to last
814
+ self.ln_f = self.ln_f.to(self.last_device)
815
+
816
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
817
+ def deparallelize(self):
818
+ warnings.warn(
819
+ "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
820
+ FutureWarning,
821
+ )
822
+ self.model_parallel = False
823
+ self.device_map = None
824
+ self.first_device = "cpu"
825
+ self.last_device = "cpu"
826
+ self.wte = self.wte.to("cpu")
827
+ if self.wpe is not None:
828
+ self.wpe = self.wpe.to("cpu")
829
+ for index in range(len(self.h)):
830
+ self.h[index] = self.h[index].to("cpu")
831
+ self.ln_f = self.ln_f.to("cpu")
832
+ torch.cuda.empty_cache()
833
+
834
+ def get_input_embeddings(self):
835
+ return self.wte
836
+
837
+ def set_input_embeddings(self, new_embeddings):
838
+ self.wte = new_embeddings
839
+
840
+ def _prune_heads(self, heads_to_prune):
841
+ """
842
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
843
+ """
844
+ for layer, heads in heads_to_prune.items():
845
+ self.h[layer].attn.prune_heads(heads)
846
+
847
+ @add_start_docstrings_to_model_forward(JAIS_INPUTS_DOCSTRING)
848
+ @add_code_sample_docstrings(
849
+ checkpoint=_CHECKPOINT_FOR_DOC,
850
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
851
+ config_class=_CONFIG_FOR_DOC,
852
+ )
853
+ def forward(
854
+ self,
855
+ input_ids: Optional[torch.LongTensor] = None,
856
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
857
+ attention_mask: Optional[torch.FloatTensor] = None,
858
+ token_type_ids: Optional[torch.LongTensor] = None,
859
+ position_ids: Optional[torch.LongTensor] = None,
860
+ head_mask: Optional[torch.FloatTensor] = None,
861
+ inputs_embeds: Optional[torch.FloatTensor] = None,
862
+ encoder_hidden_states: Optional[torch.Tensor] = None,
863
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
864
+ use_cache: Optional[bool] = None,
865
+ output_attentions: Optional[bool] = None,
866
+ output_hidden_states: Optional[bool] = None,
867
+ return_dict: Optional[bool] = None,
868
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
869
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
870
+ output_hidden_states = (
871
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
872
+ )
873
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
874
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
875
+
876
+ if input_ids is not None and inputs_embeds is not None:
877
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
878
+ elif input_ids is not None:
879
+ input_shape = input_ids.size()
880
+ input_ids = input_ids.view(-1, input_shape[-1])
881
+ batch_size = input_ids.shape[0]
882
+ elif inputs_embeds is not None:
883
+ input_shape = inputs_embeds.size()[:-1]
884
+ batch_size = inputs_embeds.shape[0]
885
+ else:
886
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
887
+
888
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
889
+
890
+ if token_type_ids is not None:
891
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
892
+ if position_ids is not None:
893
+ position_ids = position_ids.view(-1, input_shape[-1])
894
+
895
+ if past_key_values is None:
896
+ past_length = 0
897
+ past_key_values = tuple([None] * len(self.h))
898
+ else:
899
+ past_length = past_key_values[0][0].size(-2)
900
+ if position_ids is None:
901
+ position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
902
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
903
+
904
+ # JAISAttention mask.
905
+ if attention_mask is not None:
906
+ if batch_size <= 0:
907
+ raise ValueError("batch_size has to be defined and > 0")
908
+ attention_mask = attention_mask.view(batch_size, -1)
909
+ # We create a 3D attention mask from a 2D tensor mask.
910
+ # Sizes are [batch_size, 1, 1, to_seq_length]
911
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
912
+ # this attention mask is more simple than the triangular masking of causal attention
913
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
914
+ attention_mask = attention_mask[:, None, None, :]
915
+
916
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
917
+ # masked positions, this operation will create a tensor which is 0.0 for
918
+ # positions we want to attend and the dtype's smallest value for masked positions.
919
+ # Since we are adding it to the raw scores before the softmax, this is
920
+ # effectively the same as removing these entirely.
921
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
922
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
923
+
924
+ # If a 2D or 3D attention mask is provided for the cross-attention
925
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
926
+ if self.config.add_cross_attention and encoder_hidden_states is not None:
927
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
928
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
929
+ if encoder_attention_mask is None:
930
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
931
+ encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
932
+ else:
933
+ encoder_attention_mask = None
934
+
935
+ # Prepare head mask if needed
936
+ # 1.0 in head_mask indicate we keep the head
937
+ # attention_probs has shape bsz x n_heads x N x N
938
+ # head_mask has shape n_layer x batch x n_heads x N x N
939
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
940
+
941
+ if inputs_embeds is None:
942
+ inputs_embeds = self.wte(input_ids)
943
+ if self.wpe is not None:
944
+ position_embeds = self.wpe(position_ids)
945
+ hidden_states = inputs_embeds + position_embeds
946
+ else:
947
+ hidden_states = inputs_embeds
948
+ hidden_states *= torch.tensor(
949
+ float(self.embeddings_scale), dtype=hidden_states.dtype, device=hidden_states.device
950
+ )
951
+
952
+ if token_type_ids is not None:
953
+ token_type_embeds = self.wte(token_type_ids)
954
+ hidden_states = hidden_states + token_type_embeds
955
+
956
+ hidden_states = self.drop(hidden_states)
957
+
958
+ if self.relative_pe is not None:
959
+ length = input_ids.shape[1]
960
+ cached_kv_length = 0
961
+ cached_kv = past_key_values[0]
962
+ if cached_kv is not None:
963
+ cached_kv_length = cached_kv[0].shape[-2]
964
+ position_bias = self.relative_pe(length, length, cached_kv_length)
965
+ else:
966
+ position_bias = None
967
+
968
+ output_shape = input_shape + (hidden_states.size(-1),)
969
+
970
+ if self.gradient_checkpointing and self.training:
971
+ if use_cache:
972
+ logger.warning_once(
973
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
974
+ )
975
+ use_cache = False
976
+
977
+ presents = () if use_cache else None
978
+ all_self_attentions = () if output_attentions else None
979
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
980
+ all_hidden_states = () if output_hidden_states else None
981
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
982
+ # Model parallel
983
+ if self.model_parallel:
984
+ torch.cuda.set_device(hidden_states.device)
985
+ # Ensure layer_past is on same device as hidden_states (might not be correct)
986
+ if layer_past is not None:
987
+ layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
988
+ # Ensure that attention_mask is always on the same device as hidden_states
989
+ if attention_mask is not None:
990
+ attention_mask = attention_mask.to(hidden_states.device)
991
+ if isinstance(head_mask, torch.Tensor):
992
+ head_mask = head_mask.to(hidden_states.device)
993
+ if output_hidden_states:
994
+ all_hidden_states = all_hidden_states + (hidden_states,)
995
+
996
+ if self.gradient_checkpointing and self.training:
997
+
998
+ def create_custom_forward(module):
999
+ def custom_forward(*inputs):
1000
+ # None for past_key_value
1001
+ return module(*inputs, use_cache, output_attentions)
1002
+
1003
+ return custom_forward
1004
+
1005
+ outputs = torch.utils.checkpoint.checkpoint(
1006
+ create_custom_forward(block),
1007
+ hidden_states,
1008
+ None,
1009
+ attention_mask,
1010
+ head_mask[i],
1011
+ encoder_hidden_states,
1012
+ encoder_attention_mask,
1013
+ )
1014
+ else:
1015
+ outputs = block(
1016
+ hidden_states,
1017
+ layer_past=layer_past,
1018
+ attention_mask=attention_mask,
1019
+ head_mask=head_mask[i],
1020
+ encoder_hidden_states=encoder_hidden_states,
1021
+ encoder_attention_mask=encoder_attention_mask,
1022
+ use_cache=use_cache,
1023
+ output_attentions=output_attentions,
1024
+ position_bias=position_bias,
1025
+ )
1026
+
1027
+ hidden_states = outputs[0]
1028
+ if use_cache is True:
1029
+ presents = presents + (outputs[1],)
1030
+
1031
+ if output_attentions:
1032
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
1033
+ if self.config.add_cross_attention:
1034
+ all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
1035
+
1036
+ # Model Parallel: If it's the last layer for that device, put things on the next device
1037
+ if self.model_parallel:
1038
+ for k, v in self.device_map.items():
1039
+ if i == v[-1] and "cuda:" + str(k) != self.last_device:
1040
+ hidden_states = hidden_states.to("cuda:" + str(k + 1))
1041
+
1042
+ hidden_states = self.ln_f(hidden_states)
1043
+
1044
+ hidden_states = hidden_states.view(output_shape)
1045
+ # Add last hidden state
1046
+ if output_hidden_states:
1047
+ all_hidden_states = all_hidden_states + (hidden_states,)
1048
+
1049
+ if not return_dict:
1050
+ return tuple(
1051
+ v
1052
+ for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions]
1053
+ if v is not None
1054
+ )
1055
+
1056
+ return BaseModelOutputWithPastAndCrossAttentions(
1057
+ last_hidden_state=hidden_states,
1058
+ past_key_values=presents,
1059
+ hidden_states=all_hidden_states,
1060
+ attentions=all_self_attentions,
1061
+ cross_attentions=all_cross_attentions,
1062
+ )
1063
+
1064
+
1065
+ @add_start_docstrings(
1066
+ """
1067
+ The JAIS Model transformer with a language modeling head on top (linear layer with weights tied to the input
1068
+ embeddings).
1069
+ """,
1070
+ JAIS_START_DOCSTRING,
1071
+ )
1072
+ class JAISLMHeadModel(JAISPreTrainedModel):
1073
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
1074
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias"]
1075
+
1076
+ def __init__(self, config):
1077
+ super().__init__(config)
1078
+ self.transformer = JAISModel(config)
1079
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
1080
+ self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
1081
+
1082
+ # Model parallel
1083
+ self.model_parallel = False
1084
+ self.device_map = None
1085
+
1086
+ # Initialize weights and apply final processing
1087
+ self.post_init()
1088
+
1089
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
1090
+ def parallelize(self, device_map=None):
1091
+ warnings.warn(
1092
+ "`JAISLMHeadModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load"
1093
+ " your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
1094
+ " `device_map` but it needs to be a dictionary module_name to device, so for instance {'transformer.h.0':"
1095
+ " 0, 'transformer.h.1': 1, ...}",
1096
+ FutureWarning,
1097
+ )
1098
+ self.device_map = (
1099
+ get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
1100
+ if device_map is None
1101
+ else device_map
1102
+ )
1103
+ assert_device_map(self.device_map, len(self.transformer.h))
1104
+ self.transformer.parallelize(self.device_map)
1105
+ self.lm_head = self.lm_head.to(self.transformer.first_device)
1106
+ self.model_parallel = True
1107
+
1108
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1109
+ def deparallelize(self):
1110
+ warnings.warn(
1111
+ "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
1112
+ FutureWarning,
1113
+ )
1114
+ self.transformer.deparallelize()
1115
+ self.transformer = self.transformer.to("cpu")
1116
+ self.lm_head = self.lm_head.to("cpu")
1117
+ self.model_parallel = False
1118
+ torch.cuda.empty_cache()
1119
+
1120
+ def get_output_embeddings(self):
1121
+ return self.lm_head
1122
+
1123
+ def set_output_embeddings(self, new_embeddings):
1124
+ self.lm_head = new_embeddings
1125
+
1126
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
1127
+ token_type_ids = kwargs.get("token_type_ids", None)
1128
+ # only last token for inputs_ids if past is defined in kwargs
1129
+ if past_key_values:
1130
+ input_ids = input_ids[:, -1].unsqueeze(-1)
1131
+ if token_type_ids is not None:
1132
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
1133
+
1134
+ attention_mask = kwargs.get("attention_mask", None)
1135
+ position_ids = kwargs.get("position_ids", None)
1136
+
1137
+ if attention_mask is not None and position_ids is None:
1138
+ # create position_ids on the fly for batch generation
1139
+ position_ids = attention_mask.long().cumsum(-1) - 1
1140
+ position_ids.masked_fill_(attention_mask == 0, 1)
1141
+ if past_key_values:
1142
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1143
+ else:
1144
+ position_ids = None
1145
+
1146
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1147
+ if inputs_embeds is not None and past_key_values is None:
1148
+ model_inputs = {"inputs_embeds": inputs_embeds}
1149
+ else:
1150
+ model_inputs = {"input_ids": input_ids}
1151
+
1152
+ model_inputs.update(
1153
+ {
1154
+ "past_key_values": past_key_values,
1155
+ "use_cache": kwargs.get("use_cache"),
1156
+ "position_ids": position_ids,
1157
+ "attention_mask": attention_mask,
1158
+ "token_type_ids": token_type_ids,
1159
+ }
1160
+ )
1161
+ return model_inputs
1162
+
1163
+ @add_start_docstrings_to_model_forward(JAIS_INPUTS_DOCSTRING)
1164
+ @add_code_sample_docstrings(
1165
+ checkpoint=_CHECKPOINT_FOR_DOC,
1166
+ output_type=CausalLMOutputWithCrossAttentions,
1167
+ config_class=_CONFIG_FOR_DOC,
1168
+ )
1169
+ def forward(
1170
+ self,
1171
+ input_ids: Optional[torch.LongTensor] = None,
1172
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1173
+ attention_mask: Optional[torch.FloatTensor] = None,
1174
+ token_type_ids: Optional[torch.LongTensor] = None,
1175
+ position_ids: Optional[torch.LongTensor] = None,
1176
+ head_mask: Optional[torch.FloatTensor] = None,
1177
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1178
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1179
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1180
+ labels: Optional[torch.LongTensor] = None,
1181
+ use_cache: Optional[bool] = None,
1182
+ output_attentions: Optional[bool] = None,
1183
+ output_hidden_states: Optional[bool] = None,
1184
+ return_dict: Optional[bool] = None,
1185
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1186
+ r"""
1187
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1188
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1189
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1190
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1191
+ """
1192
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1193
+
1194
+ transformer_outputs = self.transformer(
1195
+ input_ids,
1196
+ past_key_values=past_key_values,
1197
+ attention_mask=attention_mask,
1198
+ token_type_ids=token_type_ids,
1199
+ position_ids=position_ids,
1200
+ head_mask=head_mask,
1201
+ inputs_embeds=inputs_embeds,
1202
+ encoder_hidden_states=encoder_hidden_states,
1203
+ encoder_attention_mask=encoder_attention_mask,
1204
+ use_cache=use_cache,
1205
+ output_attentions=output_attentions,
1206
+ output_hidden_states=output_hidden_states,
1207
+ return_dict=return_dict,
1208
+ )
1209
+ hidden_states = transformer_outputs[0]
1210
+
1211
+ # Set device for model parallelism
1212
+ if self.model_parallel:
1213
+ torch.cuda.set_device(self.transformer.first_device)
1214
+ hidden_states = hidden_states.to(self.lm_head.weight.device)
1215
+
1216
+ lm_logits = self.lm_head(hidden_states)
1217
+ lm_logits *= torch.tensor(float(self.output_logits_scale), dtype=lm_logits.dtype, device=lm_logits.device)
1218
+
1219
+ loss = None
1220
+ if labels is not None:
1221
+ # move labels to correct device to enable model parallelism
1222
+ labels = labels.to(lm_logits.device)
1223
+ # Shift so that tokens < n predict n
1224
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1225
+ shift_labels = labels[..., 1:].contiguous()
1226
+ # Flatten the tokens
1227
+ loss_fct = CrossEntropyLoss()
1228
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1229
+
1230
+ if not return_dict:
1231
+ output = (lm_logits,) + transformer_outputs[1:]
1232
+ return ((loss,) + output) if loss is not None else output
1233
+
1234
+ return CausalLMOutputWithCrossAttentions(
1235
+ loss=loss,
1236
+ logits=lm_logits,
1237
+ past_key_values=transformer_outputs.past_key_values,
1238
+ hidden_states=transformer_outputs.hidden_states,
1239
+ attentions=transformer_outputs.attentions,
1240
+ cross_attentions=transformer_outputs.cross_attentions,
1241
+ )
1242
+
1243
+ @staticmethod
1244
+ def _reorder_cache(
1245
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1246
+ ) -> Tuple[Tuple[torch.Tensor]]:
1247
+ """
1248
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1249
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1250
+ beam_idx at every generation step.
1251
+ """
1252
+ return tuple(
1253
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1254
+ for layer_past in past_key_values
1255
+ )
1256
+
1257
+
1258
+ @add_start_docstrings(
1259
+ """
1260
+ The JAIS Model transformer with a sequence classification head on top (linear layer).
1261
+
1262
+ [`JAISForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1263
+ (e.g. GPT-1) do.
1264
+
1265
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1266
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1267
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1268
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1269
+ each row of the batch).
1270
+ """,
1271
+ JAIS_START_DOCSTRING,
1272
+ )
1273
+ class JAISForSequenceClassification(JAISPreTrainedModel):
1274
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
1275
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"lm_head.weight"]
1276
+
1277
+ def __init__(self, config):
1278
+ super().__init__(config)
1279
+ self.num_labels = config.num_labels
1280
+ self.transformer = JAISModel(config)
1281
+ self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
1282
+ self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
1283
+
1284
+ # Model parallel
1285
+ self.model_parallel = False
1286
+ self.device_map = None
1287
+
1288
+ # Initialize weights and apply final processing
1289
+ self.post_init()
1290
+
1291
+ @add_start_docstrings_to_model_forward(JAIS_INPUTS_DOCSTRING)
1292
+ @add_code_sample_docstrings(
1293
+ checkpoint="microsoft/DialogRPT-updown",
1294
+ output_type=SequenceClassifierOutputWithPast,
1295
+ config_class=_CONFIG_FOR_DOC,
1296
+ )
1297
+ def forward(
1298
+ self,
1299
+ input_ids: Optional[torch.LongTensor] = None,
1300
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1301
+ attention_mask: Optional[torch.FloatTensor] = None,
1302
+ token_type_ids: Optional[torch.LongTensor] = None,
1303
+ position_ids: Optional[torch.LongTensor] = None,
1304
+ head_mask: Optional[torch.FloatTensor] = None,
1305
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1306
+ labels: Optional[torch.LongTensor] = None,
1307
+ use_cache: Optional[bool] = None,
1308
+ output_attentions: Optional[bool] = None,
1309
+ output_hidden_states: Optional[bool] = None,
1310
+ return_dict: Optional[bool] = None,
1311
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1312
+ r"""
1313
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1314
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1315
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1316
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1317
+ """
1318
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1319
+
1320
+ transformer_outputs = self.transformer(
1321
+ input_ids,
1322
+ past_key_values=past_key_values,
1323
+ attention_mask=attention_mask,
1324
+ token_type_ids=token_type_ids,
1325
+ position_ids=position_ids,
1326
+ head_mask=head_mask,
1327
+ inputs_embeds=inputs_embeds,
1328
+ use_cache=use_cache,
1329
+ output_attentions=output_attentions,
1330
+ output_hidden_states=output_hidden_states,
1331
+ return_dict=return_dict,
1332
+ )
1333
+ hidden_states = transformer_outputs[0]
1334
+ logits = self.score(hidden_states)
1335
+ logits *= torch.tensor(float(self.output_logits_scale), dtype=logits.dtype, device=logits.device)
1336
+
1337
+ if input_ids is not None:
1338
+ batch_size, sequence_length = input_ids.shape[:2]
1339
+ else:
1340
+ batch_size, sequence_length = inputs_embeds.shape[:2]
1341
+
1342
+ assert (
1343
+ self.config.pad_token_id is not None or batch_size == 1
1344
+ ), "Cannot handle batch sizes > 1 if no padding token is defined."
1345
+ if self.config.pad_token_id is None:
1346
+ sequence_lengths = -1
1347
+ else:
1348
+ if input_ids is not None:
1349
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
1350
+ else:
1351
+ sequence_lengths = -1
1352
+ logger.warning(
1353
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1354
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1355
+ )
1356
+
1357
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1358
+
1359
+ loss = None
1360
+ if labels is not None:
1361
+ if self.config.problem_type is None:
1362
+ if self.num_labels == 1:
1363
+ self.config.problem_type = "regression"
1364
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1365
+ self.config.problem_type = "single_label_classification"
1366
+ else:
1367
+ self.config.problem_type = "multi_label_classification"
1368
+
1369
+ if self.config.problem_type == "regression":
1370
+ loss_fct = MSELoss()
1371
+ if self.num_labels == 1:
1372
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1373
+ else:
1374
+ loss = loss_fct(pooled_logits, labels)
1375
+ elif self.config.problem_type == "single_label_classification":
1376
+ loss_fct = CrossEntropyLoss()
1377
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1378
+ elif self.config.problem_type == "multi_label_classification":
1379
+ loss_fct = BCEWithLogitsLoss()
1380
+ loss = loss_fct(pooled_logits, labels)
1381
+ if not return_dict:
1382
+ output = (pooled_logits,) + transformer_outputs[1:]
1383
+ return ((loss,) + output) if loss is not None else output
1384
+
1385
+ return SequenceClassifierOutputWithPast(
1386
+ loss=loss,
1387
+ logits=pooled_logits,
1388
+ past_key_values=transformer_outputs.past_key_values,
1389
+ hidden_states=transformer_outputs.hidden_states,
1390
+ attentions=transformer_outputs.attentions,
1391
+ )
1392
+
1393
+
1394
+ @add_start_docstrings(
1395
+ """
1396
+ JAIS Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1397
+ Named-Entity-Recognition (NER) tasks.
1398
+ """,
1399
+ JAIS_START_DOCSTRING,
1400
+ )
1401
+ class JAISForTokenClassification(JAISPreTrainedModel):
1402
+ def __init__(self, config):
1403
+ super().__init__(config)
1404
+ self.num_labels = config.num_labels
1405
+
1406
+ self.transformer = JAISModel(config)
1407
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1408
+ classifier_dropout = config.classifier_dropout
1409
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1410
+ classifier_dropout = config.hidden_dropout
1411
+ else:
1412
+ classifier_dropout = 0.1
1413
+ self.dropout = nn.Dropout(classifier_dropout)
1414
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1415
+ self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
1416
+
1417
+ # Model parallel
1418
+ self.model_parallel = False
1419
+ self.device_map = None
1420
+
1421
+ # Initialize weights and apply final processing
1422
+ self.post_init()
1423
+
1424
+ @add_start_docstrings_to_model_forward(JAIS_INPUTS_DOCSTRING)
1425
+ # fmt: off
1426
+ @add_code_sample_docstrings(
1427
+ checkpoint="brad1141/gpt2-finetuned-comp2",
1428
+ output_type=TokenClassifierOutput,
1429
+ config_class=_CONFIG_FOR_DOC,
1430
+ expected_loss=0.25,
1431
+ expected_output=["Lead", "Lead", "Lead", "Position", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead"],
1432
+ )
1433
+ # fmt: on
1434
+ def forward(
1435
+ self,
1436
+ input_ids: Optional[torch.LongTensor] = None,
1437
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1438
+ attention_mask: Optional[torch.FloatTensor] = None,
1439
+ token_type_ids: Optional[torch.LongTensor] = None,
1440
+ position_ids: Optional[torch.LongTensor] = None,
1441
+ head_mask: Optional[torch.FloatTensor] = None,
1442
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1443
+ labels: Optional[torch.LongTensor] = None,
1444
+ use_cache: Optional[bool] = None,
1445
+ output_attentions: Optional[bool] = None,
1446
+ output_hidden_states: Optional[bool] = None,
1447
+ return_dict: Optional[bool] = None,
1448
+ ) -> Union[Tuple, TokenClassifierOutput]:
1449
+ r"""
1450
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1451
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1452
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1453
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1454
+ """
1455
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1456
+
1457
+ transformer_outputs = self.transformer(
1458
+ input_ids,
1459
+ past_key_values=past_key_values,
1460
+ attention_mask=attention_mask,
1461
+ token_type_ids=token_type_ids,
1462
+ position_ids=position_ids,
1463
+ head_mask=head_mask,
1464
+ inputs_embeds=inputs_embeds,
1465
+ use_cache=use_cache,
1466
+ output_attentions=output_attentions,
1467
+ output_hidden_states=output_hidden_states,
1468
+ return_dict=return_dict,
1469
+ )
1470
+
1471
+ hidden_states = transformer_outputs[0]
1472
+ hidden_states = self.dropout(hidden_states)
1473
+ logits = self.classifier(hidden_states)
1474
+ logits *= torch.tensor(float(self.output_logits_scale), dtype=logits.dtype, device=logits.device)
1475
+
1476
+ loss = None
1477
+ if labels is not None:
1478
+ labels = labels.to(logits.device)
1479
+ loss_fct = CrossEntropyLoss()
1480
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1481
+
1482
+ if not return_dict:
1483
+ output = (logits,) + transformer_outputs[2:]
1484
+ return ((loss,) + output) if loss is not None else output
1485
+
1486
+ return TokenClassifierOutput(
1487
+ loss=loss,
1488
+ logits=logits,
1489
+ hidden_states=transformer_outputs.hidden_states,
1490
+ attentions=transformer_outputs.attentions,
1491
+ )
1492
+
1493
+
1494
+ @add_start_docstrings(
1495
+ """
1496
+ The JAIS Model transformer with a span classification head on top for extractive question-answering tasks like
1497
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1498
+ """,
1499
+ JAIS_START_DOCSTRING,
1500
+ )
1501
+ class JAISForQuestionAnswering(JAISPreTrainedModel):
1502
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
1503
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias", r"lm_head.weight"]
1504
+
1505
+ def __init__(self, config):
1506
+ super().__init__(config)
1507
+ self.num_labels = config.num_labels
1508
+ self.transformer = JAISModel(config)
1509
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1510
+ self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
1511
+
1512
+ # Model parallel
1513
+ self.model_parallel = False
1514
+ self.device_map = None
1515
+ self.gradient_checkpointing = False
1516
+
1517
+ # Initialize weights and apply final processing
1518
+ self.post_init()
1519
+
1520
+ @add_start_docstrings_to_model_forward(JAIS_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1521
+ @add_code_sample_docstrings(
1522
+ checkpoint=_CHECKPOINT_FOR_DOC,
1523
+ output_type=QuestionAnsweringModelOutput,
1524
+ config_class=_CONFIG_FOR_DOC,
1525
+ real_checkpoint=_CHECKPOINT_FOR_DOC,
1526
+ )
1527
+ def forward(
1528
+ self,
1529
+ input_ids: Optional[torch.LongTensor] = None,
1530
+ attention_mask: Optional[torch.FloatTensor] = None,
1531
+ token_type_ids: Optional[torch.LongTensor] = None,
1532
+ position_ids: Optional[torch.LongTensor] = None,
1533
+ head_mask: Optional[torch.FloatTensor] = None,
1534
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1535
+ start_positions: Optional[torch.LongTensor] = None,
1536
+ end_positions: Optional[torch.LongTensor] = None,
1537
+ output_attentions: Optional[bool] = None,
1538
+ output_hidden_states: Optional[bool] = None,
1539
+ return_dict: Optional[bool] = None,
1540
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1541
+ r"""
1542
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1543
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1544
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1545
+ are not taken into account for computing the loss.
1546
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1547
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1548
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1549
+ are not taken into account for computing the loss.
1550
+ """
1551
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1552
+
1553
+ outputs = self.transformer(
1554
+ input_ids,
1555
+ attention_mask=attention_mask,
1556
+ token_type_ids=token_type_ids,
1557
+ position_ids=position_ids,
1558
+ head_mask=head_mask,
1559
+ inputs_embeds=inputs_embeds,
1560
+ output_attentions=output_attentions,
1561
+ output_hidden_states=output_hidden_states,
1562
+ return_dict=return_dict,
1563
+ )
1564
+
1565
+ sequence_output = outputs[0]
1566
+
1567
+ logits = self.qa_outputs(sequence_output)
1568
+ logits *= torch.tensor(float(self.output_logits_scale), dtype=logits.dtype, device=logits.device)
1569
+ start_logits, end_logits = logits.split(1, dim=-1)
1570
+ start_logits = start_logits.squeeze(-1).contiguous()
1571
+ end_logits = end_logits.squeeze(-1).contiguous()
1572
+
1573
+ total_loss = None
1574
+ if start_positions is not None and end_positions is not None:
1575
+ # If we are on multi-GPU, split add a dimension
1576
+ if len(start_positions.size()) > 1:
1577
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1578
+ if len(end_positions.size()) > 1:
1579
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1580
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1581
+ ignored_index = start_logits.size(1)
1582
+ start_positions = start_positions.clamp(0, ignored_index)
1583
+ end_positions = end_positions.clamp(0, ignored_index)
1584
+
1585
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1586
+ start_loss = loss_fct(start_logits, start_positions)
1587
+ end_loss = loss_fct(end_logits, end_positions)
1588
+ total_loss = (start_loss + end_loss) / 2
1589
+
1590
+ if not return_dict:
1591
+ output = (start_logits, end_logits) + outputs[2:]
1592
+ return ((total_loss,) + output) if total_loss is not None else output
1593
+
1594
+ return QuestionAnsweringModelOutput(
1595
+ loss=total_loss,
1596
+ start_logits=start_logits,
1597
+ end_logits=end_logits,
1598
+ hidden_states=outputs.hidden_states,
1599
+ attentions=outputs.attentions,
1600
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|endoftext|>",
3
+ "eos_token": "<|endoftext|>",
4
+ "pad_token": "<|endoftext|>",
5
+ "unk_token": "<|endoftext|>"
6
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|endoftext|>",
3
+ "clean_up_tokenization_spaces": true,
4
+ "eos_token": "<|endoftext|>",
5
+ "model_max_length": 2048,
6
+ "pad_token": "<|endoftext|>",
7
+ "tokenizer_class": "PreTrainedTokenizerFast",
8
+ "unk_token": "<|endoftext|>"
9
+ }