Maxscha commited on
Commit
ea13f00
·
verified ·
1 Parent(s): b76e59c

Upload BertForMaskedLM

Browse files
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
bert_padding.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 MosaicML Examples authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # Adapted from https://github.com/HazyResearch/flash-attention/blob/main/flash_attn/bert_padding.py
5
+ # Which was adapted from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/padding.py
6
+
7
+ """Helper functions for padding and unpadding batches.
8
+
9
+ These functions are used extensively throughout the Mosaic BERT implementation
10
+ in `bert_layers.py`.
11
+ """
12
+
13
+ from typing import Tuple, cast
14
+
15
+ import torch
16
+ import torch.nn.functional as F
17
+ from einops import rearrange, repeat
18
+
19
+
20
+ class IndexFirstAxis(torch.autograd.Function):
21
+
22
+ @staticmethod
23
+ def forward(ctx, input: torch.Tensor,
24
+ indices: torch.Tensor) -> torch.Tensor:
25
+ """Get just the values of `input` which are at `indices`.
26
+
27
+ Arguments:
28
+ ctx: the autograd context object
29
+ input: (b, ...) 2+ dimensional tensor
30
+ indices: (num_idx) 1D tensor
31
+ """
32
+ ctx.save_for_backward(indices)
33
+ assert input.ndim >= 2
34
+ ctx.first_axis_dim, other_shape = input.shape[0], input.shape[
35
+ 1:] # type: ignore
36
+ second_dim = other_shape.numel(
37
+ ) # product of sizes of all but first dimension
38
+ # TD [2022-03-04] For some reason torch.gather is a bit faster than indexing.
39
+ return torch.gather(
40
+ rearrange(input, 'b ... -> b (...)'), # (b, ...) -> (b, second_dim)
41
+ 0,
42
+ repeat(indices, 'z -> z d',
43
+ d=second_dim) # (indices,) -> (indices, second_dim)
44
+ ).reshape(-1, *other_shape) # (num_idx, ...)
45
+
46
+ @staticmethod
47
+ def backward(ctx, grad_output: torch.Tensor) -> Tuple[torch.Tensor, None]:
48
+ indices, = ctx.saved_tensors
49
+ assert grad_output.ndim >= 2
50
+ other_shape = grad_output.shape[1:]
51
+ grad_output = rearrange(grad_output, 'b ... -> b (...)')
52
+ grad_input = torch.zeros([ctx.first_axis_dim, grad_output.shape[1]],
53
+ device=grad_output.device,
54
+ dtype=grad_output.dtype)
55
+ # TD [2022-03-04] For some reason torch.scatter is a bit faster than indexing.
56
+ # grad_input[indices] = grad_output
57
+ grad_input.scatter_(0,
58
+ repeat(indices, 'z -> z d', d=grad_output.shape[1]),
59
+ grad_output)
60
+ return grad_input.reshape(ctx.first_axis_dim, *other_shape), None
61
+
62
+
63
+ index_first_axis = IndexFirstAxis.apply
64
+
65
+
66
+ class IndexPutFirstAxis(torch.autograd.Function):
67
+
68
+ @staticmethod
69
+ def forward(ctx, values: torch.Tensor, indices: torch.Tensor,
70
+ first_axis_dim) -> torch.Tensor:
71
+ ctx.save_for_backward(indices)
72
+ assert indices.ndim == 1
73
+ assert values.ndim >= 2
74
+ output = torch.zeros(first_axis_dim,
75
+ *values.shape[1:],
76
+ device=values.device,
77
+ dtype=values.dtype)
78
+ output[indices] = values
79
+ return output
80
+
81
+ @staticmethod
82
+ def backward(ctx,
83
+ grad_output: torch.Tensor) -> Tuple[torch.Tensor, None, None]:
84
+ indices, = ctx.saved_tensors
85
+ grad_values = grad_output[indices]
86
+ return grad_values, None, None
87
+
88
+
89
+ index_put_first_axis = IndexPutFirstAxis.apply
90
+
91
+
92
+ def unpad_input(
93
+ hidden_states: torch.Tensor,
94
+ attention_mask: torch.Tensor,
95
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]:
96
+ """Remove padding from input sequences.
97
+
98
+ Arguments:
99
+ hidden_states: (batch, seqlen, ...)
100
+ attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
101
+
102
+ Returns:
103
+ hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
104
+ indices: (total_nnz)
105
+ cu_seqlens: (batch + 1), the cumulative sequence lengths, used to index into hidden_states.
106
+ max_seqlen_in_batch: int ()
107
+ """
108
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
109
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
110
+ max_seqlen_in_batch = int(seqlens_in_batch.max().item())
111
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32),
112
+ (1, 0))
113
+ # TD [2022-03-04] We don't want to index with a bool mask, because Pytorch will expand the
114
+ # bool mask, then call nonzero to get the indices, then index with those. The indices is @dim
115
+ # times larger than it needs to be, wasting memory. It's faster and more memory-efficient to
116
+ # index with integer indices. Moreover, torch's index is a bit slower than it needs to be,
117
+ # so we write custom forward and backward to make it a bit faster.
118
+ hidden_states = cast(
119
+ torch.Tensor,
120
+ index_first_axis(rearrange(hidden_states, 'b s ... -> (b s) ...'),
121
+ indices))
122
+ return hidden_states, indices, cu_seqlens, max_seqlen_in_batch
123
+
124
+
125
+ def unpad_input_only(
126
+ hidden_states: torch.Tensor,
127
+ attention_mask: torch.Tensor,
128
+ ) -> torch.Tensor:
129
+ """Like unpad_input, but only return the unpadded first tensor.
130
+
131
+ Save a small amount of overhead.
132
+
133
+ Arguments:
134
+ hidden_states: (batch, seqlen, ...)
135
+ attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
136
+
137
+ Returns:
138
+ hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
139
+ """
140
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
141
+ return index_first_axis(rearrange(hidden_states, 'b s ... -> (b s) ...'),
142
+ indices)
143
+
144
+
145
+ def pad_input(hidden_states: torch.Tensor, indices: torch.Tensor, batch: int,
146
+ seqlen: int) -> torch.Tensor:
147
+ """Add padding to sequences.
148
+
149
+ Arguments:
150
+ hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
151
+ indices: (total_nnz)
152
+ batch: int batch_size
153
+ seqlen: int max sequence length
154
+
155
+ Returns:
156
+ hidden_states: (batch, seqlen, ...)
157
+ """
158
+ output = index_put_first_axis(hidden_states, indices, batch * seqlen)
159
+ return rearrange(output, '(b s) ... -> b s ...', b=batch)
config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "mosaicml/mosaic-bert",
3
+ "alibi_starting_size": 512,
4
+ "architectures": [
5
+ "BertForMaskedLM"
6
+ ],
7
+ "attention_probs_dropout_prob": 0.1,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_bert.BertConfig",
10
+ "AutoModelForMaskedLM": "modeling_bert.BertForMaskedLM"
11
+ },
12
+ "classifier_dropout": null,
13
+ "gradient_checkpointing": false,
14
+ "hidden_act": "gelu",
15
+ "hidden_dropout_prob": 0.1,
16
+ "hidden_size": 768,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 3072,
19
+ "layer_norm_eps": 1e-12,
20
+ "max_position_embeddings": 512,
21
+ "model_type": "bert",
22
+ "num_attention_heads": 12,
23
+ "num_hidden_layers": 12,
24
+ "pad_token_id": 0,
25
+ "position_embedding_type": "absolute",
26
+ "torch_dtype": "float32",
27
+ "transformers_version": "4.44.0",
28
+ "type_vocab_size": 2,
29
+ "use_cache": true,
30
+ "vocab_size": 32064
31
+ }
configuration_bert.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 MosaicML Examples authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ from transformers import BertConfig as TransformersBertConfig
5
+
6
+
7
+ class BertConfig(TransformersBertConfig):
8
+
9
+ def __init__(
10
+ self,
11
+ alibi_starting_size: int = 512,
12
+ attention_probs_dropout_prob: float = 0.0,
13
+ **kwargs,
14
+ ):
15
+ """Configuration class for MosaicBert.
16
+
17
+ Args:
18
+ alibi_starting_size (int): Use `alibi_starting_size` to determine how large of an alibi tensor to
19
+ create when initializing the model. You should be able to ignore this parameter in most cases.
20
+ Defaults to 512.
21
+ attention_probs_dropout_prob (float): By default, turn off attention dropout in Mosaic BERT
22
+ (otherwise, Flash Attention will be off by default). Defaults to 0.0.
23
+ """
24
+ super().__init__(
25
+ attention_probs_dropout_prob=attention_probs_dropout_prob, **kwargs)
26
+ self.alibi_starting_size = alibi_starting_size
generation_config.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "pad_token_id": 0,
4
+ "transformers_version": "4.44.0"
5
+ }
modeling_bert.py ADDED
@@ -0,0 +1,1256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 MosaicML Examples authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # Copyright 2023 MosaicML Examples authors
5
+ # SPDX-License-Identifier: Apache-2.0
6
+
7
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
8
+ # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
9
+ # Copyright (c) 2023, Tri Dao.
10
+
11
+ """Implements Mosaic BERT, with an eye towards the Hugging Face API.
12
+
13
+ Mosaic BERT improves performance over Hugging Face BERT through the following:
14
+
15
+ 1. ALiBi. This architectural change removes positional embeddings and instead encodes positional
16
+ information through attention biases based on query-key position distance. It improves the effectiveness
17
+ of training with shorter sequence lengths by enabling extrapolation to longer sequences.
18
+
19
+ 2. Gated Linear Units (GLU). This architectural change replaces the FFN component of the BERT layer
20
+ to improve overall expressiveness, providing better convergence properties.
21
+
22
+ 3. Flash Attention. The MosaicBERT's self-attention layer makes use of Flash Attention, which dramatically
23
+ improves the speed of self-attention. Our implementation utilizes a bleeding edge implementation that
24
+ supports attention biases, which allows us to use Flash Attention with ALiBi.
25
+
26
+ 4. Unpadding. Padding is often used to simplify batching across sequences of different lengths. Standard BERT
27
+ implementations waste computation on padded tokens. MosaicBERT internally unpads to reduce unnecessary computation
28
+ and improve speed. It does this without changing how the user interfaces with the model, thereby
29
+ preserving the simple API of standard implementations.
30
+
31
+
32
+ Currently, MosaicBERT is available for masked language modeling :class:`BertForMaskedLM` and sequence
33
+ classification :class:`BertForSequenceClassification`. We aim to expand this catalogue in future releases.
34
+
35
+ See :file:`./mosaic_bert.py` for utilities to simplify working with MosaicBERT in Composer, and for example usage
36
+ of the core Mosaic BERT classes.
37
+ """
38
+
39
+ import copy
40
+ import logging
41
+ import math
42
+ import os
43
+ import sys
44
+ import warnings
45
+ from functools import lru_cache
46
+ from typing import List, Optional, Tuple, Union
47
+
48
+ # Add folder root to path to allow us to use relative imports regardless of what directory the script is run from
49
+ sys.path.append(os.path.dirname(os.path.realpath(__file__)))
50
+
51
+ import importlib.metadata
52
+
53
+
54
+ from .bert_padding import pad_input, unpad_input_only, index_first_axis, unpad_input, pad_input, index_put_first_axis
55
+ from .configuration_bert import BertConfig
56
+ import torch
57
+ import torch.nn as nn
58
+ from einops import rearrange
59
+ from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
60
+ from transformers.activations import ACT2FN
61
+ from transformers.modeling_outputs import (MaskedLMOutput,
62
+ SequenceClassifierOutput)
63
+ from transformers.models.bert.modeling_bert import BertPreTrainedModel
64
+
65
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
66
+
67
+
68
+ IMPL_USE_FLASH2 = False
69
+ # Import Flash Attention 2, which supports ALiBi https://github.com/Dao-AILab/flash-attention
70
+ try:
71
+ from flash_attn import flash_attn_qkvpacked_func # type: ignore
72
+ installed_version = importlib.metadata.version('flash_attn') # type: ignore
73
+ if installed_version < '2.4.2':
74
+ raise ImportError('newer version of flash_attn required (>= 2.4.2)')
75
+ IMPL_USE_FLASH2 = True
76
+ except ImportError as e:
77
+ warnings.warn(
78
+ f'Failed to import flash_attn. Will try to import triton implementation: {e}',
79
+ stacklevel=2)
80
+ # Import custom Triton Flash Attention implementation that supports ALiBi
81
+ try:
82
+ import flash_attn_triton as flash_attn_triton
83
+ flash_attn_qkvpacked_func = flash_attn_triton.flash_attn_qkvpacked_func
84
+ except ImportError as e:
85
+ flash_attn_qkvpacked_func = None
86
+ warnings.warn(f'Failed to import flash_attn_triton as a fallback: {e}',
87
+ stacklevel=2)
88
+
89
+ logger = logging.getLogger(__name__)
90
+
91
+
92
+ @lru_cache
93
+ def _get_half_dtype() -> torch.dtype:
94
+ if torch.cuda.is_bf16_supported():
95
+ return torch.bfloat16
96
+ return torch.float16
97
+
98
+
99
+ class BertEmbeddings(nn.Module):
100
+ """Construct the embeddings for words, ignoring position.
101
+
102
+ There are no positional embeddings since we use ALiBi and token_type
103
+ embeddings.
104
+
105
+ This module is modeled after the Hugging Face BERT's
106
+ :class:`~transformers.model.bert.modeling_bert.BertEmbeddings`, but is
107
+ modified as part of Mosaic BERT's ALiBi implementation. The key change is
108
+ that position embeddings are removed. Position information instead comes
109
+ from attention biases that scale linearly with the position distance
110
+ between query and key tokens.
111
+
112
+ This module ignores the `position_ids` input to the `forward` method.
113
+ """
114
+
115
+ def __init__(self, config):
116
+ super().__init__()
117
+ self.word_embeddings = nn.Embedding(config.vocab_size,
118
+ config.hidden_size,
119
+ padding_idx=config.pad_token_id)
120
+ # ALiBi doesn't use position embeddings
121
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size,
122
+ config.hidden_size)
123
+
124
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model
125
+ # variable name and be able to load any TensorFlow checkpoint file
126
+ self.LayerNorm = nn.LayerNorm(config.hidden_size,
127
+ eps=config.layer_norm_eps)
128
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
129
+ self.register_buffer('token_type_ids',
130
+ torch.zeros(config.max_position_embeddings,
131
+ dtype=torch.long),
132
+ persistent=False)
133
+
134
+ def forward(
135
+ self,
136
+ input_ids: Optional[torch.LongTensor] = None,
137
+ token_type_ids: Optional[torch.LongTensor] = None,
138
+ position_ids: Optional[torch.LongTensor] = None,
139
+ inputs_embeds: Optional[torch.FloatTensor] = None,
140
+ past_key_values_length: int = 0,
141
+ ) -> torch.Tensor:
142
+ if (input_ids is not None) == (inputs_embeds is not None):
143
+ raise ValueError('Must specify either input_ids or input_embeds!')
144
+ if input_ids is not None:
145
+ input_shape = input_ids.size()
146
+ else:
147
+ assert inputs_embeds is not None # just for type checking
148
+ input_shape = inputs_embeds.size()[:-1]
149
+
150
+ seq_length = input_shape[1]
151
+
152
+ if position_ids is None:
153
+ # great! ALiBi
154
+ pass
155
+
156
+ # Setting the token_type_ids to the registered buffer in constructor
157
+ # where it is all zeros, which usually occurs when it's auto-generated;
158
+ # registered buffer helps users when tracing the model without passing
159
+ # token_type_ids, solves issue #5664
160
+ if token_type_ids is None:
161
+ if hasattr(self, 'token_type_ids'):
162
+ assert isinstance(self.token_type_ids, torch.LongTensor)
163
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
164
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(
165
+ input_shape[0], seq_length)
166
+ token_type_ids = buffered_token_type_ids_expanded # type: ignore
167
+ else:
168
+ token_type_ids = torch.zeros(input_shape, # type: ignore
169
+ dtype=torch.long,
170
+ device=self.word_embeddings.device) # type: ignore # yapf: disable
171
+
172
+ if inputs_embeds is None:
173
+ inputs_embeds = self.word_embeddings(input_ids)
174
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
175
+
176
+ embeddings = inputs_embeds + token_type_embeddings
177
+ # no position embeddings! ALiBi
178
+ embeddings = self.LayerNorm(embeddings)
179
+ embeddings = self.dropout(embeddings)
180
+ return embeddings
181
+
182
+
183
+ class BertUnpadSelfAttention(nn.Module):
184
+ """Performs multi-headed self attention on a batch of unpadded sequences.
185
+
186
+ If Flash Attention 2 is installed, this module uses Flash Attention to greatly improve throughput.
187
+ The Flash Attention implementation used in MosaicBERT supports arbitrary attention biases (which
188
+ we use to implement ALiBi), but does not support attention dropout. If either Flash Attention 2 is
189
+ not installed or `config.attention_probs_dropout_prob > 0`, the implementation will default to a
190
+ math-equivalent pytorch version, which is much slower.
191
+
192
+ See `forward` method for additional detail.
193
+ """
194
+
195
+ def __init__(self, config):
196
+ super().__init__()
197
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
198
+ config, 'embedding_size'):
199
+ raise ValueError(
200
+ f'The hidden size ({config.hidden_size}) is not a multiple of the number of attention '
201
+ f'heads ({config.num_attention_heads})')
202
+
203
+ self.num_attention_heads = config.num_attention_heads
204
+ self.attention_head_size = int(config.hidden_size /
205
+ config.num_attention_heads)
206
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
207
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
208
+ self.p_dropout = config.attention_probs_dropout_prob
209
+ self.Wqkv = nn.Linear(self.all_head_size, 3 * config.hidden_size)
210
+
211
+ # Warn if defaulting to pytorch because of import issues
212
+ if flash_attn_qkvpacked_func is None:
213
+ warnings.warn(
214
+ 'Unable to import Triton; defaulting MosaicBERT attention implementation to pytorch (this will reduce throughput when using this model).'
215
+ )
216
+
217
+ def forward(self, hidden_states: torch.Tensor, cu_seqlens: torch.Tensor,
218
+ max_seqlen_in_batch: int, indices: torch.Tensor,
219
+ attn_mask: torch.Tensor, bias: torch.Tensor,
220
+ slopes: torch.Tensor) -> torch.Tensor:
221
+ """Perform self-attention.
222
+
223
+ There are three attention implementations supported: vanilla attention with ALiBi,
224
+ Triton Flash Attention with ALibi, and Flash Attention 2 with ALiBi
225
+
226
+ In order to use the Triton kernel, dropout must be zero (i.e. attention_probs_dropout_prob = 0)
227
+
228
+ The arguments are unpadded, and our implementations of attention require padded arguments,
229
+ so we first call `pad_input`. Once we compute attention, we re-unpad our outputs for the other layers.
230
+ The pad/unpad operations add overhead, but not sending pad tokens through ffs saves compute.
231
+
232
+ Args:
233
+ hidden_states: (total_nnz, dim)
234
+ cu_seqlens: (batch + 1,)
235
+ max_seqlen_in_batch: int
236
+ indices: (total_nnz,)
237
+ attn_mask: (batch, max_seqlen_in_batch)
238
+ bias: (batch, heads, max_seqlen_in_batch, max_seqlen_in_batch)
239
+ slopes: (heads) or (batch, heads)
240
+
241
+ Returns:
242
+ attention: (total_nnz, dim)
243
+ """
244
+ qkv = self.Wqkv(hidden_states)
245
+ qkv = pad_input(
246
+ qkv, indices, cu_seqlens.shape[0] - 1,
247
+ max_seqlen_in_batch) # batch, max_seqlen_in_batch, thd
248
+ qkv = rearrange(qkv,
249
+ 'b s (t h d) -> b s t h d',
250
+ t=3,
251
+ h=self.num_attention_heads)
252
+
253
+ # Option 1: Vanilla Self Attention with ALiBi
254
+ # if (not IMPL_USE_FLASH2 and
255
+ # self.p_dropout) or flash_attn_qkvpacked_func is None:
256
+ if False:
257
+ # if we have nonzero attention dropout (e.g. during fine-tuning) or no Triton, compute attention in PyTorch
258
+ q = qkv[:, :, 0, :, :].permute(0, 2, 1, 3) # b h s d
259
+ k = qkv[:, :, 1, :, :].permute(0, 2, 3, 1) # b h d s
260
+ v = qkv[:, :, 2, :, :].permute(0, 2, 1, 3) # b h s d
261
+ attention_scores = torch.matmul(q, k) / math.sqrt(
262
+ self.attention_head_size)
263
+ attention_scores = attention_scores + bias
264
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
265
+ attention_probs = self.dropout(attention_probs)
266
+ attention = torch.matmul(attention_probs, v).permute(0, 2, 1,
267
+ 3) # b s h d
268
+ else:
269
+ # Option 2: Flash Attention 2 with ALiBi
270
+ # if IMPL_USE_FLASH2:
271
+ if True:
272
+ assert 1 <= len(slopes.shape) <= 2, f'{slopes=}'
273
+ assert slopes.shape[
274
+ -1] == self.num_attention_heads, f'{slopes=}'
275
+
276
+ convert_dtype = qkv.dtype not in (torch.float16, torch.bfloat16)
277
+ if convert_dtype:
278
+ # FA2 implementation only supports fp16 and bf16
279
+ # If FA2 is supported, bfloat16 must be supported
280
+ # as of FA2 2.4.2. (Turing GPUs not supported)
281
+ orig_dtype = qkv.dtype
282
+ qkv = qkv.to(torch.bfloat16)
283
+ bias_dtype = bias.dtype
284
+ bias = bias.to(torch.bfloat16)
285
+
286
+ attention = flash_attn_qkvpacked_func(
287
+ qkv, dropout_p=self.p_dropout, alibi_slopes=slopes)
288
+ attention = attention.to(orig_dtype) # type: ignore
289
+ bias = bias.to(bias_dtype)
290
+ else:
291
+ attention = flash_attn_qkvpacked_func(
292
+ qkv, dropout_p=self.p_dropout, alibi_slopes=slopes)
293
+ # Option 3: Triton Implementation of Flash Attention with ALiBi
294
+ else:
295
+ # Triton implementation only supports 0 attention dropout
296
+ if self.p_dropout > 0.0:
297
+ raise ValueError(
298
+ f'dropout probability of the attention layer is ({self.p_dropout} '
299
+ f'the Triton kernel for Flash Attention requires attention_probs_dropout_prob=0'
300
+ )
301
+
302
+ convert_dtype = qkv.dtype not in (torch.float16, torch.bfloat16)
303
+ if convert_dtype:
304
+ half = _get_half_dtype()
305
+
306
+ # Triton implementation only supports fp16 and bf16
307
+ orig_dtype = qkv.dtype
308
+ qkv = qkv.to(half)
309
+ bias_dtype = bias.dtype
310
+ bias = bias.to(half)
311
+ attention = flash_attn_qkvpacked_func(qkv, bias)
312
+ attention = attention.to(orig_dtype) # type: ignore
313
+ bias = bias.to(bias_dtype)
314
+ else:
315
+ attention = flash_attn_qkvpacked_func(qkv, bias)
316
+
317
+ # attn_mask is 1 for attend and 0 for don't attend
318
+ attention = unpad_input_only(
319
+ attention, # type: ignore
320
+ torch.squeeze(attn_mask) == 1)
321
+ return rearrange(attention, 'nnz h d -> nnz (h d)')
322
+
323
+
324
+ # Copy of transformer's library BertSelfOutput that will not be caught by surgery methods looking for HF BERT modules.
325
+ class BertSelfOutput(nn.Module):
326
+ """Computes the output of the attention layer.
327
+
328
+ This module is modeled after the Hugging Face BERT's
329
+ :class:`~transformers.model.bert.modeling_bert.BertSelfOutput`.
330
+ The implementation is identical. Rather than use the original module
331
+ directly, we re-implement it here so that Mosaic BERT's modules will not
332
+ be affected by any Composer surgery algorithm that modifies Hugging Face
333
+ BERT modules.
334
+ """
335
+
336
+ def __init__(self, config):
337
+ super().__init__()
338
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
339
+ self.LayerNorm = nn.LayerNorm(config.hidden_size,
340
+ eps=config.layer_norm_eps)
341
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
342
+
343
+ def forward(self, hidden_states: torch.Tensor,
344
+ input_tensor: torch.Tensor) -> torch.Tensor:
345
+ hidden_states = self.dense(hidden_states)
346
+ hidden_states = self.dropout(hidden_states)
347
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
348
+ return hidden_states
349
+
350
+
351
+ class BertUnpadAttention(nn.Module):
352
+ """Chains attention, Dropout, and LayerNorm for Mosaic BERT."""
353
+
354
+ def __init__(self, config):
355
+ super().__init__()
356
+ self.self = BertUnpadSelfAttention(config)
357
+ self.output = BertSelfOutput(config)
358
+
359
+ def forward(
360
+ self,
361
+ input_tensor: torch.Tensor,
362
+ cu_seqlens: torch.Tensor,
363
+ max_s: int,
364
+ subset_idx: Optional[torch.Tensor] = None,
365
+ indices: Optional[torch.Tensor] = None,
366
+ attn_mask: Optional[torch.Tensor] = None,
367
+ bias: Optional[torch.Tensor] = None,
368
+ slopes: Optional[torch.Tensor] = None,
369
+ ) -> torch.Tensor:
370
+ """Forward pass for scaled self-attention without padding.
371
+
372
+ Arguments:
373
+ input_tensor: (total_nnz, dim)
374
+ cu_seqlens: (batch + 1,)
375
+ max_s: int
376
+ subset_idx: () set of indices whose values we care about at the end of the layer
377
+ (e.g., the masked tokens, if this is the final layer).
378
+ indices: None or (total_nnz,)
379
+ attn_mask: None or (batch, max_seqlen_in_batch)
380
+ bias: None or (batch, heads, max_seqlen_in_batch, max_seqlen_in_batch)
381
+ slopes: None or (batch, heads) or (heads,)
382
+ """
383
+ assert (bias is None) == (slopes is None), f'{bias=}, {slopes=}'
384
+ self_output = self.self(input_tensor, cu_seqlens, max_s, indices,
385
+ attn_mask, bias, slopes)
386
+ if subset_idx is not None:
387
+ return self.output(
388
+ index_first_axis(self_output, subset_idx),
389
+ index_first_axis(input_tensor, subset_idx))
390
+ else:
391
+ return self.output(self_output, input_tensor)
392
+
393
+
394
+ class BertGatedLinearUnitMLP(nn.Module):
395
+ """Applies the FFN at the end of each Mosaic BERT layer.
396
+
397
+ Compared to the default BERT architecture, this block replaces :class:`~transformers.model.bert.modeling_bert.BertIntermediate`
398
+ and :class:`~transformers.model.bert.modeling_bert.SelfOutput` with a single module that has similar functionality, but
399
+ introduces Gated Linear Units.
400
+
401
+ Note: Mosaic BERT adds parameters in order to implement Gated Linear Units. To keep parameter count consistent with that of a
402
+ standard Hugging Face BERT, scale down `config.intermediate_size` by 2/3. For example, a Mosaic BERT constructed with
403
+ `config.intermediate_size=2048` will have the same parameter footprint as its Hugging Face BERT counterpart constructed
404
+ with the `config.intermediate_size=3072`.
405
+ However, in most cases it will not be necessary to adjust `config.intermediate_size` since, despite the increased
406
+ parameter size, Mosaic BERT typically offers a net higher throughput than a Hugging Face BERT built from the same `config`.
407
+ """
408
+
409
+ def __init__(self, config):
410
+ super().__init__()
411
+ self.config = config
412
+ self.gated_layers = nn.Linear(config.hidden_size,
413
+ config.intermediate_size * 2,
414
+ bias=False)
415
+ self.act = nn.GELU(approximate='none')
416
+ self.wo = nn.Linear(config.intermediate_size, config.hidden_size)
417
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
418
+ self.layernorm = nn.LayerNorm(config.hidden_size,
419
+ eps=config.layer_norm_eps)
420
+
421
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
422
+ """Compute new hidden states from current hidden states.
423
+
424
+ Args:
425
+ hidden_states (torch.Tensor): The (unpadded) hidden states from
426
+ the attention layer [nnz, dim].
427
+ """
428
+ residual_connection = hidden_states
429
+ # compute the activation
430
+ hidden_states = self.gated_layers(hidden_states)
431
+ gated = hidden_states[:, :self.config.intermediate_size]
432
+ non_gated = hidden_states[:, self.config.intermediate_size:]
433
+ hidden_states = self.act(gated) * non_gated
434
+ hidden_states = self.dropout(hidden_states)
435
+ # multiply by the second matrix
436
+ hidden_states = self.wo(hidden_states)
437
+ # add the residual connection and post-LN
438
+ hidden_states = self.layernorm(hidden_states + residual_connection)
439
+ return hidden_states
440
+
441
+
442
+ class BertLayer(nn.Module):
443
+ """Composes the Mosaic BERT attention and FFN blocks into a single layer."""
444
+
445
+ def __init__(self, config):
446
+ super(BertLayer, self).__init__()
447
+ self.attention = BertUnpadAttention(config)
448
+ self.mlp = BertGatedLinearUnitMLP(config)
449
+
450
+ def forward(
451
+ self,
452
+ hidden_states: torch.Tensor,
453
+ cu_seqlens: torch.Tensor,
454
+ seqlen: int,
455
+ subset_idx: Optional[torch.Tensor] = None,
456
+ indices: Optional[torch.Tensor] = None,
457
+ attn_mask: Optional[torch.Tensor] = None,
458
+ bias: Optional[torch.Tensor] = None,
459
+ slopes: Optional[torch.Tensor] = None,
460
+ ) -> torch.Tensor:
461
+ """Forward pass for a BERT layer, including both attention and MLP.
462
+
463
+ Args:
464
+ hidden_states: (total_nnz, dim)
465
+ cu_seqlens: (batch + 1,)
466
+ seqlen: int
467
+ subset_idx: () set of indices whose values we care about at the end of the layer
468
+ (e.g., the masked tokens, if this is the final layer).
469
+ indices: None or (total_nnz,)
470
+ attn_mask: None or (batch, max_seqlen_in_batch)
471
+ bias: None or (batch, heads, max_seqlen_in_batch, max_seqlen_in_batch)
472
+ slopes: None or (batch, heads) or (heads,)
473
+ """
474
+ assert (bias is None) == (slopes is None), f'{bias=}, {slopes=}'
475
+ attention_output = self.attention(hidden_states, cu_seqlens, seqlen,
476
+ subset_idx, indices, attn_mask, bias,
477
+ slopes)
478
+ layer_output = self.mlp(attention_output)
479
+ return layer_output
480
+
481
+
482
+ class BertEncoder(nn.Module):
483
+ """A stack of BERT layers providing the backbone of Mosaic BERT.
484
+
485
+ This module is modeled after the Hugging Face BERT's :class:`~transformers.model.bert.modeling_bert.BertEncoder`,
486
+ but with substantial modifications to implement unpadding and ALiBi.
487
+
488
+ Compared to the analogous Hugging Face BERT module, this module handles unpadding to reduce unnecessary computation
489
+ at padded tokens, and pre-computes attention biases to implement ALiBi.
490
+ """
491
+
492
+ def __init__(self, config):
493
+ super().__init__()
494
+ layer = BertLayer(config)
495
+ self.layer = nn.ModuleList(
496
+ [copy.deepcopy(layer) for _ in range(config.num_hidden_layers)])
497
+
498
+ self.num_attention_heads = config.num_attention_heads
499
+
500
+ # The alibi mask will be dynamically expanded if it is too small for
501
+ # the input the model receives. But it generally helps to initialize it
502
+ # to a reasonably large size to help pre-allocate CUDA memory.
503
+ # The default `alibi_starting_size` is 512.
504
+ self._current_alibi_size = int(config.alibi_starting_size)
505
+ self.alibi = torch.zeros(
506
+ (1, self.num_attention_heads, self._current_alibi_size,
507
+ self._current_alibi_size))
508
+ self.rebuild_alibi_tensor(size=config.alibi_starting_size)
509
+
510
+ def rebuild_alibi_tensor(self,
511
+ size: int,
512
+ device: Optional[Union[torch.device, str]] = None):
513
+ # Alibi
514
+ # Following https://github.com/ofirpress/attention_with_linear_biases/issues/5 (Implementation 1)
515
+ # In the causal case, you can exploit the fact that softmax is invariant to a uniform translation
516
+ # of the logits, which makes the math work out *after* applying causal masking. If no causal masking
517
+ # will be applied, it is necessary to construct the diagonal mask.
518
+ n_heads = self.num_attention_heads
519
+
520
+ def _get_alibi_head_slopes(n_heads: int) -> List[float]:
521
+
522
+ def get_slopes_power_of_2(n_heads: int) -> List[float]:
523
+ start = (2**(-2**-(math.log2(n_heads) - 3)))
524
+ ratio = start
525
+ return [start * ratio**i for i in range(n_heads)]
526
+
527
+ # In the paper, they only train models that have 2^a heads for some a. This function
528
+ # has some good properties that only occur when the input is a power of 2. To
529
+ # maintain that even when the number of heads is not a power of 2, we use a
530
+ # workaround.
531
+ if math.log2(n_heads).is_integer():
532
+ return get_slopes_power_of_2(n_heads)
533
+
534
+ closest_power_of_2 = 2**math.floor(math.log2(n_heads))
535
+ slopes_a = get_slopes_power_of_2(closest_power_of_2)
536
+ slopes_b = _get_alibi_head_slopes(2 * closest_power_of_2)
537
+ slopes_b = slopes_b[0::2][:n_heads - closest_power_of_2]
538
+ return slopes_a + slopes_b
539
+
540
+ context_position = torch.arange(size, device=device)[:, None]
541
+ memory_position = torch.arange(size, device=device)[None, :]
542
+ relative_position = torch.abs(memory_position - context_position)
543
+ # [n_heads, max_token_length, max_token_length]
544
+ relative_position = relative_position.unsqueeze(0).expand(
545
+ n_heads, -1, -1)
546
+ slopes = torch.Tensor(_get_alibi_head_slopes(n_heads)).to(device)
547
+ self.slopes = slopes
548
+ alibi = slopes.unsqueeze(1).unsqueeze(1) * -relative_position
549
+ # [1, n_heads, max_token_length, max_token_length]
550
+ alibi = alibi.unsqueeze(0)
551
+ assert alibi.shape == torch.Size([1, n_heads, size, size])
552
+
553
+ self._current_alibi_size = size
554
+ self.alibi = alibi
555
+
556
+ def forward(
557
+ self,
558
+ hidden_states: torch.Tensor,
559
+ attention_mask: torch.Tensor,
560
+ output_all_encoded_layers: Optional[bool] = True,
561
+ subset_mask: Optional[torch.Tensor] = None,
562
+ ) -> List[torch.Tensor]:
563
+
564
+ extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
565
+ extended_attention_mask = extended_attention_mask.to(
566
+ dtype=next(self.parameters()).dtype) # fp16 compatibility
567
+ extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
568
+
569
+ attention_mask_bool = attention_mask.bool()
570
+ batch, seqlen = hidden_states.shape[:2]
571
+ # Unpad inputs and mask. It will remove tokens that are padded.
572
+ # Assume ntokens is total number of tokens (padded and non-padded)
573
+ # and ntokens_unpad is total number of non-padded tokens.
574
+ # Then unpadding performs the following compression of the inputs:
575
+ # hidden_states[ntokens,hidden] -> hidden_states[ntokens_unpad,hidden]
576
+ hidden_states, indices, cu_seqlens, _ = unpad_input(
577
+ hidden_states, attention_mask_bool)
578
+
579
+ # Add alibi matrix to extended_attention_mask
580
+ if self._current_alibi_size < seqlen:
581
+ # Rebuild the alibi tensor when needed
582
+ warnings.warn(
583
+ f'Increasing alibi size from {self._current_alibi_size} to {seqlen}'
584
+ )
585
+ self.rebuild_alibi_tensor(size=seqlen, device=hidden_states.device)
586
+ elif self.alibi.device != hidden_states.device:
587
+ # Device catch-up
588
+ self.alibi = self.alibi.to(hidden_states.device)
589
+ self.slopes = self.slopes.to(hidden_states.device) # type: ignore
590
+ alibi_bias = self.alibi[:, :, :seqlen, :seqlen]
591
+ attn_bias = extended_attention_mask[:, :, :seqlen, :seqlen]
592
+ alibi_attn_mask = attn_bias + alibi_bias
593
+
594
+ all_encoder_layers = []
595
+ if subset_mask is None:
596
+ for layer_module in self.layer:
597
+ hidden_states = layer_module(hidden_states,
598
+ cu_seqlens,
599
+ seqlen,
600
+ None,
601
+ indices,
602
+ attn_mask=attention_mask,
603
+ bias=alibi_attn_mask,
604
+ slopes=self.slopes)
605
+ if output_all_encoded_layers:
606
+ all_encoder_layers.append(hidden_states)
607
+ # Pad inputs and mask. It will insert back zero-padded tokens.
608
+ # Assume ntokens is total number of tokens (padded and non-padded)
609
+ # and ntokens_unpad is total number of non-padded tokens.
610
+ # Then padding performs the following de-compression:
611
+ # hidden_states[ntokens_unpad,hidden] -> hidden_states[ntokens,hidden]
612
+ hidden_states = pad_input(
613
+ hidden_states, indices, batch, seqlen)
614
+ else:
615
+ for i in range(len(self.layer) - 1):
616
+ layer_module = self.layer[i]
617
+ hidden_states = layer_module(hidden_states,
618
+ cu_seqlens,
619
+ seqlen,
620
+ None,
621
+ indices,
622
+ attn_mask=attention_mask,
623
+ bias=alibi_attn_mask,
624
+ slopes=self.slopes)
625
+ if output_all_encoded_layers:
626
+ all_encoder_layers.append(hidden_states)
627
+ subset_idx = torch.nonzero(subset_mask[attention_mask_bool],
628
+ as_tuple=False).flatten()
629
+ hidden_states = self.layer[-1](hidden_states,
630
+ cu_seqlens,
631
+ seqlen,
632
+ subset_idx=subset_idx,
633
+ indices=indices,
634
+ attn_mask=attention_mask,
635
+ bias=alibi_attn_mask,
636
+ slopes=self.slopes)
637
+
638
+ if not output_all_encoded_layers:
639
+ all_encoder_layers.append(hidden_states)
640
+ return all_encoder_layers
641
+
642
+
643
+ class BertPooler(nn.Module):
644
+
645
+ def __init__(self, config):
646
+ super(BertPooler, self).__init__()
647
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
648
+ self.activation = nn.Tanh()
649
+
650
+ def forward(self,
651
+ hidden_states: torch.Tensor,
652
+ pool: Optional[bool] = True) -> torch.Tensor:
653
+ # We "pool" the model by simply taking the hidden state corresponding
654
+ # to the first token.
655
+ first_token_tensor = hidden_states[:, 0] if pool else hidden_states
656
+ pooled_output = self.dense(first_token_tensor)
657
+ pooled_output = self.activation(pooled_output)
658
+ return pooled_output
659
+
660
+
661
+ class BertPredictionHeadTransform(nn.Module):
662
+
663
+ def __init__(self, config):
664
+ super().__init__()
665
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
666
+ if isinstance(config.hidden_act, str):
667
+ self.transform_act_fn = ACT2FN[config.hidden_act]
668
+ else:
669
+ self.transform_act_fn = config.hidden_act
670
+ self.LayerNorm = torch.nn.LayerNorm(config.hidden_size, eps=1e-12)
671
+
672
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
673
+ hidden_states = self.dense(hidden_states)
674
+ hidden_states = self.transform_act_fn(hidden_states)
675
+ hidden_states = self.LayerNorm(hidden_states)
676
+ return hidden_states
677
+
678
+
679
+ class BertModel(BertPreTrainedModel):
680
+ """Overall BERT model.
681
+
682
+ Args:
683
+ config: a BertConfig class instance with the configuration to build a new model
684
+
685
+ Inputs:
686
+ `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
687
+ with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts
688
+ `extract_features.py`, `run_classifier.py` and `run_squad.py`)
689
+ `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
690
+ types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
691
+ a `sentence B` token (see BERT paper for more details).
692
+ `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
693
+ selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
694
+ input sequence length in the current batch. It's the mask that we typically use for attention when
695
+ a batch has varying length sentences.
696
+ `output_all_encoded_layers`: boolean which controls the content of the `encoded_layers` output as described below. Default: `True`.
697
+
698
+ Outputs: Tuple of (encoded_layers, pooled_output)
699
+ `encoded_layers`: controlled by `output_all_encoded_layers` argument:
700
+ - `output_all_encoded_layers=True`: outputs a list of the full sequences of encoded-hidden-states at the end
701
+ of each attention block (i.e. 12 full sequences for BERT-base, 24 for BERT-large), each
702
+ encoded-hidden-state is a torch.FloatTensor of size [batch_size, sequence_length, hidden_size],
703
+ - `output_all_encoded_layers=False`: outputs only the full sequence of hidden-states corresponding
704
+ to the last attention block of shape [batch_size, sequence_length, hidden_size],
705
+ `pooled_output`: a torch.FloatTensor of size [batch_size, hidden_size] which is the output of a
706
+ classifier pretrained on top of the hidden state associated to the first character of the
707
+ input (`CLS`) to train on the Next-Sentence task (see BERT's paper).
708
+
709
+ Example usage:
710
+ ```python
711
+ # Already been converted into WordPiece token ids
712
+ input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
713
+ input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
714
+ token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
715
+ config = modeling.BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,
716
+ num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)
717
+ model = BertModel(config=config)
718
+ all_encoder_layers, pooled_output = model(input_ids, token_type_ids, input_mask)
719
+ ```
720
+ """
721
+
722
+ def __init__(self, config, add_pooling_layer=False):
723
+ super(BertModel, self).__init__(config)
724
+ self.embeddings = BertEmbeddings(config)
725
+ self.encoder = BertEncoder(config)
726
+ self.pooler = BertPooler(config) if add_pooling_layer else None
727
+ self.post_init()
728
+
729
+ def get_input_embeddings(self):
730
+ return self.embeddings.word_embeddings
731
+
732
+ def set_input_embeddings(self, value):
733
+ self.embeddings.word_embeddings = value
734
+
735
+ def forward(
736
+ self,
737
+ input_ids: torch.Tensor,
738
+ token_type_ids: Optional[torch.Tensor] = None,
739
+ attention_mask: Optional[torch.Tensor] = None,
740
+ position_ids: Optional[torch.Tensor] = None,
741
+ output_all_encoded_layers: Optional[bool] = False,
742
+ masked_tokens_mask: Optional[torch.Tensor] = None,
743
+ **kwargs
744
+ ) -> Tuple[Union[List[torch.Tensor], torch.Tensor], Optional[torch.Tensor]]:
745
+ if attention_mask is None:
746
+ attention_mask = torch.ones_like(input_ids)
747
+ if token_type_ids is None:
748
+ token_type_ids = torch.zeros_like(input_ids)
749
+
750
+ embedding_output = self.embeddings(input_ids, token_type_ids,
751
+ position_ids)
752
+
753
+ subset_mask = []
754
+ first_col_mask = []
755
+
756
+ if masked_tokens_mask is None:
757
+ subset_mask = None
758
+ else:
759
+ first_col_mask = torch.zeros_like(masked_tokens_mask)
760
+ first_col_mask[:, 0] = True
761
+ subset_mask = masked_tokens_mask | first_col_mask
762
+
763
+ encoder_outputs = self.encoder(
764
+ embedding_output,
765
+ attention_mask,
766
+ output_all_encoded_layers=output_all_encoded_layers,
767
+ subset_mask=subset_mask)
768
+
769
+ if masked_tokens_mask is None:
770
+ sequence_output = encoder_outputs[-1]
771
+ pooled_output = self.pooler(
772
+ sequence_output) if self.pooler is not None else None
773
+ else:
774
+ # TD [2022-03-01]: the indexing here is very tricky.
775
+ attention_mask_bool = attention_mask.bool()
776
+ subset_idx = subset_mask[attention_mask_bool] # type: ignore
777
+ sequence_output = encoder_outputs[-1][
778
+ masked_tokens_mask[attention_mask_bool][subset_idx]]
779
+ if self.pooler is not None:
780
+ pool_input = encoder_outputs[-1][
781
+ first_col_mask[attention_mask_bool][subset_idx]]
782
+ pooled_output = self.pooler(pool_input, pool=False)
783
+ else:
784
+ pooled_output = None
785
+
786
+ if not output_all_encoded_layers:
787
+ encoder_outputs = sequence_output
788
+
789
+ if self.pooler is not None:
790
+ return encoder_outputs, pooled_output
791
+
792
+ return encoder_outputs, None
793
+
794
+
795
+ ###################
796
+ # Bert Heads
797
+ ###################
798
+ class BertLMPredictionHead(nn.Module):
799
+
800
+ def __init__(self, config, bert_model_embedding_weights):
801
+ super().__init__()
802
+ self.transform = BertPredictionHeadTransform(config)
803
+ # The output weights are the same as the input embeddings, but there is
804
+ # an output-only bias for each token.
805
+ self.decoder = nn.Linear(bert_model_embedding_weights.size(1),
806
+ bert_model_embedding_weights.size(0))
807
+ self.decoder.weight = bert_model_embedding_weights
808
+
809
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
810
+ hidden_states = self.transform(hidden_states)
811
+ hidden_states = self.decoder(hidden_states)
812
+ return hidden_states
813
+
814
+
815
+ class BertOnlyMLMHead(nn.Module):
816
+
817
+ def __init__(self, config, bert_model_embedding_weights):
818
+ super().__init__()
819
+ self.predictions = BertLMPredictionHead(config,
820
+ bert_model_embedding_weights)
821
+
822
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
823
+ prediction_scores = self.predictions(sequence_output)
824
+ return prediction_scores
825
+
826
+
827
+ class BertOnlyNSPHead(nn.Module):
828
+
829
+ def __init__(self, config):
830
+ super().__init__()
831
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
832
+
833
+ def forward(self, pooled_output: torch.Tensor) -> torch.Tensor:
834
+ seq_relationship_score = self.seq_relationship(pooled_output)
835
+ return seq_relationship_score
836
+
837
+
838
+ #####################
839
+ # Various Bert models
840
+ #####################
841
+
842
+
843
+ class BertForPreTraining(BertPreTrainedModel):
844
+ #TBD: Coming in Future Commit
845
+ pass
846
+
847
+
848
+ class BertLMHeadModel(BertPreTrainedModel):
849
+ #TBD: Coming in Future Commit
850
+ pass
851
+
852
+
853
+ class BertForMaskedLM(BertPreTrainedModel):
854
+
855
+ config_class = BertConfig
856
+
857
+ def __init__(self, config):
858
+ super().__init__(config)
859
+
860
+ if config.is_decoder:
861
+ warnings.warn(
862
+ 'If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for '
863
+ 'bi-directional self-attention.')
864
+
865
+ self.bert = BertModel(config, add_pooling_layer=False)
866
+ self.cls = BertOnlyMLMHead(config,
867
+ self.bert.embeddings.word_embeddings.weight)
868
+
869
+ # Initialize weights and apply final processing
870
+ self.post_init()
871
+
872
+ @classmethod
873
+ def from_composer(cls,
874
+ pretrained_checkpoint,
875
+ state_dict=None,
876
+ cache_dir=None,
877
+ from_tf=False,
878
+ config=None,
879
+ *inputs,
880
+ **kwargs):
881
+ """Load from pre-trained."""
882
+ model = cls(config, *inputs, **kwargs)
883
+ if from_tf:
884
+ raise ValueError(
885
+ 'Mosaic BERT does not support loading TensorFlow weights.')
886
+
887
+ state_dict = torch.load(pretrained_checkpoint)
888
+ # If the state_dict was saved after wrapping with `composer.HuggingFaceModel`, it takes on the `model` prefix
889
+ consume_prefix_in_state_dict_if_present(state_dict, prefix='model.')
890
+ missing_keys, unexpected_keys = model.load_state_dict(state_dict,
891
+ strict=False)
892
+
893
+ if len(missing_keys) > 0:
894
+ logger.warning(
895
+ f"Found these missing keys in the checkpoint: {', '.join(missing_keys)}"
896
+ )
897
+ if len(unexpected_keys) > 0:
898
+ logger.warning(
899
+ f"Found these unexpected keys in the checkpoint: {', '.join(unexpected_keys)}"
900
+ )
901
+
902
+ return model
903
+
904
+ def get_output_embeddings(self):
905
+ return self.cls.predictions.decoder
906
+
907
+ def set_output_embeddings(self, new_embeddings):
908
+ self.cls.predictions.decoder = new_embeddings
909
+
910
+ def forward(
911
+ self,
912
+ input_ids: Optional[torch.Tensor] = None,
913
+ attention_mask: Optional[torch.Tensor] = None,
914
+ token_type_ids: Optional[torch.Tensor] = None,
915
+ position_ids: Optional[torch.Tensor] = None,
916
+ head_mask: Optional[torch.Tensor] = None,
917
+ inputs_embeds: Optional[torch.Tensor] = None,
918
+ encoder_hidden_states: Optional[torch.Tensor] = None,
919
+ encoder_attention_mask: Optional[torch.Tensor] = None,
920
+ labels: Optional[torch.Tensor] = None,
921
+ output_attentions: Optional[bool] = None,
922
+ output_hidden_states: Optional[bool] = None,
923
+ return_dict: Optional[bool] = None,
924
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
925
+ # labels should be a `torch.LongTensor` of shape
926
+ # `(batch_size, sequence_length)`. These are used for computing the
927
+ # masked language modeling loss.
928
+ #
929
+ # Indices should be in `[-100, 0, ..., config.vocab_size]` (see
930
+ # `input_ids` docstring) Tokens with indices set to `-100` are ignored
931
+ # (masked), the loss is only computed for the tokens with labels in `[0,
932
+ # ..., config.vocab_size]`
933
+ #
934
+ # Prediction scores are only computed for masked tokens and the (bs,
935
+ # seqlen) dimensions are flattened
936
+ if (input_ids is not None) == (inputs_embeds is not None):
937
+ raise ValueError('Must specify either input_ids or input_embeds!')
938
+
939
+ if labels is None:
940
+ masked_tokens_mask = None
941
+ else:
942
+ masked_tokens_mask = labels > 0
943
+
944
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
945
+
946
+ outputs = self.bert(
947
+ input_ids,
948
+ attention_mask=attention_mask,
949
+ token_type_ids=token_type_ids,
950
+ position_ids=position_ids,
951
+ head_mask=head_mask,
952
+ inputs_embeds=inputs_embeds,
953
+ encoder_hidden_states=encoder_hidden_states,
954
+ encoder_attention_mask=encoder_attention_mask,
955
+ output_attentions=output_attentions,
956
+ output_hidden_states=output_hidden_states,
957
+ return_dict=return_dict,
958
+ masked_tokens_mask=masked_tokens_mask,
959
+ )
960
+
961
+ sequence_output = outputs[0]
962
+ prediction_scores = self.cls(sequence_output)
963
+
964
+ loss = None
965
+ if labels is not None:
966
+ # Compute loss
967
+ loss_fct = nn.CrossEntropyLoss()
968
+ masked_token_idx = torch.nonzero(labels.flatten() > 0,
969
+ as_tuple=False).flatten()
970
+ loss = loss_fct(prediction_scores,
971
+ labels.flatten()[masked_token_idx])
972
+
973
+ assert input_ids is not None, 'Coding error; please open an issue'
974
+ batch, seqlen = input_ids.shape[:2]
975
+ prediction_scores = rearrange(
976
+ index_put_first_axis(
977
+ prediction_scores, masked_token_idx, batch * seqlen),
978
+ '(b s) d -> b s d',
979
+ b=batch)
980
+
981
+ if not return_dict:
982
+ output = (prediction_scores,) + outputs[2:]
983
+ return ((loss,) + output) if loss is not None else output
984
+
985
+ return MaskedLMOutput(
986
+ loss=loss,
987
+ logits=prediction_scores,
988
+ hidden_states=None,
989
+ attentions=None,
990
+ )
991
+
992
+ def prepare_inputs_for_generation(self, input_ids: torch.Tensor,
993
+ attention_mask: torch.Tensor,
994
+ **model_kwargs):
995
+ input_shape = input_ids.shape
996
+ effective_batch_size = input_shape[0]
997
+
998
+ # add a dummy token
999
+ if self.config.pad_token_id is None:
1000
+ raise ValueError('The PAD token should be defined for generation')
1001
+
1002
+ attention_mask = torch.cat([
1003
+ attention_mask,
1004
+ attention_mask.new_zeros((attention_mask.shape[0], 1))
1005
+ ],
1006
+ dim=-1)
1007
+ dummy_token = torch.full((effective_batch_size, 1),
1008
+ self.config.pad_token_id,
1009
+ dtype=torch.long,
1010
+ device=input_ids.device)
1011
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
1012
+
1013
+ return {'input_ids': input_ids, 'attention_mask': attention_mask}
1014
+
1015
+
1016
+ class BertForNextSentencePrediction(BertPreTrainedModel):
1017
+ #TBD: Push in future commit
1018
+ pass
1019
+
1020
+
1021
+ class BertForSequenceClassification(BertPreTrainedModel):
1022
+ """Bert Model transformer with a sequence classification/regression head.
1023
+
1024
+ This head is just a linear layer on top of the pooled output. Used for,
1025
+ e.g., GLUE tasks.
1026
+ """
1027
+
1028
+ def __init__(self, config):
1029
+ super().__init__(config)
1030
+ self.num_labels = config.num_labels
1031
+ self.config = config
1032
+
1033
+ self.bert = BertModel(config)
1034
+ classifier_dropout = (config.classifier_dropout
1035
+ if config.classifier_dropout is not None else
1036
+ config.hidden_dropout_prob)
1037
+ self.dropout = nn.Dropout(classifier_dropout)
1038
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1039
+
1040
+ # Initialize weights and apply final processing
1041
+ self.post_init()
1042
+
1043
+ @classmethod
1044
+ def from_composer(cls,
1045
+ pretrained_checkpoint,
1046
+ state_dict=None,
1047
+ cache_dir=None,
1048
+ from_tf=False,
1049
+ config=None,
1050
+ *inputs,
1051
+ **kwargs):
1052
+ """Load from pre-trained."""
1053
+ model = cls(config, *inputs, **kwargs)
1054
+ if from_tf:
1055
+ raise ValueError(
1056
+ 'Mosaic BERT does not support loading TensorFlow weights.')
1057
+
1058
+ state_dict = torch.load(pretrained_checkpoint)
1059
+ # If the state_dict was saved after wrapping with `composer.HuggingFaceModel`, it takes on the `model` prefix
1060
+ consume_prefix_in_state_dict_if_present(state_dict, prefix='model.')
1061
+ missing_keys, unexpected_keys = model.load_state_dict(state_dict,
1062
+ strict=False)
1063
+
1064
+ if len(missing_keys) > 0:
1065
+ logger.warning(
1066
+ f"Found these missing keys in the checkpoint: {', '.join(missing_keys)}"
1067
+ )
1068
+ if len(unexpected_keys) > 0:
1069
+ logger.warning(
1070
+ f"Found these unexpected keys in the checkpoint: {', '.join(unexpected_keys)}"
1071
+ )
1072
+
1073
+ return model
1074
+
1075
+ def forward(
1076
+ self,
1077
+ input_ids: Optional[torch.Tensor] = None,
1078
+ attention_mask: Optional[torch.Tensor] = None,
1079
+ token_type_ids: Optional[torch.Tensor] = None,
1080
+ position_ids: Optional[torch.Tensor] = None,
1081
+ head_mask: Optional[torch.Tensor] = None,
1082
+ inputs_embeds: Optional[torch.Tensor] = None,
1083
+ labels: Optional[torch.Tensor] = None,
1084
+ output_attentions: Optional[bool] = None,
1085
+ output_hidden_states: Optional[bool] = None,
1086
+ return_dict: Optional[bool] = None,
1087
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
1088
+ # labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1089
+ # Labels for computing the sequence classification/regression loss.
1090
+ # Indices should be in `[0, ..., config.num_labels - 1]`.
1091
+ # If `config.num_labels == 1` a regression loss is computed
1092
+ # (mean-square loss). If `config.num_labels > 1` a classification loss
1093
+ # is computed (cross-entropy).
1094
+
1095
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1096
+
1097
+ outputs = self.bert(
1098
+ input_ids,
1099
+ attention_mask=attention_mask,
1100
+ token_type_ids=token_type_ids,
1101
+ position_ids=position_ids,
1102
+ head_mask=head_mask,
1103
+ inputs_embeds=inputs_embeds,
1104
+ output_attentions=output_attentions,
1105
+ output_hidden_states=output_hidden_states,
1106
+ return_dict=return_dict,
1107
+ )
1108
+
1109
+ pooled_output = outputs[1]
1110
+
1111
+ pooled_output = self.dropout(pooled_output)
1112
+ logits = self.classifier(pooled_output)
1113
+
1114
+ loss = None
1115
+ if labels is not None:
1116
+ # Compute loss
1117
+ if self.config.problem_type is None:
1118
+ if self.num_labels == 1:
1119
+ self.config.problem_type = 'regression'
1120
+ elif self.num_labels > 1 and (labels.dtype == torch.long or
1121
+ labels.dtype == torch.int):
1122
+ self.config.problem_type = 'single_label_classification'
1123
+ else:
1124
+ self.config.problem_type = 'multi_label_classification'
1125
+
1126
+ if self.config.problem_type == 'regression':
1127
+ loss_fct = nn.MSELoss()
1128
+ if self.num_labels == 1:
1129
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1130
+ else:
1131
+ loss = loss_fct(logits, labels)
1132
+ elif self.config.problem_type == 'single_label_classification':
1133
+ loss_fct = nn.CrossEntropyLoss()
1134
+ loss = loss_fct(logits.view(-1, self.num_labels),
1135
+ labels.view(-1))
1136
+ elif self.config.problem_type == 'multi_label_classification':
1137
+ loss_fct = nn.BCEWithLogitsLoss()
1138
+ loss = loss_fct(logits, labels)
1139
+
1140
+ if not return_dict:
1141
+ output = (logits,) + outputs[2:]
1142
+ return ((loss,) + output) if loss is not None else output
1143
+
1144
+ return SequenceClassifierOutput(
1145
+ loss=loss,
1146
+ logits=logits,
1147
+ hidden_states=None,
1148
+ attentions=None,
1149
+ )
1150
+
1151
+
1152
+ class BertForMultipleChoice(BertPreTrainedModel):
1153
+ #TBD: Push in future commit
1154
+ pass
1155
+
1156
+
1157
+ class BertForTokenClassification(BertPreTrainedModel):
1158
+ #TBD: Push in future commit
1159
+ pass
1160
+
1161
+
1162
+ class BertForQuestionAnswering(BertPreTrainedModel):
1163
+ """Bert Model with a span classification head.
1164
+
1165
+ This is used for extractive question-answering tasks like SQuAD (a linear
1166
+ layers on top of the hidden states' output to compute `span start logits`
1167
+ and `span end logits`).
1168
+ """
1169
+ #TBD: Push in future commit
1170
+
1171
+ class BertForSequenceClassification(BertPreTrainedModel):
1172
+ def __init__(self, config):
1173
+ super().__init__(config)
1174
+ self.num_labels = config.num_labels
1175
+ self.config = config
1176
+
1177
+ self.bert = BertModel(config)
1178
+ classifier_dropout = (
1179
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1180
+ )
1181
+ self.dropout = nn.Dropout(classifier_dropout)
1182
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1183
+
1184
+ # Initialize weights and apply final processing
1185
+ self.post_init()
1186
+
1187
+ def forward(
1188
+ self,
1189
+ input_ids: Optional[torch.Tensor] = None,
1190
+ attention_mask: Optional[torch.Tensor] = None,
1191
+ token_type_ids: Optional[torch.Tensor] = None,
1192
+ position_ids: Optional[torch.Tensor] = None,
1193
+ head_mask: Optional[torch.Tensor] = None,
1194
+ inputs_embeds: Optional[torch.Tensor] = None,
1195
+ labels: Optional[torch.Tensor] = None,
1196
+ output_attentions: Optional[bool] = None,
1197
+ output_hidden_states: Optional[bool] = None,
1198
+ return_dict: Optional[bool] = None,
1199
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
1200
+ r"""
1201
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1202
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1203
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1204
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1205
+ """
1206
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1207
+
1208
+ outputs = self.bert(
1209
+ input_ids,
1210
+ attention_mask=attention_mask,
1211
+ token_type_ids=token_type_ids,
1212
+ position_ids=position_ids,
1213
+ head_mask=head_mask,
1214
+ inputs_embeds=inputs_embeds,
1215
+ output_attentions=output_attentions,
1216
+ output_hidden_states=output_hidden_states,
1217
+ return_dict=return_dict,
1218
+ )
1219
+
1220
+ pooled_output = outputs[1]
1221
+
1222
+ pooled_output = self.dropout(pooled_output)
1223
+ logits = self.classifier(pooled_output)
1224
+
1225
+ loss = None
1226
+ if labels is not None:
1227
+ if self.config.problem_type is None:
1228
+ if self.num_labels == 1:
1229
+ self.config.problem_type = "regression"
1230
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1231
+ self.config.problem_type = "single_label_classification"
1232
+ else:
1233
+ self.config.problem_type = "multi_label_classification"
1234
+
1235
+ if self.config.problem_type == "regression":
1236
+ loss_fct = MSELoss()
1237
+ if self.num_labels == 1:
1238
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1239
+ else:
1240
+ loss = loss_fct(logits, labels)
1241
+ elif self.config.problem_type == "single_label_classification":
1242
+ loss_fct = CrossEntropyLoss()
1243
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1244
+ elif self.config.problem_type == "multi_label_classification":
1245
+ loss_fct = BCEWithLogitsLoss()
1246
+ loss = loss_fct(logits, labels)
1247
+ if not return_dict:
1248
+ output = (logits,) + outputs[2:]
1249
+ return ((loss,) + output) if loss is not None else output
1250
+
1251
+ return SequenceClassifierOutput(
1252
+ loss=loss,
1253
+ logits=logits,
1254
+ hidden_states=outputs.hidden_states,
1255
+ attentions=outputs.attentions,
1256
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1e8eb2928bf708bfda5a3e0ad05e4f3686043b0651662d00c1582f8572b6be39
3
+ size 554372478