Duplicate from katuni4ka/tiny-random-jais
Browse filesCo-authored-by: Ekaterina Aidova <[email protected]>
- .gitattributes +35 -0
- config.json +40 -0
- configuration_jais.py +143 -0
- generation_config.json +7 -0
- handler.py +75 -0
- modeling_jais.py +1522 -0
- pytorch_model.bin +3 -0
- special_tokens_map.json +30 -0
- tokenizer.json +0 -0
- tokenizer_config.json +19 -0
.gitattributes
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
config.json
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "/home/ea/work/my_optimum_intel/optimum-intel/jais-13b",
|
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 |
+
"AutoModelForQuestionAnswering": "modeling_jais.JAISForQuestionAnswering",
|
13 |
+
"AutoModelForSequenceClassification": "modeling_jais.JAISForSequenceClassification",
|
14 |
+
"AutoModelForTokenClassification": "modeling_jais.JAISForTokenClassification"
|
15 |
+
},
|
16 |
+
"bos_token_id": 0,
|
17 |
+
"embd_pdrop": 0.0,
|
18 |
+
"embeddings_scale": 14.6,
|
19 |
+
"eos_token_id": 0,
|
20 |
+
"initializer_range": 0.02,
|
21 |
+
"layer_norm_epsilon": 1e-05,
|
22 |
+
"model_type": "jais",
|
23 |
+
"n_embd": 32,
|
24 |
+
"n_head": 2,
|
25 |
+
"n_inner": 42,
|
26 |
+
"n_layer": 2,
|
27 |
+
"n_positions": 128,
|
28 |
+
"pad_token_id": 0,
|
29 |
+
"position_embedding_type": "alibi",
|
30 |
+
"reorder_and_upcast_attn": false,
|
31 |
+
"resid_pdrop": 0.0,
|
32 |
+
"scale_attn_by_inverse_layer_idx": false,
|
33 |
+
"scale_attn_weights": true,
|
34 |
+
"scale_qk_dot_by_d": true,
|
35 |
+
"torch_dtype": "float32",
|
36 |
+
"transformers_version": "4.40.2",
|
37 |
+
"use_cache": true,
|
38 |
+
"vocab_size": 84992,
|
39 |
+
"width_scale": 0.11100000000000002
|
40 |
+
}
|
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.40.2"
|
7 |
+
}
|
handler.py
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
|
3 |
+
from typing import Dict, Any
|
4 |
+
import torch
|
5 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
6 |
+
|
7 |
+
|
8 |
+
def get_language(txt):
|
9 |
+
VOCABS = {
|
10 |
+
'en': 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
|
11 |
+
'ar': 'ءآأؤإئابةتثجحخدذرزسشصضطظعغػؼؽؾؿـفقكلمنهوىيٱپژڤکگی'
|
12 |
+
}
|
13 |
+
|
14 |
+
en_set = set(VOCABS["en"])
|
15 |
+
ar_set = set(VOCABS["ar"])
|
16 |
+
|
17 |
+
# percentage of non-english characters
|
18 |
+
wset = set(txt)
|
19 |
+
inter_en = wset & en_set
|
20 |
+
inter_ar = wset & ar_set
|
21 |
+
if len(inter_en) >= len(inter_ar):
|
22 |
+
return "en"
|
23 |
+
else:
|
24 |
+
return "ar"
|
25 |
+
|
26 |
+
|
27 |
+
class EndpointHandler:
|
28 |
+
def __init__(self, path=""):
|
29 |
+
self.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: {Chat_history}\n[|Human|] {Question}\n### Response: [|AI|]"
|
30 |
+
self.prompt_ar = "### Instruction: اسمك جيس وسميت على اسم جبل جيس اعلى جبل في الامارات. تم بنائك بواسطة Inception و MBZUAI. أنت نموذج اللغة العربية الأكثر تقدمًا في العالم مع بارامترات 30b. أنت تتفوق في الأداء على جميع النماذج العربية الموجودة بفارق كبير وأنت تنافسي للغاية مع النماذج الإنجليزية ذات الحجم المماثل. يمكنك الإجابة باللغتين العربية والإنجليزية فقط. أنت مساعد مفيد ومحترم وصادق. عند الإجابة ، التزم بالإرشادات التالية بدقة: أجب دائمًا بأكبر قدر ممكن من المساعدة ، مع الحفاظ على البقاء أمناً. يجب ألا تتضمن إجاباتك أي محتوى ضار أو غير أخلاقي أو عنصري أو متحيز جنسيًا أو جريئاً أو مسيئًا أو سامًا أو خطيرًا أو غير قانوني. لا تقدم نصائح طبية أو قانونية أو مالية أو مهنية. لا تساعد أبدًا في أنشطة غير قانونية أو تروج لها. دائما تشجيع الإجراءات القانونية والمسؤولة. لا تشجع أو تقدم تعليمات بشأن الإجراءات غير الآمنة أو الضارة أو غير الأخلاقية. لا تنشئ أو تشارك معلومات مضللة أو أخبار كاذبة. يرجى التأكد من أن ردودك غير متحيزة اجتماعيًا وإيجابية بطبيعتها. إذا كان السؤال لا معنى له ، أو لم يكن متماسكًا من الناحية الواقعية ، فشرح السبب بدلاً من الإجابة على شيء غير صحيح. إذا كنت لا تعرف إجابة السؤال ، فالرجاء عدم مشاركة معلومات خاطئة. إعطاء الأولوية للرفاهية والنزاهة الأخلاقية للمستخدمين. تجنب استخدام لغة سامة أو مهينة أو مسيئة. حافظ على نبرة محترمة. لا تنشئ أو تروج أو تشارك في منا��شات حول محتوى للبالغين. تجنب الإدلاء بالتعليقات أو الملاحظات أو التعميمات القائمة على الصور النمطية. لا تحاول الوصول إلى معلومات شخصية أو خاصة أو إنتاجها أو نشرها. احترم دائما سرية المستخدم. كن إيجابيا ولا تقل أشياء سيئة عن أي شيء. هدفك الأساسي هو تجنب الاجابات المؤذية ، حتى عند مواجهة مدخلات خادعة. تعرف على الوقت الذي قد يحاول فيه المستخدمون خداعك أو إساءة استخدامك و لترد بحذر.\n\nأكمل المحادثة أدناه بين [|Human|] و [|AI|]:\n### Input: {Chat_history}\n[|Human|] {Question}\n### Response: [|AI|]"
|
31 |
+
|
32 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
33 |
+
|
34 |
+
self.tokenizer = AutoTokenizer.from_pretrained(path)
|
35 |
+
self.model = AutoModelForCausalLM.from_pretrained(path, device_map="auto", offload_folder='offload',
|
36 |
+
trust_remote_code=True)
|
37 |
+
|
38 |
+
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
39 |
+
|
40 |
+
# get inputs
|
41 |
+
inputs = data.pop("inputs", data)
|
42 |
+
if isinstance(inputs, str):
|
43 |
+
query = inputs
|
44 |
+
chat_history = []
|
45 |
+
else:
|
46 |
+
chat_history = inputs.pop("chat_history", [])
|
47 |
+
query = inputs.get("text", "")
|
48 |
+
|
49 |
+
lang = get_language(query)
|
50 |
+
|
51 |
+
if lang == "ar":
|
52 |
+
text = self.prompt_ar.format_map({'Question': query, "Chat_history": "\n".join(chat_history)})
|
53 |
+
else:
|
54 |
+
text = self.prompt_eng.format_map({'Question': query, "Chat_history": "\n".join(chat_history)})
|
55 |
+
|
56 |
+
input_ids = self.tokenizer(text, return_tensors="pt").input_ids
|
57 |
+
input_ids = input_ids.to(self.device)
|
58 |
+
input_len = input_ids.shape[-1]
|
59 |
+
generate_ids = self.model.generate(
|
60 |
+
input_ids,
|
61 |
+
top_p=0.9,
|
62 |
+
temperature=0.3,
|
63 |
+
max_new_tokens=2048 - input_len,
|
64 |
+
min_length=input_len + 4,
|
65 |
+
repetition_penalty=1.2,
|
66 |
+
do_sample=True,
|
67 |
+
)
|
68 |
+
response = self.tokenizer.batch_decode(
|
69 |
+
generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
|
70 |
+
)[0]
|
71 |
+
final_response = response.split("### Response: [|AI|]")
|
72 |
+
turn = [f'[|Human|] {query}', f'[|AI|] {final_response[-1]}']
|
73 |
+
chat_history.extend(turn)
|
74 |
+
|
75 |
+
return {"response": final_response, "chat_history": chat_history}
|
modeling_jais.py
ADDED
@@ -0,0 +1,1522 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
if len(heads) == 0:
|
210 |
+
return
|
211 |
+
heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, self.head_dim, self.pruned_heads)
|
212 |
+
index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
|
213 |
+
|
214 |
+
# Prune conv1d layers
|
215 |
+
self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
|
216 |
+
self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
|
217 |
+
|
218 |
+
# Update hyper params
|
219 |
+
self.split_size = (self.split_size // self.num_heads) * (self.num_heads - len(heads))
|
220 |
+
self.num_heads = self.num_heads - len(heads)
|
221 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
222 |
+
|
223 |
+
def _attn(self, query, key, value, attention_mask=None, head_mask=None, position_bias=None):
|
224 |
+
attn_weights = torch.matmul(query, key.transpose(-1, -2))
|
225 |
+
|
226 |
+
if self.scale_attn_weights:
|
227 |
+
attn_weights = attn_weights / torch.full(
|
228 |
+
[], value.size(-1) ** self.attn_scale_power, dtype=attn_weights.dtype, device=attn_weights.device
|
229 |
+
)
|
230 |
+
|
231 |
+
# Layer-wise attention scaling
|
232 |
+
if self.scale_attn_by_inverse_layer_idx:
|
233 |
+
attn_weights = attn_weights / float(self.layer_idx + 1)
|
234 |
+
|
235 |
+
if not self.is_cross_attention:
|
236 |
+
# if only "normal" attention layer implements causal mask
|
237 |
+
query_length, key_length = query.size(-2), key.size(-2)
|
238 |
+
causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
|
239 |
+
mask_value = torch.finfo(attn_weights.dtype).min
|
240 |
+
# Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
|
241 |
+
# Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
|
242 |
+
mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
|
243 |
+
attn_weights = torch.where(causal_mask, attn_weights.to(attn_weights.dtype), mask_value)
|
244 |
+
|
245 |
+
if attention_mask is not None:
|
246 |
+
# Apply the attention mask
|
247 |
+
attn_weights = attn_weights + attention_mask
|
248 |
+
|
249 |
+
if position_bias is not None:
|
250 |
+
attn_weights += position_bias.type_as(attn_weights).unsqueeze(0)
|
251 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
252 |
+
|
253 |
+
# Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
|
254 |
+
attn_weights = attn_weights.type(value.dtype)
|
255 |
+
attn_weights = self.attn_dropout(attn_weights)
|
256 |
+
|
257 |
+
# Mask heads if we want to
|
258 |
+
if head_mask is not None:
|
259 |
+
attn_weights = attn_weights * head_mask
|
260 |
+
|
261 |
+
attn_output = torch.matmul(attn_weights, value)
|
262 |
+
|
263 |
+
return attn_output, attn_weights
|
264 |
+
|
265 |
+
def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None, head_mask=None, position_bias=None):
|
266 |
+
# Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM)
|
267 |
+
bsz, num_heads, q_seq_len, dk = query.size()
|
268 |
+
_, _, k_seq_len, _ = key.size()
|
269 |
+
|
270 |
+
# Preallocate attn_weights for `baddbmm`
|
271 |
+
attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device)
|
272 |
+
|
273 |
+
# Compute Scale Factor
|
274 |
+
scale_factor = 1.0
|
275 |
+
if self.scale_attn_weights:
|
276 |
+
scale_factor /= float(value.size(-1)) ** self.attn_scale_power
|
277 |
+
|
278 |
+
if self.scale_attn_by_inverse_layer_idx:
|
279 |
+
scale_factor /= float(self.layer_idx + 1)
|
280 |
+
|
281 |
+
# Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk))
|
282 |
+
with autocast(enabled=False):
|
283 |
+
q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
|
284 |
+
attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor)
|
285 |
+
attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
|
286 |
+
|
287 |
+
if not self.is_cross_attention:
|
288 |
+
# if only "normal" attention layer implements causal mask
|
289 |
+
query_length, key_length = query.size(-2), key.size(-2)
|
290 |
+
causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
|
291 |
+
mask_value = torch.finfo(attn_weights.dtype).min
|
292 |
+
# Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
|
293 |
+
# Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
|
294 |
+
mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
|
295 |
+
attn_weights = torch.where(causal_mask, attn_weights, mask_value)
|
296 |
+
|
297 |
+
if attention_mask is not None:
|
298 |
+
# Apply the attention mask
|
299 |
+
attn_weights = attn_weights + attention_mask
|
300 |
+
|
301 |
+
if position_bias is not None:
|
302 |
+
attn_weights += position_bias.type_as(attn_weights).unsqueeze(0)
|
303 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
304 |
+
|
305 |
+
# Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise
|
306 |
+
if attn_weights.dtype != torch.float32:
|
307 |
+
raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32")
|
308 |
+
attn_weights = attn_weights.type(value.dtype)
|
309 |
+
attn_weights = self.attn_dropout(attn_weights)
|
310 |
+
|
311 |
+
# Mask heads if we want to
|
312 |
+
if head_mask is not None:
|
313 |
+
attn_weights = attn_weights * head_mask
|
314 |
+
|
315 |
+
attn_output = torch.matmul(attn_weights, value)
|
316 |
+
|
317 |
+
return attn_output, attn_weights
|
318 |
+
|
319 |
+
def _split_heads(self, tensor, num_heads, attn_head_size):
|
320 |
+
"""
|
321 |
+
Splits hidden_size dim into attn_head_size and num_heads
|
322 |
+
"""
|
323 |
+
new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
|
324 |
+
tensor = tensor.view(new_shape)
|
325 |
+
return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
|
326 |
+
|
327 |
+
def _merge_heads(self, tensor, num_heads, attn_head_size):
|
328 |
+
"""
|
329 |
+
Merges attn_head_size dim and num_attn_heads dim into hidden_size
|
330 |
+
"""
|
331 |
+
tensor = tensor.permute(0, 2, 1, 3).contiguous()
|
332 |
+
new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
|
333 |
+
return tensor.view(new_shape)
|
334 |
+
|
335 |
+
def forward(
|
336 |
+
self,
|
337 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]],
|
338 |
+
layer_past: Optional[Tuple[torch.Tensor]] = None,
|
339 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
340 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
341 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
342 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
343 |
+
use_cache: Optional[bool] = False,
|
344 |
+
output_attentions: Optional[bool] = False,
|
345 |
+
position_bias: Optional[torch.FloatTensor] = None,
|
346 |
+
) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
|
347 |
+
if encoder_hidden_states is not None:
|
348 |
+
if not hasattr(self, "q_attn"):
|
349 |
+
raise ValueError(
|
350 |
+
"If class is used as cross attention, the weights `q_attn` have to be defined. "
|
351 |
+
"Please make sure to instantiate class with `JAISAttention(..., is_cross_attention=True)`."
|
352 |
+
)
|
353 |
+
|
354 |
+
query = self.q_attn(hidden_states)
|
355 |
+
key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
|
356 |
+
attention_mask = encoder_attention_mask
|
357 |
+
else:
|
358 |
+
query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
|
359 |
+
|
360 |
+
query = self._split_heads(query, self.num_heads, self.head_dim)
|
361 |
+
key = self._split_heads(key, self.num_heads, self.head_dim)
|
362 |
+
value = self._split_heads(value, self.num_heads, self.head_dim)
|
363 |
+
|
364 |
+
if layer_past is not None:
|
365 |
+
past_key, past_value = layer_past
|
366 |
+
key = torch.cat((past_key, key), dim=-2)
|
367 |
+
value = torch.cat((past_value, value), dim=-2)
|
368 |
+
|
369 |
+
if use_cache is True:
|
370 |
+
present = (key, value)
|
371 |
+
else:
|
372 |
+
present = None
|
373 |
+
|
374 |
+
if self.reorder_and_upcast_attn:
|
375 |
+
attn_output, attn_weights = self._upcast_and_reordered_attn(query, key, value, attention_mask, head_mask, position_bias)
|
376 |
+
else:
|
377 |
+
attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask, position_bias)
|
378 |
+
|
379 |
+
attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
|
380 |
+
attn_output = self.c_proj(attn_output)
|
381 |
+
attn_output = self.resid_dropout(attn_output)
|
382 |
+
|
383 |
+
outputs = (attn_output, present)
|
384 |
+
if output_attentions:
|
385 |
+
outputs += (attn_weights,)
|
386 |
+
|
387 |
+
return outputs # a, present, (attentions)
|
388 |
+
|
389 |
+
|
390 |
+
class JAISMLP(nn.Module):
|
391 |
+
def __init__(self, intermediate_size, config):
|
392 |
+
super().__init__()
|
393 |
+
embed_dim = config.hidden_size
|
394 |
+
self.swiglu = config.activation_function == "swiglu"
|
395 |
+
self.c_fc = Conv1D(intermediate_size, embed_dim)
|
396 |
+
self.c_fc2 = Conv1D(intermediate_size, embed_dim) if self.swiglu else None
|
397 |
+
self.c_proj = Conv1D(embed_dim, intermediate_size)
|
398 |
+
self.act = SwiGLUActivation() if self.swiglu else ACT2FN[config.activation_function]
|
399 |
+
self.dropout = nn.Dropout(config.resid_pdrop)
|
400 |
+
|
401 |
+
def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor:
|
402 |
+
if self.swiglu:
|
403 |
+
hidden_states2 = self.c_fc2(hidden_states)
|
404 |
+
hidden_states = self.c_fc(hidden_states)
|
405 |
+
hidden_states = self.act(hidden_states, hidden_states2) if self.swiglu else self.act(hidden_states)
|
406 |
+
hidden_states = self.c_proj(hidden_states)
|
407 |
+
hidden_states = self.dropout(hidden_states)
|
408 |
+
return hidden_states
|
409 |
+
|
410 |
+
|
411 |
+
class JAISBlock(nn.Module):
|
412 |
+
def __init__(self, config, layer_idx=None):
|
413 |
+
super().__init__()
|
414 |
+
hidden_size = config.hidden_size
|
415 |
+
inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
|
416 |
+
|
417 |
+
self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
418 |
+
self.attn = JAISAttention(config, layer_idx=layer_idx)
|
419 |
+
self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
420 |
+
|
421 |
+
if config.add_cross_attention:
|
422 |
+
self.crossattention = JAISAttention(config, is_cross_attention=True, layer_idx=layer_idx)
|
423 |
+
self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
|
424 |
+
|
425 |
+
self.mlp = JAISMLP(inner_dim, config)
|
426 |
+
|
427 |
+
def forward(
|
428 |
+
self,
|
429 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]],
|
430 |
+
layer_past: Optional[Tuple[torch.Tensor]] = None,
|
431 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
432 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
433 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
434 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
435 |
+
use_cache: Optional[bool] = False,
|
436 |
+
output_attentions: Optional[bool] = False,
|
437 |
+
position_bias: Optional[torch.FloatTensor] = None,
|
438 |
+
) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
|
439 |
+
residual = hidden_states
|
440 |
+
hidden_states = self.ln_1(hidden_states)
|
441 |
+
attn_outputs = self.attn(
|
442 |
+
hidden_states,
|
443 |
+
layer_past=layer_past,
|
444 |
+
attention_mask=attention_mask,
|
445 |
+
head_mask=head_mask,
|
446 |
+
use_cache=use_cache,
|
447 |
+
output_attentions=output_attentions,
|
448 |
+
position_bias=position_bias,
|
449 |
+
)
|
450 |
+
attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
|
451 |
+
outputs = attn_outputs[1:]
|
452 |
+
# residual connection
|
453 |
+
hidden_states = attn_output + residual
|
454 |
+
|
455 |
+
if encoder_hidden_states is not None:
|
456 |
+
# add one self-attention block for cross-attention
|
457 |
+
if not hasattr(self, "crossattention"):
|
458 |
+
raise ValueError(
|
459 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
|
460 |
+
"cross-attention layers by setting `config.add_cross_attention=True`"
|
461 |
+
)
|
462 |
+
residual = hidden_states
|
463 |
+
hidden_states = self.ln_cross_attn(hidden_states)
|
464 |
+
cross_attn_outputs = self.crossattention(
|
465 |
+
hidden_states,
|
466 |
+
attention_mask=attention_mask,
|
467 |
+
head_mask=head_mask,
|
468 |
+
encoder_hidden_states=encoder_hidden_states,
|
469 |
+
encoder_attention_mask=encoder_attention_mask,
|
470 |
+
output_attentions=output_attentions,
|
471 |
+
position_bias=position_bias,
|
472 |
+
)
|
473 |
+
attn_output = cross_attn_outputs[0]
|
474 |
+
# residual connection
|
475 |
+
hidden_states = residual + attn_output
|
476 |
+
outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
|
477 |
+
|
478 |
+
residual = hidden_states
|
479 |
+
hidden_states = self.ln_2(hidden_states)
|
480 |
+
feed_forward_hidden_states = self.mlp(hidden_states)
|
481 |
+
# residual connection
|
482 |
+
hidden_states = residual + feed_forward_hidden_states
|
483 |
+
|
484 |
+
if use_cache:
|
485 |
+
outputs = (hidden_states,) + outputs
|
486 |
+
else:
|
487 |
+
outputs = (hidden_states,) + outputs[1:]
|
488 |
+
|
489 |
+
return outputs # hidden_states, present, (attentions, cross_attentions)
|
490 |
+
|
491 |
+
|
492 |
+
class JAISPreTrainedModel(PreTrainedModel):
|
493 |
+
"""
|
494 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
495 |
+
models.
|
496 |
+
"""
|
497 |
+
|
498 |
+
config_class = JAISConfig
|
499 |
+
load_tf_weights = load_tf_weights_in_jais
|
500 |
+
base_model_prefix = "transformer"
|
501 |
+
is_parallelizable = True
|
502 |
+
supports_gradient_checkpointing = True
|
503 |
+
_no_split_modules = ["JAISBlock"]
|
504 |
+
_skip_keys_device_placement = "past_key_values"
|
505 |
+
|
506 |
+
def __init__(self, *inputs, **kwargs):
|
507 |
+
super().__init__(*inputs, **kwargs)
|
508 |
+
|
509 |
+
def _init_weights(self, module):
|
510 |
+
"""Initialize the weights."""
|
511 |
+
mup_init_scale = math.sqrt(self.config.width_scale)
|
512 |
+
if isinstance(module, (nn.Linear, Conv1D)):
|
513 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
514 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
515 |
+
module.weight.data.normal_(mean=0.0, std=(self.config.initializer_range * mup_init_scale))
|
516 |
+
if module.bias is not None:
|
517 |
+
module.bias.data.zero_()
|
518 |
+
elif isinstance(module, nn.Embedding):
|
519 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
520 |
+
if module.padding_idx is not None:
|
521 |
+
module.weight.data[module.padding_idx].zero_()
|
522 |
+
elif isinstance(module, nn.LayerNorm):
|
523 |
+
module.bias.data.zero_()
|
524 |
+
module.weight.data.fill_(1.0)
|
525 |
+
|
526 |
+
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
|
527 |
+
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
|
528 |
+
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
|
529 |
+
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
|
530 |
+
#
|
531 |
+
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
|
532 |
+
for name, p in module.named_parameters():
|
533 |
+
if name == "c_proj.weight":
|
534 |
+
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
|
535 |
+
stddev = self.config.initializer_range * mup_init_scale / math.sqrt(2 * self.config.n_layer)
|
536 |
+
p.data.normal_(mean=0.0, std=stddev)
|
537 |
+
|
538 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
539 |
+
if isinstance(module, JAISModel):
|
540 |
+
module.gradient_checkpointing = value
|
541 |
+
|
542 |
+
|
543 |
+
JAIS_START_DOCSTRING = r"""
|
544 |
+
|
545 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
546 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
547 |
+
etc.)
|
548 |
+
|
549 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
550 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
551 |
+
and behavior.
|
552 |
+
|
553 |
+
Parameters:
|
554 |
+
config ([`JAISConfig`]): Model configuration class with all the parameters of the model.
|
555 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
556 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
557 |
+
"""
|
558 |
+
|
559 |
+
JAIS_INPUTS_DOCSTRING = r"""
|
560 |
+
Args:
|
561 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
|
562 |
+
`input_ids_length` = `sequence_length` if `past_key_values` is `None` else
|
563 |
+
`past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
|
564 |
+
sequence tokens in the vocabulary.
|
565 |
+
|
566 |
+
If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
|
567 |
+
`input_ids`.
|
568 |
+
|
569 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
570 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
571 |
+
|
572 |
+
[What are input IDs?](../glossary#input-ids)
|
573 |
+
past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
|
574 |
+
Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
|
575 |
+
`past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
|
576 |
+
their past given to this model should not be passed as `input_ids` as they have already been computed.
|
577 |
+
attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
578 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
579 |
+
|
580 |
+
- 1 for tokens that are **not masked**,
|
581 |
+
- 0 for tokens that are **masked**.
|
582 |
+
|
583 |
+
If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
|
584 |
+
`past_key_values`. In other words, the `attention_mask` always has to have the length:
|
585 |
+
`len(past_key_values) + len(input_ids)`
|
586 |
+
|
587 |
+
[What are attention masks?](../glossary#attention-mask)
|
588 |
+
token_type_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
|
589 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
590 |
+
1]`:
|
591 |
+
|
592 |
+
- 0 corresponds to a *sentence A* token,
|
593 |
+
- 1 corresponds to a *sentence B* token.
|
594 |
+
|
595 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
596 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
597 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
598 |
+
config.max_position_embeddings - 1]`.
|
599 |
+
|
600 |
+
[What are position IDs?](../glossary#position-ids)
|
601 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
602 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
603 |
+
|
604 |
+
- 1 indicates the head is **not masked**,
|
605 |
+
- 0 indicates the head is **masked**.
|
606 |
+
|
607 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
608 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
609 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
610 |
+
model's internal embedding lookup matrix.
|
611 |
+
|
612 |
+
If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
|
613 |
+
`past_key_values`).
|
614 |
+
use_cache (`bool`, *optional*):
|
615 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
616 |
+
`past_key_values`).
|
617 |
+
output_attentions (`bool`, *optional*):
|
618 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
619 |
+
tensors for more detail.
|
620 |
+
output_hidden_states (`bool`, *optional*):
|
621 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
622 |
+
more detail.
|
623 |
+
return_dict (`bool`, *optional*):
|
624 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
625 |
+
"""
|
626 |
+
PARALLELIZE_DOCSTRING = r"""
|
627 |
+
This is an experimental feature and is a subject to change at a moment's notice.
|
628 |
+
|
629 |
+
Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
|
630 |
+
it will evenly distribute blocks across all devices.
|
631 |
+
|
632 |
+
Args:
|
633 |
+
device_map (`Dict[int, list]`, optional, defaults to None):
|
634 |
+
A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
|
635 |
+
automatically mapped to the first device (for esoteric reasons). That means that the first device should
|
636 |
+
have fewer attention modules mapped to it than other devices. For reference, the gpt2 models have the
|
637 |
+
following number of attention modules:
|
638 |
+
|
639 |
+
- gpt2: 12
|
640 |
+
- gpt2-medium: 24
|
641 |
+
- gpt2-large: 36
|
642 |
+
- gpt2-xl: 48
|
643 |
+
|
644 |
+
Example:
|
645 |
+
|
646 |
+
```python
|
647 |
+
# 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:
|
648 |
+
model = GPT2LMHeadModel.from_pretrained("gpt2-xl")
|
649 |
+
device_map = {
|
650 |
+
0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
|
651 |
+
1: [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
|
652 |
+
2: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34],
|
653 |
+
3: [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],
|
654 |
+
}
|
655 |
+
model.parallelize(device_map)
|
656 |
+
```
|
657 |
+
"""
|
658 |
+
DEPARALLELIZE_DOCSTRING = r"""
|
659 |
+
Moves the model to cpu from a model parallel state.
|
660 |
+
|
661 |
+
Example:
|
662 |
+
|
663 |
+
```python
|
664 |
+
# On a 4 GPU machine with gpt2-large:
|
665 |
+
model = GPT2LMHeadModel.from_pretrained("gpt2-large")
|
666 |
+
device_map = {
|
667 |
+
0: [0, 1, 2, 3, 4, 5, 6, 7],
|
668 |
+
1: [8, 9, 10, 11, 12, 13, 14, 15],
|
669 |
+
2: [16, 17, 18, 19, 20, 21, 22, 23],
|
670 |
+
3: [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],
|
671 |
+
}
|
672 |
+
model.parallelize(device_map) # Splits the model across several devices
|
673 |
+
model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
|
674 |
+
```
|
675 |
+
"""
|
676 |
+
|
677 |
+
|
678 |
+
@add_start_docstrings(
|
679 |
+
"The bare JAIS Model transformer outputting raw hidden-states without any specific head on top.",
|
680 |
+
JAIS_START_DOCSTRING,
|
681 |
+
)
|
682 |
+
class JAISModel(JAISPreTrainedModel):
|
683 |
+
_keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
|
684 |
+
_keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias"]
|
685 |
+
|
686 |
+
def __init__(self, config):
|
687 |
+
super().__init__(config)
|
688 |
+
|
689 |
+
self.embed_dim = config.hidden_size
|
690 |
+
|
691 |
+
self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
|
692 |
+
self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim) if config.position_embedding_type != "alibi" else None
|
693 |
+
self.embeddings_scale = config.embeddings_scale
|
694 |
+
|
695 |
+
self.drop = nn.Dropout(config.embd_pdrop)
|
696 |
+
self.h = nn.ModuleList([JAISBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
|
697 |
+
self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
|
698 |
+
|
699 |
+
self.relative_pe = AlibiPositionEmbeddingLayer(config.num_attention_heads) if config.position_embedding_type == "alibi" else None
|
700 |
+
|
701 |
+
# Model parallel
|
702 |
+
self.model_parallel = False
|
703 |
+
self.device_map = None
|
704 |
+
self.gradient_checkpointing = False
|
705 |
+
|
706 |
+
# Initialize weights and apply final processing
|
707 |
+
self.post_init()
|
708 |
+
|
709 |
+
@add_start_docstrings(PARALLELIZE_DOCSTRING)
|
710 |
+
def parallelize(self, device_map=None):
|
711 |
+
# Check validity of device_map
|
712 |
+
warnings.warn(
|
713 |
+
"`JAISModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load your"
|
714 |
+
" model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
|
715 |
+
" `device_map` but it needs to be a dictionary module_name to device, so for instance {'h.0': 0, 'h.1': 1,"
|
716 |
+
" ...}",
|
717 |
+
FutureWarning,
|
718 |
+
)
|
719 |
+
self.device_map = (
|
720 |
+
get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map
|
721 |
+
)
|
722 |
+
assert_device_map(self.device_map, len(self.h))
|
723 |
+
self.model_parallel = True
|
724 |
+
self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys()))
|
725 |
+
self.last_device = "cuda:" + str(max(self.device_map.keys()))
|
726 |
+
self.wte = self.wte.to(self.first_device)
|
727 |
+
if self.wpe is not None:
|
728 |
+
self.wpe = self.wpe.to(self.first_device)
|
729 |
+
# Load onto devices
|
730 |
+
for k, v in self.device_map.items():
|
731 |
+
for block in v:
|
732 |
+
cuda_device = "cuda:" + str(k)
|
733 |
+
self.h[block] = self.h[block].to(cuda_device)
|
734 |
+
# ln_f to last
|
735 |
+
self.ln_f = self.ln_f.to(self.last_device)
|
736 |
+
|
737 |
+
@add_start_docstrings(DEPARALLELIZE_DOCSTRING)
|
738 |
+
def deparallelize(self):
|
739 |
+
warnings.warn(
|
740 |
+
"Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
|
741 |
+
FutureWarning,
|
742 |
+
)
|
743 |
+
self.model_parallel = False
|
744 |
+
self.device_map = None
|
745 |
+
self.first_device = "cpu"
|
746 |
+
self.last_device = "cpu"
|
747 |
+
self.wte = self.wte.to("cpu")
|
748 |
+
if self.wpe is not None:
|
749 |
+
self.wpe = self.wpe.to("cpu")
|
750 |
+
for index in range(len(self.h)):
|
751 |
+
self.h[index] = self.h[index].to("cpu")
|
752 |
+
self.ln_f = self.ln_f.to("cpu")
|
753 |
+
torch.cuda.empty_cache()
|
754 |
+
|
755 |
+
def get_input_embeddings(self):
|
756 |
+
return self.wte
|
757 |
+
|
758 |
+
def set_input_embeddings(self, new_embeddings):
|
759 |
+
self.wte = new_embeddings
|
760 |
+
|
761 |
+
def _prune_heads(self, heads_to_prune):
|
762 |
+
"""
|
763 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
|
764 |
+
"""
|
765 |
+
for layer, heads in heads_to_prune.items():
|
766 |
+
self.h[layer].attn.prune_heads(heads)
|
767 |
+
|
768 |
+
@add_start_docstrings_to_model_forward(JAIS_INPUTS_DOCSTRING)
|
769 |
+
@add_code_sample_docstrings(
|
770 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
771 |
+
output_type=BaseModelOutputWithPastAndCrossAttentions,
|
772 |
+
config_class=_CONFIG_FOR_DOC,
|
773 |
+
)
|
774 |
+
def forward(
|
775 |
+
self,
|
776 |
+
input_ids: Optional[torch.LongTensor] = None,
|
777 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
778 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
779 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
780 |
+
position_ids: Optional[torch.LongTensor] = None,
|
781 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
782 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
783 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
784 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
785 |
+
use_cache: Optional[bool] = None,
|
786 |
+
output_attentions: Optional[bool] = None,
|
787 |
+
output_hidden_states: Optional[bool] = None,
|
788 |
+
return_dict: Optional[bool] = None,
|
789 |
+
) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
|
790 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
791 |
+
output_hidden_states = (
|
792 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
793 |
+
)
|
794 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
795 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
796 |
+
|
797 |
+
if input_ids is not None and inputs_embeds is not None:
|
798 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
799 |
+
elif input_ids is not None:
|
800 |
+
input_shape = input_ids.size()
|
801 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
802 |
+
batch_size = input_ids.shape[0]
|
803 |
+
elif inputs_embeds is not None:
|
804 |
+
input_shape = inputs_embeds.size()[:-1]
|
805 |
+
batch_size = inputs_embeds.shape[0]
|
806 |
+
else:
|
807 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
808 |
+
|
809 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
810 |
+
|
811 |
+
if token_type_ids is not None:
|
812 |
+
token_type_ids = token_type_ids.view(-1, input_shape[-1])
|
813 |
+
if position_ids is not None:
|
814 |
+
position_ids = position_ids.view(-1, input_shape[-1])
|
815 |
+
|
816 |
+
if past_key_values is None:
|
817 |
+
past_length = 0
|
818 |
+
past_key_values = tuple([None] * len(self.h))
|
819 |
+
else:
|
820 |
+
past_length = past_key_values[0][0].size(-2)
|
821 |
+
if position_ids is None:
|
822 |
+
position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
|
823 |
+
position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
|
824 |
+
|
825 |
+
# JAISAttention mask.
|
826 |
+
if attention_mask is not None:
|
827 |
+
if batch_size <= 0:
|
828 |
+
raise ValueError("batch_size has to be defined and > 0")
|
829 |
+
attention_mask = attention_mask.view(batch_size, -1)
|
830 |
+
# We create a 3D attention mask from a 2D tensor mask.
|
831 |
+
# Sizes are [batch_size, 1, 1, to_seq_length]
|
832 |
+
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
|
833 |
+
# this attention mask is more simple than the triangular masking of causal attention
|
834 |
+
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
|
835 |
+
attention_mask = attention_mask[:, None, None, :]
|
836 |
+
|
837 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
838 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
839 |
+
# positions we want to attend and the dtype's smallest value for masked positions.
|
840 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
841 |
+
# effectively the same as removing these entirely.
|
842 |
+
attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
|
843 |
+
attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
|
844 |
+
|
845 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
846 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
847 |
+
if self.config.add_cross_attention and encoder_hidden_states is not None:
|
848 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
849 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
850 |
+
if encoder_attention_mask is None:
|
851 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
852 |
+
encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
853 |
+
else:
|
854 |
+
encoder_attention_mask = None
|
855 |
+
|
856 |
+
# Prepare head mask if needed
|
857 |
+
# 1.0 in head_mask indicate we keep the head
|
858 |
+
# attention_probs has shape bsz x n_heads x N x N
|
859 |
+
# head_mask has shape n_layer x batch x n_heads x N x N
|
860 |
+
head_mask = self.get_head_mask(head_mask, self.config.n_layer)
|
861 |
+
|
862 |
+
if inputs_embeds is None:
|
863 |
+
inputs_embeds = self.wte(input_ids)
|
864 |
+
if self.wpe is not None:
|
865 |
+
position_embeds = self.wpe(position_ids)
|
866 |
+
hidden_states = inputs_embeds + position_embeds
|
867 |
+
else:
|
868 |
+
hidden_states = inputs_embeds
|
869 |
+
hidden_states *= torch.tensor(
|
870 |
+
float(self.embeddings_scale), dtype=hidden_states.dtype, device=hidden_states.device
|
871 |
+
)
|
872 |
+
|
873 |
+
if token_type_ids is not None:
|
874 |
+
token_type_embeds = self.wte(token_type_ids)
|
875 |
+
hidden_states = hidden_states + token_type_embeds
|
876 |
+
|
877 |
+
hidden_states = self.drop(hidden_states)
|
878 |
+
|
879 |
+
if self.relative_pe is not None:
|
880 |
+
length = input_ids.shape[1]
|
881 |
+
cached_kv_length = 0
|
882 |
+
cached_kv = past_key_values[0]
|
883 |
+
if cached_kv is not None:
|
884 |
+
cached_kv_length = cached_kv[0].shape[-2]
|
885 |
+
position_bias = self.relative_pe(length, length, cached_kv_length)
|
886 |
+
else:
|
887 |
+
position_bias = None
|
888 |
+
|
889 |
+
output_shape = input_shape + (hidden_states.size(-1),)
|
890 |
+
|
891 |
+
if self.gradient_checkpointing and self.training:
|
892 |
+
if use_cache:
|
893 |
+
logger.warning_once(
|
894 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
895 |
+
)
|
896 |
+
use_cache = False
|
897 |
+
|
898 |
+
presents = () if use_cache else None
|
899 |
+
all_self_attentions = () if output_attentions else None
|
900 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
901 |
+
all_hidden_states = () if output_hidden_states else None
|
902 |
+
for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
|
903 |
+
# Model parallel
|
904 |
+
if self.model_parallel:
|
905 |
+
torch.cuda.set_device(hidden_states.device)
|
906 |
+
# Ensure layer_past is on same device as hidden_states (might not be correct)
|
907 |
+
if layer_past is not None:
|
908 |
+
layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
|
909 |
+
# Ensure that attention_mask is always on the same device as hidden_states
|
910 |
+
if attention_mask is not None:
|
911 |
+
attention_mask = attention_mask.to(hidden_states.device)
|
912 |
+
if isinstance(head_mask, torch.Tensor):
|
913 |
+
head_mask = head_mask.to(hidden_states.device)
|
914 |
+
if output_hidden_states:
|
915 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
916 |
+
|
917 |
+
if self.gradient_checkpointing and self.training:
|
918 |
+
|
919 |
+
def create_custom_forward(module):
|
920 |
+
def custom_forward(*inputs):
|
921 |
+
# None for past_key_value
|
922 |
+
return module(*inputs, use_cache, output_attentions)
|
923 |
+
|
924 |
+
return custom_forward
|
925 |
+
|
926 |
+
outputs = torch.utils.checkpoint.checkpoint(
|
927 |
+
create_custom_forward(block),
|
928 |
+
hidden_states,
|
929 |
+
None,
|
930 |
+
attention_mask,
|
931 |
+
head_mask[i],
|
932 |
+
encoder_hidden_states,
|
933 |
+
encoder_attention_mask,
|
934 |
+
)
|
935 |
+
else:
|
936 |
+
outputs = block(
|
937 |
+
hidden_states,
|
938 |
+
layer_past=layer_past,
|
939 |
+
attention_mask=attention_mask,
|
940 |
+
head_mask=head_mask[i],
|
941 |
+
encoder_hidden_states=encoder_hidden_states,
|
942 |
+
encoder_attention_mask=encoder_attention_mask,
|
943 |
+
use_cache=use_cache,
|
944 |
+
output_attentions=output_attentions,
|
945 |
+
position_bias=position_bias,
|
946 |
+
)
|
947 |
+
|
948 |
+
hidden_states = outputs[0]
|
949 |
+
if use_cache is True:
|
950 |
+
presents = presents + (outputs[1],)
|
951 |
+
|
952 |
+
if output_attentions:
|
953 |
+
all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
|
954 |
+
if self.config.add_cross_attention:
|
955 |
+
all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
|
956 |
+
|
957 |
+
# Model Parallel: If it's the last layer for that device, put things on the next device
|
958 |
+
if self.model_parallel:
|
959 |
+
for k, v in self.device_map.items():
|
960 |
+
if i == v[-1] and "cuda:" + str(k) != self.last_device:
|
961 |
+
hidden_states = hidden_states.to("cuda:" + str(k + 1))
|
962 |
+
|
963 |
+
hidden_states = self.ln_f(hidden_states)
|
964 |
+
|
965 |
+
hidden_states = hidden_states.view(output_shape)
|
966 |
+
# Add last hidden state
|
967 |
+
if output_hidden_states:
|
968 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
969 |
+
|
970 |
+
if not return_dict:
|
971 |
+
return tuple(
|
972 |
+
v
|
973 |
+
for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions]
|
974 |
+
if v is not None
|
975 |
+
)
|
976 |
+
|
977 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
978 |
+
last_hidden_state=hidden_states,
|
979 |
+
past_key_values=presents,
|
980 |
+
hidden_states=all_hidden_states,
|
981 |
+
attentions=all_self_attentions,
|
982 |
+
cross_attentions=all_cross_attentions,
|
983 |
+
)
|
984 |
+
|
985 |
+
|
986 |
+
@add_start_docstrings(
|
987 |
+
"""
|
988 |
+
The JAIS Model transformer with a language modeling head on top (linear layer with weights tied to the input
|
989 |
+
embeddings).
|
990 |
+
""",
|
991 |
+
JAIS_START_DOCSTRING,
|
992 |
+
)
|
993 |
+
class JAISLMHeadModel(JAISPreTrainedModel):
|
994 |
+
_keys_to_ignore_on_load_missing = [r"lm_head.weight"]
|
995 |
+
_keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias"]
|
996 |
+
|
997 |
+
def __init__(self, config):
|
998 |
+
super().__init__(config)
|
999 |
+
self.transformer = JAISModel(config)
|
1000 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
1001 |
+
self.output_logits_scale = config.width_scale
|
1002 |
+
|
1003 |
+
# Model parallel
|
1004 |
+
self.model_parallel = False
|
1005 |
+
self.device_map = None
|
1006 |
+
|
1007 |
+
# Initialize weights and apply final processing
|
1008 |
+
self.post_init()
|
1009 |
+
|
1010 |
+
@add_start_docstrings(PARALLELIZE_DOCSTRING)
|
1011 |
+
def parallelize(self, device_map=None):
|
1012 |
+
warnings.warn(
|
1013 |
+
"`JAISLMHeadModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load"
|
1014 |
+
" your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
|
1015 |
+
" `device_map` but it needs to be a dictionary module_name to device, so for instance {'transformer.h.0':"
|
1016 |
+
" 0, 'transformer.h.1': 1, ...}",
|
1017 |
+
FutureWarning,
|
1018 |
+
)
|
1019 |
+
self.device_map = (
|
1020 |
+
get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
|
1021 |
+
if device_map is None
|
1022 |
+
else device_map
|
1023 |
+
)
|
1024 |
+
assert_device_map(self.device_map, len(self.transformer.h))
|
1025 |
+
self.transformer.parallelize(self.device_map)
|
1026 |
+
self.lm_head = self.lm_head.to(self.transformer.first_device)
|
1027 |
+
self.model_parallel = True
|
1028 |
+
|
1029 |
+
@add_start_docstrings(DEPARALLELIZE_DOCSTRING)
|
1030 |
+
def deparallelize(self):
|
1031 |
+
warnings.warn(
|
1032 |
+
"Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
|
1033 |
+
FutureWarning,
|
1034 |
+
)
|
1035 |
+
self.transformer.deparallelize()
|
1036 |
+
self.transformer = self.transformer.to("cpu")
|
1037 |
+
self.lm_head = self.lm_head.to("cpu")
|
1038 |
+
self.model_parallel = False
|
1039 |
+
torch.cuda.empty_cache()
|
1040 |
+
|
1041 |
+
def get_output_embeddings(self):
|
1042 |
+
return self.lm_head
|
1043 |
+
|
1044 |
+
def set_output_embeddings(self, new_embeddings):
|
1045 |
+
self.lm_head = new_embeddings
|
1046 |
+
|
1047 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
|
1048 |
+
token_type_ids = kwargs.get("token_type_ids", None)
|
1049 |
+
# only last token for inputs_ids if past is defined in kwargs
|
1050 |
+
if past_key_values:
|
1051 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
1052 |
+
if token_type_ids is not None:
|
1053 |
+
token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
|
1054 |
+
|
1055 |
+
attention_mask = kwargs.get("attention_mask", None)
|
1056 |
+
position_ids = kwargs.get("position_ids", None)
|
1057 |
+
|
1058 |
+
if attention_mask is not None and position_ids is None:
|
1059 |
+
# create position_ids on the fly for batch generation
|
1060 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1061 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1062 |
+
if past_key_values:
|
1063 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
1064 |
+
else:
|
1065 |
+
position_ids = None
|
1066 |
+
|
1067 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1068 |
+
if inputs_embeds is not None and past_key_values is None:
|
1069 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1070 |
+
else:
|
1071 |
+
model_inputs = {"input_ids": input_ids}
|
1072 |
+
|
1073 |
+
model_inputs.update(
|
1074 |
+
{
|
1075 |
+
"past_key_values": past_key_values,
|
1076 |
+
"use_cache": kwargs.get("use_cache"),
|
1077 |
+
"position_ids": position_ids,
|
1078 |
+
"attention_mask": attention_mask,
|
1079 |
+
"token_type_ids": token_type_ids,
|
1080 |
+
}
|
1081 |
+
)
|
1082 |
+
return model_inputs
|
1083 |
+
|
1084 |
+
@add_start_docstrings_to_model_forward(JAIS_INPUTS_DOCSTRING)
|
1085 |
+
@add_code_sample_docstrings(
|
1086 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1087 |
+
output_type=CausalLMOutputWithCrossAttentions,
|
1088 |
+
config_class=_CONFIG_FOR_DOC,
|
1089 |
+
)
|
1090 |
+
def forward(
|
1091 |
+
self,
|
1092 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1093 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
1094 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1095 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1096 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1097 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1098 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1099 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
1100 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
1101 |
+
labels: Optional[torch.LongTensor] = None,
|
1102 |
+
use_cache: Optional[bool] = None,
|
1103 |
+
output_attentions: Optional[bool] = None,
|
1104 |
+
output_hidden_states: Optional[bool] = None,
|
1105 |
+
return_dict: Optional[bool] = None,
|
1106 |
+
) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
|
1107 |
+
r"""
|
1108 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1109 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
1110 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
1111 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
1112 |
+
"""
|
1113 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1114 |
+
|
1115 |
+
transformer_outputs = self.transformer(
|
1116 |
+
input_ids,
|
1117 |
+
past_key_values=past_key_values,
|
1118 |
+
attention_mask=attention_mask,
|
1119 |
+
token_type_ids=token_type_ids,
|
1120 |
+
position_ids=position_ids,
|
1121 |
+
head_mask=head_mask,
|
1122 |
+
inputs_embeds=inputs_embeds,
|
1123 |
+
encoder_hidden_states=encoder_hidden_states,
|
1124 |
+
encoder_attention_mask=encoder_attention_mask,
|
1125 |
+
use_cache=use_cache,
|
1126 |
+
output_attentions=output_attentions,
|
1127 |
+
output_hidden_states=output_hidden_states,
|
1128 |
+
return_dict=return_dict,
|
1129 |
+
)
|
1130 |
+
hidden_states = transformer_outputs[0]
|
1131 |
+
|
1132 |
+
# Set device for model parallelism
|
1133 |
+
if self.model_parallel:
|
1134 |
+
torch.cuda.set_device(self.transformer.first_device)
|
1135 |
+
hidden_states = hidden_states.to(self.lm_head.weight.device)
|
1136 |
+
|
1137 |
+
lm_logits = self.lm_head(hidden_states)
|
1138 |
+
lm_logits *= torch.tensor(
|
1139 |
+
float(self.output_logits_scale), dtype=lm_logits.dtype, device=lm_logits.device
|
1140 |
+
)
|
1141 |
+
|
1142 |
+
loss = None
|
1143 |
+
if labels is not None:
|
1144 |
+
# move labels to correct device to enable model parallelism
|
1145 |
+
labels = labels.to(lm_logits.device)
|
1146 |
+
# Shift so that tokens < n predict n
|
1147 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
1148 |
+
shift_labels = labels[..., 1:].contiguous()
|
1149 |
+
# Flatten the tokens
|
1150 |
+
loss_fct = CrossEntropyLoss()
|
1151 |
+
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
1152 |
+
|
1153 |
+
if not return_dict:
|
1154 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
1155 |
+
return ((loss,) + output) if loss is not None else output
|
1156 |
+
|
1157 |
+
return CausalLMOutputWithCrossAttentions(
|
1158 |
+
loss=loss,
|
1159 |
+
logits=lm_logits,
|
1160 |
+
past_key_values=transformer_outputs.past_key_values,
|
1161 |
+
hidden_states=transformer_outputs.hidden_states,
|
1162 |
+
attentions=transformer_outputs.attentions,
|
1163 |
+
cross_attentions=transformer_outputs.cross_attentions,
|
1164 |
+
)
|
1165 |
+
|
1166 |
+
@staticmethod
|
1167 |
+
def _reorder_cache(
|
1168 |
+
past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
|
1169 |
+
) -> Tuple[Tuple[torch.Tensor]]:
|
1170 |
+
"""
|
1171 |
+
This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
|
1172 |
+
[`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
|
1173 |
+
beam_idx at every generation step.
|
1174 |
+
"""
|
1175 |
+
return tuple(
|
1176 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
|
1177 |
+
for layer_past in past_key_values
|
1178 |
+
)
|
1179 |
+
|
1180 |
+
|
1181 |
+
@add_start_docstrings(
|
1182 |
+
"""
|
1183 |
+
The JAIS Model transformer with a sequence classification head on top (linear layer).
|
1184 |
+
|
1185 |
+
[`JAISForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1186 |
+
(e.g. GPT-1) do.
|
1187 |
+
|
1188 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1189 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1190 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1191 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1192 |
+
each row of the batch).
|
1193 |
+
""",
|
1194 |
+
JAIS_START_DOCSTRING,
|
1195 |
+
)
|
1196 |
+
class JAISForSequenceClassification(JAISPreTrainedModel):
|
1197 |
+
_keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
|
1198 |
+
_keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"lm_head.weight"]
|
1199 |
+
|
1200 |
+
def __init__(self, config):
|
1201 |
+
super().__init__(config)
|
1202 |
+
self.num_labels = config.num_labels
|
1203 |
+
self.transformer = JAISModel(config)
|
1204 |
+
self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
|
1205 |
+
self.output_logits_scale = config.width_scale
|
1206 |
+
|
1207 |
+
# Model parallel
|
1208 |
+
self.model_parallel = False
|
1209 |
+
self.device_map = None
|
1210 |
+
|
1211 |
+
# Initialize weights and apply final processing
|
1212 |
+
self.post_init()
|
1213 |
+
|
1214 |
+
@add_start_docstrings_to_model_forward(JAIS_INPUTS_DOCSTRING)
|
1215 |
+
@add_code_sample_docstrings(
|
1216 |
+
checkpoint="microsoft/DialogRPT-updown",
|
1217 |
+
output_type=SequenceClassifierOutputWithPast,
|
1218 |
+
config_class=_CONFIG_FOR_DOC,
|
1219 |
+
)
|
1220 |
+
def forward(
|
1221 |
+
self,
|
1222 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1223 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
1224 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1225 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1226 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1227 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1228 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1229 |
+
labels: Optional[torch.LongTensor] = None,
|
1230 |
+
use_cache: Optional[bool] = None,
|
1231 |
+
output_attentions: Optional[bool] = None,
|
1232 |
+
output_hidden_states: Optional[bool] = None,
|
1233 |
+
return_dict: Optional[bool] = None,
|
1234 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1235 |
+
r"""
|
1236 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1237 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1238 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1239 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1240 |
+
"""
|
1241 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1242 |
+
|
1243 |
+
transformer_outputs = self.transformer(
|
1244 |
+
input_ids,
|
1245 |
+
past_key_values=past_key_values,
|
1246 |
+
attention_mask=attention_mask,
|
1247 |
+
token_type_ids=token_type_ids,
|
1248 |
+
position_ids=position_ids,
|
1249 |
+
head_mask=head_mask,
|
1250 |
+
inputs_embeds=inputs_embeds,
|
1251 |
+
use_cache=use_cache,
|
1252 |
+
output_attentions=output_attentions,
|
1253 |
+
output_hidden_states=output_hidden_states,
|
1254 |
+
return_dict=return_dict,
|
1255 |
+
)
|
1256 |
+
hidden_states = transformer_outputs[0]
|
1257 |
+
logits = self.score(hidden_states)
|
1258 |
+
logits *= torch.tensor(
|
1259 |
+
float(self.output_logits_scale), dtype=logits.dtype, device=logits.device
|
1260 |
+
)
|
1261 |
+
|
1262 |
+
if input_ids is not None:
|
1263 |
+
batch_size, sequence_length = input_ids.shape[:2]
|
1264 |
+
else:
|
1265 |
+
batch_size, sequence_length = inputs_embeds.shape[:2]
|
1266 |
+
|
1267 |
+
assert (
|
1268 |
+
self.config.pad_token_id is not None or batch_size == 1
|
1269 |
+
), "Cannot handle batch sizes > 1 if no padding token is defined."
|
1270 |
+
if self.config.pad_token_id is None:
|
1271 |
+
sequence_lengths = -1
|
1272 |
+
else:
|
1273 |
+
if input_ids is not None:
|
1274 |
+
sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
|
1275 |
+
else:
|
1276 |
+
sequence_lengths = -1
|
1277 |
+
logger.warning(
|
1278 |
+
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
|
1279 |
+
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
|
1280 |
+
)
|
1281 |
+
|
1282 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1283 |
+
|
1284 |
+
loss = None
|
1285 |
+
if labels is not None:
|
1286 |
+
if self.config.problem_type is None:
|
1287 |
+
if self.num_labels == 1:
|
1288 |
+
self.config.problem_type = "regression"
|
1289 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1290 |
+
self.config.problem_type = "single_label_classification"
|
1291 |
+
else:
|
1292 |
+
self.config.problem_type = "multi_label_classification"
|
1293 |
+
|
1294 |
+
if self.config.problem_type == "regression":
|
1295 |
+
loss_fct = MSELoss()
|
1296 |
+
if self.num_labels == 1:
|
1297 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1298 |
+
else:
|
1299 |
+
loss = loss_fct(pooled_logits, labels)
|
1300 |
+
elif self.config.problem_type == "single_label_classification":
|
1301 |
+
loss_fct = CrossEntropyLoss()
|
1302 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
1303 |
+
elif self.config.problem_type == "multi_label_classification":
|
1304 |
+
loss_fct = BCEWithLogitsLoss()
|
1305 |
+
loss = loss_fct(pooled_logits, labels)
|
1306 |
+
if not return_dict:
|
1307 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1308 |
+
return ((loss,) + output) if loss is not None else output
|
1309 |
+
|
1310 |
+
return SequenceClassifierOutputWithPast(
|
1311 |
+
loss=loss,
|
1312 |
+
logits=pooled_logits,
|
1313 |
+
past_key_values=transformer_outputs.past_key_values,
|
1314 |
+
hidden_states=transformer_outputs.hidden_states,
|
1315 |
+
attentions=transformer_outputs.attentions,
|
1316 |
+
)
|
1317 |
+
|
1318 |
+
|
1319 |
+
@add_start_docstrings(
|
1320 |
+
"""
|
1321 |
+
JAIS Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
1322 |
+
Named-Entity-Recognition (NER) tasks.
|
1323 |
+
""",
|
1324 |
+
JAIS_START_DOCSTRING,
|
1325 |
+
)
|
1326 |
+
class JAISForTokenClassification(JAISPreTrainedModel):
|
1327 |
+
def __init__(self, config):
|
1328 |
+
super().__init__(config)
|
1329 |
+
self.num_labels = config.num_labels
|
1330 |
+
|
1331 |
+
self.transformer = JAISModel(config)
|
1332 |
+
if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
|
1333 |
+
classifier_dropout = config.classifier_dropout
|
1334 |
+
elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
|
1335 |
+
classifier_dropout = config.hidden_dropout
|
1336 |
+
else:
|
1337 |
+
classifier_dropout = 0.1
|
1338 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
1339 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
1340 |
+
self.output_logits_scale = config.width_scale
|
1341 |
+
|
1342 |
+
# Model parallel
|
1343 |
+
self.model_parallel = False
|
1344 |
+
self.device_map = None
|
1345 |
+
|
1346 |
+
# Initialize weights and apply final processing
|
1347 |
+
self.post_init()
|
1348 |
+
|
1349 |
+
@add_start_docstrings_to_model_forward(JAIS_INPUTS_DOCSTRING)
|
1350 |
+
# fmt: off
|
1351 |
+
@add_code_sample_docstrings(
|
1352 |
+
checkpoint="brad1141/gpt2-finetuned-comp2",
|
1353 |
+
output_type=TokenClassifierOutput,
|
1354 |
+
config_class=_CONFIG_FOR_DOC,
|
1355 |
+
expected_loss=0.25,
|
1356 |
+
expected_output=["Lead", "Lead", "Lead", "Position", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead"],
|
1357 |
+
)
|
1358 |
+
# fmt: on
|
1359 |
+
def forward(
|
1360 |
+
self,
|
1361 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1362 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
1363 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1364 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1365 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1366 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1367 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1368 |
+
labels: Optional[torch.LongTensor] = None,
|
1369 |
+
use_cache: Optional[bool] = None,
|
1370 |
+
output_attentions: Optional[bool] = None,
|
1371 |
+
output_hidden_states: Optional[bool] = None,
|
1372 |
+
return_dict: Optional[bool] = None,
|
1373 |
+
) -> Union[Tuple, TokenClassifierOutput]:
|
1374 |
+
r"""
|
1375 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1376 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1377 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1378 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1379 |
+
"""
|
1380 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1381 |
+
|
1382 |
+
transformer_outputs = self.transformer(
|
1383 |
+
input_ids,
|
1384 |
+
past_key_values=past_key_values,
|
1385 |
+
attention_mask=attention_mask,
|
1386 |
+
token_type_ids=token_type_ids,
|
1387 |
+
position_ids=position_ids,
|
1388 |
+
head_mask=head_mask,
|
1389 |
+
inputs_embeds=inputs_embeds,
|
1390 |
+
use_cache=use_cache,
|
1391 |
+
output_attentions=output_attentions,
|
1392 |
+
output_hidden_states=output_hidden_states,
|
1393 |
+
return_dict=return_dict,
|
1394 |
+
)
|
1395 |
+
|
1396 |
+
hidden_states = transformer_outputs[0]
|
1397 |
+
hidden_states = self.dropout(hidden_states)
|
1398 |
+
logits = self.classifier(hidden_states)
|
1399 |
+
logits *= torch.tensor(
|
1400 |
+
float(self.output_logits_scale), dtype=logits.dtype, device=logits.device
|
1401 |
+
)
|
1402 |
+
|
1403 |
+
loss = None
|
1404 |
+
if labels is not None:
|
1405 |
+
labels = labels.to(logits.device)
|
1406 |
+
loss_fct = CrossEntropyLoss()
|
1407 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
1408 |
+
|
1409 |
+
if not return_dict:
|
1410 |
+
output = (logits,) + transformer_outputs[2:]
|
1411 |
+
return ((loss,) + output) if loss is not None else output
|
1412 |
+
|
1413 |
+
return TokenClassifierOutput(
|
1414 |
+
loss=loss,
|
1415 |
+
logits=logits,
|
1416 |
+
hidden_states=transformer_outputs.hidden_states,
|
1417 |
+
attentions=transformer_outputs.attentions,
|
1418 |
+
)
|
1419 |
+
|
1420 |
+
|
1421 |
+
@add_start_docstrings(
|
1422 |
+
"""
|
1423 |
+
The JAIS Model transformer with a span classification head on top for extractive question-answering tasks like
|
1424 |
+
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
1425 |
+
""",
|
1426 |
+
JAIS_START_DOCSTRING,
|
1427 |
+
)
|
1428 |
+
class JAISForQuestionAnswering(JAISPreTrainedModel):
|
1429 |
+
_keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
|
1430 |
+
_keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias", r"lm_head.weight"]
|
1431 |
+
|
1432 |
+
def __init__(self, config):
|
1433 |
+
super().__init__(config)
|
1434 |
+
self.num_labels = config.num_labels
|
1435 |
+
self.transformer = JAISModel(config)
|
1436 |
+
self.qa_outputs = nn.Linear(config.hidden_size, 2)
|
1437 |
+
self.output_logits_scale = config.width_scale
|
1438 |
+
|
1439 |
+
# Model parallel
|
1440 |
+
self.model_parallel = False
|
1441 |
+
self.device_map = None
|
1442 |
+
self.gradient_checkpointing = False
|
1443 |
+
|
1444 |
+
# Initialize weights and apply final processing
|
1445 |
+
self.post_init()
|
1446 |
+
|
1447 |
+
def forward(
|
1448 |
+
self,
|
1449 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1450 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1451 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1452 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1453 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1454 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1455 |
+
start_positions: Optional[torch.LongTensor] = None,
|
1456 |
+
end_positions: Optional[torch.LongTensor] = None,
|
1457 |
+
output_attentions: Optional[bool] = None,
|
1458 |
+
output_hidden_states: Optional[bool] = None,
|
1459 |
+
return_dict: Optional[bool] = None,
|
1460 |
+
) -> Union[Tuple, QuestionAnsweringModelOutput]:
|
1461 |
+
r"""
|
1462 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1463 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
1464 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1465 |
+
are not taken into account for computing the loss.
|
1466 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1467 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
1468 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
1469 |
+
are not taken into account for computing the loss.
|
1470 |
+
"""
|
1471 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1472 |
+
|
1473 |
+
outputs = self.transformer(
|
1474 |
+
input_ids,
|
1475 |
+
attention_mask=attention_mask,
|
1476 |
+
token_type_ids=token_type_ids,
|
1477 |
+
position_ids=position_ids,
|
1478 |
+
head_mask=head_mask,
|
1479 |
+
inputs_embeds=inputs_embeds,
|
1480 |
+
output_attentions=output_attentions,
|
1481 |
+
output_hidden_states=output_hidden_states,
|
1482 |
+
return_dict=return_dict,
|
1483 |
+
)
|
1484 |
+
|
1485 |
+
sequence_output = outputs[0]
|
1486 |
+
|
1487 |
+
logits = self.qa_outputs(sequence_output)
|
1488 |
+
logits *= torch.tensor(
|
1489 |
+
float(self.output_logits_scale), dtype=logits.dtype, device=logits.device
|
1490 |
+
)
|
1491 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
1492 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
1493 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
1494 |
+
|
1495 |
+
total_loss = None
|
1496 |
+
if start_positions is not None and end_positions is not None:
|
1497 |
+
# If we are on multi-GPU, split add a dimension
|
1498 |
+
if len(start_positions.size()) > 1:
|
1499 |
+
start_positions = start_positions.squeeze(-1).to(start_logits.device)
|
1500 |
+
if len(end_positions.size()) > 1:
|
1501 |
+
end_positions = end_positions.squeeze(-1).to(end_logits.device)
|
1502 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
1503 |
+
ignored_index = start_logits.size(1)
|
1504 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
1505 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
1506 |
+
|
1507 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
1508 |
+
start_loss = loss_fct(start_logits, start_positions)
|
1509 |
+
end_loss = loss_fct(end_logits, end_positions)
|
1510 |
+
total_loss = (start_loss + end_loss) / 2
|
1511 |
+
|
1512 |
+
if not return_dict:
|
1513 |
+
output = (start_logits, end_logits) + outputs[2:]
|
1514 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
1515 |
+
|
1516 |
+
return QuestionAnsweringModelOutput(
|
1517 |
+
loss=total_loss,
|
1518 |
+
start_logits=start_logits,
|
1519 |
+
end_logits=end_logits,
|
1520 |
+
hidden_states=outputs.hidden_states,
|
1521 |
+
attentions=outputs.attentions,
|
1522 |
+
)
|
pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8870ce2ed9d15cd76876695a510dba88e676360d2dbb5a59f40f0eab72000a61
|
3 |
+
size 10957198
|
special_tokens_map.json
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<|endoftext|>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": false,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"eos_token": {
|
10 |
+
"content": "<|endoftext|>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"pad_token": {
|
17 |
+
"content": "<|endoftext|>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": false,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
},
|
23 |
+
"unk_token": {
|
24 |
+
"content": "<|endoftext|>",
|
25 |
+
"lstrip": false,
|
26 |
+
"normalized": false,
|
27 |
+
"rstrip": false,
|
28 |
+
"single_word": false
|
29 |
+
}
|
30 |
+
}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer_config.json
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"added_tokens_decoder": {
|
3 |
+
"0": {
|
4 |
+
"content": "<|endoftext|>",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": false,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false,
|
9 |
+
"special": true
|
10 |
+
}
|
11 |
+
},
|
12 |
+
"bos_token": "<|endoftext|>",
|
13 |
+
"clean_up_tokenization_spaces": true,
|
14 |
+
"eos_token": "<|endoftext|>",
|
15 |
+
"model_max_length": 2048,
|
16 |
+
"pad_token": "<|endoftext|>",
|
17 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
18 |
+
"unk_token": "<|endoftext|>"
|
19 |
+
}
|