Faisal AlKhateeb commited on
Commit
2c2d81f
1 Parent(s): dd1bb13

add model files

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