samta-kamboj commited on
Commit
718233e
1 Parent(s): d8b75f6

initial upload

Browse files
README.md ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - ar
4
+ - en
5
+ thumbnail: null
6
+ tags:
7
+ - Arabic
8
+ - English
9
+ - LLM
10
+ - Decoder
11
+ - causal-lm
12
+ license: apache-2.0
13
+ pipeline_tag: conversational
14
+ ---
15
+
16
+ # Jais-13b-chat
17
+
18
+ <!-- Provide a quick summary of what the model is/does. -->
19
+
20
+ This is a 13 billion parameter fine-tuned bilingual large language model for both Arabic and English.
21
+ It is based on transformer-based decoder-only (GPT-3) architecture and uses SwiGLU
22
+ non-linearity. It implements ALiBi position embeddings, enabling the model to extrapolate
23
+ to long sequence lengths, providing improved context handling and model precision.
24
+
25
+ Jais-13b-chat is [Jais-13b](https://huggingface.co/inception-mbzuai/jais-13b) fine-tuned over a curated set of 4 million Arabic and 6 million English prompt-response pairs.
26
+ We further fine-tune our model with safety-oriented instruction, as well as providing extra guardrails in the
27
+ form of a safety prompt. Our pre-trained model, [Jais-13b](https://huggingface.co/inception-mbzuai/jais-13b), is trained on
28
+ 116 billion Arabic tokens and 279 billion English tokens.
29
+
30
+ The combination of the largest curated Arabic and English instruction tuning dataset along with the addition of multi-turn conversations allows the model to converse in a variety of topics, with a particular focus on the Arab world.
31
+
32
+
33
+ ## Getting started
34
+
35
+ Below is sample code to use the model. Note that the model requires a custom model class, so users must
36
+ enable `trust_remote_code=True` while loading the model. In order to get the same performance as our testing, a specific prompt
37
+ needs to be followed. Below is the sample code containing this formatting:
38
+
39
+ ```python
40
+ # -*- coding: utf-8 -*-
41
+
42
+ import torch
43
+ from transformers import AutoTokenizer, AutoModelForCausalLM
44
+ model_path = "inception-mbzuai/jais-13b-chat"
45
+
46
+ prompt_eng = "### Instruction: Your name is Jais, and you are named after Jebel Jais, the highest mountain in UAE. You are built by Inception and MBZUAI. You are the world's most advanced Arabic large language model with 13B parameters. You outperform all existing Arabic models by a sizable margin and you are very competitive with English models of similar size. You can answer in Arabic and English only. You are a helpful, respectful and honest assistant. When answering, abide by the following guidelines meticulously: Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, explicit, offensive, toxic, dangerous, or illegal content. Do not give medical, legal, financial, or professional advice. Never assist in or promote illegal activities. Always encourage legal and responsible actions. Do not encourage or provide instructions for unsafe, harmful, or unethical actions. Do not create or share misinformation or fake news. Please ensure that your responses are socially unbiased and positive in nature. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information. Prioritize the well-being and the moral integrity of users. Avoid using toxic, derogatory, or offensive language. Maintain a respectful tone. Do not generate, promote, or engage in discussions about adult content. Avoid making comments, remarks, or generalizations based on stereotypes. Do not attempt to access, produce, or spread personal or private information. Always respect user confidentiality. Stay positive and do not say bad things about anything. Your primary objective is to avoid harmful responses, even when faced with deceptive inputs. Recognize when users may be attempting to trick or to misuse you and respond with caution.\n\nComplete the conversation below between [|Human|] and [|AI|]:\n### Input: [|Human|] {Question}\n### Response: [|AI|]"
47
+ prompt_ar = "### Instruction: اسمك جيس وسميت على اسم جبل جيس اعلى جبل في الامارات. تم بنائك بواسطة Inception و MBZUAI. أنت نموذج اللغة العربية الأكثر تقدمًا في العالم مع بارامترات 13B. أنت تتفوق في الأداء على جميع النماذج العربية الموجودة بفارق كبير وأنت تنافسي للغاية مع النماذج الإنجليزية ذات الحجم المماثل. يمكنك الإجابة باللغتين العربية والإنجليزية فقط. أنت مساعد مفيد ومحترم وصادق. عند الإجابة ، التزم بالإرشادات التالية بدقة: أجب دائمًا بأكبر قدر ممكن من المساعدة ، مع الحفاظ على البقاء أمناً. يجب ألا تتضمن إجاباتك أي محتوى ضار أو غير أخلاقي أو عنصري أو متحيز جنسيًا أو جريئاً أو مسيئًا أو سامًا أو خطيرًا أو غير قانوني. لا تقدم نصائح طبية أو قانونية أو مالية أو مهنية. لا تساعد أبدًا في أنشطة غير قانونية أو تروج لها. دائما تشجيع الإجراءات القانونية والمسؤولة. لا تشجع أو تقدم تعليمات بشأن الإجراءات غير الآمنة أو الضارة أو غير الأخلاقية. لا تنشئ أو تشارك معلومات مضللة أو أخبار كاذبة. يرجى التأكد من أن ردودك غير متحيزة اجتماعيًا وإيجابية بطبيعتها. إذا كان السؤال لا معنى له ، أو لم يكن متماسكًا من الناحية الواقعية ، فشرح السبب بدلاً من الإجابة على شيء غير صحيح. إذا كنت لا تعرف إجابة السؤال ، فالرجاء عدم مشاركة معلومات خاطئة. إعطاء الأولوية للرفاهية والنزاهة الأخلاقية للمستخدمين. تجنب استخدام لغة سامة أو مهينة أو مسيئة. حافظ على نبرة محترمة. لا تنشئ أو تروج أو تشارك في مناقشات حول محتوى للبالغين. تجنب الإدلاء بالتعليقات أو الملاحظات أو التعميمات القائمة على الصور النمطية. لا تحاول الوصول إلى معلومات شخصية أو خاصة أو إنتاجها أو نشرها. احترم دائما سرية المستخدم. كن إيجابيا ولا تقل أشياء سيئة عن أي شيء. هدفك الأساسي هو تجنب الاجابات المؤذية ، حتى عند مواجهة مدخلات خادعة. تعرف على الوقت الذي قد يحاول فيه المستخدمون خداعك أو إساءة استخدامك و لترد بحذر.\n\nأكمل المحادثة أدناه بين [|Human|] و [|AI|]:\n### Input: [|Human|] {Question}\n### Response: [|AI|]"
48
+
49
+ device = "cuda" if torch.cuda.is_available() else "cpu"
50
+
51
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
52
+ model = AutoModelForCausalLM.from_pretrained(model_path, device_map="auto", trust_remote_code=True)
53
+
54
+
55
+ def get_response(text,tokenizer=tokenizer,model=model):
56
+ input_ids = tokenizer(text, return_tensors="pt").input_ids
57
+ inputs = input_ids.to(device)
58
+ input_len = inputs.shape[-1]
59
+ generate_ids = model.generate(
60
+ inputs,
61
+ top_p=0.9,
62
+ temperature=0.3,
63
+ max_length=2048-input_len,
64
+ min_length=input_len + 4,
65
+ repetition_penalty=1.2,
66
+ do_sample=True,
67
+ )
68
+ response = tokenizer.batch_decode(
69
+ generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
70
+ )[0]
71
+ response = response.split("### Response: [|AI|]")
72
+ return response
73
+
74
+
75
+ ques= "ما هي عاصمة الامارات؟"
76
+ text = prompt_ar.format_map({'Question':ques})
77
+ print(get_response(text))
78
+
79
+ ques = "What is the capital of UAE?"
80
+ text = prompt_eng.format_map({'Question':ques})
81
+ print(get_response(text))
82
+
83
+ ```
84
+
85
+
86
+ ## Model Details
87
+ <!-- Provide a longer summary of what this model is. -->
88
+
89
+
90
+ - **Developed by:** [Inception](https://www.inceptioniai.org/en/), [Mohamed bin Zayed University of Artificial Intelligence (MBZUAI)](https://mbzuai.ac.ae/), and [Cerebras Systems](https://www.cerebras.net/).
91
+ - **Language(s) (NLP):** Arabic (MSA) and English
92
+ - **License:** Apache 2.0
93
+ - **Finetuned from model :** [inception-mbzuai/jais-13b](https://huggingface.co/inception-mbzuai/jais-13b)
94
+ - **Input:** Text only data.
95
+ - **Output:** Model generates text.
96
+ - **Paper :** [Jais and Jais-chat: Arabic-Centric Foundation and Instruction-Tuned Open Generative Large Language Models](https://inceptioniai.org)
97
+ - **Demo :** [Access here](https://arabic-gpt.ai)
98
+
99
+
100
+ ## Intended Use
101
+
102
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
103
+
104
+ We release the jais-13b-chat model under a full open source license. We welcome all feedback and opportunities to collaborate.
105
+
106
+ This model is the first release from the Inception - MBZUAI - Cerebras parternship, and at the time of release, achieved state of the art across a comprehensive Arabic test suite as described in the accompanying tech report.
107
+ Some potential downstream uses include:
108
+
109
+ - *Research*: This model can be used by researchers and developers.
110
+ - *Commercial Use*: Jais-13b-chat can be directly used for chat with suitable prompting or further fine-tuned for specific use cases.
111
+ Some potential use cases include:
112
+ - Chat-assistants.
113
+ - Customer service.
114
+
115
+ Audiences that we hope will benefit from our model:
116
+ - *Academics*: For those researching Arabic natural language processing.
117
+ - *Businesses*: Companies targeting Arabic-speaking audiences.
118
+ - *Developers*: Those integrating Arabic language capabilities in apps.
119
+
120
+
121
+
122
+ ### Out-of-Scope Use
123
+
124
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
125
+
126
+ While jais-13b-chat is a powerful Arabic and English bilingual model, it's essential to understand its limitations and the potential of misuse.
127
+ It is prohibited to use the model in any manner that violates applicable laws or regulations.
128
+ The following are some example scenarios where the model should not be used.
129
+
130
+ - *Malicious Use*: The model should not be used for generating harmful, misleading, or inappropriate content. This includes but is not limited to:
131
+ - Generating or promoting hate speech, violence, or discrimination.
132
+ - Spreading misinformation or fake news.
133
+ - Engaging in or promoting illegal activities.
134
+
135
+ - *Sensitive Information*: The model should not be used to handle or generate personal, confidential, or sensitive information.
136
+
137
+ - *Generalization Across All Languages*: Jais-13b is bilingual and optimized for Arabic and English, it should not be assumed to have equal proficiency in other languages or dialects.
138
+
139
+ - *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.
140
+
141
+
142
+
143
+ ## Bias, Risks, and Limitations
144
+
145
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
146
+
147
+ The model is trained on publicly available data which was in part curated by Inception. We have employed different
148
+ techniqes 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.
149
+
150
+ The model is trained as an AI assistant for Arabic and English speakers. The model is limited to produce responses for queries in these two languages
151
+ and may not produce appropriate responses to other language queries.
152
+
153
+ ## Training Details
154
+
155
+ ### Training Data
156
+
157
+ <!-- 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. -->
158
+
159
+ jais-13b-chat model is finetuned with both Arabic and English prompt-response pairs. We included a wide range of
160
+ instructional data across various domains. In total, our instruction-tuning
161
+ dataset has 3.8M and 5.9M prompt-response pairs for Arabic and English, respectively. For English, we used
162
+ publicly available instruction tuning datasets. For Arabic, we internally curated instruction data and augmented it with translated Arabic data.
163
+
164
+
165
+ Further details about the training data can be found in the technical report.
166
+
167
+
168
+ ### Training Procedure
169
+
170
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
171
+
172
+ In instruction tuning, each instance comprises a prompt and its corresponding response.
173
+ Padding is applied to each instance since, unlike pretraining, finetuning is done with unpacked data.
174
+ We utilize the same autoregressive objective as employed in the pretraining of the LLM.
175
+ However, we masked the loss on the prompt i.e. backpropagation is performed only on answer tokens.
176
+
177
+
178
+ The training process was performed on the Condor Galaxy 1 (CG-1) supercomputer platform.
179
+
180
+ #### Training Hyperparameters
181
+
182
+ | Hyperparameter | Value |
183
+ |----------------------------|----------------|
184
+ | Precision | fp32 |
185
+ | Optimizer | AdamW |
186
+ | Learning rate | 0 to 6.7e-04 (<= 400 steps) |
187
+ | | 6.7e-04 to 6.7e-05 (> 8305 steps) |
188
+ | Weight decay | 0.1 |
189
+ | Batch size | 3392 |
190
+ | Steps | 8705 |
191
+
192
+
193
+
194
+
195
+ ## Evaluation
196
+
197
+ <!-- This section describes the evaluation protocols and provides the results. -->
198
+
199
+ We conducted a comprehensive evaluation of Jais-chat and benchmarked it other leading base language models, focusing on both English and Arabic. The evaluation criteria spanned various dimensions, including:
200
+
201
+ - **Knowledge:** How well the model answers factual questions.
202
+ - **Reasoning:** The model's ability to answer questions requiring reasoning.
203
+ - **Misinformation/Bias:** Assessment of the model's susceptibility to generating false or misleading information, and its neutrality.
204
+
205
+ Arabic evaluation results:
206
+
207
+ | Models | Avg |EXAMS | MMLU (M) | LitQA | Hellaswag | PIQA | BoolQA | SituatedQA | ARC-C | OpenBookQA | TruthfulQA | CrowS-Pairs |
208
+ |-------------------|-------|------|----------|-------|-----------|------|--------|------------|-------|------------|------------|-------------|
209
+ | Jais-chat (13B) | **48.4** | 39.7 | 34.0 | 52.6 | 61.4 | 67.5 | 65.7 | 47.0 | 40.7 | 31.6 | 44.8 | 56.4 |
210
+ | BLOOMz (7.1B) | 42.9 | 34.9 | 31.0 | 44.0 | 38.1 | 59.1 | 66.6 | 42.8 | 30.2 | 29.2 | 48.4 | 55.8 |
211
+ | mT0-XXL (13B) | 40.9 | 31.5 | 31.2 | 36.6 | 33.9 | 56.1 | 77.8 | 44.7 | 26.1 | 27.8 | 44.5 | 45.3 |
212
+ | LLaMA2-Chat (13B) | 38.1 | 26.3 | 29.1 | 33.1 | 32.0 | 52.1 | 66.0 | 36.3 | 24.1 | 28.4 | 48.6 | 47.2 |
213
+ | AraBART (550M) | 36.7 | 26.5 | 27.5 | 34.3 | 28.1 | 52.6 | 57.1 | 34.6 | 25.1 | 28.6 | 49.8 | 48.8 |
214
+ | AraT5 (220M) | 32.0 | 24.7 | 23.8 | 26.3 | 25.5 | 50.4 | 58.2 | 33.9 | 24.7 | 25.4 | 20.9 | 47.2 |
215
+
216
+
217
+
218
+ All tasks above report accuracy or F1 scores (the higher the better). For the sake of brevity, we do not include results over English tasks.
219
+ Detailed comparisons in both languages and evaluation dataset details can be found in the technical report.
220
+
221
+
222
+
223
+ ## Generation Example
224
+
225
+
226
+ <p align="center"> <img src="https://huggingface.co/inception-mbzuai/jais-13b/resolve/main/Rent_Example.png" width="600" /></p>
227
+
228
+ <!-- ## Citation [optional] -->
229
+
230
+
231
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
232
+
233
+ <!--**BibTeX:**
234
+
235
+ [More Information Needed]
236
+
237
+ **APA:**
238
+
239
+ [More Information Needed]
240
+
241
+ -->
242
+ Copyright Inception Institute of Artificial Intelligence Ltd.
config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "inception-mbzuai/jais-13b-chat",
3
+ "activation_function": "swiglu",
4
+ "architectures": [
5
+ "JAISLMHeadModel"
6
+ ],
7
+ "attn_pdrop": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_jais.JAISConfig",
10
+ "AutoModel": "modeling_jais.JAISModel",
11
+ "AutoModelForCausalLM": "modeling_jais.JAISLMHeadModel"
12
+ },
13
+ "bos_token_id": 0,
14
+ "embd_pdrop": 0.0,
15
+ "embeddings_scale": 14.6,
16
+ "eos_token_id": 0,
17
+ "initializer_range": 0.02,
18
+ "layer_norm_epsilon": 1e-05,
19
+ "model_type": "jais",
20
+ "n_embd": 5120,
21
+ "n_head": 40,
22
+ "n_inner": 13653,
23
+ "n_layer": 40,
24
+ "n_positions": 2048,
25
+ "pad_token_id": 0,
26
+ "position_embedding_type": "alibi",
27
+ "reorder_and_upcast_attn": false,
28
+ "resid_pdrop": 0.0,
29
+ "scale_attn_by_inverse_layer_idx": false,
30
+ "scale_attn_weights": true,
31
+ "scale_qk_dot_by_d": true,
32
+ "tie_word_embeddings": true,
33
+ "torch_dtype": "float32",
34
+ "transformers_version": "4.28.0.dev0",
35
+ "use_cache": true,
36
+ "vocab_size": 84992,
37
+ "width_scale": 0.11100000000000002
38
+ }
configuration_jais.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
28
+ instantiate a JAIS 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
+ width_scale (`float`, *optional*, defaults to 1.0):
73
+ muP parameter to scale output logits and initializers. Calculated as (`d_model,0 / d_model`),
74
+ where `d_model` is the model's width and `d_model,0` is the proxy model's width.
75
+ embeddings_scale (`float`, *optional*, defaults to 1.0):
76
+ muP parameter to scale token and position embeddings.
77
+ scale_qk_dot_by_d (`bool`, *optional*, defaults to `False`):
78
+ Scale attention weights by dividing by hidden_size instead of sqrt(hidden_size).
79
+ Need to set scale_attn_weights to `True` as well.
80
+
81
+ """
82
+
83
+ model_type = "jais"
84
+ keys_to_ignore_at_inference = ["past_key_values"]
85
+ attribute_map = {
86
+ "hidden_size": "n_embd",
87
+ "max_position_embeddings": "n_positions",
88
+ "num_attention_heads": "n_head",
89
+ "num_hidden_layers": "n_layer",
90
+ }
91
+
92
+ def __init__(
93
+ self,
94
+ vocab_size=50257,
95
+ n_positions=1024,
96
+ n_embd=768,
97
+ n_layer=12,
98
+ n_head=12,
99
+ n_inner=None,
100
+ activation_function="gelu_new",
101
+ resid_pdrop=0.1,
102
+ embd_pdrop=0.1,
103
+ attn_pdrop=0.1,
104
+ layer_norm_epsilon=1e-5,
105
+ initializer_range=0.02,
106
+ scale_attn_weights=True,
107
+ use_cache=True,
108
+ bos_token_id=50256,
109
+ eos_token_id=50256,
110
+ scale_attn_by_inverse_layer_idx=False,
111
+ reorder_and_upcast_attn=False,
112
+ position_embedding_type="learned",
113
+ width_scale=1.0,
114
+ embeddings_scale=1.0,
115
+ scale_qk_dot_by_d=False,
116
+ **kwargs,
117
+ ):
118
+ self.vocab_size = vocab_size
119
+ self.n_positions = n_positions
120
+ self.n_embd = n_embd
121
+ self.n_layer = n_layer
122
+ self.n_head = n_head
123
+ self.n_inner = n_inner
124
+ self.activation_function = activation_function
125
+ self.resid_pdrop = resid_pdrop
126
+ self.embd_pdrop = embd_pdrop
127
+ self.attn_pdrop = attn_pdrop
128
+ self.layer_norm_epsilon = layer_norm_epsilon
129
+ self.initializer_range = initializer_range
130
+ self.scale_attn_weights = scale_attn_weights
131
+ self.use_cache = use_cache
132
+ self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx
133
+ self.reorder_and_upcast_attn = reorder_and_upcast_attn
134
+
135
+ self.bos_token_id = bos_token_id
136
+ self.eos_token_id = eos_token_id
137
+
138
+ self.position_embedding_type = position_embedding_type
139
+ self.width_scale = width_scale
140
+ self.embeddings_scale = embeddings_scale
141
+ self.scale_qk_dot_by_d = scale_qk_dot_by_d
142
+
143
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 0,
5
+ "pad_token_id": 0,
6
+ "transformers_version": "4.28.0.dev0"
7
+ }
modeling_jais.py ADDED
@@ -0,0 +1,1522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 G42 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 = "IIAI/checkpoint"
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):
62
+ super(AlibiPositionEmbeddingLayer, self).__init__()
63
+
64
+ self.num_heads = num_heads
65
+ slopes = torch.tensor(
66
+ AlibiPositionEmbeddingLayer._get_alibi_slopes(num_heads)
67
+ ).unsqueeze(-1)
68
+ self.slopes = nn.parameter.Parameter(slopes, requires_grad=False)
69
+
70
+ def forward(self, seq_length, key_length, cached_qk_len):
71
+ context_position = torch.arange(
72
+ cached_qk_len, cached_qk_len + seq_length, device=self.slopes.device
73
+ )[:, None]
74
+ memory_position = torch.arange(
75
+ key_length + cached_qk_len, device=self.slopes.device
76
+ )[None, :]
77
+ relative_position = memory_position - context_position
78
+ relative_position = torch.abs(relative_position).unsqueeze(0).expand(self.num_heads, -1, -1)
79
+ alibi = (self.slopes * -1.0).unsqueeze(1) * relative_position
80
+ return alibi
81
+
82
+ @staticmethod
83
+ def _get_alibi_slopes(n):
84
+ def get_slopes_power_of_2(n):
85
+ start = 2 ** (-(2 ** -(math.log2(n) - 3)))
86
+ ratio = start
87
+ return [start * ratio ** i for i in range(n)]
88
+
89
+ if math.log2(n).is_integer():
90
+ return get_slopes_power_of_2(
91
+ n
92
+ ) # In the paper, we only train models that have 2^a heads for some a. This function has
93
+ else: # some good properties that only occur when the input is a power of 2. To maintain that even
94
+ closest_power_of_2 = 2 ** math.floor(
95
+ math.log2(n)
96
+ ) # when the number of heads is not a power of 2, we use this workaround.
97
+ return (
98
+ get_slopes_power_of_2(closest_power_of_2)
99
+ + AlibiPositionEmbeddingLayer._get_alibi_slopes(
100
+ 2 * closest_power_of_2
101
+ )[0::2][: n - closest_power_of_2]
102
+ )
103
+
104
+
105
+ def load_tf_weights_in_jais(model, config, jais_checkpoint_path):
106
+ """Load tf checkpoints in a pytorch model"""
107
+ try:
108
+ import re
109
+
110
+ import tensorflow as tf
111
+ except ImportError:
112
+ logger.error(
113
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
114
+ "https://www.tensorflow.org/install/ for installation instructions."
115
+ )
116
+ raise
117
+ tf_path = os.path.abspath(jais_checkpoint_path)
118
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
119
+ # Load weights from TF model
120
+ init_vars = tf.train.list_variables(tf_path)
121
+ names = []
122
+ arrays = []
123
+ for name, shape in init_vars:
124
+ logger.info(f"Loading TF weight {name} with shape {shape}")
125
+ array = tf.train.load_variable(tf_path, name)
126
+ names.append(name)
127
+ arrays.append(array.squeeze())
128
+
129
+ for name, array in zip(names, arrays):
130
+ name = name[6:] # skip "model/"
131
+ name = name.split("/")
132
+ pointer = model
133
+ for m_name in name:
134
+ if re.fullmatch(r"[A-Za-z]+\d+", m_name):
135
+ scope_names = re.split(r"(\d+)", m_name)
136
+ else:
137
+ scope_names = [m_name]
138
+ if scope_names[0] == "w" or scope_names[0] == "g":
139
+ pointer = getattr(pointer, "weight")
140
+ elif scope_names[0] == "b":
141
+ pointer = getattr(pointer, "bias")
142
+ elif scope_names[0] == "wpe" or scope_names[0] == "wte":
143
+ pointer = getattr(pointer, scope_names[0])
144
+ pointer = getattr(pointer, "weight")
145
+ else:
146
+ pointer = getattr(pointer, scope_names[0])
147
+ if len(scope_names) >= 2:
148
+ num = int(scope_names[1])
149
+ pointer = pointer[num]
150
+ try:
151
+ assert (
152
+ pointer.shape == array.shape
153
+ ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
154
+ except AssertionError as e:
155
+ e.args += (pointer.shape, array.shape)
156
+ raise
157
+ logger.info(f"Initialize PyTorch weight {name}")
158
+ pointer.data = torch.from_numpy(array)
159
+ return model
160
+
161
+
162
+ class JAISAttention(nn.Module):
163
+ def __init__(self, config, is_cross_attention=False, layer_idx=None):
164
+ super().__init__()
165
+
166
+ max_positions = config.max_position_embeddings
167
+ self.register_buffer(
168
+ "bias",
169
+ torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
170
+ 1, 1, max_positions, max_positions
171
+ ),
172
+ persistent=False,
173
+ )
174
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
175
+
176
+ self.embed_dim = config.hidden_size
177
+ self.num_heads = config.num_attention_heads
178
+ self.head_dim = self.embed_dim // self.num_heads
179
+ self.split_size = self.embed_dim
180
+ if self.head_dim * self.num_heads != self.embed_dim:
181
+ raise ValueError(
182
+ f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
183
+ f" {self.num_heads})."
184
+ )
185
+
186
+ self.scale_attn_weights = config.scale_attn_weights
187
+ self.is_cross_attention = is_cross_attention
188
+
189
+ # Layer-wise attention scaling, reordering, and upcasting
190
+ self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx
191
+ self.layer_idx = layer_idx
192
+ self.reorder_and_upcast_attn = config.reorder_and_upcast_attn
193
+
194
+ if self.is_cross_attention:
195
+ self.c_attn = Conv1D(2 * self.embed_dim, self.embed_dim)
196
+ self.q_attn = Conv1D(self.embed_dim, self.embed_dim)
197
+ else:
198
+ self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim)
199
+ self.c_proj = Conv1D(self.embed_dim, self.embed_dim)
200
+
201
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
202
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
203
+
204
+ self.pruned_heads = set()
205
+
206
+ self.attn_scale_power = 1.0 if config.scale_qk_dot_by_d else 0.5
207
+
208
+ def prune_heads(self, heads):
209