T-Almeida commited on
Commit
0c49199
1 Parent(s): c814775

Upload model

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]
config.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "trained-models/lcampillos-None-C32-H3-E60-ANone-%0.0-P0.0-42/checkpoint-1080",
3
+ "architectures": [
4
+ "RobertaMultiHeadCRFModel"
5
+ ],
6
+ "args_random_seed": 42,
7
+ "attention_probs_dropout_prob": 0.1,
8
+ "augmentation": "None",
9
+ "auto_map": {
10
+ "AutoConfig": "configuration_multiheadcrf.MultiHeadCRFConfig",
11
+ "AutoModel": "modeling_multiheadcrf.RobertaMultiHeadCRFModel"
12
+ },
13
+ "bos_token_id": 0,
14
+ "classes": [
15
+ "SINTOMA",
16
+ "PROCEDIMIENTO",
17
+ "ENFERMEDAD",
18
+ "PROTEINAS",
19
+ "CHEMICAL"
20
+ ],
21
+ "classifier_dropout": null,
22
+ "context_size": 32,
23
+ "crf_reduction": "mean",
24
+ "eos_token_id": 2,
25
+ "freeze": false,
26
+ "gradient_checkpointing": false,
27
+ "hidden_act": "gelu",
28
+ "hidden_dropout_prob": 0.1,
29
+ "hidden_size": 768,
30
+ "id2label": {
31
+ "0": "O",
32
+ "1": "B",
33
+ "2": "I"
34
+ },
35
+ "initializer_range": 0.02,
36
+ "intermediate_size": 3072,
37
+ "label2id": {
38
+ "B": 1,
39
+ "I": 2,
40
+ "O": 0
41
+ },
42
+ "layer_norm_eps": 1e-05,
43
+ "max_position_embeddings": 514,
44
+ "model_type": "crf-tagger",
45
+ "num_attention_heads": 12,
46
+ "num_hidden_layers": 12,
47
+ "number_of_layer_per_head": 3,
48
+ "p_augmentation": 0.5,
49
+ "pad_token_id": 1,
50
+ "percentage_tags": 0.0,
51
+ "position_embedding_type": "absolute",
52
+ "torch_dtype": "float32",
53
+ "transformers_version": "4.40.2",
54
+ "type_vocab_size": 1,
55
+ "use_cache": true,
56
+ "version": "0.1.2",
57
+ "vocab_size": 50262
58
+ }
configuration_multiheadcrf.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from transformers import PretrainedConfig, AutoConfig
3
+ from typing import List
4
+
5
+
6
+ class MultiHeadCRFConfig(PretrainedConfig):
7
+ model_type = "crf-tagger"
8
+
9
+ def __init__(
10
+ self,
11
+ classes = list(),
12
+ number_of_layer_per_head = 1,
13
+ augmentation = "random",
14
+ context_size = 64,
15
+ percentage_tags = 0.2,
16
+ p_augmentation = 0.5,
17
+ crf_reduction = "mean",
18
+ freeze = False,
19
+ version="0.1.2",
20
+ **kwargs,
21
+ ):
22
+ self.classes = classes
23
+ self.number_of_layer_per_head=number_of_layer_per_head
24
+ self.version = version
25
+ self.augmentation = augmentation
26
+ self.context_size = context_size
27
+ self.percentage_tags = percentage_tags
28
+ self.p_augmentation = p_augmentation
29
+ self.crf_reduction = crf_reduction
30
+ self.freeze=freeze
31
+ super().__init__(**kwargs)
32
+
33
+
34
+
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:12130943acd65f1bfc010c10a8cf964e583a9bca41e69cf44efc79234bd5060e
3
+ size 531721208
modeling_multiheadcrf.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Optional, Union, List
3
+ from transformers import AutoModel, PreTrainedModel, AutoConfig, AutoModel, RobertaModel, BertModel
4
+ from transformers.modeling_outputs import TokenClassifierOutput
5
+ from torch import nn
6
+ from torch.nn import CrossEntropyLoss
7
+ import torch
8
+ from itertools import islice
9
+ from.configuration_multiheadcrf import MultiHeadCRFConfig
10
+
11
+ NUM_PER_LAYER = 16
12
+
13
+ class RobertaMultiHeadCRFModel(PreTrainedModel):
14
+ config_class = MultiHeadCRFConfig
15
+ transformer_backbone_class = RobertaModel
16
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
17
+
18
+ def __init__(self, config):
19
+ super().__init__(config)
20
+ self.num_labels = config.num_labels
21
+
22
+ self.number_of_layer_per_head = config.number_of_layer_per_head
23
+
24
+ self.heads = config.classes #expected an array of classes we are predicting
25
+
26
+ # this can be BERT ROBERTA and other BERT-variants
27
+ self.bert = self.transformer_backbone_class(config, add_pooling_layer=False)
28
+ #AutoModel(config, add_pooling_layer=False)
29
+ #AutoModel.from_pretrained(config._name_or_path, config=config, add_pooling_layer=False)
30
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
31
+
32
+ print(sorted(self.heads))
33
+ for ent in self.heads:
34
+ for i in range(self.number_of_layer_per_head):
35
+ setattr(self, f"{ent}_dense_{i}", nn.Linear(config.hidden_size, config.hidden_size))
36
+ setattr(self, f"{ent}_dense_activation_{i}", nn.GELU(approximate='none'))
37
+ setattr(self, f"{ent}_classifier", nn.Linear(config.hidden_size, config.num_labels))
38
+ setattr(self, f"{ent}_crf", CRF(num_tags=config.num_labels, batch_first=True))
39
+ setattr(self, f"{ent}_reduction", config.crf_reduction)
40
+ self.reduction=config.crf_reduction
41
+
42
+ if self.config.freeze == True:
43
+ self.manage_freezing()
44
+
45
+ def manage_freezing(self):
46
+ for _, param in self.bert.embeddings.named_parameters():
47
+ param.requires_grad = False
48
+
49
+ num_encoders_to_freeze = self.config.num_frozen_encoder
50
+ if num_encoders_to_freeze > 0:
51
+ for _, param in islice(self.bert.encoder.named_parameters(), num_encoders_to_freeze*NUM_PER_LAYER):
52
+ param.requires_grad = False
53
+
54
+
55
+ def forward(self,
56
+ input_ids=None,
57
+ attention_mask=None,
58
+ token_type_ids=None,
59
+ position_ids=None,
60
+ head_mask=None,
61
+ inputs_embeds=None,
62
+ labels=None,
63
+ output_attentions=None,
64
+ output_hidden_states=None,
65
+ return_dict=None
66
+ ):
67
+ # Default `model.config.use_return_dict´ is `True´
68
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
69
+
70
+ outputs = self.bert(input_ids,
71
+ attention_mask=attention_mask,
72
+ token_type_ids=token_type_ids,
73
+ position_ids=position_ids,
74
+ head_mask=head_mask,
75
+ inputs_embeds=inputs_embeds,
76
+ output_attentions=output_attentions,
77
+ output_hidden_states=output_hidden_states,
78
+ return_dict=return_dict)
79
+
80
+ sequence_output = outputs[0]
81
+ sequence_output = self.dropout(sequence_output) # B S E
82
+
83
+ logits = {k:0 for k in self.heads}
84
+ for ent in self.heads:
85
+ for i in range(self.number_of_layer_per_head):
86
+ dense_output = getattr(self, f"{ent}_dense_{i}")(sequence_output)
87
+ dense_output = getattr(self, f"{ent}_dense_activation_{i}")(dense_output)
88
+ logits[ent] = getattr(self, f"{ent}_classifier")(dense_output)
89
+ #logits = self.classifier(sequence_output)
90
+ loss = None
91
+ if labels is not None:
92
+ # During train/test as we don't pass labels during inference
93
+
94
+ # loss
95
+ outputs = {k:0 for k in self.heads}
96
+ for ent in self.heads:
97
+
98
+ outputs[ent] = getattr(self, f"{ent}_crf")(logits[ent],labels[ent], reduction=self.reduction)
99
+
100
+ # print(outputs)
101
+ return sum(outputs.values()), logits
102
+ else: #running prediction?
103
+ # decoded tags
104
+ # NOTE: This gather operation (multiGPU) not work here, bc it uses tensors that are on CPU...
105
+ outputs = {k:0 for k in self.heads}
106
+
107
+ for ent in self.heads:
108
+ outputs[ent] = torch.Tensor(getattr(self, f"{ent}_crf").decode(logits[ent]))
109
+ return [outputs[ent] for ent in sorted(self.heads)]
110
+
111
+
112
+ class BertMultiHeadCRFModel(RobertaMultiHeadCRFModel):
113
+ config_class = MultiHeadCRFConfig
114
+ transformer_backbone_class = BertModel
115
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
116
+
117
+ # Taken from https://github.com/kmkurn/pytorch-crf/blob/master/torchcrf/__init__.py and fixed got uint8 warning
118
+ LARGE_NEGATIVE_NUMBER = -1e9
119
+ class CRF(nn.Module):
120
+ """Conditional random field.
121
+ This module implements a conditional random field [LMP01]_. The forward computation
122
+ of this class computes the log likelihood of the given sequence of tags and
123
+ emission score tensor. This class also has `~CRF.decode` method which finds
124
+ the best tag sequence given an emission score tensor using `Viterbi algorithm`_.
125
+ Args:
126
+ num_tags: Number of tags.
127
+ batch_first: Whether the first dimension corresponds to the size of a minibatch.
128
+ Attributes:
129
+ start_transitions (`~torch.nn.Parameter`): Start transition score tensor of size
130
+ ``(num_tags,)``.
131
+ end_transitions (`~torch.nn.Parameter`): End transition score tensor of size
132
+ ``(num_tags,)``.
133
+ transitions (`~torch.nn.Parameter`): Transition score tensor of size
134
+ ``(num_tags, num_tags)``.
135
+ .. [LMP01] Lafferty, J., McCallum, A., Pereira, F. (2001).
136
+ "Conditional random fields: Probabilistic models for segmenting and
137
+ labeling sequence data". *Proc. 18th International Conf. on Machine
138
+ Learning*. Morgan Kaufmann. pp. 282–289.
139
+ .. _Viterbi algorithm: https://en.wikipedia.org/wiki/Viterbi_algorithm
140
+ """
141
+
142
+ def __init__(self, num_tags: int, batch_first: bool = False) -> None:
143
+ if num_tags <= 0:
144
+ raise ValueError(f'invalid number of tags: {num_tags}')
145
+ super().__init__()
146
+ self.num_tags = num_tags
147
+ self.batch_first = batch_first
148
+ self.start_transitions = nn.Parameter(torch.empty(num_tags))
149
+ self.end_transitions = nn.Parameter(torch.empty(num_tags))
150
+ self.transitions = nn.Parameter(torch.empty(num_tags, num_tags))
151
+
152
+ self.reset_parameters()
153
+ self.mask_impossible_transitions()
154
+
155
+ def reset_parameters(self) -> None:
156
+ """Initialize the transition parameters.
157
+ The parameters will be initialized randomly from a uniform distribution
158
+ between -0.1 and 0.1.
159
+ """
160
+ nn.init.uniform_(self.start_transitions, -0.1, 0.1)
161
+ nn.init.uniform_(self.end_transitions, -0.1, 0.1)
162
+ nn.init.uniform_(self.transitions, -0.1, 0.1)
163
+
164
+ def mask_impossible_transitions(self) -> None:
165
+ """Set the value of impossible transitions to LARGE_NEGATIVE_NUMBER
166
+ - start transition value of I-X
167
+ - transition score of O -> I
168
+ """
169
+ with torch.no_grad():
170
+ self.start_transitions[2] = LARGE_NEGATIVE_NUMBER
171
+
172
+ self.transitions[0][2] = LARGE_NEGATIVE_NUMBER
173
+
174
+ def __repr__(self) -> str:
175
+ return f'{self.__class__.__name__}(num_tags={self.num_tags})'
176
+
177
+ def forward(
178
+ self,
179
+ emissions: torch.Tensor,
180
+ tags: torch.LongTensor,
181
+ mask: Optional[torch.ByteTensor] = None,
182
+ reduction: str = 'sum',
183
+ ) -> torch.Tensor:
184
+ """Compute the conditional log likelihood of a sequence of tags given emission scores.
185
+ Args:
186
+ emissions (`~torch.Tensor`): Emission score tensor of size
187
+ ``(seq_length, batch_size, num_tags)`` if ``batch_first`` is ``False``,
188
+ ``(batch_size, seq_length, num_tags)`` otherwise.
189
+ tags (`~torch.LongTensor`): Sequence of tags tensor of size
190
+ ``(seq_length, batch_size)`` if ``batch_first`` is ``False``,
191
+ ``(batch_size, seq_length)`` otherwise.
192
+ mask (`~torch.ByteTensor`): Mask tensor of size ``(seq_length, batch_size)``
193
+ if ``batch_first`` is ``False``, ``(batch_size, seq_length)`` otherwise.
194
+ reduction: Specifies the reduction to apply to the output:
195
+ ``none|sum|mean|token_mean``. ``none``: no reduction will be applied.
196
+ ``sum``: the output will be summed over batches. ``mean``: the output will be
197
+ averaged over batches. ``token_mean``: the output will be averaged over tokens.
198
+ Returns:
199
+ `~torch.Tensor`: The log likelihood. This will have size ``(batch_size,)`` if
200
+ reduction is ``none``, ``()`` otherwise.
201
+ """
202
+ #self.mask_impossible_transitions()
203
+ self._validate(emissions, tags=tags, mask=mask)
204
+ if reduction not in ('none', 'sum', 'mean', 'token_mean'):
205
+ raise ValueError(f'invalid reduction: {reduction}')
206
+ if mask is None:
207
+ mask = torch.ones_like(tags, dtype=torch.uint8)
208
+
209
+ if self.batch_first:
210
+ emissions = emissions.transpose(0, 1)
211
+ tags = tags.transpose(0, 1)
212
+ mask = mask.transpose(0, 1)
213
+
214
+ # shape: (batch_size,)
215
+ numerator = self._compute_score(emissions, tags, mask)
216
+ # shape: (batch_size,)
217
+ denominator = self._compute_normalizer(emissions, mask)
218
+ # shape: (batch_size,)
219
+ llh = numerator - denominator
220
+ nllh = -llh
221
+
222
+ if reduction == 'none':
223
+ return nllh
224
+ if reduction == 'sum':
225
+ return nllh.sum()
226
+ if reduction == 'mean':
227
+ return nllh.mean()
228
+ assert reduction == 'token_mean'
229
+ return nllh.sum() / mask.type_as(emissions).sum()
230
+
231
+ def decode(self, emissions: torch.Tensor,
232
+ mask: Optional[torch.ByteTensor] = None) -> List[List[int]]:
233
+ """Find the most likely tag sequence using Viterbi algorithm.
234
+ Args:
235
+ emissions (`~torch.Tensor`): Emission score tensor of size
236
+ ``(seq_length, batch_size, num_tags)`` if ``batch_first`` is ``False``,
237
+ ``(batch_size, seq_length, num_tags)`` otherwise.
238
+ mask (`~torch.ByteTensor`): Mask tensor of size ``(seq_length, batch_size)``
239
+ if ``batch_first`` is ``False``, ``(batch_size, seq_length)`` otherwise.
240
+ Returns:
241
+ List of list containing the best tag sequence for each batch.
242
+ """
243
+ self._validate(emissions, mask=mask)
244
+ if mask is None:
245
+ mask = emissions.new_ones(emissions.shape[:2], dtype=torch.uint8)
246
+
247
+ if self.batch_first:
248
+ emissions = emissions.transpose(0, 1)
249
+ mask = mask.transpose(0, 1)
250
+
251
+ return self._viterbi_decode(emissions, mask)
252
+
253
+ def _validate(
254
+ self,
255
+ emissions: torch.Tensor,
256
+ tags: Optional[torch.LongTensor] = None,
257
+ mask: Optional[torch.ByteTensor] = None) -> None:
258
+ if emissions.dim() != 3:
259
+ raise ValueError(f'emissions must have dimension of 3, got {emissions.dim()}')
260
+ if emissions.size(2) != self.num_tags:
261
+ raise ValueError(
262
+ f'expected last dimension of emissions is {self.num_tags}, '
263
+ f'got {emissions.size(2)}')
264
+
265
+ if tags is not None:
266
+ if emissions.shape[:2] != tags.shape:
267
+ raise ValueError(
268
+ 'the first two dimensions of emissions and tags must match, '
269
+ f'got {tuple(emissions.shape[:2])} and {tuple(tags.shape)}')
270
+
271
+ if mask is not None:
272
+ if emissions.shape[:2] != mask.shape:
273
+ raise ValueError(
274
+ 'the first two dimensions of emissions and mask must match, '
275
+ f'got {tuple(emissions.shape[:2])} and {tuple(mask.shape)}')
276
+ no_empty_seq = not self.batch_first and mask[0].all()
277
+ no_empty_seq_bf = self.batch_first and mask[:, 0].all()
278
+ if not no_empty_seq and not no_empty_seq_bf:
279
+ raise ValueError('mask of the first timestep must all be on')
280
+
281
+ def _compute_score(
282
+ self, emissions: torch.Tensor, tags: torch.LongTensor,
283
+ mask: torch.ByteTensor) -> torch.Tensor:
284
+ # emissions: (seq_length, batch_size, num_tags)
285
+ # tags: (seq_length, batch_size)
286
+ # mask: (seq_length, batch_size)
287
+ assert emissions.dim() == 3 and tags.dim() == 2
288
+ assert emissions.shape[:2] == tags.shape
289
+ assert emissions.size(2) == self.num_tags
290
+ assert mask.shape == tags.shape
291
+ assert mask[0].all()
292
+
293
+ seq_length, batch_size = tags.shape
294
+ mask = mask.type_as(emissions)
295
+
296
+ # Start transition score and first emission
297
+ # shape: (batch_size,)
298
+ score = self.start_transitions[tags[0]]
299
+ score += emissions[0, torch.arange(batch_size), tags[0]]
300
+
301
+ for i in range(1, seq_length):
302
+ # Transition score to next tag, only added if next timestep is valid (mask == 1)
303
+ # shape: (batch_size,)
304
+ score += self.transitions[tags[i - 1], tags[i]] * mask[i]
305
+
306
+ # Emission score for next tag, only added if next timestep is valid (mask == 1)
307
+ # shape: (batch_size,)
308
+ score += emissions[i, torch.arange(batch_size), tags[i]] * mask[i]
309
+
310
+ # End transition score
311
+ # shape: (batch_size,)
312
+ seq_ends = mask.long().sum(dim=0) - 1
313
+ # shape: (batch_size,)
314
+ last_tags = tags[seq_ends, torch.arange(batch_size)]
315
+ # shape: (batch_size,)
316
+ score += self.end_transitions[last_tags]
317
+
318
+ return score
319
+
320
+ def _compute_normalizer(
321
+ self, emissions: torch.Tensor, mask: torch.ByteTensor) -> torch.Tensor:
322
+ # emissions: (seq_length, batch_size, num_tags)
323
+ # mask: (seq_length, batch_size)
324
+ assert emissions.dim() == 3 and mask.dim() == 2
325
+ assert emissions.shape[:2] == mask.shape
326
+ assert emissions.size(2) == self.num_tags
327
+ assert mask[0].all()
328
+
329
+ seq_length = emissions.size(0)
330
+
331
+ # Start transition score and first emission; score has size of
332
+ # (batch_size, num_tags) where for each batch, the j-th column stores
333
+ # the score that the first timestep has tag j
334
+ # shape: (batch_size, num_tags)
335
+ score = self.start_transitions + emissions[0]
336
+
337
+ for i in range(1, seq_length):
338
+ # Broadcast score for every possible next tag
339
+ # shape: (batch_size, num_tags, 1)
340
+ broadcast_score = score.unsqueeze(2)
341
+
342
+ # Broadcast emission score for every possible current tag
343
+ # shape: (batch_size, 1, num_tags)
344
+ broadcast_emissions = emissions[i].unsqueeze(1)
345
+
346
+ # Compute the score tensor of size (batch_size, num_tags, num_tags) where
347
+ # for each sample, entry at row i and column j stores the sum of scores of all
348
+ # possible tag sequences so far that end with transitioning from tag i to tag j
349
+ # and emitting
350
+ # shape: (batch_size, num_tags, num_tags)
351
+ next_score = broadcast_score + self.transitions + broadcast_emissions
352
+
353
+ # Sum over all possible current tags, but we're in score space, so a sum
354
+ # becomes a log-sum-exp: for each sample, entry i stores the sum of scores of
355
+ # all possible tag sequences so far, that end in tag i
356
+ # shape: (batch_size, num_tags)
357
+ next_score = torch.logsumexp(next_score, dim=1)
358
+
359
+ # Set score to the next score if this timestep is valid (mask == 1)
360
+ # shape: (batch_size, num_tags)
361
+ score = torch.where(mask[i].unsqueeze(1).bool(), next_score, score)
362
+
363
+ # End transition score
364
+ # shape: (batch_size, num_tags)
365
+ score += self.end_transitions
366
+
367
+ # Sum (log-sum-exp) over all possible tags
368
+ # shape: (batch_size,)
369
+ return torch.logsumexp(score, dim=1)
370
+
371
+ def _viterbi_decode(self, emissions: torch.FloatTensor,
372
+ mask: torch.ByteTensor) -> List[List[int]]:
373
+ # emissions: (seq_length, batch_size, num_tags)
374
+ # mask: (seq_length, batch_size)
375
+ assert emissions.dim() == 3 and mask.dim() == 2
376
+ assert emissions.shape[:2] == mask.shape
377
+ assert emissions.size(2) == self.num_tags
378
+ assert mask[0].all()
379
+
380
+ seq_length, batch_size = mask.shape
381
+
382
+ # Start transition and first emission
383
+ # shape: (batch_size, num_tags)
384
+ score = self.start_transitions + emissions[0]
385
+ history = []
386
+
387
+ # score is a tensor of size (batch_size, num_tags) where for every batch,
388
+ # value at column j stores the score of the best tag sequence so far that ends
389
+ # with tag j
390
+ # history saves where the best tags candidate transitioned from; this is used
391
+ # when we trace back the best tag sequence
392
+
393
+ # Viterbi algorithm recursive case: we compute the score of the best tag sequence
394
+ # for every possible next tag
395
+ for i in range(1, seq_length):
396
+ # Broadcast viterbi score for every possible next tag
397
+ # shape: (batch_size, num_tags, 1)
398
+ broadcast_score = score.unsqueeze(2)
399
+
400
+ # Broadcast emission score for every possible current tag
401
+ # shape: (batch_size, 1, num_tags)
402
+ broadcast_emission = emissions[i].unsqueeze(1)
403
+
404
+ # Compute the score tensor of size (batch_size, num_tags, num_tags) where
405
+ # for each sample, entry at row i and column j stores the score of the best
406
+ # tag sequence so far that ends with transitioning from tag i to tag j and emitting
407
+ # shape: (batch_size, num_tags, num_tags)
408
+ next_score = broadcast_score + self.transitions + broadcast_emission
409
+
410
+ # Find the maximum score over all possible current tag
411
+ # shape: (batch_size, num_tags)
412
+ next_score, indices = next_score.max(dim=1)
413
+
414
+ # Set score to the next score if this timestep is valid (mask == 1)
415
+ # and save the index that produces the next score
416
+ # shape: (batch_size, num_tags)
417
+ score = torch.where(mask[i].unsqueeze(1).bool(), next_score, score)
418
+ history.append(indices)
419
+
420
+ # End transition score
421
+ # shape: (batch_size, num_tags)
422
+ score += self.end_transitions
423
+
424
+ # Now, compute the best path for each sample
425
+
426
+ # shape: (batch_size,)
427
+ seq_ends = mask.long().sum(dim=0) - 1
428
+ best_tags_list = []
429
+
430
+ for idx in range(batch_size):
431
+ # Find the tag which maximizes the score at the last timestep; this is our best tag
432
+ # for the last timestep
433
+ _, best_last_tag = score[idx].max(dim=0)
434
+ best_tags = [best_last_tag.item()]
435
+
436
+ # We trace back where the best last tag comes from, append that to our best tag
437
+ # sequence, and trace it back again, and so on
438
+ for hist in reversed(history[:seq_ends[idx]]):
439
+ best_last_tag = hist[idx][best_tags[-1]]
440
+ best_tags.append(best_last_tag.item())
441
+
442
+ # Reverse the order because we start from the last timestep
443
+ best_tags.reverse()
444
+ best_tags_list.append(best_tags)
445
+
446
+ return best_tags_list