KnutJaegersberg commited on
Commit
7fb30a4
1 Parent(s): 154872e

Upload 12 files

Browse files
config.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/run/media/knut/HD/huggingface models/language models/LLMs/pretrained/3b/btlm-3b-8k-base/",
3
+ "activation_function": "swiglu",
4
+ "architectures": [
5
+ "BTLMLMHeadModel"
6
+ ],
7
+ "attn_pdrop": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_btlm.BTLMConfig",
10
+ "AutoModel": "modeling_btlm.BTLMModel",
11
+ "AutoModelForCausalLM": "modeling_btlm.BTLMLMHeadModel",
12
+ "AutoModelForQuestionAnswering": "modeling_btlm.BTLMForQuestionAnswering",
13
+ "AutoModelForSequenceClassification": "modeling_btlm.BTLMForSequenceClassification",
14
+ "AutoModelForTokenClassification": "modeling_btlm.BTLMForTokenClassification"
15
+ },
16
+ "bos_token_id": 50256,
17
+ "embd_pdrop": 0.0,
18
+ "eos_token_id": 50256,
19
+ "initializer_range": 0.073,
20
+ "layer_norm_epsilon": 1e-05,
21
+ "model_type": "btlm",
22
+ "mup_embeddings_scale": 14.6,
23
+ "mup_output_alpha": 2.22,
24
+ "mup_scale_qk_dot_by_d": true,
25
+ "mup_width_scale": 0.1,
26
+ "n_embd": 2560,
27
+ "n_head": 32,
28
+ "n_inner": 6826,
29
+ "n_layer": 32,
30
+ "n_positions": 8192,
31
+ "position_embedding_type": "alibi",
32
+ "reorder_and_upcast_attn": false,
33
+ "resid_pdrop": 0.0,
34
+ "scale_attn_by_inverse_layer_idx": false,
35
+ "scale_attn_weights": true,
36
+ "torch_dtype": "float16",
37
+ "transformers_version": "4.35.0",
38
+ "use_cache": true,
39
+ "vocab_size": 50257
40
+ }
configuration_btlm.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """ BTLM 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
+ BTLM_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "cerebras/btlm-3b-8k-base": "https://huggingface.co/cerebras/btlm-3b-8k-base/resolve/main/config.json",
27
+ }
28
+
29
+
30
+ class BTLMConfig(PretrainedConfig):
31
+ """
32
+ This is the configuration class to store the configuration of a [`BTLMModel`]. It is used to instantiate a BTLM
33
+ model according to the specified arguments, defining the model architecture.
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 50257):
41
+ Vocabulary size of the BTLM model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`BTLMModel`].
43
+ n_positions (`int`, *optional*, defaults to 1024):
44
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
45
+ just in case (e.g., 512 or 1024 or 2048).
46
+ n_embd (`int`, *optional*, defaults to 768):
47
+ Dimensionality of the embeddings and hidden states.
48
+ n_layer (`int`, *optional*, defaults to 12):
49
+ Number of hidden layers in the Transformer encoder.
50
+ n_head (`int`, *optional*, defaults to 12):
51
+ Number of attention heads for each attention layer in the Transformer encoder.
52
+ n_inner (`int`, *optional*, defaults to None):
53
+ Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
54
+ activation_function (`str`, *optional*, defaults to `"gelu"`):
55
+ Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new", "swiglu"]`.
56
+ resid_pdrop (`float`, *optional*, defaults to 0.1):
57
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
58
+ embd_pdrop (`float`, *optional*, defaults to 0.1):
59
+ The dropout ratio for the embeddings.
60
+ attn_pdrop (`float`, *optional*, defaults to 0.1):
61
+ The dropout ratio for the attention.
62
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
63
+ The epsilon to use in the layer normalization layers.
64
+ initializer_range (`float`, *optional*, defaults to 0.02):
65
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
66
+ scale_attn_weights (`bool`, *optional*, defaults to `True`):
67
+ Scale attention weights by dividing by sqrt(hidden_size)..
68
+ use_cache (`bool`, *optional*, defaults to `True`):
69
+ Whether or not the model should return the last key/values attentions (not used by all models).
70
+ scale_attn_by_inverse_layer_idx (`bool`, *optional*, defaults to `False`):
71
+ Whether to additionally scale attention weights by `1 / layer_idx + 1`.
72
+ reorder_and_upcast_attn (`bool`, *optional*, defaults to `False`):
73
+ Whether to scale keys (K) prior to computing attention (dot-product) and upcast attention
74
+ dot-product/softmax to float() when training with mixed precision.
75
+ position_embedding_type (`str`, *optional*, defaults to `"learned"`):
76
+ Positional embedding can be either `"alibi"` or `"learned"`.
77
+ mup_width_scale (`float`, *optional*, defaults to 1.0):
78
+ muP parameter to scale learning rate and initializers. Calculated as (`d_model,0 / d_model`), where
79
+ `d_model` is the model's width and `d_model,0` is the proxy model's width.
80
+ mup_embeddings_scale (`float`, *optional*, defaults to 1.0):
81
+ muP parameter to scale token and position embeddings.
82
+ mup_output_alpha (`float`, *optional*, defaults to 1.0):
83
+ muP parameter to scale output logits (`output_logits_scale = mup_output_alpha * mup_width_scale`).
84
+ mup_scale_qk_dot_by_d (`bool`, *optional*, defaults to `False`):
85
+ Scale attention weights by dividing by hidden_size instead of sqrt(hidden_size). Need to set
86
+ scale_attn_weights to `True` as well.
87
+
88
+ Example:
89
+
90
+ ```python
91
+ >>> from transformers import BTLMConfig, BTLMModel
92
+
93
+ >>> # Initializing a BTLM configuration
94
+ >>> configuration = BTLMConfig()
95
+
96
+ >>> # Initializing a model (with random weights) from the configuration
97
+ >>> model = BTLMModel(configuration)
98
+
99
+ >>> # Accessing the model configuration
100
+ >>> configuration = model.config
101
+ ```"""
102
+
103
+ model_type = "btlm"
104
+ keys_to_ignore_at_inference = ["past_key_values"]
105
+ attribute_map = {
106
+ "hidden_size": "n_embd",
107
+ "max_position_embeddings": "n_positions",
108
+ "num_attention_heads": "n_head",
109
+ "num_hidden_layers": "n_layer",
110
+ }
111
+
112
+ def __init__(
113
+ self,
114
+ vocab_size=50257,
115
+ n_positions=1024,
116
+ n_embd=768,
117
+ n_layer=12,
118
+ n_head=12,
119
+ n_inner=None,
120
+ activation_function="gelu_new",
121
+ resid_pdrop=0.1,
122
+ embd_pdrop=0.1,
123
+ attn_pdrop=0.1,
124
+ layer_norm_epsilon=1e-5,
125
+ initializer_range=0.02,
126
+ scale_attn_weights=True,
127
+ use_cache=True,
128
+ bos_token_id=50256,
129
+ eos_token_id=50256,
130
+ scale_attn_by_inverse_layer_idx=False,
131
+ reorder_and_upcast_attn=False,
132
+ position_embedding_type="learned",
133
+ mup_width_scale=1.0,
134
+ mup_embeddings_scale=1.0,
135
+ mup_output_alpha=1.0,
136
+ mup_scale_qk_dot_by_d=False,
137
+ **kwargs,
138
+ ):
139
+ self.vocab_size = vocab_size
140
+ self.n_positions = n_positions
141
+ self.n_embd = n_embd
142
+ self.n_layer = n_layer
143
+ self.n_head = n_head
144
+ self.n_inner = n_inner
145
+ self.activation_function = activation_function
146
+ self.resid_pdrop = resid_pdrop
147
+ self.embd_pdrop = embd_pdrop
148
+ self.attn_pdrop = attn_pdrop
149
+ self.layer_norm_epsilon = layer_norm_epsilon
150
+ self.initializer_range = initializer_range
151
+ self.scale_attn_weights = scale_attn_weights
152
+ self.use_cache = use_cache
153
+ self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx
154
+ self.reorder_and_upcast_attn = reorder_and_upcast_attn
155
+
156
+ self.bos_token_id = bos_token_id
157
+ self.eos_token_id = eos_token_id
158
+
159
+ self.position_embedding_type = position_embedding_type
160
+ self.mup_width_scale = mup_width_scale
161
+ self.mup_embeddings_scale = mup_embeddings_scale
162
+ self.mup_output_alpha = mup_output_alpha
163
+ self.mup_scale_qk_dot_by_d = mup_scale_qk_dot_by_d
164
+
165
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 50256,
4
+ "eos_token_id": 50256,
5
+ "transformers_version": "4.35.0"
6
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:22c2fbaf3750aec5c7a4eb7dd3e185c98260294838d8028eccea5c6bc4b7c726
3
+ size 4977856872
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b94fe455cbb08e2b79aa24a87b7fc5267bce67680bf36804ba43aab9712578c5
3
+ size 314702168
model.safetensors.index.json ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 5292511552
4
+ },
5
+ "weight_map": {
6
+ "transformer.h.0.attn.c_attn.bias": "model-00001-of-00002.safetensors",
7
+ "transformer.h.0.attn.c_attn.weight": "model-00001-of-00002.safetensors",
8
+ "transformer.h.0.attn.c_proj.bias": "model-00001-of-00002.safetensors",
9
+ "transformer.h.0.attn.c_proj.weight": "model-00001-of-00002.safetensors",
10
+ "transformer.h.0.ln_1.bias": "model-00001-of-00002.safetensors",
11
+ "transformer.h.0.ln_1.weight": "model-00001-of-00002.safetensors",
12
+ "transformer.h.0.ln_2.bias": "model-00001-of-00002.safetensors",
13
+ "transformer.h.0.ln_2.weight": "model-00001-of-00002.safetensors",
14
+ "transformer.h.0.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
15
+ "transformer.h.0.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
16
+ "transformer.h.0.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
17
+ "transformer.h.0.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
18
+ "transformer.h.0.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
19
+ "transformer.h.0.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
20
+ "transformer.h.1.attn.c_attn.bias": "model-00001-of-00002.safetensors",
21
+ "transformer.h.1.attn.c_attn.weight": "model-00001-of-00002.safetensors",
22
+ "transformer.h.1.attn.c_proj.bias": "model-00001-of-00002.safetensors",
23
+ "transformer.h.1.attn.c_proj.weight": "model-00001-of-00002.safetensors",
24
+ "transformer.h.1.ln_1.bias": "model-00001-of-00002.safetensors",
25
+ "transformer.h.1.ln_1.weight": "model-00001-of-00002.safetensors",
26
+ "transformer.h.1.ln_2.bias": "model-00001-of-00002.safetensors",
27
+ "transformer.h.1.ln_2.weight": "model-00001-of-00002.safetensors",
28
+ "transformer.h.1.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
29
+ "transformer.h.1.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
30
+ "transformer.h.1.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
31
+ "transformer.h.1.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
32
+ "transformer.h.1.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
33
+ "transformer.h.1.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
34
+ "transformer.h.10.attn.c_attn.bias": "model-00001-of-00002.safetensors",
35
+ "transformer.h.10.attn.c_attn.weight": "model-00001-of-00002.safetensors",
36
+ "transformer.h.10.attn.c_proj.bias": "model-00001-of-00002.safetensors",
37
+ "transformer.h.10.attn.c_proj.weight": "model-00001-of-00002.safetensors",
38
+ "transformer.h.10.ln_1.bias": "model-00001-of-00002.safetensors",
39
+ "transformer.h.10.ln_1.weight": "model-00001-of-00002.safetensors",
40
+ "transformer.h.10.ln_2.bias": "model-00001-of-00002.safetensors",
41
+ "transformer.h.10.ln_2.weight": "model-00001-of-00002.safetensors",
42
+ "transformer.h.10.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
43
+ "transformer.h.10.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
44
+ "transformer.h.10.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
45
+ "transformer.h.10.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
46
+ "transformer.h.10.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
47
+ "transformer.h.10.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
48
+ "transformer.h.11.attn.c_attn.bias": "model-00001-of-00002.safetensors",
49
+ "transformer.h.11.attn.c_attn.weight": "model-00001-of-00002.safetensors",
50
+ "transformer.h.11.attn.c_proj.bias": "model-00001-of-00002.safetensors",
51
+ "transformer.h.11.attn.c_proj.weight": "model-00001-of-00002.safetensors",
52
+ "transformer.h.11.ln_1.bias": "model-00001-of-00002.safetensors",
53
+ "transformer.h.11.ln_1.weight": "model-00001-of-00002.safetensors",
54
+ "transformer.h.11.ln_2.bias": "model-00001-of-00002.safetensors",
55
+ "transformer.h.11.ln_2.weight": "model-00001-of-00002.safetensors",
56
+ "transformer.h.11.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
57
+ "transformer.h.11.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
58
+ "transformer.h.11.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
59
+ "transformer.h.11.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
60
+ "transformer.h.11.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
61
+ "transformer.h.11.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
62
+ "transformer.h.12.attn.c_attn.bias": "model-00001-of-00002.safetensors",
63
+ "transformer.h.12.attn.c_attn.weight": "model-00001-of-00002.safetensors",
64
+ "transformer.h.12.attn.c_proj.bias": "model-00001-of-00002.safetensors",
65
+ "transformer.h.12.attn.c_proj.weight": "model-00001-of-00002.safetensors",
66
+ "transformer.h.12.ln_1.bias": "model-00001-of-00002.safetensors",
67
+ "transformer.h.12.ln_1.weight": "model-00001-of-00002.safetensors",
68
+ "transformer.h.12.ln_2.bias": "model-00001-of-00002.safetensors",
69
+ "transformer.h.12.ln_2.weight": "model-00001-of-00002.safetensors",
70
+ "transformer.h.12.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
71
+ "transformer.h.12.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
72
+ "transformer.h.12.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
73
+ "transformer.h.12.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
74
+ "transformer.h.12.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
75
+ "transformer.h.12.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
76
+ "transformer.h.13.attn.c_attn.bias": "model-00001-of-00002.safetensors",
77
+ "transformer.h.13.attn.c_attn.weight": "model-00001-of-00002.safetensors",
78
+ "transformer.h.13.attn.c_proj.bias": "model-00001-of-00002.safetensors",
79
+ "transformer.h.13.attn.c_proj.weight": "model-00001-of-00002.safetensors",
80
+ "transformer.h.13.ln_1.bias": "model-00001-of-00002.safetensors",
81
+ "transformer.h.13.ln_1.weight": "model-00001-of-00002.safetensors",
82
+ "transformer.h.13.ln_2.bias": "model-00001-of-00002.safetensors",
83
+ "transformer.h.13.ln_2.weight": "model-00001-of-00002.safetensors",
84
+ "transformer.h.13.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
85
+ "transformer.h.13.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
86
+ "transformer.h.13.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
87
+ "transformer.h.13.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
88
+ "transformer.h.13.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
89
+ "transformer.h.13.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
90
+ "transformer.h.14.attn.c_attn.bias": "model-00001-of-00002.safetensors",
91
+ "transformer.h.14.attn.c_attn.weight": "model-00001-of-00002.safetensors",
92
+ "transformer.h.14.attn.c_proj.bias": "model-00001-of-00002.safetensors",
93
+ "transformer.h.14.attn.c_proj.weight": "model-00001-of-00002.safetensors",
94
+ "transformer.h.14.ln_1.bias": "model-00001-of-00002.safetensors",
95
+ "transformer.h.14.ln_1.weight": "model-00001-of-00002.safetensors",
96
+ "transformer.h.14.ln_2.bias": "model-00001-of-00002.safetensors",
97
+ "transformer.h.14.ln_2.weight": "model-00001-of-00002.safetensors",
98
+ "transformer.h.14.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
99
+ "transformer.h.14.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
100
+ "transformer.h.14.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
101
+ "transformer.h.14.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
102
+ "transformer.h.14.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
103
+ "transformer.h.14.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
104
+ "transformer.h.15.attn.c_attn.bias": "model-00001-of-00002.safetensors",
105
+ "transformer.h.15.attn.c_attn.weight": "model-00001-of-00002.safetensors",
106
+ "transformer.h.15.attn.c_proj.bias": "model-00001-of-00002.safetensors",
107
+ "transformer.h.15.attn.c_proj.weight": "model-00001-of-00002.safetensors",
108
+ "transformer.h.15.ln_1.bias": "model-00001-of-00002.safetensors",
109
+ "transformer.h.15.ln_1.weight": "model-00001-of-00002.safetensors",
110
+ "transformer.h.15.ln_2.bias": "model-00001-of-00002.safetensors",
111
+ "transformer.h.15.ln_2.weight": "model-00001-of-00002.safetensors",
112
+ "transformer.h.15.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
113
+ "transformer.h.15.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
114
+ "transformer.h.15.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
115
+ "transformer.h.15.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
116
+ "transformer.h.15.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
117
+ "transformer.h.15.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
118
+ "transformer.h.16.attn.c_attn.bias": "model-00001-of-00002.safetensors",
119
+ "transformer.h.16.attn.c_attn.weight": "model-00001-of-00002.safetensors",
120
+ "transformer.h.16.attn.c_proj.bias": "model-00001-of-00002.safetensors",
121
+ "transformer.h.16.attn.c_proj.weight": "model-00001-of-00002.safetensors",
122
+ "transformer.h.16.ln_1.bias": "model-00001-of-00002.safetensors",
123
+ "transformer.h.16.ln_1.weight": "model-00001-of-00002.safetensors",
124
+ "transformer.h.16.ln_2.bias": "model-00001-of-00002.safetensors",
125
+ "transformer.h.16.ln_2.weight": "model-00001-of-00002.safetensors",
126
+ "transformer.h.16.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
127
+ "transformer.h.16.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
128
+ "transformer.h.16.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
129
+ "transformer.h.16.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
130
+ "transformer.h.16.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
131
+ "transformer.h.16.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
132
+ "transformer.h.17.attn.c_attn.bias": "model-00001-of-00002.safetensors",
133
+ "transformer.h.17.attn.c_attn.weight": "model-00001-of-00002.safetensors",
134
+ "transformer.h.17.attn.c_proj.bias": "model-00001-of-00002.safetensors",
135
+ "transformer.h.17.attn.c_proj.weight": "model-00001-of-00002.safetensors",
136
+ "transformer.h.17.ln_1.bias": "model-00001-of-00002.safetensors",
137
+ "transformer.h.17.ln_1.weight": "model-00001-of-00002.safetensors",
138
+ "transformer.h.17.ln_2.bias": "model-00001-of-00002.safetensors",
139
+ "transformer.h.17.ln_2.weight": "model-00001-of-00002.safetensors",
140
+ "transformer.h.17.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
141
+ "transformer.h.17.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
142
+ "transformer.h.17.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
143
+ "transformer.h.17.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
144
+ "transformer.h.17.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
145
+ "transformer.h.17.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
146
+ "transformer.h.18.attn.c_attn.bias": "model-00001-of-00002.safetensors",
147
+ "transformer.h.18.attn.c_attn.weight": "model-00001-of-00002.safetensors",
148
+ "transformer.h.18.attn.c_proj.bias": "model-00001-of-00002.safetensors",
149
+ "transformer.h.18.attn.c_proj.weight": "model-00001-of-00002.safetensors",
150
+ "transformer.h.18.ln_1.bias": "model-00001-of-00002.safetensors",
151
+ "transformer.h.18.ln_1.weight": "model-00001-of-00002.safetensors",
152
+ "transformer.h.18.ln_2.bias": "model-00001-of-00002.safetensors",
153
+ "transformer.h.18.ln_2.weight": "model-00001-of-00002.safetensors",
154
+ "transformer.h.18.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
155
+ "transformer.h.18.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
156
+ "transformer.h.18.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
157
+ "transformer.h.18.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
158
+ "transformer.h.18.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
159
+ "transformer.h.18.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
160
+ "transformer.h.19.attn.c_attn.bias": "model-00001-of-00002.safetensors",
161
+ "transformer.h.19.attn.c_attn.weight": "model-00001-of-00002.safetensors",
162
+ "transformer.h.19.attn.c_proj.bias": "model-00001-of-00002.safetensors",
163
+ "transformer.h.19.attn.c_proj.weight": "model-00001-of-00002.safetensors",
164
+ "transformer.h.19.ln_1.bias": "model-00001-of-00002.safetensors",
165
+ "transformer.h.19.ln_1.weight": "model-00001-of-00002.safetensors",
166
+ "transformer.h.19.ln_2.bias": "model-00001-of-00002.safetensors",
167
+ "transformer.h.19.ln_2.weight": "model-00001-of-00002.safetensors",
168
+ "transformer.h.19.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
169
+ "transformer.h.19.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
170
+ "transformer.h.19.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
171
+ "transformer.h.19.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
172
+ "transformer.h.19.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
173
+ "transformer.h.19.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
174
+ "transformer.h.2.attn.c_attn.bias": "model-00001-of-00002.safetensors",
175
+ "transformer.h.2.attn.c_attn.weight": "model-00001-of-00002.safetensors",
176
+ "transformer.h.2.attn.c_proj.bias": "model-00001-of-00002.safetensors",
177
+ "transformer.h.2.attn.c_proj.weight": "model-00001-of-00002.safetensors",
178
+ "transformer.h.2.ln_1.bias": "model-00001-of-00002.safetensors",
179
+ "transformer.h.2.ln_1.weight": "model-00001-of-00002.safetensors",
180
+ "transformer.h.2.ln_2.bias": "model-00001-of-00002.safetensors",
181
+ "transformer.h.2.ln_2.weight": "model-00001-of-00002.safetensors",
182
+ "transformer.h.2.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
183
+ "transformer.h.2.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
184
+ "transformer.h.2.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
185
+ "transformer.h.2.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
186
+ "transformer.h.2.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
187
+ "transformer.h.2.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
188
+ "transformer.h.20.attn.c_attn.bias": "model-00001-of-00002.safetensors",
189
+ "transformer.h.20.attn.c_attn.weight": "model-00001-of-00002.safetensors",
190
+ "transformer.h.20.attn.c_proj.bias": "model-00001-of-00002.safetensors",
191
+ "transformer.h.20.attn.c_proj.weight": "model-00001-of-00002.safetensors",
192
+ "transformer.h.20.ln_1.bias": "model-00001-of-00002.safetensors",
193
+ "transformer.h.20.ln_1.weight": "model-00001-of-00002.safetensors",
194
+ "transformer.h.20.ln_2.bias": "model-00001-of-00002.safetensors",
195
+ "transformer.h.20.ln_2.weight": "model-00001-of-00002.safetensors",
196
+ "transformer.h.20.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
197
+ "transformer.h.20.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
198
+ "transformer.h.20.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
199
+ "transformer.h.20.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
200
+ "transformer.h.20.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
201
+ "transformer.h.20.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
202
+ "transformer.h.21.attn.c_attn.bias": "model-00001-of-00002.safetensors",
203
+ "transformer.h.21.attn.c_attn.weight": "model-00001-of-00002.safetensors",
204
+ "transformer.h.21.attn.c_proj.bias": "model-00001-of-00002.safetensors",
205
+ "transformer.h.21.attn.c_proj.weight": "model-00001-of-00002.safetensors",
206
+ "transformer.h.21.ln_1.bias": "model-00001-of-00002.safetensors",
207
+ "transformer.h.21.ln_1.weight": "model-00001-of-00002.safetensors",
208
+ "transformer.h.21.ln_2.bias": "model-00001-of-00002.safetensors",
209
+ "transformer.h.21.ln_2.weight": "model-00001-of-00002.safetensors",
210
+ "transformer.h.21.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
211
+ "transformer.h.21.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
212
+ "transformer.h.21.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
213
+ "transformer.h.21.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
214
+ "transformer.h.21.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
215
+ "transformer.h.21.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
216
+ "transformer.h.22.attn.c_attn.bias": "model-00001-of-00002.safetensors",
217
+ "transformer.h.22.attn.c_attn.weight": "model-00001-of-00002.safetensors",
218
+ "transformer.h.22.attn.c_proj.bias": "model-00001-of-00002.safetensors",
219
+ "transformer.h.22.attn.c_proj.weight": "model-00001-of-00002.safetensors",
220
+ "transformer.h.22.ln_1.bias": "model-00001-of-00002.safetensors",
221
+ "transformer.h.22.ln_1.weight": "model-00001-of-00002.safetensors",
222
+ "transformer.h.22.ln_2.bias": "model-00001-of-00002.safetensors",
223
+ "transformer.h.22.ln_2.weight": "model-00001-of-00002.safetensors",
224
+ "transformer.h.22.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
225
+ "transformer.h.22.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
226
+ "transformer.h.22.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
227
+ "transformer.h.22.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
228
+ "transformer.h.22.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
229
+ "transformer.h.22.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
230
+ "transformer.h.23.attn.c_attn.bias": "model-00001-of-00002.safetensors",
231
+ "transformer.h.23.attn.c_attn.weight": "model-00001-of-00002.safetensors",
232
+ "transformer.h.23.attn.c_proj.bias": "model-00001-of-00002.safetensors",
233
+ "transformer.h.23.attn.c_proj.weight": "model-00001-of-00002.safetensors",
234
+ "transformer.h.23.ln_1.bias": "model-00001-of-00002.safetensors",
235
+ "transformer.h.23.ln_1.weight": "model-00001-of-00002.safetensors",
236
+ "transformer.h.23.ln_2.bias": "model-00001-of-00002.safetensors",
237
+ "transformer.h.23.ln_2.weight": "model-00001-of-00002.safetensors",
238
+ "transformer.h.23.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
239
+ "transformer.h.23.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
240
+ "transformer.h.23.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
241
+ "transformer.h.23.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
242
+ "transformer.h.23.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
243
+ "transformer.h.23.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
244
+ "transformer.h.24.attn.c_attn.bias": "model-00001-of-00002.safetensors",
245
+ "transformer.h.24.attn.c_attn.weight": "model-00001-of-00002.safetensors",
246
+ "transformer.h.24.attn.c_proj.bias": "model-00001-of-00002.safetensors",
247
+ "transformer.h.24.attn.c_proj.weight": "model-00001-of-00002.safetensors",
248
+ "transformer.h.24.ln_1.bias": "model-00001-of-00002.safetensors",
249
+ "transformer.h.24.ln_1.weight": "model-00001-of-00002.safetensors",
250
+ "transformer.h.24.ln_2.bias": "model-00001-of-00002.safetensors",
251
+ "transformer.h.24.ln_2.weight": "model-00001-of-00002.safetensors",
252
+ "transformer.h.24.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
253
+ "transformer.h.24.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
254
+ "transformer.h.24.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
255
+ "transformer.h.24.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
256
+ "transformer.h.24.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
257
+ "transformer.h.24.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
258
+ "transformer.h.25.attn.c_attn.bias": "model-00001-of-00002.safetensors",
259
+ "transformer.h.25.attn.c_attn.weight": "model-00001-of-00002.safetensors",
260
+ "transformer.h.25.attn.c_proj.bias": "model-00001-of-00002.safetensors",
261
+ "transformer.h.25.attn.c_proj.weight": "model-00001-of-00002.safetensors",
262
+ "transformer.h.25.ln_1.bias": "model-00001-of-00002.safetensors",
263
+ "transformer.h.25.ln_1.weight": "model-00001-of-00002.safetensors",
264
+ "transformer.h.25.ln_2.bias": "model-00001-of-00002.safetensors",
265
+ "transformer.h.25.ln_2.weight": "model-00001-of-00002.safetensors",
266
+ "transformer.h.25.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
267
+ "transformer.h.25.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
268
+ "transformer.h.25.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
269
+ "transformer.h.25.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
270
+ "transformer.h.25.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
271
+ "transformer.h.25.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
272
+ "transformer.h.26.attn.c_attn.bias": "model-00001-of-00002.safetensors",
273
+ "transformer.h.26.attn.c_attn.weight": "model-00001-of-00002.safetensors",
274
+ "transformer.h.26.attn.c_proj.bias": "model-00001-of-00002.safetensors",
275
+ "transformer.h.26.attn.c_proj.weight": "model-00001-of-00002.safetensors",
276
+ "transformer.h.26.ln_1.bias": "model-00001-of-00002.safetensors",
277
+ "transformer.h.26.ln_1.weight": "model-00001-of-00002.safetensors",
278
+ "transformer.h.26.ln_2.bias": "model-00001-of-00002.safetensors",
279
+ "transformer.h.26.ln_2.weight": "model-00001-of-00002.safetensors",
280
+ "transformer.h.26.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
281
+ "transformer.h.26.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
282
+ "transformer.h.26.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
283
+ "transformer.h.26.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
284
+ "transformer.h.26.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
285
+ "transformer.h.26.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
286
+ "transformer.h.27.attn.c_attn.bias": "model-00001-of-00002.safetensors",
287
+ "transformer.h.27.attn.c_attn.weight": "model-00001-of-00002.safetensors",
288
+ "transformer.h.27.attn.c_proj.bias": "model-00001-of-00002.safetensors",
289
+ "transformer.h.27.attn.c_proj.weight": "model-00001-of-00002.safetensors",
290
+ "transformer.h.27.ln_1.bias": "model-00001-of-00002.safetensors",
291
+ "transformer.h.27.ln_1.weight": "model-00001-of-00002.safetensors",
292
+ "transformer.h.27.ln_2.bias": "model-00001-of-00002.safetensors",
293
+ "transformer.h.27.ln_2.weight": "model-00001-of-00002.safetensors",
294
+ "transformer.h.27.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
295
+ "transformer.h.27.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
296
+ "transformer.h.27.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
297
+ "transformer.h.27.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
298
+ "transformer.h.27.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
299
+ "transformer.h.27.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
300
+ "transformer.h.28.attn.c_attn.bias": "model-00001-of-00002.safetensors",
301
+ "transformer.h.28.attn.c_attn.weight": "model-00001-of-00002.safetensors",
302
+ "transformer.h.28.attn.c_proj.bias": "model-00001-of-00002.safetensors",
303
+ "transformer.h.28.attn.c_proj.weight": "model-00001-of-00002.safetensors",
304
+ "transformer.h.28.ln_1.bias": "model-00001-of-00002.safetensors",
305
+ "transformer.h.28.ln_1.weight": "model-00001-of-00002.safetensors",
306
+ "transformer.h.28.ln_2.bias": "model-00001-of-00002.safetensors",
307
+ "transformer.h.28.ln_2.weight": "model-00001-of-00002.safetensors",
308
+ "transformer.h.28.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
309
+ "transformer.h.28.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
310
+ "transformer.h.28.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
311
+ "transformer.h.28.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
312
+ "transformer.h.28.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
313
+ "transformer.h.28.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
314
+ "transformer.h.29.attn.c_attn.bias": "model-00001-of-00002.safetensors",
315
+ "transformer.h.29.attn.c_attn.weight": "model-00001-of-00002.safetensors",
316
+ "transformer.h.29.attn.c_proj.bias": "model-00001-of-00002.safetensors",
317
+ "transformer.h.29.attn.c_proj.weight": "model-00001-of-00002.safetensors",
318
+ "transformer.h.29.ln_1.bias": "model-00001-of-00002.safetensors",
319
+ "transformer.h.29.ln_1.weight": "model-00001-of-00002.safetensors",
320
+ "transformer.h.29.ln_2.bias": "model-00001-of-00002.safetensors",
321
+ "transformer.h.29.ln_2.weight": "model-00001-of-00002.safetensors",
322
+ "transformer.h.29.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
323
+ "transformer.h.29.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
324
+ "transformer.h.29.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
325
+ "transformer.h.29.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
326
+ "transformer.h.29.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
327
+ "transformer.h.29.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
328
+ "transformer.h.3.attn.c_attn.bias": "model-00001-of-00002.safetensors",
329
+ "transformer.h.3.attn.c_attn.weight": "model-00001-of-00002.safetensors",
330
+ "transformer.h.3.attn.c_proj.bias": "model-00001-of-00002.safetensors",
331
+ "transformer.h.3.attn.c_proj.weight": "model-00001-of-00002.safetensors",
332
+ "transformer.h.3.ln_1.bias": "model-00001-of-00002.safetensors",
333
+ "transformer.h.3.ln_1.weight": "model-00001-of-00002.safetensors",
334
+ "transformer.h.3.ln_2.bias": "model-00001-of-00002.safetensors",
335
+ "transformer.h.3.ln_2.weight": "model-00001-of-00002.safetensors",
336
+ "transformer.h.3.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
337
+ "transformer.h.3.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
338
+ "transformer.h.3.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
339
+ "transformer.h.3.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
340
+ "transformer.h.3.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
341
+ "transformer.h.3.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
342
+ "transformer.h.30.attn.c_attn.bias": "model-00002-of-00002.safetensors",
343
+ "transformer.h.30.attn.c_attn.weight": "model-00002-of-00002.safetensors",
344
+ "transformer.h.30.attn.c_proj.bias": "model-00002-of-00002.safetensors",
345
+ "transformer.h.30.attn.c_proj.weight": "model-00002-of-00002.safetensors",
346
+ "transformer.h.30.ln_1.bias": "model-00001-of-00002.safetensors",
347
+ "transformer.h.30.ln_1.weight": "model-00001-of-00002.safetensors",
348
+ "transformer.h.30.ln_2.bias": "model-00002-of-00002.safetensors",
349
+ "transformer.h.30.ln_2.weight": "model-00002-of-00002.safetensors",
350
+ "transformer.h.30.mlp.c_fc.bias": "model-00002-of-00002.safetensors",
351
+ "transformer.h.30.mlp.c_fc.weight": "model-00002-of-00002.safetensors",
352
+ "transformer.h.30.mlp.c_fc2.bias": "model-00002-of-00002.safetensors",
353
+ "transformer.h.30.mlp.c_fc2.weight": "model-00002-of-00002.safetensors",
354
+ "transformer.h.30.mlp.c_proj.bias": "model-00002-of-00002.safetensors",
355
+ "transformer.h.30.mlp.c_proj.weight": "model-00002-of-00002.safetensors",
356
+ "transformer.h.31.attn.c_attn.bias": "model-00002-of-00002.safetensors",
357
+ "transformer.h.31.attn.c_attn.weight": "model-00002-of-00002.safetensors",
358
+ "transformer.h.31.attn.c_proj.bias": "model-00002-of-00002.safetensors",
359
+ "transformer.h.31.attn.c_proj.weight": "model-00002-of-00002.safetensors",
360
+ "transformer.h.31.ln_1.bias": "model-00002-of-00002.safetensors",
361
+ "transformer.h.31.ln_1.weight": "model-00002-of-00002.safetensors",
362
+ "transformer.h.31.ln_2.bias": "model-00002-of-00002.safetensors",
363
+ "transformer.h.31.ln_2.weight": "model-00002-of-00002.safetensors",
364
+ "transformer.h.31.mlp.c_fc.bias": "model-00002-of-00002.safetensors",
365
+ "transformer.h.31.mlp.c_fc.weight": "model-00002-of-00002.safetensors",
366
+ "transformer.h.31.mlp.c_fc2.bias": "model-00002-of-00002.safetensors",
367
+ "transformer.h.31.mlp.c_fc2.weight": "model-00002-of-00002.safetensors",
368
+ "transformer.h.31.mlp.c_proj.bias": "model-00002-of-00002.safetensors",
369
+ "transformer.h.31.mlp.c_proj.weight": "model-00002-of-00002.safetensors",
370
+ "transformer.h.4.attn.c_attn.bias": "model-00001-of-00002.safetensors",
371
+ "transformer.h.4.attn.c_attn.weight": "model-00001-of-00002.safetensors",
372
+ "transformer.h.4.attn.c_proj.bias": "model-00001-of-00002.safetensors",
373
+ "transformer.h.4.attn.c_proj.weight": "model-00001-of-00002.safetensors",
374
+ "transformer.h.4.ln_1.bias": "model-00001-of-00002.safetensors",
375
+ "transformer.h.4.ln_1.weight": "model-00001-of-00002.safetensors",
376
+ "transformer.h.4.ln_2.bias": "model-00001-of-00002.safetensors",
377
+ "transformer.h.4.ln_2.weight": "model-00001-of-00002.safetensors",
378
+ "transformer.h.4.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
379
+ "transformer.h.4.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
380
+ "transformer.h.4.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
381
+ "transformer.h.4.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
382
+ "transformer.h.4.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
383
+ "transformer.h.4.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
384
+ "transformer.h.5.attn.c_attn.bias": "model-00001-of-00002.safetensors",
385
+ "transformer.h.5.attn.c_attn.weight": "model-00001-of-00002.safetensors",
386
+ "transformer.h.5.attn.c_proj.bias": "model-00001-of-00002.safetensors",
387
+ "transformer.h.5.attn.c_proj.weight": "model-00001-of-00002.safetensors",
388
+ "transformer.h.5.ln_1.bias": "model-00001-of-00002.safetensors",
389
+ "transformer.h.5.ln_1.weight": "model-00001-of-00002.safetensors",
390
+ "transformer.h.5.ln_2.bias": "model-00001-of-00002.safetensors",
391
+ "transformer.h.5.ln_2.weight": "model-00001-of-00002.safetensors",
392
+ "transformer.h.5.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
393
+ "transformer.h.5.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
394
+ "transformer.h.5.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
395
+ "transformer.h.5.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
396
+ "transformer.h.5.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
397
+ "transformer.h.5.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
398
+ "transformer.h.6.attn.c_attn.bias": "model-00001-of-00002.safetensors",
399
+ "transformer.h.6.attn.c_attn.weight": "model-00001-of-00002.safetensors",
400
+ "transformer.h.6.attn.c_proj.bias": "model-00001-of-00002.safetensors",
401
+ "transformer.h.6.attn.c_proj.weight": "model-00001-of-00002.safetensors",
402
+ "transformer.h.6.ln_1.bias": "model-00001-of-00002.safetensors",
403
+ "transformer.h.6.ln_1.weight": "model-00001-of-00002.safetensors",
404
+ "transformer.h.6.ln_2.bias": "model-00001-of-00002.safetensors",
405
+ "transformer.h.6.ln_2.weight": "model-00001-of-00002.safetensors",
406
+ "transformer.h.6.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
407
+ "transformer.h.6.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
408
+ "transformer.h.6.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
409
+ "transformer.h.6.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
410
+ "transformer.h.6.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
411
+ "transformer.h.6.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
412
+ "transformer.h.7.attn.c_attn.bias": "model-00001-of-00002.safetensors",
413
+ "transformer.h.7.attn.c_attn.weight": "model-00001-of-00002.safetensors",
414
+ "transformer.h.7.attn.c_proj.bias": "model-00001-of-00002.safetensors",
415
+ "transformer.h.7.attn.c_proj.weight": "model-00001-of-00002.safetensors",
416
+ "transformer.h.7.ln_1.bias": "model-00001-of-00002.safetensors",
417
+ "transformer.h.7.ln_1.weight": "model-00001-of-00002.safetensors",
418
+ "transformer.h.7.ln_2.bias": "model-00001-of-00002.safetensors",
419
+ "transformer.h.7.ln_2.weight": "model-00001-of-00002.safetensors",
420
+ "transformer.h.7.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
421
+ "transformer.h.7.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
422
+ "transformer.h.7.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
423
+ "transformer.h.7.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
424
+ "transformer.h.7.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
425
+ "transformer.h.7.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
426
+ "transformer.h.8.attn.c_attn.bias": "model-00001-of-00002.safetensors",
427
+ "transformer.h.8.attn.c_attn.weight": "model-00001-of-00002.safetensors",
428
+ "transformer.h.8.attn.c_proj.bias": "model-00001-of-00002.safetensors",
429
+ "transformer.h.8.attn.c_proj.weight": "model-00001-of-00002.safetensors",
430
+ "transformer.h.8.ln_1.bias": "model-00001-of-00002.safetensors",
431
+ "transformer.h.8.ln_1.weight": "model-00001-of-00002.safetensors",
432
+ "transformer.h.8.ln_2.bias": "model-00001-of-00002.safetensors",
433
+ "transformer.h.8.ln_2.weight": "model-00001-of-00002.safetensors",
434
+ "transformer.h.8.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
435
+ "transformer.h.8.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
436
+ "transformer.h.8.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
437
+ "transformer.h.8.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
438
+ "transformer.h.8.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
439
+ "transformer.h.8.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
440
+ "transformer.h.9.attn.c_attn.bias": "model-00001-of-00002.safetensors",
441
+ "transformer.h.9.attn.c_attn.weight": "model-00001-of-00002.safetensors",
442
+ "transformer.h.9.attn.c_proj.bias": "model-00001-of-00002.safetensors",
443
+ "transformer.h.9.attn.c_proj.weight": "model-00001-of-00002.safetensors",
444
+ "transformer.h.9.ln_1.bias": "model-00001-of-00002.safetensors",
445
+ "transformer.h.9.ln_1.weight": "model-00001-of-00002.safetensors",
446
+ "transformer.h.9.ln_2.bias": "model-00001-of-00002.safetensors",
447
+ "transformer.h.9.ln_2.weight": "model-00001-of-00002.safetensors",
448
+ "transformer.h.9.mlp.c_fc.bias": "model-00001-of-00002.safetensors",
449
+ "transformer.h.9.mlp.c_fc.weight": "model-00001-of-00002.safetensors",
450
+ "transformer.h.9.mlp.c_fc2.bias": "model-00001-of-00002.safetensors",
451
+ "transformer.h.9.mlp.c_fc2.weight": "model-00001-of-00002.safetensors",
452
+ "transformer.h.9.mlp.c_proj.bias": "model-00001-of-00002.safetensors",
453
+ "transformer.h.9.mlp.c_proj.weight": "model-00001-of-00002.safetensors",
454
+ "transformer.ln_f.bias": "model-00002-of-00002.safetensors",
455
+ "transformer.ln_f.weight": "model-00002-of-00002.safetensors",
456
+ "transformer.relative_pe.slopes": "model-00002-of-00002.safetensors",
457
+ "transformer.wte.weight": "model-00001-of-00002.safetensors"
458
+ }
459
+ }
modeling_btlm.py ADDED
@@ -0,0 +1,1594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The OpenAI Team Authors and HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ # Copyright 2023 Cerebras Systems.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """ PyTorch BTLM 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_btlm import BTLMConfig
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+ _CHECKPOINT_FOR_DOC = "cerebras/btlm-3b-8k-base"
52
+ _CONFIG_FOR_DOC = "BTLMConfig"
53
+
54
+ BTLM_PRETRAINED_MODEL_ARCHIVE_LIST = [
55
+ "cerebras/btlm-3b-8k-base",
56
+ # See all BTLM models at https://huggingface.co/models?filter=btlm
57
+ ]
58
+
59
+
60
+ class SwiGLUActivation(nn.Module):
61
+ def forward(self, x1: Tensor, x2: Tensor) -> Tensor:
62
+ return x1 * nn.functional.silu(x2)
63
+
64
+
65
+ class AlibiPositionEmbeddingLayer(nn.Module):
66
+ def __init__(self, num_heads):
67
+ super(AlibiPositionEmbeddingLayer, self).__init__()
68
+
69
+ self.num_heads = num_heads
70
+ slopes = torch.tensor(AlibiPositionEmbeddingLayer._get_alibi_slopes(num_heads)).unsqueeze(-1)
71
+ self.slopes = nn.parameter.Parameter(slopes, requires_grad=False)
72
+
73
+ def forward(
74
+ self,
75
+ seq_length,
76
+ key_length,
77
+ cached_qk_len,
78
+ ):
79
+ context_position = torch.arange(
80
+ cached_qk_len, cached_qk_len + seq_length, device=self.slopes.device
81
+ )[:, None]
82
+ memory_position = torch.arange(
83
+ key_length + cached_qk_len, device=self.slopes.device
84
+ )[None, :]
85
+ relative_position = memory_position - context_position
86
+ relative_position = torch.abs(relative_position).unsqueeze(0).expand(self.num_heads, -1, -1)
87
+ alibi = (self.slopes * -1.0).unsqueeze(1) * relative_position
88
+ return alibi
89
+
90
+ @staticmethod
91
+ def _get_alibi_slopes(n):
92
+ def get_slopes_power_of_2(n):
93
+ start = 2 ** (-(2 ** -(math.log2(n) - 3)))
94
+ ratio = start
95
+ return [start * ratio**i for i in range(n)]
96
+
97
+ if math.log2(n).is_integer():
98
+ return get_slopes_power_of_2(
99
+ n
100
+ ) # In the paper, we only train models that have 2^a heads for some a. This function has
101
+ else: # some good properties that only occur when the input is a power of 2. To maintain that even
102
+ closest_power_of_2 = 2 ** math.floor(
103
+ math.log2(n)
104
+ ) # when the number of heads is not a power of 2, we use this workaround.
105
+ return (
106
+ get_slopes_power_of_2(closest_power_of_2)
107
+ + AlibiPositionEmbeddingLayer._get_alibi_slopes(2 * closest_power_of_2)[0::2][: n - closest_power_of_2]
108
+ )
109
+
110
+
111
+ def load_tf_weights_in_btlm(model, config, btlm_checkpoint_path):
112
+ """Load tf checkpoints in a pytorch model"""
113
+ try:
114
+ import re
115
+
116
+ import tensorflow as tf
117
+ except ImportError:
118
+ logger.error(
119
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
120
+ "https://www.tensorflow.org/install/ for installation instructions."
121
+ )
122
+ raise
123
+ tf_path = os.path.abspath(btlm_checkpoint_path)
124
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
125
+ # Load weights from TF model
126
+ init_vars = tf.train.list_variables(tf_path)
127
+ names = []
128
+ arrays = []
129
+ for name, shape in init_vars:
130
+ logger.info(f"Loading TF weight {name} with shape {shape}")
131
+ array = tf.train.load_variable(tf_path, name)
132
+ names.append(name)
133
+ arrays.append(array.squeeze())
134
+
135
+ for name, array in zip(names, arrays):
136
+ name = name[6:] # skip "model/"
137
+ name = name.split("/")
138
+ pointer = model
139
+ for m_name in name:
140
+ if re.fullmatch(r"[A-Za-z]+\d+", m_name):
141
+ scope_names = re.split(r"(\d+)", m_name)
142
+ else:
143
+ scope_names = [m_name]
144
+ if scope_names[0] == "w" or scope_names[0] == "g":
145
+ pointer = getattr(pointer, "weight")
146
+ elif scope_names[0] == "b":
147
+ pointer = getattr(pointer, "bias")
148
+ elif scope_names[0] == "wpe" or scope_names[0] == "wte":
149
+ pointer = getattr(pointer, scope_names[0])
150
+ pointer = getattr(pointer, "weight")
151
+ else:
152
+ pointer = getattr(pointer, scope_names[0])
153
+ if len(scope_names) >= 2:
154
+ num = int(scope_names[1])
155
+ pointer = pointer[num]
156
+ try:
157
+ assert (
158
+ pointer.shape == array.shape
159
+ ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
160
+ except AssertionError as e:
161
+ e.args += (pointer.shape, array.shape)
162
+ raise
163
+ logger.info(f"Initialize PyTorch weight {name}")
164
+ pointer.data = torch.from_numpy(array)
165
+ return model
166
+
167
+
168
+ class BTLMAttention(nn.Module):
169
+ def __init__(self, config, is_cross_attention=False, layer_idx=None):
170
+ super().__init__()
171
+
172
+ max_positions = config.max_position_embeddings
173
+ self.register_buffer(
174
+ "bias",
175
+ torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
176
+ 1, 1, max_positions, max_positions
177
+ ),
178
+ persistent=False,
179
+ )
180
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
181
+
182
+ self.embed_dim = config.hidden_size
183
+ self.num_heads = config.num_attention_heads
184
+ self.head_dim = self.embed_dim // self.num_heads
185
+ self.split_size = self.embed_dim
186
+ if self.head_dim * self.num_heads != self.embed_dim:
187
+ raise ValueError(
188
+ f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
189
+ f" {self.num_heads})."
190
+ )
191
+
192
+ self.scale_attn_weights = config.scale_attn_weights
193
+ self.is_cross_attention = is_cross_attention
194
+
195
+ # Layer-wise attention scaling, reordering, and upcasting
196
+ self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx
197
+ self.layer_idx = layer_idx
198
+ self.reorder_and_upcast_attn = config.reorder_and_upcast_attn
199
+
200
+ if self.is_cross_attention:
201
+ self.c_attn = Conv1D(2 * self.embed_dim, self.embed_dim)
202
+ self.q_attn = Conv1D(self.embed_dim, self.embed_dim)
203
+ else:
204
+ self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim)
205
+ self.c_proj = Conv1D(self.embed_dim, self.embed_dim)
206
+
207
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
208
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
209
+
210
+ self.pruned_heads = set()
211
+
212
+ self.attn_scale_power = 1.0 if config.mup_scale_qk_dot_by_d else 0.5
213
+
214
+ def prune_heads(self, heads):
215
+ if len(heads) == 0:
216
+ return
217
+ heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, self.head_dim, self.pruned_heads)
218
+ index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
219
+
220
+ # Prune conv1d layers
221
+ self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
222
+ self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
223
+
224
+ # Update hyper params
225
+ self.split_size = (self.split_size // self.num_heads) * (self.num_heads - len(heads))
226
+ self.num_heads = self.num_heads - len(heads)
227
+ self.pruned_heads = self.pruned_heads.union(heads)
228
+
229
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None, position_bias=None):
230
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
231
+
232
+ if self.scale_attn_weights:
233
+ attn_weights = attn_weights / torch.full(
234
+ [], value.size(-1) ** self.attn_scale_power, dtype=attn_weights.dtype, device=attn_weights.device
235
+ )
236
+
237
+ # Layer-wise attention scaling
238
+ if self.scale_attn_by_inverse_layer_idx:
239
+ attn_weights = attn_weights / float(self.layer_idx + 1)
240
+
241
+ if not self.is_cross_attention:
242
+ # if only "normal" attention layer implements causal mask
243
+ query_length, key_length = query.size(-2), key.size(-2)
244
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
245
+ mask_value = torch.finfo(attn_weights.dtype).min
246
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
247
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
248
+ mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
249
+ attn_weights = torch.where(causal_mask, attn_weights.to(attn_weights.dtype), mask_value)
250
+
251
+ if attention_mask is not None:
252
+ # Apply the attention mask
253
+ attn_weights = attn_weights + attention_mask
254
+
255
+ if position_bias is not None:
256
+ attn_weights += position_bias.type_as(attn_weights).unsqueeze(0)
257
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
258
+
259
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
260
+ attn_weights = attn_weights.type(value.dtype)
261
+ attn_weights = self.attn_dropout(attn_weights)
262
+
263
+ # Mask heads if we want to
264
+ if head_mask is not None:
265
+ attn_weights = attn_weights * head_mask
266
+
267
+ attn_output = torch.matmul(attn_weights, value)
268
+
269
+ return attn_output, attn_weights
270
+
271
+ def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None, head_mask=None, position_bias=None):
272
+ # Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM)
273
+ bsz, num_heads, q_seq_len, dk = query.size()
274
+ _, _, k_seq_len, _ = key.size()
275
+
276
+ # Preallocate attn_weights for `baddbmm`
277
+ attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device)
278
+
279
+ # Compute Scale Factor
280
+ scale_factor = 1.0
281
+ if self.scale_attn_weights:
282
+ scale_factor /= float(value.size(-1)) ** self.attn_scale_power
283
+
284
+ if self.scale_attn_by_inverse_layer_idx:
285
+ scale_factor /= float(self.layer_idx + 1)
286
+
287
+ # Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk))
288
+ with autocast(enabled=False):
289
+ q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
290
+ attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor)
291
+ attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
292
+
293
+ if not self.is_cross_attention:
294
+ # if only "normal" attention layer implements causal mask
295
+ query_length, key_length = query.size(-2), key.size(-2)
296
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
297
+ mask_value = torch.finfo(attn_weights.dtype).min
298
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
299
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
300
+ mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
301
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
302
+
303
+ if attention_mask is not None:
304
+ # Apply the attention mask
305
+ attn_weights = attn_weights + attention_mask
306
+
307
+ if position_bias is not None:
308
+ attn_weights += position_bias.type_as(attn_weights).unsqueeze(0)
309
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
310
+
311
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise
312
+ if attn_weights.dtype != torch.float32:
313
+ raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32")
314
+ attn_weights = attn_weights.type(value.dtype)
315
+ attn_weights = self.attn_dropout(attn_weights)
316
+
317
+ # Mask heads if we want to
318
+ if head_mask is not None:
319
+ attn_weights = attn_weights * head_mask
320
+
321
+ attn_output = torch.matmul(attn_weights, value)
322
+
323
+ return attn_output, attn_weights
324
+
325
+ def _split_heads(self, tensor, num_heads, attn_head_size):
326
+ """
327
+ Splits hidden_size dim into attn_head_size and num_heads
328
+ """
329
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
330
+ tensor = tensor.view(new_shape)
331
+ return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
332
+
333
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
334
+ """
335
+ Merges attn_head_size dim and num_attn_heads dim into hidden_size
336
+ """
337
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
338
+ new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
339
+ return tensor.view(new_shape)
340
+
341
+ def forward(
342
+ self,
343
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
344
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
345
+ attention_mask: Optional[torch.FloatTensor] = None,
346
+ head_mask: Optional[torch.FloatTensor] = None,
347
+ encoder_hidden_states: Optional[torch.Tensor] = None,
348
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
349
+ use_cache: Optional[bool] = False,
350
+ output_attentions: Optional[bool] = False,
351
+ position_bias: Optional[torch.FloatTensor] = None,
352
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
353
+ if encoder_hidden_states is not None:
354
+ if not hasattr(self, "q_attn"):
355
+ raise ValueError(
356
+ "If class is used as cross attention, the weights `q_attn` have to be defined. "
357
+ "Please make sure to instantiate class with `BTLMAttention(..., is_cross_attention=True)`."
358
+ )
359
+
360
+ query = self.q_attn(hidden_states)
361
+ key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
362
+ attention_mask = encoder_attention_mask
363
+ else:
364
+ query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
365
+
366
+ query = self._split_heads(query, self.num_heads, self.head_dim)
367
+ key = self._split_heads(key, self.num_heads, self.head_dim)
368
+ value = self._split_heads(value, self.num_heads, self.head_dim)
369
+
370
+ if layer_past is not None:
371
+ past_key, past_value = layer_past
372
+ key = torch.cat((past_key, key), dim=-2)
373
+ value = torch.cat((past_value, value), dim=-2)
374
+
375
+ if use_cache is True:
376
+ present = (key, value)
377
+ else:
378
+ present = None
379
+
380
+ if self.reorder_and_upcast_attn:
381
+ attn_output, attn_weights = self._upcast_and_reordered_attn(
382
+ query, key, value, attention_mask, head_mask, position_bias
383
+ )
384
+ else:
385
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask, position_bias)
386
+
387
+ attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
388
+ attn_output = self.c_proj(attn_output)
389
+ attn_output = self.resid_dropout(attn_output)
390
+
391
+ outputs = (attn_output, present)
392
+ if output_attentions:
393
+ outputs += (attn_weights,)
394
+
395
+ return outputs # a, present, (attentions)
396
+
397
+
398
+ class BTLMMLP(nn.Module):
399
+ def __init__(self, intermediate_size, config):
400
+ super().__init__()
401
+ embed_dim = config.hidden_size
402
+ self.swiglu = config.activation_function == "swiglu"
403
+ self.c_fc = Conv1D(intermediate_size, embed_dim)
404
+ self.c_fc2 = Conv1D(intermediate_size, embed_dim) if self.swiglu else None
405
+ self.c_proj = Conv1D(embed_dim, intermediate_size)
406
+ self.act = SwiGLUActivation() if self.swiglu else ACT2FN[config.activation_function]
407
+ self.dropout = nn.Dropout(config.resid_pdrop)
408
+
409
+ def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor:
410
+ if self.swiglu:
411
+ hidden_states2 = self.c_fc2(hidden_states)
412
+ hidden_states = self.c_fc(hidden_states)
413
+ hidden_states = self.act(hidden_states, hidden_states2) if self.swiglu else self.act(hidden_states)
414
+ hidden_states = self.c_proj(hidden_states)
415
+ hidden_states = self.dropout(hidden_states)
416
+ return hidden_states
417
+
418
+
419
+ class BTLMBlock(nn.Module):
420
+ def __init__(self, config, layer_idx=None):
421
+ super().__init__()
422
+ hidden_size = config.hidden_size
423
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
424
+
425
+ self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
426
+ self.attn = BTLMAttention(config, layer_idx=layer_idx)
427
+ self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
428
+
429
+ if config.add_cross_attention:
430
+ self.crossattention = BTLMAttention(config, is_cross_attention=True, layer_idx=layer_idx)
431
+ self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
432
+
433
+ self.mlp = BTLMMLP(inner_dim, config)
434
+
435
+ def forward(
436
+ self,
437
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
438
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
439
+ attention_mask: Optional[torch.FloatTensor] = None,
440
+ head_mask: Optional[torch.FloatTensor] = None,
441
+ encoder_hidden_states: Optional[torch.Tensor] = None,
442
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
443
+ use_cache: Optional[bool] = False,
444
+ output_attentions: Optional[bool] = False,
445
+ position_bias: Optional[torch.FloatTensor] = None,
446
+ ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
447
+ residual = hidden_states
448
+ hidden_states = self.ln_1(hidden_states)
449
+ attn_outputs = self.attn(
450
+ hidden_states,
451
+ layer_past=layer_past,
452
+ attention_mask=attention_mask,
453
+ head_mask=head_mask,
454
+ use_cache=use_cache,
455
+ output_attentions=output_attentions,
456
+ position_bias=position_bias,
457
+ )
458
+ attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
459
+ outputs = attn_outputs[1:]
460
+ # residual connection
461
+ hidden_states = attn_output + residual
462
+
463
+ if encoder_hidden_states is not None:
464
+ # add one self-attention block for cross-attention
465
+ if not hasattr(self, "crossattention"):
466
+ raise ValueError(
467
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
468
+ "cross-attention layers by setting `config.add_cross_attention=True`"
469
+ )
470
+ residual = hidden_states
471
+ hidden_states = self.ln_cross_attn(hidden_states)
472
+ cross_attn_outputs = self.crossattention(
473
+ hidden_states,
474
+ attention_mask=attention_mask,
475
+ head_mask=head_mask,
476
+ encoder_hidden_states=encoder_hidden_states,
477
+ encoder_attention_mask=encoder_attention_mask,
478
+ output_attentions=output_attentions,
479
+ position_bias=position_bias,
480
+ )
481
+ attn_output = cross_attn_outputs[0]
482
+ # residual connection
483
+ hidden_states = residual + attn_output
484
+ outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
485
+
486
+ residual = hidden_states
487
+ hidden_states = self.ln_2(hidden_states)
488
+ feed_forward_hidden_states = self.mlp(hidden_states)
489
+ # residual connection
490
+ hidden_states = residual + feed_forward_hidden_states
491
+
492
+ if use_cache:
493
+ outputs = (hidden_states,) + outputs
494
+ else:
495
+ outputs = (hidden_states,) + outputs[1:]
496
+
497
+ return outputs # hidden_states, present, (attentions, cross_attentions)
498
+
499
+
500
+ class BTLMPreTrainedModel(PreTrainedModel):
501
+ """
502
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
503
+ models.
504
+ """
505
+
506
+ config_class = BTLMConfig
507
+ load_tf_weights = load_tf_weights_in_btlm
508
+ base_model_prefix = "transformer"
509
+ is_parallelizable = True
510
+ supports_gradient_checkpointing = True
511
+ _no_split_modules = ["BTLMBlock"]
512
+ _skip_keys_device_placement = "past_key_values"
513
+
514
+ def __init__(self, *inputs, **kwargs):
515
+ super().__init__(*inputs, **kwargs)
516
+
517
+ def _init_weights(self, module):
518
+ """Initialize the weights."""
519
+ mup_init_scale = math.sqrt(self.config.mup_width_scale)
520
+ if isinstance(module, (nn.Linear, Conv1D)):
521
+ # Slightly different from the TF version which uses truncated_normal for initialization
522
+ # cf https://github.com/pytorch/pytorch/pull/5617
523
+ module.weight.data.normal_(mean=0.0, std=(self.config.initializer_range * mup_init_scale))
524
+ if module.bias is not None:
525
+ module.bias.data.zero_()
526
+ elif isinstance(module, nn.Embedding):
527
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
528
+ if module.padding_idx is not None:
529
+ module.weight.data[module.padding_idx].zero_()
530
+ elif isinstance(module, nn.LayerNorm):
531
+ module.bias.data.zero_()
532
+ module.weight.data.fill_(1.0)
533
+
534
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
535
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
536
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
537
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
538
+ #
539
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
540
+ for name, p in module.named_parameters():
541
+ if name == "c_proj.weight":
542
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
543
+ stddev = self.config.initializer_range * mup_init_scale / math.sqrt(2 * self.config.n_layer)
544
+ p.data.normal_(mean=0.0, std=stddev)
545
+
546
+ def _set_gradient_checkpointing(self, module, value=False):
547
+ if isinstance(module, BTLMModel):
548
+ module.gradient_checkpointing = value
549
+
550
+ def get_mup_param_groups(self, lr, weight_decay=0.0, decoupled_wd=True):
551
+ """
552
+ Returns list of dicts defining parameter groups for muP:
553
+ group 0: most model params get scaled learning rate and weight decay.
554
+ group 1: embedding layer gets non-scaled learning rate and weight decay.
555
+ group 2: normalization layers and biases get non-scaled learning rate only.
556
+
557
+ The output can be passed to Adam-base optimizers
558
+ e.g.
559
+ param_groups = model.get_mup_param_groups(lr=1e-3, weight_decay=0.1)
560
+ torch.optim.AdamW(param_groups, betas=(0.9, 0.95), eps=1e-8)
561
+ """
562
+ norm_modules = (
563
+ torch.nn.LayerNorm,
564
+ torch.nn.BatchNorm1d,
565
+ torch.nn.BatchNorm2d,
566
+ torch.nn.BatchNorm3d,
567
+ torch.nn.InstanceNorm1d,
568
+ torch.nn.InstanceNorm2d,
569
+ torch.nn.InstanceNorm3d,
570
+ torch.nn.GroupNorm,
571
+ torch.nn.SyncBatchNorm,
572
+ torch.nn.LocalResponseNorm,
573
+ )
574
+
575
+ def get_group_index(param_name):
576
+ for name, module in self.named_modules():
577
+ if name in param_name:
578
+ if isinstance(module, norm_modules):
579
+ return 2
580
+ elif isinstance(module, torch.nn.Embedding):
581
+ return 1
582
+ return 0
583
+
584
+ width_scale = self.config.mup_width_scale
585
+ new_param_groups = []
586
+ new_param_groups.append({"params": [], "lr": lr * width_scale, "weight_decay": weight_decay})
587
+ if not decoupled_wd:
588
+ new_param_groups[0]["weight_decay"] /= width_scale
589
+ new_param_groups.append({"params": [], "lr": lr, "weight_decay": weight_decay})
590
+ new_param_groups.append({"params": [], "lr": lr, "weight_decay": 0.0})
591
+
592
+ for name, param in self.named_parameters():
593
+ if not param.requires_grad:
594
+ continue
595
+
596
+ if name.endswith("bias"):
597
+ new_param_groups[2]["params"].append(param)
598
+ else:
599
+ new_param_groups[get_group_index(name)]["params"].append(param)
600
+
601
+ for idx, param_group in enumerate(new_param_groups):
602
+ if len(param_group["params"]) == 0:
603
+ del new_param_groups[idx]
604
+
605
+ return new_param_groups
606
+
607
+
608
+ BTLM_START_DOCSTRING = r"""
609
+
610
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
611
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
612
+ etc.)
613
+
614
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
615
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
616
+ and behavior.
617
+
618
+ Parameters:
619
+ config ([`BTLMConfig`]): Model configuration class with all the parameters of the model.
620
+ Initializing with a config file does not load the weights associated with the model, only the
621
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
622
+ """
623
+
624
+ BTLM_INPUTS_DOCSTRING = r"""
625
+ Args:
626
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
627
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
628
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
629
+ sequence tokens in the vocabulary.
630
+
631
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
632
+ `input_ids`.
633
+
634
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
635
+ [`PreTrainedTokenizer.__call__`] for details.
636
+
637
+ [What are input IDs?](../glossary#input-ids)
638
+ past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
639
+ Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
640
+ `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
641
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
642
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
643
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
644
+
645
+ - 1 for tokens that are **not masked**,
646
+ - 0 for tokens that are **masked**.
647
+
648
+ If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
649
+ `past_key_values`. In other words, the `attention_mask` always has to have the length:
650
+ `len(past_key_values) + len(input_ids)`
651
+
652
+ [What are attention masks?](../glossary#attention-mask)
653
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
654
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
655
+ 1]`:
656
+
657
+ - 0 corresponds to a *sentence A* token,
658
+ - 1 corresponds to a *sentence B* token.
659
+
660
+ [What are token type IDs?](../glossary#token-type-ids)
661
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
662
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
663
+ config.max_position_embeddings - 1]`.
664
+
665
+ [What are position IDs?](../glossary#position-ids)
666
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
667
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
668
+
669
+ - 1 indicates the head is **not masked**,
670
+ - 0 indicates the head is **masked**.
671
+
672
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
673
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
674
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
675
+ model's internal embedding lookup matrix.
676
+
677
+ If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
678
+ `past_key_values`).
679
+ use_cache (`bool`, *optional*):
680
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
681
+ `past_key_values`).
682
+ output_attentions (`bool`, *optional*):
683
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
684
+ tensors for more detail.
685
+ output_hidden_states (`bool`, *optional*):
686
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
687
+ more detail.
688
+ return_dict (`bool`, *optional*):
689
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
690
+ """
691
+ PARALLELIZE_DOCSTRING = r"""
692
+ This is an experimental feature and is a subject to change at a moment's notice.
693
+
694
+ Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
695
+ it will evenly distribute blocks across all devices.
696
+
697
+ Args:
698
+ device_map (`Dict[int, list]`, optional, defaults to None):
699
+ A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
700
+ automatically mapped to the first device (for esoteric reasons). That means that the first device should
701
+ have fewer attention modules mapped to it than other devices. For reference, the gpt2 models have the
702
+ following number of attention modules:
703
+
704
+ - gpt2: 12
705
+ - gpt2-medium: 24
706
+ - gpt2-large: 36
707
+ - gpt2-xl: 48
708
+
709
+ Example:
710
+
711
+ ```python
712
+ # 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:
713
+ model = GPT2LMHeadModel.from_pretrained("gpt2-xl")
714
+ device_map = {
715
+ 0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
716
+ 1: [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
717
+ 2: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34],
718
+ 3: [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],
719
+ }
720
+ model.parallelize(device_map)
721
+ ```
722
+ """
723
+ DEPARALLELIZE_DOCSTRING = r"""
724
+ Moves the model to cpu from a model parallel state.
725
+
726
+ Example:
727
+
728
+ ```python
729
+ # On a 4 GPU machine with gpt2-large:
730
+ model = GPT2LMHeadModel.from_pretrained("gpt2-large")
731
+ device_map = {
732
+ 0: [0, 1, 2, 3, 4, 5, 6, 7],
733
+ 1: [8, 9, 10, 11, 12, 13, 14, 15],
734
+ 2: [16, 17, 18, 19, 20, 21, 22, 23],
735
+ 3: [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],
736
+ }
737
+ model.parallelize(device_map) # Splits the model across several devices
738
+ model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
739
+ ```
740
+ """
741
+
742
+
743
+ @add_start_docstrings(
744
+ "The bare BTLM Model transformer outputting raw hidden-states without any specific head on top.",
745
+ BTLM_START_DOCSTRING,
746
+ )
747
+ class BTLMModel(BTLMPreTrainedModel):
748
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
749
+ _keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias"]
750
+
751
+ def __init__(self, config):
752
+ super().__init__(config)
753
+
754
+ self.embed_dim = config.hidden_size
755
+
756
+ self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
757
+ self.wpe = (
758
+ nn.Embedding(config.max_position_embeddings, self.embed_dim)
759
+ if config.position_embedding_type != "alibi"
760
+ else None
761
+ )
762
+ self.embeddings_scale = config.mup_embeddings_scale
763
+
764
+ self.drop = nn.Dropout(config.embd_pdrop)
765
+ self.h = nn.ModuleList([BTLMBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
766
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
767
+
768
+ self.relative_pe = (
769
+ AlibiPositionEmbeddingLayer(config.num_attention_heads)
770
+ if config.position_embedding_type == "alibi"
771
+ else None
772
+ )
773
+
774
+ # Model parallel
775
+ self.model_parallel = False
776
+ self.device_map = None
777
+ self.gradient_checkpointing = False
778
+
779
+ # Initialize weights and apply final processing
780
+ self.post_init()
781
+
782
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
783
+ def parallelize(self, device_map=None):
784
+ # Check validity of device_map
785
+ warnings.warn(
786
+ "`BTLMModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load your"
787
+ " model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
788
+ " `device_map` but it needs to be a dictionary module_name to device, so for instance {'h.0': 0, 'h.1': 1,"
789
+ " ...}",
790
+ FutureWarning,
791
+ )
792
+ self.device_map = (
793
+ get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map
794
+ )
795
+ assert_device_map(self.device_map, len(self.h))
796
+ self.model_parallel = True
797
+ self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys()))
798
+ self.last_device = "cuda:" + str(max(self.device_map.keys()))
799
+ self.wte = self.wte.to(self.first_device)
800
+ if self.wpe is not None:
801
+ self.wpe = self.wpe.to(self.first_device)
802
+ # Load onto devices
803
+ for k, v in self.device_map.items():
804
+ for block in v:
805
+ cuda_device = "cuda:" + str(k)
806
+ self.h[block] = self.h[block].to(cuda_device)
807
+ # ln_f to last
808
+ self.ln_f = self.ln_f.to(self.last_device)
809
+
810
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
811
+ def deparallelize(self):
812
+ warnings.warn(
813
+ "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
814
+ FutureWarning,
815
+ )
816
+ self.model_parallel = False
817
+ self.device_map = None
818
+ self.first_device = "cpu"
819
+ self.last_device = "cpu"
820
+ self.wte = self.wte.to("cpu")
821
+ if self.wpe is not None:
822
+ self.wpe = self.wpe.to("cpu")
823
+ for index in range(len(self.h)):
824
+ self.h[index] = self.h[index].to("cpu")
825
+ self.ln_f = self.ln_f.to("cpu")
826
+ torch.cuda.empty_cache()
827
+
828
+ def get_input_embeddings(self):
829
+ return self.wte
830
+
831
+ def set_input_embeddings(self, new_embeddings):
832
+ self.wte = new_embeddings
833
+
834
+ def _prune_heads(self, heads_to_prune):
835
+ """
836
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
837
+ """
838
+ for layer, heads in heads_to_prune.items():
839
+ self.h[layer].attn.prune_heads(heads)
840
+
841
+ @add_start_docstrings_to_model_forward(BTLM_INPUTS_DOCSTRING)
842
+ @add_code_sample_docstrings(
843
+ checkpoint=_CHECKPOINT_FOR_DOC,
844
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
845
+ config_class=_CONFIG_FOR_DOC,
846
+ )
847
+ def forward(
848
+ self,
849
+ input_ids: Optional[torch.LongTensor] = None,
850
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
851
+ attention_mask: Optional[torch.FloatTensor] = None,
852
+ token_type_ids: Optional[torch.LongTensor] = None,
853
+ position_ids: Optional[torch.LongTensor] = None,
854
+ head_mask: Optional[torch.FloatTensor] = None,
855
+ inputs_embeds: Optional[torch.FloatTensor] = None,
856
+ encoder_hidden_states: Optional[torch.Tensor] = None,
857
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
858
+ use_cache: Optional[bool] = None,
859
+ output_attentions: Optional[bool] = None,
860
+ output_hidden_states: Optional[bool] = None,
861
+ return_dict: Optional[bool] = None,
862
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
863
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
864
+ output_hidden_states = (
865
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
866
+ )
867
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
868
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
869
+
870
+ if input_ids is not None and inputs_embeds is not None:
871
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
872
+ elif input_ids is not None:
873
+ input_shape = input_ids.size()
874
+ input_ids = input_ids.view(-1, input_shape[-1])
875
+ batch_size = input_ids.shape[0]
876
+ elif inputs_embeds is not None:
877
+ input_shape = inputs_embeds.size()[:-1]
878
+ batch_size = inputs_embeds.shape[0]
879
+ else:
880
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
881
+
882
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
883
+
884
+ if token_type_ids is not None:
885
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
886
+ if position_ids is not None:
887
+ position_ids = position_ids.view(-1, input_shape[-1])
888
+
889
+ if past_key_values is None:
890
+ past_length = 0
891
+ past_key_values = tuple([None] * len(self.h))
892
+ else:
893
+ past_length = past_key_values[0][0].size(-2)
894
+ if position_ids is None:
895
+ position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
896
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
897
+
898
+ # BTLMAttention mask.
899
+ if attention_mask is not None:
900
+ if batch_size <= 0:
901
+ raise ValueError("batch_size has to be defined and > 0")
902
+ attention_mask = attention_mask.view(batch_size, -1)
903
+ # We create a 3D attention mask from a 2D tensor mask.
904
+ # Sizes are [batch_size, 1, 1, to_seq_length]
905
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
906
+ # this attention mask is more simple than the triangular masking of causal attention
907
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
908
+ attention_mask = attention_mask[:, None, None, :]
909
+
910
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
911
+ # masked positions, this operation will create a tensor which is 0.0 for
912
+ # positions we want to attend and the dtype's smallest value for masked positions.
913
+ # Since we are adding it to the raw scores before the softmax, this is
914
+ # effectively the same as removing these entirely.
915
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
916
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
917
+
918
+ # If a 2D or 3D attention mask is provided for the cross-attention
919
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
920
+ if self.config.add_cross_attention and encoder_hidden_states is not None:
921
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
922
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
923
+ if encoder_attention_mask is None:
924
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
925
+ encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
926
+ else:
927
+ encoder_attention_mask = None
928
+
929
+ # Prepare head mask if needed
930
+ # 1.0 in head_mask indicate we keep the head
931
+ # attention_probs has shape bsz x n_heads x N x N
932
+ # head_mask has shape n_layer x batch x n_heads x N x N
933
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
934
+
935
+ if inputs_embeds is None:
936
+ inputs_embeds = self.wte(input_ids)
937
+ if self.wpe is not None:
938
+ position_embeds = self.wpe(position_ids)
939
+ hidden_states = inputs_embeds + position_embeds
940
+ else:
941
+ hidden_states = inputs_embeds
942
+ hidden_states *= torch.tensor(
943
+ float(self.embeddings_scale), dtype=hidden_states.dtype, device=hidden_states.device
944
+ )
945
+
946
+ if token_type_ids is not None:
947
+ token_type_embeds = self.wte(token_type_ids)
948
+ hidden_states = hidden_states + token_type_embeds
949
+
950
+ hidden_states = self.drop(hidden_states)
951
+
952
+ if self.relative_pe is not None:
953
+ length = input_ids.shape[1]
954
+ cached_kv_length = 0
955
+ cached_kv = past_key_values[0]
956
+ if cached_kv is not None:
957
+ cached_kv_length = cached_kv[0].shape[-2]
958
+ position_bias = self.relative_pe(length, length, cached_kv_length)
959
+ else:
960
+ position_bias = None
961
+
962
+ output_shape = input_shape + (hidden_states.size(-1),)
963
+
964
+ if self.gradient_checkpointing and self.training:
965
+ if use_cache:
966
+ logger.warning_once(
967
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
968
+ )
969
+ use_cache = False
970
+
971
+ presents = () if use_cache else None
972
+ all_self_attentions = () if output_attentions else None
973
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
974
+ all_hidden_states = () if output_hidden_states else None
975
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
976
+ # Model parallel
977
+ if self.model_parallel:
978
+ torch.cuda.set_device(hidden_states.device)
979
+ # Ensure layer_past is on same device as hidden_states (might not be correct)
980
+ if layer_past is not None:
981
+ layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
982
+ # Ensure that attention_mask is always on the same device as hidden_states
983
+ if attention_mask is not None:
984
+ attention_mask = attention_mask.to(hidden_states.device)
985
+ if isinstance(head_mask, torch.Tensor):
986
+ head_mask = head_mask.to(hidden_states.device)
987
+ if output_hidden_states:
988
+ all_hidden_states = all_hidden_states + (hidden_states,)
989
+
990
+ if self.gradient_checkpointing and self.training:
991
+
992
+ def create_custom_forward(module):
993
+ def custom_forward(*inputs):
994
+ # None for past_key_value
995
+ return module(*inputs, use_cache, output_attentions)
996
+
997
+ return custom_forward
998
+
999
+ outputs = torch.utils.checkpoint.checkpoint(
1000
+ create_custom_forward(block),
1001
+ hidden_states,
1002
+ None,
1003
+ attention_mask,
1004
+ head_mask[i],
1005
+ encoder_hidden_states,
1006
+ encoder_attention_mask,
1007
+ )
1008
+ else:
1009
+ outputs = block(
1010
+ hidden_states,
1011
+ layer_past=layer_past,
1012
+ attention_mask=attention_mask,
1013
+ head_mask=head_mask[i],
1014
+ encoder_hidden_states=encoder_hidden_states,
1015
+ encoder_attention_mask=encoder_attention_mask,
1016
+ use_cache=use_cache,
1017
+ output_attentions=output_attentions,
1018
+ position_bias=position_bias,
1019
+ )
1020
+
1021
+ hidden_states = outputs[0]
1022
+ if use_cache is True:
1023
+ presents = presents + (outputs[1],)
1024
+
1025
+ if output_attentions:
1026
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
1027
+ if self.config.add_cross_attention:
1028
+ all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
1029
+
1030
+ # Model Parallel: If it's the last layer for that device, put things on the next device
1031
+ if self.model_parallel:
1032
+ for k, v in self.device_map.items():
1033
+ if i == v[-1] and "cuda:" + str(k) != self.last_device:
1034
+ hidden_states = hidden_states.to("cuda:" + str(k + 1))
1035
+
1036
+ hidden_states = self.ln_f(hidden_states)
1037
+
1038
+ hidden_states = hidden_states.view(output_shape)
1039
+ # Add last hidden state
1040
+ if output_hidden_states:
1041
+ all_hidden_states = all_hidden_states + (hidden_states,)
1042
+
1043
+ if not return_dict:
1044
+ return tuple(
1045
+ v
1046
+ for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions]
1047
+ if v is not None
1048
+ )
1049
+
1050
+ return BaseModelOutputWithPastAndCrossAttentions(
1051
+ last_hidden_state=hidden_states,
1052
+ past_key_values=presents,
1053
+ hidden_states=all_hidden_states,
1054
+ attentions=all_self_attentions,
1055
+ cross_attentions=all_cross_attentions,
1056
+ )
1057
+
1058
+
1059
+ @add_start_docstrings(
1060
+ """
1061
+ The BTLM Model transformer with a language modeling head on top (linear layer with weights tied to the input
1062
+ embeddings).
1063
+ """,
1064
+ BTLM_START_DOCSTRING,
1065
+ )
1066
+ class BTLMLMHeadModel(BTLMPreTrainedModel):
1067
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
1068
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias"]
1069
+
1070
+ def __init__(self, config):
1071
+ super().__init__(config)
1072
+ self.transformer = BTLMModel(config)
1073
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
1074
+ self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
1075
+
1076
+ # Model parallel
1077
+ self.model_parallel = False
1078
+ self.device_map = None
1079
+
1080
+ # Initialize weights and apply final processing
1081
+ self.post_init()
1082
+
1083
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
1084
+ def parallelize(self, device_map=None):
1085
+ warnings.warn(
1086
+ "`BTLMLMHeadModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load"
1087
+ " your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
1088
+ " `device_map` but it needs to be a dictionary module_name to device, so for instance {'transformer.h.0':"
1089
+ " 0, 'transformer.h.1': 1, ...}",
1090
+ FutureWarning,
1091
+ )
1092
+ self.device_map = (
1093
+ get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
1094
+ if device_map is None
1095
+ else device_map
1096
+ )
1097
+ assert_device_map(self.device_map, len(self.transformer.h))
1098
+ self.transformer.parallelize(self.device_map)
1099
+ self.lm_head = self.lm_head.to(self.transformer.first_device)
1100
+ self.model_parallel = True
1101
+
1102
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1103
+ def deparallelize(self):
1104
+ warnings.warn(
1105
+ "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
1106
+ FutureWarning,
1107
+ )
1108
+ self.transformer.deparallelize()
1109
+ self.transformer = self.transformer.to("cpu")
1110
+ self.lm_head = self.lm_head.to("cpu")
1111
+ self.model_parallel = False
1112
+ torch.cuda.empty_cache()
1113
+
1114
+ def get_output_embeddings(self):
1115
+ return self.lm_head
1116
+
1117
+ def set_output_embeddings(self, new_embeddings):
1118
+ self.lm_head = new_embeddings
1119
+
1120
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
1121
+ token_type_ids = kwargs.get("token_type_ids", None)
1122
+ # only last token for inputs_ids if past is defined in kwargs
1123
+ if past_key_values:
1124
+ input_ids = input_ids[:, -1].unsqueeze(-1)
1125
+ if token_type_ids is not None:
1126
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
1127
+
1128
+ attention_mask = kwargs.get("attention_mask", None)
1129
+ position_ids = kwargs.get("position_ids", None)
1130
+
1131
+ if attention_mask is not None and position_ids is None:
1132
+ # create position_ids on the fly for batch generation
1133
+ position_ids = attention_mask.long().cumsum(-1) - 1
1134
+ position_ids.masked_fill_(attention_mask == 0, 1)
1135
+ if past_key_values:
1136
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1137
+ else:
1138
+ position_ids = None
1139
+
1140
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1141
+ if inputs_embeds is not None and past_key_values is None:
1142
+ model_inputs = {"inputs_embeds": inputs_embeds}
1143
+ else:
1144
+ model_inputs = {"input_ids": input_ids}
1145
+
1146
+ model_inputs.update(
1147
+ {
1148
+ "past_key_values": past_key_values,
1149
+ "use_cache": kwargs.get("use_cache"),
1150
+ "position_ids": position_ids,
1151
+ "attention_mask": attention_mask,
1152
+ "token_type_ids": token_type_ids,
1153
+ }
1154
+ )
1155
+ return model_inputs
1156
+
1157
+ @add_start_docstrings_to_model_forward(BTLM_INPUTS_DOCSTRING)
1158
+ @add_code_sample_docstrings(
1159
+ checkpoint=_CHECKPOINT_FOR_DOC,
1160
+ output_type=CausalLMOutputWithCrossAttentions,
1161
+ config_class=_CONFIG_FOR_DOC,
1162
+ )
1163
+ def forward(
1164
+ self,
1165
+ input_ids: Optional[torch.LongTensor] = None,
1166
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1167
+ attention_mask: Optional[torch.FloatTensor] = None,
1168
+ token_type_ids: Optional[torch.LongTensor] = None,
1169
+ position_ids: Optional[torch.LongTensor] = None,
1170
+ head_mask: Optional[torch.FloatTensor] = None,
1171
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1172
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1173
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1174
+ labels: Optional[torch.LongTensor] = None,
1175
+ use_cache: Optional[bool] = None,
1176
+ output_attentions: Optional[bool] = None,
1177
+ output_hidden_states: Optional[bool] = None,
1178
+ return_dict: Optional[bool] = None,
1179
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1180
+ r"""
1181
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1182
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1183
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1184
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1185
+ """
1186
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1187
+
1188
+ transformer_outputs = self.transformer(
1189
+ input_ids,
1190
+ past_key_values=past_key_values,
1191
+ attention_mask=attention_mask,
1192
+ token_type_ids=token_type_ids,
1193
+ position_ids=position_ids,
1194
+ head_mask=head_mask,
1195
+ inputs_embeds=inputs_embeds,
1196
+ encoder_hidden_states=encoder_hidden_states,
1197
+ encoder_attention_mask=encoder_attention_mask,
1198
+ use_cache=use_cache,
1199
+ output_attentions=output_attentions,
1200
+ output_hidden_states=output_hidden_states,
1201
+ return_dict=return_dict,
1202
+ )
1203
+ hidden_states = transformer_outputs[0]
1204
+
1205
+ # Set device for model parallelism
1206
+ if self.model_parallel:
1207
+ torch.cuda.set_device(self.transformer.first_device)
1208
+ hidden_states = hidden_states.to(self.lm_head.weight.device)
1209
+
1210
+ lm_logits = self.lm_head(hidden_states)
1211
+ lm_logits *= torch.tensor(float(self.output_logits_scale), dtype=lm_logits.dtype, device=lm_logits.device)
1212
+
1213
+ loss = None
1214
+ if labels is not None:
1215
+ # move labels to correct device to enable model parallelism
1216
+ labels = labels.to(lm_logits.device)
1217
+ # Shift so that tokens < n predict n
1218
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1219
+ shift_labels = labels[..., 1:].contiguous()
1220
+ # Flatten the tokens
1221
+ loss_fct = CrossEntropyLoss()
1222
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1223
+
1224
+ if not return_dict:
1225
+ output = (lm_logits,) + transformer_outputs[1:]
1226
+ return ((loss,) + output) if loss is not None else output
1227
+
1228
+ return CausalLMOutputWithCrossAttentions(
1229
+ loss=loss,
1230
+ logits=lm_logits,
1231
+ past_key_values=transformer_outputs.past_key_values,
1232
+ hidden_states=transformer_outputs.hidden_states,
1233
+ attentions=transformer_outputs.attentions,
1234
+ cross_attentions=transformer_outputs.cross_attentions,
1235
+ )
1236
+
1237
+ @staticmethod
1238
+ def _reorder_cache(
1239
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1240
+ ) -> Tuple[Tuple[torch.Tensor]]:
1241
+ """
1242
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1243
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1244
+ beam_idx at every generation step.
1245
+ """
1246
+ return tuple(
1247
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1248
+ for layer_past in past_key_values
1249
+ )
1250
+
1251
+
1252
+ @add_start_docstrings(
1253
+ """
1254
+ The BTLM Model transformer with a sequence classification head on top (linear layer).
1255
+
1256
+ [`BTLMForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1257
+ (e.g. GPT-1) do.
1258
+
1259
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1260
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1261
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1262
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1263
+ each row of the batch).
1264
+ """,
1265
+ BTLM_START_DOCSTRING,
1266
+ )
1267
+ class BTLMForSequenceClassification(BTLMPreTrainedModel):
1268
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
1269
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"lm_head.weight"]
1270
+
1271
+ def __init__(self, config):
1272
+ super().__init__(config)
1273
+ self.num_labels = config.num_labels
1274
+ self.transformer = BTLMModel(config)
1275
+ self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
1276
+ self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
1277
+
1278
+ # Model parallel
1279
+ self.model_parallel = False
1280
+ self.device_map = None
1281
+
1282
+ # Initialize weights and apply final processing
1283
+ self.post_init()
1284
+
1285
+ @add_start_docstrings_to_model_forward(BTLM_INPUTS_DOCSTRING)
1286
+ @add_code_sample_docstrings(
1287
+ checkpoint="microsoft/DialogRPT-updown",
1288
+ output_type=SequenceClassifierOutputWithPast,
1289
+ config_class=_CONFIG_FOR_DOC,
1290
+ )
1291
+ def forward(
1292
+ self,
1293
+ input_ids: Optional[torch.LongTensor] = None,
1294
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1295
+ attention_mask: Optional[torch.FloatTensor] = None,
1296
+ token_type_ids: Optional[torch.LongTensor] = None,
1297
+ position_ids: Optional[torch.LongTensor] = None,
1298
+ head_mask: Optional[torch.FloatTensor] = None,
1299
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1300
+ labels: Optional[torch.LongTensor] = None,
1301
+ use_cache: Optional[bool] = None,
1302
+ output_attentions: Optional[bool] = None,
1303
+ output_hidden_states: Optional[bool] = None,
1304
+ return_dict: Optional[bool] = None,
1305
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1306
+ r"""
1307
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1308
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1309
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1310
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1311
+ """
1312
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1313
+
1314
+ transformer_outputs = self.transformer(
1315
+ input_ids,
1316
+ past_key_values=past_key_values,
1317
+ attention_mask=attention_mask,
1318
+ token_type_ids=token_type_ids,
1319
+ position_ids=position_ids,
1320
+ head_mask=head_mask,
1321
+ inputs_embeds=inputs_embeds,
1322
+ use_cache=use_cache,
1323
+ output_attentions=output_attentions,
1324
+ output_hidden_states=output_hidden_states,
1325
+ return_dict=return_dict,
1326
+ )
1327
+ hidden_states = transformer_outputs[0]
1328
+ logits = self.score(hidden_states)
1329
+ logits *= torch.tensor(float(self.output_logits_scale), dtype=logits.dtype, device=logits.device)
1330
+
1331
+ if input_ids is not None:
1332
+ batch_size, sequence_length = input_ids.shape[:2]
1333
+ else:
1334
+ batch_size, sequence_length = inputs_embeds.shape[:2]
1335
+
1336
+ assert (
1337
+ self.config.pad_token_id is not None or batch_size == 1
1338
+ ), "Cannot handle batch sizes > 1 if no padding token is defined."
1339
+ if self.config.pad_token_id is None:
1340
+ sequence_lengths = -1
1341
+ else:
1342
+ if input_ids is not None:
1343
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
1344
+ else:
1345
+ sequence_lengths = -1
1346
+ logger.warning(
1347
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1348
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1349
+ )
1350
+
1351
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1352
+
1353
+ loss = None
1354
+ if labels is not None:
1355
+ if self.config.problem_type is None:
1356
+ if self.num_labels == 1:
1357
+ self.config.problem_type = "regression"
1358
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1359
+ self.config.problem_type = "single_label_classification"
1360
+ else:
1361
+ self.config.problem_type = "multi_label_classification"
1362
+
1363
+ if self.config.problem_type == "regression":
1364
+ loss_fct = MSELoss()
1365
+ if self.num_labels == 1:
1366
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1367
+ else:
1368
+ loss = loss_fct(pooled_logits, labels)
1369
+ elif self.config.problem_type == "single_label_classification":
1370
+ loss_fct = CrossEntropyLoss()
1371
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1372
+ elif self.config.problem_type == "multi_label_classification":
1373
+ loss_fct = BCEWithLogitsLoss()
1374
+ loss = loss_fct(pooled_logits, labels)
1375
+ if not return_dict:
1376
+ output = (pooled_logits,) + transformer_outputs[1:]
1377
+ return ((loss,) + output) if loss is not None else output
1378
+
1379
+ return SequenceClassifierOutputWithPast(
1380
+ loss=loss,
1381
+ logits=pooled_logits,
1382
+ past_key_values=transformer_outputs.past_key_values,
1383
+ hidden_states=transformer_outputs.hidden_states,
1384
+ attentions=transformer_outputs.attentions,
1385
+ )
1386
+
1387
+
1388
+ @add_start_docstrings(
1389
+ """
1390
+ BTLM Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1391
+ Named-Entity-Recognition (NER) tasks.
1392
+ """,
1393
+ BTLM_START_DOCSTRING,
1394
+ )
1395
+ class BTLMForTokenClassification(BTLMPreTrainedModel):
1396
+ def __init__(self, config):
1397
+ super().__init__(config)
1398
+ self.num_labels = config.num_labels
1399
+
1400
+ self.transformer = BTLMModel(config)
1401
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1402
+ classifier_dropout = config.classifier_dropout
1403
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1404
+ classifier_dropout = config.hidden_dropout
1405
+ else:
1406
+ classifier_dropout = 0.1
1407
+ self.dropout = nn.Dropout(classifier_dropout)
1408
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1409
+ self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
1410
+
1411
+ # Model parallel
1412
+ self.model_parallel = False
1413
+ self.device_map = None
1414
+
1415
+ # Initialize weights and apply final processing
1416
+ self.post_init()
1417
+
1418
+ @add_start_docstrings_to_model_forward(BTLM_INPUTS_DOCSTRING)
1419
+ # fmt: off
1420
+ @add_code_sample_docstrings(
1421
+ checkpoint="brad1141/gpt2-finetuned-comp2",
1422
+ output_type=TokenClassifierOutput,
1423
+ config_class=_CONFIG_FOR_DOC,
1424
+ expected_loss=0.25,
1425
+ expected_output=["Lead", "Lead", "Lead", "Position", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead"],
1426
+ )
1427
+ # fmt: on
1428
+ def forward(
1429
+ self,
1430
+ input_ids: Optional[torch.LongTensor] = None,
1431
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1432
+ attention_mask: Optional[torch.FloatTensor] = None,
1433
+ token_type_ids: Optional[torch.LongTensor] = None,
1434
+ position_ids: Optional[torch.LongTensor] = None,
1435
+ head_mask: Optional[torch.FloatTensor] = None,
1436
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1437
+ labels: Optional[torch.LongTensor] = None,
1438
+ use_cache: Optional[bool] = None,
1439
+ output_attentions: Optional[bool] = None,
1440
+ output_hidden_states: Optional[bool] = None,
1441
+ return_dict: Optional[bool] = None,
1442
+ ) -> Union[Tuple, TokenClassifierOutput]:
1443
+ r"""
1444
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1445
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1446
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1447
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1448
+ """
1449
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1450
+
1451
+ transformer_outputs = self.transformer(
1452
+ input_ids,
1453
+ past_key_values=past_key_values,
1454
+ attention_mask=attention_mask,
1455
+ token_type_ids=token_type_ids,
1456
+ position_ids=position_ids,
1457
+ head_mask=head_mask,
1458
+ inputs_embeds=inputs_embeds,
1459
+ use_cache=use_cache,
1460
+ output_attentions=output_attentions,
1461
+ output_hidden_states=output_hidden_states,
1462
+ return_dict=return_dict,
1463
+ )
1464
+
1465
+ hidden_states = transformer_outputs[0]
1466
+ hidden_states = self.dropout(hidden_states)
1467
+ logits = self.classifier(hidden_states)
1468
+ logits *= torch.tensor(float(self.output_logits_scale), dtype=logits.dtype, device=logits.device)
1469
+
1470
+ loss = None
1471
+ if labels is not None:
1472
+ labels = labels.to(logits.device)
1473
+ loss_fct = CrossEntropyLoss()
1474
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1475
+
1476
+ if not return_dict:
1477
+ output = (logits,) + transformer_outputs[2:]
1478
+ return ((loss,) + output) if loss is not None else output
1479
+
1480
+ return TokenClassifierOutput(
1481
+ loss=loss,
1482
+ logits=logits,
1483
+ hidden_states=transformer_outputs.hidden_states,
1484
+ attentions=transformer_outputs.attentions,
1485
+ )
1486
+
1487
+
1488
+ @add_start_docstrings(
1489
+ """
1490
+ The BTLM Model transformer with a span classification head on top for extractive question-answering tasks like
1491
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1492
+ """,
1493
+ BTLM_START_DOCSTRING,
1494
+ )
1495
+ class BTLMForQuestionAnswering(BTLMPreTrainedModel):
1496
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
1497
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias", r"lm_head.weight"]
1498
+
1499
+ def __init__(self, config):
1500
+ super().__init__(config)
1501
+ self.num_labels = config.num_labels
1502
+ self.transformer = BTLMModel(config)
1503
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1504
+ self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
1505
+
1506
+ # Model parallel
1507
+ self.model_parallel = False
1508
+ self.device_map = None
1509
+ self.gradient_checkpointing = False
1510
+
1511
+ # Initialize weights and apply final processing
1512
+ self.post_init()
1513
+
1514
+ @add_start_docstrings_to_model_forward(BTLM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1515
+ @add_code_sample_docstrings(
1516
+ checkpoint=_CHECKPOINT_FOR_DOC,
1517
+ output_type=QuestionAnsweringModelOutput,
1518
+ config_class=_CONFIG_FOR_DOC,
1519
+ real_checkpoint=_CHECKPOINT_FOR_DOC,
1520
+ )
1521
+ def forward(
1522
+ self,
1523
+ input_ids: Optional[torch.LongTensor] = None,
1524
+ attention_mask: Optional[torch.FloatTensor] = None,
1525
+ token_type_ids: Optional[torch.LongTensor] = None,
1526
+ position_ids: Optional[torch.LongTensor] = None,
1527
+ head_mask: Optional[torch.FloatTensor] = None,
1528
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1529
+ start_positions: Optional[torch.LongTensor] = None,
1530
+ end_positions: Optional[torch.LongTensor] = None,
1531
+ output_attentions: Optional[bool] = None,
1532
+ output_hidden_states: Optional[bool] = None,
1533
+ return_dict: Optional[bool] = None,
1534
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1535
+ r"""
1536
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1537
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1538
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1539
+ are not taken into account for computing the loss.
1540
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1541
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1542
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1543
+ are not taken into account for computing the loss.
1544
+ """
1545
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1546
+
1547
+ outputs = self.transformer(
1548
+ input_ids,
1549
+ attention_mask=attention_mask,
1550
+ token_type_ids=token_type_ids,
1551
+ position_ids=position_ids,
1552
+ head_mask=head_mask,
1553
+ inputs_embeds=inputs_embeds,
1554
+ output_attentions=output_attentions,
1555
+ output_hidden_states=output_hidden_states,
1556
+ return_dict=return_dict,
1557
+ )
1558
+
1559
+ sequence_output = outputs[0]
1560
+
1561
+ logits = self.qa_outputs(sequence_output)
1562
+ logits *= torch.tensor(float(self.output_logits_scale), dtype=logits.dtype, device=logits.device)
1563
+ start_logits, end_logits = logits.split(1, dim=-1)
1564
+ start_logits = start_logits.squeeze(-1).contiguous()
1565
+ end_logits = end_logits.squeeze(-1).contiguous()
1566
+
1567
+ total_loss = None
1568
+ if start_positions is not None and end_positions is not None:
1569
+ # If we are on multi-GPU, split add a dimension
1570
+ if len(start_positions.size()) > 1:
1571
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1572
+ if len(end_positions.size()) > 1:
1573
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1574
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1575
+ ignored_index = start_logits.size(1)
1576
+ start_positions = start_positions.clamp(0, ignored_index)
1577
+ end_positions = end_positions.clamp(0, ignored_index)
1578
+
1579
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1580
+ start_loss = loss_fct(start_logits, start_positions)
1581
+ end_loss = loss_fct(end_logits, end_positions)
1582
+ total_loss = (start_loss + end_loss) / 2
1583
+
1584
+ if not return_dict:
1585
+ output = (start_logits, end_logits) + outputs[2:]
1586
+ return ((total_loss,) + output) if total_loss is not None else output
1587
+
1588
+ return QuestionAnsweringModelOutput(
1589
+ loss=total_loss,
1590
+ start_logits=start_logits,
1591
+ end_logits=end_logits,
1592
+ hidden_states=outputs.hidden_states,
1593
+ attentions=outputs.attentions,
1594
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|endoftext|>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "unk_token": {
17
+ "content": "<|endoftext|>",
18
+ "lstrip": false,
19
+ "normalized": true,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "50256": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ }
13
+ },
14
+ "bos_token": "<|endoftext|>",
15
+ "clean_up_tokenization_spaces": true,
16
+ "eos_token": "<|endoftext|>",
17
+ "errors": "replace",
18
+ "model_max_length": 8192,
19
+ "pad_token": null,
20
+ "tokenizer_class": "GPT2Tokenizer",
21
+ "unk_token": "<|endoftext|>"
22
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff