ZTWHHH commited on
Commit
ef91db4
·
verified ·
1 Parent(s): 6874fce

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. evalkit_tf433/lib/python3.10/site-packages/transformers/models/__pycache__/__init__.cpython-310.pyc +0 -0
  2. evalkit_tf433/lib/python3.10/site-packages/transformers/models/bert_generation/__init__.py +71 -0
  3. evalkit_tf433/lib/python3.10/site-packages/transformers/models/bert_generation/__pycache__/__init__.cpython-310.pyc +0 -0
  4. evalkit_tf433/lib/python3.10/site-packages/transformers/models/bert_generation/__pycache__/modeling_bert_generation.cpython-310.pyc +0 -0
  5. evalkit_tf433/lib/python3.10/site-packages/transformers/models/bert_generation/__pycache__/tokenization_bert_generation.cpython-310.pyc +0 -0
  6. evalkit_tf433/lib/python3.10/site-packages/transformers/models/bert_generation/modeling_bert_generation.py +1006 -0
  7. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/__init__.py +138 -0
  8. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/__init__.cpython-310.pyc +0 -0
  9. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/configuration_blenderbot_small.cpython-310.pyc +0 -0
  10. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_blenderbot_small.cpython-310.pyc +0 -0
  11. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_flax_blenderbot_small.cpython-310.pyc +0 -0
  12. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_tf_blenderbot_small.cpython-310.pyc +0 -0
  13. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small.cpython-310.pyc +0 -0
  14. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small_fast.cpython-310.pyc +0 -0
  15. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/configuration_blenderbot_small.py +391 -0
  16. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/modeling_blenderbot_small.py +1605 -0
  17. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/modeling_flax_blenderbot_small.py +1522 -0
  18. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/modeling_tf_blenderbot_small.py +1415 -0
  19. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/tokenization_blenderbot_small.py +238 -0
  20. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/tokenization_blenderbot_small_fast.py +119 -0
  21. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blip_2/__pycache__/__init__.cpython-310.pyc +0 -0
  22. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blip_2/__pycache__/convert_blip_2_original_to_pytorch.cpython-310.pyc +0 -0
  23. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blip_2/__pycache__/modeling_blip_2.cpython-310.pyc +0 -0
  24. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blip_2/__pycache__/processing_blip_2.cpython-310.pyc +0 -0
  25. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blip_2/configuration_blip_2.py +355 -0
  26. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blip_2/convert_blip_2_original_to_pytorch.py +293 -0
  27. evalkit_tf433/lib/python3.10/site-packages/transformers/models/blip_2/processing_blip_2.py +154 -0
  28. evalkit_tf433/lib/python3.10/site-packages/transformers/models/byt5/__pycache__/convert_byt5_original_tf_checkpoint_to_pytorch.cpython-310.pyc +0 -0
  29. evalkit_tf433/lib/python3.10/site-packages/transformers/models/cvt/__pycache__/__init__.cpython-310.pyc +0 -0
  30. evalkit_tf433/lib/python3.10/site-packages/transformers/models/cvt/__pycache__/configuration_cvt.cpython-310.pyc +0 -0
  31. evalkit_tf433/lib/python3.10/site-packages/transformers/models/cvt/__pycache__/modeling_cvt.cpython-310.pyc +0 -0
  32. evalkit_tf433/lib/python3.10/site-packages/transformers/models/cvt/convert_cvt_original_pytorch_checkpoint_to_pytorch.py +362 -0
  33. evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/__init__.py +57 -0
  34. evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/__pycache__/__init__.cpython-310.pyc +0 -0
  35. evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/__pycache__/collating_graphormer.cpython-310.pyc +0 -0
  36. evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/__pycache__/configuration_graphormer.cpython-310.pyc +0 -0
  37. evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/__pycache__/modeling_graphormer.cpython-310.pyc +0 -0
  38. evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/algos_graphormer.pyx +107 -0
  39. evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/collating_graphormer.py +134 -0
  40. evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/configuration_graphormer.py +216 -0
  41. evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/modeling_graphormer.py +921 -0
  42. evalkit_tf433/lib/python3.10/site-packages/transformers/models/layoutlmv3/feature_extraction_layoutlmv3.py +35 -0
  43. evalkit_tf433/lib/python3.10/site-packages/transformers/models/layoutlmv3/processing_layoutlmv3.py +198 -0
  44. evalkit_tf433/lib/python3.10/site-packages/transformers/models/layoutlmv3/tokenization_layoutlmv3_fast.py +855 -0
  45. evalkit_tf433/lib/python3.10/site-packages/transformers/models/reformer/__pycache__/__init__.cpython-310.pyc +0 -0
  46. evalkit_tf433/lib/python3.10/site-packages/transformers/models/reformer/__pycache__/configuration_reformer.cpython-310.pyc +0 -0
  47. evalkit_tf433/lib/python3.10/site-packages/transformers/models/reformer/__pycache__/convert_reformer_trax_checkpoint_to_pytorch.cpython-310.pyc +0 -0
  48. evalkit_tf433/lib/python3.10/site-packages/transformers/models/reformer/__pycache__/modeling_reformer.cpython-310.pyc +0 -0
  49. evalkit_tf433/lib/python3.10/site-packages/transformers/models/reformer/__pycache__/tokenization_reformer.cpython-310.pyc +0 -0
  50. evalkit_tf433/lib/python3.10/site-packages/transformers/models/reformer/__pycache__/tokenization_reformer_fast.cpython-310.pyc +0 -0
evalkit_tf433/lib/python3.10/site-packages/transformers/models/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (4.3 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/bert_generation/__init__.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available
18
+
19
+
20
+ _import_structure = {"configuration_bert_generation": ["BertGenerationConfig"]}
21
+
22
+ try:
23
+ if not is_sentencepiece_available():
24
+ raise OptionalDependencyNotAvailable()
25
+ except OptionalDependencyNotAvailable:
26
+ pass
27
+ else:
28
+ _import_structure["tokenization_bert_generation"] = ["BertGenerationTokenizer"]
29
+
30
+ try:
31
+ if not is_torch_available():
32
+ raise OptionalDependencyNotAvailable()
33
+ except OptionalDependencyNotAvailable:
34
+ pass
35
+ else:
36
+ _import_structure["modeling_bert_generation"] = [
37
+ "BertGenerationDecoder",
38
+ "BertGenerationEncoder",
39
+ "BertGenerationPreTrainedModel",
40
+ "load_tf_weights_in_bert_generation",
41
+ ]
42
+
43
+
44
+ if TYPE_CHECKING:
45
+ from .configuration_bert_generation import BertGenerationConfig
46
+
47
+ try:
48
+ if not is_sentencepiece_available():
49
+ raise OptionalDependencyNotAvailable()
50
+ except OptionalDependencyNotAvailable:
51
+ pass
52
+ else:
53
+ from .tokenization_bert_generation import BertGenerationTokenizer
54
+
55
+ try:
56
+ if not is_torch_available():
57
+ raise OptionalDependencyNotAvailable()
58
+ except OptionalDependencyNotAvailable:
59
+ pass
60
+ else:
61
+ from .modeling_bert_generation import (
62
+ BertGenerationDecoder,
63
+ BertGenerationEncoder,
64
+ BertGenerationPreTrainedModel,
65
+ load_tf_weights_in_bert_generation,
66
+ )
67
+
68
+ else:
69
+ import sys
70
+
71
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
evalkit_tf433/lib/python3.10/site-packages/transformers/models/bert_generation/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.14 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/bert_generation/__pycache__/modeling_bert_generation.cpython-310.pyc ADDED
Binary file (32.2 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/bert_generation/__pycache__/tokenization_bert_generation.cpython-310.pyc ADDED
Binary file (6.82 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/bert_generation/modeling_bert_generation.py ADDED
@@ -0,0 +1,1006 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch BERT model specific for generation."""
16
+
17
+ import math
18
+ from typing import Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.utils.checkpoint
22
+ from torch import nn
23
+ from torch.nn import CrossEntropyLoss
24
+
25
+ from ...activations import ACT2FN
26
+ from ...modeling_outputs import BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions
27
+ from ...modeling_utils import PreTrainedModel
28
+ from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
29
+ from ...utils import (
30
+ add_code_sample_docstrings,
31
+ add_start_docstrings,
32
+ add_start_docstrings_to_model_forward,
33
+ logging,
34
+ replace_return_docstrings,
35
+ )
36
+ from .configuration_bert_generation import BertGenerationConfig
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+ _CHECKPOINT_FOR_DOC = "google/bert_for_seq_generation_L-24_bbc_encoder"
42
+ _CONFIG_FOR_DOC = "BertGenerationConfig"
43
+
44
+
45
+ # Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->BertGeneration
46
+ class BertGenerationSelfOutput(nn.Module):
47
+ def __init__(self, config):
48
+ super().__init__()
49
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
50
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
51
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
52
+
53
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
54
+ hidden_states = self.dense(hidden_states)
55
+ hidden_states = self.dropout(hidden_states)
56
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
57
+ return hidden_states
58
+
59
+
60
+ # Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->BertGeneration
61
+ class BertGenerationSelfAttention(nn.Module):
62
+ def __init__(self, config, position_embedding_type=None):
63
+ super().__init__()
64
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
65
+ raise ValueError(
66
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
67
+ f"heads ({config.num_attention_heads})"
68
+ )
69
+
70
+ self.num_attention_heads = config.num_attention_heads
71
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
72
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
73
+
74
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
75
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
76
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
77
+
78
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
79
+ self.position_embedding_type = position_embedding_type or getattr(
80
+ config, "position_embedding_type", "absolute"
81
+ )
82
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
83
+ self.max_position_embeddings = config.max_position_embeddings
84
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
85
+
86
+ self.is_decoder = config.is_decoder
87
+
88
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
89
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
90
+ x = x.view(new_x_shape)
91
+ return x.permute(0, 2, 1, 3)
92
+
93
+ def forward(
94
+ self,
95
+ hidden_states: torch.Tensor,
96
+ attention_mask: Optional[torch.FloatTensor] = None,
97
+ head_mask: Optional[torch.FloatTensor] = None,
98
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
99
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
100
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
101
+ output_attentions: Optional[bool] = False,
102
+ ) -> Tuple[torch.Tensor]:
103
+ mixed_query_layer = self.query(hidden_states)
104
+
105
+ # If this is instantiated as a cross-attention module, the keys
106
+ # and values come from an encoder; the attention mask needs to be
107
+ # such that the encoder's padding tokens are not attended to.
108
+ is_cross_attention = encoder_hidden_states is not None
109
+
110
+ if is_cross_attention and past_key_value is not None:
111
+ # reuse k,v, cross_attentions
112
+ key_layer = past_key_value[0]
113
+ value_layer = past_key_value[1]
114
+ attention_mask = encoder_attention_mask
115
+ elif is_cross_attention:
116
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
117
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
118
+ attention_mask = encoder_attention_mask
119
+ elif past_key_value is not None:
120
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
121
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
122
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
123
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
124
+ else:
125
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
126
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
127
+
128
+ query_layer = self.transpose_for_scores(mixed_query_layer)
129
+
130
+ use_cache = past_key_value is not None
131
+ if self.is_decoder:
132
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
133
+ # Further calls to cross_attention layer can then reuse all cross-attention
134
+ # key/value_states (first "if" case)
135
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
136
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
137
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
138
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
139
+ past_key_value = (key_layer, value_layer)
140
+
141
+ # Take the dot product between "query" and "key" to get the raw attention scores.
142
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
143
+
144
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
145
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
146
+ if use_cache:
147
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
148
+ -1, 1
149
+ )
150
+ else:
151
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
152
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
153
+ distance = position_ids_l - position_ids_r
154
+
155
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
156
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
157
+
158
+ if self.position_embedding_type == "relative_key":
159
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
160
+ attention_scores = attention_scores + relative_position_scores
161
+ elif self.position_embedding_type == "relative_key_query":
162
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
163
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
164
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
165
+
166
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
167
+ if attention_mask is not None:
168
+ # Apply the attention mask is (precomputed for all layers in BertGenerationModel forward() function)
169
+ attention_scores = attention_scores + attention_mask
170
+
171
+ # Normalize the attention scores to probabilities.
172
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
173
+
174
+ # This is actually dropping out entire tokens to attend to, which might
175
+ # seem a bit unusual, but is taken from the original Transformer paper.
176
+ attention_probs = self.dropout(attention_probs)
177
+
178
+ # Mask heads if we want to
179
+ if head_mask is not None:
180
+ attention_probs = attention_probs * head_mask
181
+
182
+ context_layer = torch.matmul(attention_probs, value_layer)
183
+
184
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
185
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
186
+ context_layer = context_layer.view(new_context_layer_shape)
187
+
188
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
189
+
190
+ if self.is_decoder:
191
+ outputs = outputs + (past_key_value,)
192
+ return outputs
193
+
194
+
195
+ # Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->BertGeneration
196
+ class BertGenerationAttention(nn.Module):
197
+ def __init__(self, config, position_embedding_type=None):
198
+ super().__init__()
199
+ self.self = BertGenerationSelfAttention(config, position_embedding_type=position_embedding_type)
200
+ self.output = BertGenerationSelfOutput(config)
201
+ self.pruned_heads = set()
202
+
203
+ def prune_heads(self, heads):
204
+ if len(heads) == 0:
205
+ return
206
+ heads, index = find_pruneable_heads_and_indices(
207
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
208
+ )
209
+
210
+ # Prune linear layers
211
+ self.self.query = prune_linear_layer(self.self.query, index)
212
+ self.self.key = prune_linear_layer(self.self.key, index)
213
+ self.self.value = prune_linear_layer(self.self.value, index)
214
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
215
+
216
+ # Update hyper params and store pruned heads
217
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
218
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
219
+ self.pruned_heads = self.pruned_heads.union(heads)
220
+
221
+ def forward(
222
+ self,
223
+ hidden_states: torch.Tensor,
224
+ attention_mask: Optional[torch.FloatTensor] = None,
225
+ head_mask: Optional[torch.FloatTensor] = None,
226
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
227
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
228
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
229
+ output_attentions: Optional[bool] = False,
230
+ ) -> Tuple[torch.Tensor]:
231
+ self_outputs = self.self(
232
+ hidden_states,
233
+ attention_mask,
234
+ head_mask,
235
+ encoder_hidden_states,
236
+ encoder_attention_mask,
237
+ past_key_value,
238
+ output_attentions,
239
+ )
240
+ attention_output = self.output(self_outputs[0], hidden_states)
241
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
242
+ return outputs
243
+
244
+
245
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->BertGeneration
246
+ class BertGenerationIntermediate(nn.Module):
247
+ def __init__(self, config):
248
+ super().__init__()
249
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
250
+ if isinstance(config.hidden_act, str):
251
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
252
+ else:
253
+ self.intermediate_act_fn = config.hidden_act
254
+
255
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
256
+ hidden_states = self.dense(hidden_states)
257
+ hidden_states = self.intermediate_act_fn(hidden_states)
258
+ return hidden_states
259
+
260
+
261
+ # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->BertGeneration
262
+ class BertGenerationOutput(nn.Module):
263
+ def __init__(self, config):
264
+ super().__init__()
265
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
266
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
267
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
268
+
269
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
270
+ hidden_states = self.dense(hidden_states)
271
+ hidden_states = self.dropout(hidden_states)
272
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
273
+ return hidden_states
274
+
275
+
276
+ # Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->BertGeneration
277
+ class BertGenerationLayer(nn.Module):
278
+ def __init__(self, config):
279
+ super().__init__()
280
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
281
+ self.seq_len_dim = 1
282
+ self.attention = BertGenerationAttention(config)
283
+ self.is_decoder = config.is_decoder
284
+ self.add_cross_attention = config.add_cross_attention
285
+ if self.add_cross_attention:
286
+ if not self.is_decoder:
287
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
288
+ self.crossattention = BertGenerationAttention(config, position_embedding_type="absolute")
289
+ self.intermediate = BertGenerationIntermediate(config)
290
+ self.output = BertGenerationOutput(config)
291
+
292
+ def forward(
293
+ self,
294
+ hidden_states: torch.Tensor,
295
+ attention_mask: Optional[torch.FloatTensor] = None,
296
+ head_mask: Optional[torch.FloatTensor] = None,
297
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
298
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
299
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
300
+ output_attentions: Optional[bool] = False,
301
+ ) -> Tuple[torch.Tensor]:
302
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
303
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
304
+ self_attention_outputs = self.attention(
305
+ hidden_states,
306
+ attention_mask,
307
+ head_mask,
308
+ output_attentions=output_attentions,
309
+ past_key_value=self_attn_past_key_value,
310
+ )
311
+ attention_output = self_attention_outputs[0]
312
+
313
+ # if decoder, the last output is tuple of self-attn cache
314
+ if self.is_decoder:
315
+ outputs = self_attention_outputs[1:-1]
316
+ present_key_value = self_attention_outputs[-1]
317
+ else:
318
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
319
+
320
+ cross_attn_present_key_value = None
321
+ if self.is_decoder and encoder_hidden_states is not None:
322
+ if not hasattr(self, "crossattention"):
323
+ raise ValueError(
324
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
325
+ " by setting `config.add_cross_attention=True`"
326
+ )
327
+
328
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
329
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
330
+ cross_attention_outputs = self.crossattention(
331
+ attention_output,
332
+ attention_mask,
333
+ head_mask,
334
+ encoder_hidden_states,
335
+ encoder_attention_mask,
336
+ cross_attn_past_key_value,
337
+ output_attentions,
338
+ )
339
+ attention_output = cross_attention_outputs[0]
340
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
341
+
342
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
343
+ cross_attn_present_key_value = cross_attention_outputs[-1]
344
+ present_key_value = present_key_value + cross_attn_present_key_value
345
+
346
+ layer_output = apply_chunking_to_forward(
347
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
348
+ )
349
+ outputs = (layer_output,) + outputs
350
+
351
+ # if decoder, return the attn key/values as the last output
352
+ if self.is_decoder:
353
+ outputs = outputs + (present_key_value,)
354
+
355
+ return outputs
356
+
357
+ def feed_forward_chunk(self, attention_output):
358
+ intermediate_output = self.intermediate(attention_output)
359
+ layer_output = self.output(intermediate_output, attention_output)
360
+ return layer_output
361
+
362
+
363
+ # Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->BertGeneration
364
+ class BertEncoder(nn.Module):
365
+ def __init__(self, config):
366
+ super().__init__()
367
+ self.config = config
368
+ self.layer = nn.ModuleList([BertGenerationLayer(config) for _ in range(config.num_hidden_layers)])
369
+ self.gradient_checkpointing = False
370
+
371
+ def forward(
372
+ self,
373
+ hidden_states: torch.Tensor,
374
+ attention_mask: Optional[torch.FloatTensor] = None,
375
+ head_mask: Optional[torch.FloatTensor] = None,
376
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
377
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
378
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
379
+ use_cache: Optional[bool] = None,
380
+ output_attentions: Optional[bool] = False,
381
+ output_hidden_states: Optional[bool] = False,
382
+ return_dict: Optional[bool] = True,
383
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
384
+ all_hidden_states = () if output_hidden_states else None
385
+ all_self_attentions = () if output_attentions else None
386
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
387
+
388
+ if self.gradient_checkpointing and self.training:
389
+ if use_cache:
390
+ logger.warning_once(
391
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
392
+ )
393
+ use_cache = False
394
+
395
+ next_decoder_cache = () if use_cache else None
396
+ for i, layer_module in enumerate(self.layer):
397
+ if output_hidden_states:
398
+ all_hidden_states = all_hidden_states + (hidden_states,)
399
+
400
+ layer_head_mask = head_mask[i] if head_mask is not None else None
401
+ past_key_value = past_key_values[i] if past_key_values is not None else None
402
+
403
+ if self.gradient_checkpointing and self.training:
404
+
405
+ def create_custom_forward(module):
406
+ def custom_forward(*inputs):
407
+ return module(*inputs, past_key_value, output_attentions)
408
+
409
+ return custom_forward
410
+
411
+ layer_outputs = torch.utils.checkpoint.checkpoint(
412
+ create_custom_forward(layer_module),
413
+ hidden_states,
414
+ attention_mask,
415
+ layer_head_mask,
416
+ encoder_hidden_states,
417
+ encoder_attention_mask,
418
+ )
419
+ else:
420
+ layer_outputs = layer_module(
421
+ hidden_states,
422
+ attention_mask,
423
+ layer_head_mask,
424
+ encoder_hidden_states,
425
+ encoder_attention_mask,
426
+ past_key_value,
427
+ output_attentions,
428
+ )
429
+
430
+ hidden_states = layer_outputs[0]
431
+ if use_cache:
432
+ next_decoder_cache += (layer_outputs[-1],)
433
+ if output_attentions:
434
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
435
+ if self.config.add_cross_attention:
436
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
437
+
438
+ if output_hidden_states:
439
+ all_hidden_states = all_hidden_states + (hidden_states,)
440
+
441
+ if not return_dict:
442
+ return tuple(
443
+ v
444
+ for v in [
445
+ hidden_states,
446
+ next_decoder_cache,
447
+ all_hidden_states,
448
+ all_self_attentions,
449
+ all_cross_attentions,
450
+ ]
451
+ if v is not None
452
+ )
453
+ return BaseModelOutputWithPastAndCrossAttentions(
454
+ last_hidden_state=hidden_states,
455
+ past_key_values=next_decoder_cache,
456
+ hidden_states=all_hidden_states,
457
+ attentions=all_self_attentions,
458
+ cross_attentions=all_cross_attentions,
459
+ )
460
+
461
+
462
+ def load_tf_weights_in_bert_generation(
463
+ model, tf_hub_path, model_class, is_encoder_named_decoder=False, is_encoder=False
464
+ ):
465
+ try:
466
+ import numpy as np
467
+ import tensorflow.compat.v1 as tf
468
+ import tensorflow_hub as hub
469
+ import tensorflow_text # noqa: F401
470
+
471
+ tf.disable_eager_execution()
472
+ except ImportError:
473
+ logger.error(
474
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
475
+ "https://www.tensorflow.org/install/ for installation instructions."
476
+ )
477
+ raise
478
+ tf_model = hub.Module(tf_hub_path)
479
+ init = tf.global_variables_initializer()
480
+ with tf.Session() as sess:
481
+ init.run()
482
+ all_variables = tf_model.variable_map
483
+ keep_track_variables = all_variables.copy()
484
+ for key in list(all_variables.keys()):
485
+ if "global" in key:
486
+ logger.info(f"Skipping {key}...")
487
+ continue
488
+ if not is_encoder:
489
+ model_pointer = getattr(model, model_class)
490
+ else:
491
+ model_pointer = model
492
+ is_embedding = False
493
+ logger.info(f"Trying to match {key}...")
494
+ # remove start_string = "module/bert/"
495
+ sub_layers = key.split("/")[2:]
496
+ if is_encoder_named_decoder and sub_layers[0] == "encoder":
497
+ logger.info(f"Skipping encoder layer {key} for decoder")
498
+ continue
499
+ if is_encoder and sub_layers[0] == "decoder":
500
+ logger.info(f"Skipping decoder layer {key} for encoder")
501
+ continue
502
+ for i, sub_layer in enumerate(sub_layers):
503
+ if sub_layer == "embeddings":
504
+ is_embedding = True
505
+ elif sub_layer == "LayerNorm":
506
+ is_embedding = False
507
+ if "layer" in sub_layer:
508
+ model_pointer = model_pointer.layer[int(sub_layer.split("_")[-1])]
509
+ elif sub_layer in ["kernel", "gamma"]:
510
+ model_pointer = model_pointer.weight
511
+ elif sub_layer == "beta":
512
+ model_pointer = model_pointer.bias
513
+ elif sub_layer == "encdec":
514
+ model_pointer = model_pointer.crossattention.self
515
+ elif sub_layer == "encdec_output":
516
+ model_pointer = model_pointer.crossattention.output
517
+ elif is_encoder_named_decoder and sub_layer == "decoder":
518
+ model_pointer = model_pointer.encoder
519
+ else:
520
+ if sub_layer == "attention" and "encdec" in sub_layers[i + 1]:
521
+ continue
522
+ try:
523
+ model_pointer = getattr(model_pointer, sub_layer)
524
+ except AttributeError:
525
+ logger.info(f"Skipping to initialize {key} at {sub_layer}...")
526
+ raise AttributeError
527
+
528
+ array = np.asarray(sess.run(all_variables[key]))
529
+ if not is_embedding:
530
+ logger.info(f"Transposing numpy weight of shape {array.shape} for {key}")
531
+ array = np.transpose(array)
532
+ else:
533
+ model_pointer = model_pointer.weight
534
+
535
+ if model_pointer.shape != array.shape:
536
+ raise ValueError(f"Pointer shape {model_pointer.shape} and array shape {array.shape} mismatched")
537
+ logger.info(f"Initialize PyTorch weight {key}")
538
+
539
+ model_pointer.data = torch.from_numpy(array.astype(np.float32))
540
+ keep_track_variables.pop(key, None)
541
+
542
+ logger.info(f"Weights not copied to PyTorch model: {', '.join(keep_track_variables.keys())}")
543
+ return model
544
+
545
+
546
+ class BertGenerationEmbeddings(nn.Module):
547
+ """Construct the embeddings from word and position embeddings."""
548
+
549
+ def __init__(self, config):
550
+ super().__init__()
551
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
552
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
553
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
554
+ # any TensorFlow checkpoint file
555
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
556
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
557
+
558
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
559
+ self.register_buffer(
560
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
561
+ )
562
+
563
+ def forward(self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0):
564
+ if input_ids is not None:
565
+ input_shape = input_ids.size()
566
+ else:
567
+ input_shape = inputs_embeds.size()[:-1]
568
+
569
+ seq_length = input_shape[1]
570
+
571
+ if position_ids is None:
572
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
573
+
574
+ if inputs_embeds is None:
575
+ inputs_embeds = self.word_embeddings(input_ids)
576
+ position_embeddings = self.position_embeddings(position_ids)
577
+
578
+ embeddings = inputs_embeds + position_embeddings
579
+ embeddings = self.LayerNorm(embeddings)
580
+ embeddings = self.dropout(embeddings)
581
+ return embeddings
582
+
583
+
584
+ class BertGenerationPreTrainedModel(PreTrainedModel):
585
+ """
586
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
587
+ models.
588
+ """
589
+
590
+ config_class = BertGenerationConfig
591
+ base_model_prefix = "bert"
592
+ supports_gradient_checkpointing = True
593
+
594
+ def _init_weights(self, module):
595
+ """Initialize the weights"""
596
+ if isinstance(module, nn.Linear):
597
+ # Slightly different from the TF version which uses truncated_normal for initialization
598
+ # cf https://github.com/pytorch/pytorch/pull/5617
599
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
600
+ if module.bias is not None:
601
+ module.bias.data.zero_()
602
+ elif isinstance(module, nn.Embedding):
603
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
604
+ if module.padding_idx is not None:
605
+ module.weight.data[module.padding_idx].zero_()
606
+ elif isinstance(module, nn.LayerNorm):
607
+ module.bias.data.zero_()
608
+ module.weight.data.fill_(1.0)
609
+
610
+ def _set_gradient_checkpointing(self, module, value=False):
611
+ if isinstance(module, BertEncoder):
612
+ module.gradient_checkpointing = value
613
+
614
+
615
+ BERT_GENERATION_START_DOCSTRING = r"""
616
+
617
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
618
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
619
+ etc.)
620
+
621
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
622
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
623
+ and behavior.
624
+
625
+ Parameters:
626
+ config ([`BertGenerationConfig`]): Model configuration class with all the parameters of the model.
627
+ Initializing with a config file does not load the weights associated with the model, only the
628
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
629
+ """
630
+
631
+ BERT_GENERATION_INPUTS_DOCSTRING = r"""
632
+ Args:
633
+ input_ids (`torch.LongTensor` of shape `({0})`):
634
+ Indices of input sequence tokens in the vocabulary.
635
+
636
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
637
+ [`PreTrainedTokenizer.encode`] for details.
638
+
639
+ [What are input IDs?](../glossary#input-ids)
640
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
641
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
642
+
643
+ - 1 for tokens that are **not masked**,
644
+ - 0 for tokens that are **masked**.
645
+
646
+ [What are attention masks?](../glossary#attention-mask)
647
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
648
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
649
+ config.max_position_embeddings - 1]`.
650
+
651
+ [What are position IDs?](../glossary#position-ids)
652
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
653
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
654
+
655
+ - 1 indicates the head is **not masked**,
656
+ - 0 indicates the head is **masked**.
657
+
658
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
659
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
660
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
661
+ model's internal embedding lookup matrix.
662
+ output_attentions (`bool`, *optional*):
663
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
664
+ tensors for more detail.
665
+ output_hidden_states (`bool`, *optional*):
666
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
667
+ more detail.
668
+ return_dict (`bool`, *optional*):
669
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
670
+ """
671
+
672
+
673
+ @add_start_docstrings(
674
+ "The bare BertGeneration model transformer outputting raw hidden-states without any specific head on top.",
675
+ BERT_GENERATION_START_DOCSTRING,
676
+ )
677
+ class BertGenerationEncoder(BertGenerationPreTrainedModel):
678
+ """
679
+
680
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
681
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
682
+ all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
683
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
684
+
685
+ This model should be used when leveraging Bert or Roberta checkpoints for the [`EncoderDecoderModel`] class as
686
+ described in [Leveraging Pre-trained Checkpoints for Sequence Generation Tasks](https://arxiv.org/abs/1907.12461)
687
+ by Sascha Rothe, Shashi Narayan, and Aliaksei Severyn.
688
+
689
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
690
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
691
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
692
+ """
693
+
694
+ def __init__(self, config):
695
+ super().__init__(config)
696
+ self.config = config
697
+
698
+ self.embeddings = BertGenerationEmbeddings(config)
699
+ self.encoder = BertEncoder(config)
700
+
701
+ # Initialize weights and apply final processing
702
+ self.post_init()
703
+
704
+ def get_input_embeddings(self):
705
+ return self.embeddings.word_embeddings
706
+
707
+ def set_input_embeddings(self, value):
708
+ self.embeddings.word_embeddings = value
709
+
710
+ def _prune_heads(self, heads_to_prune):
711
+ """
712
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
713
+ class PreTrainedModel
714
+ """
715
+ for layer, heads in heads_to_prune.items():
716
+ self.encoder.layer[layer].attention.prune_heads(heads)
717
+
718
+ @add_start_docstrings_to_model_forward(BERT_GENERATION_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
719
+ @add_code_sample_docstrings(
720
+ checkpoint=_CHECKPOINT_FOR_DOC,
721
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
722
+ config_class=_CONFIG_FOR_DOC,
723
+ )
724
+ def forward(
725
+ self,
726
+ input_ids: Optional[torch.Tensor] = None,
727
+ attention_mask: Optional[torch.Tensor] = None,
728
+ position_ids: Optional[torch.Tensor] = None,
729
+ head_mask: Optional[torch.Tensor] = None,
730
+ inputs_embeds: Optional[torch.Tensor] = None,
731
+ encoder_hidden_states: Optional[torch.Tensor] = None,
732
+ encoder_attention_mask: Optional[torch.Tensor] = None,
733
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
734
+ use_cache: Optional[bool] = None,
735
+ output_attentions: Optional[bool] = None,
736
+ output_hidden_states: Optional[bool] = None,
737
+ return_dict: Optional[bool] = None,
738
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
739
+ r"""
740
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
741
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
742
+ the model is configured as a decoder.
743
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
744
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
745
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: `1` for
746
+ tokens that are NOT MASKED, `0` for MASKED tokens.
747
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
748
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
749
+
750
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
751
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
752
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
753
+ use_cache (`bool`, *optional*):
754
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
755
+ `past_key_values`).
756
+ """
757
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
758
+ output_hidden_states = (
759
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
760
+ )
761
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
762
+
763
+ if self.config.is_decoder:
764
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
765
+ else:
766
+ use_cache = False
767
+
768
+ if input_ids is not None and inputs_embeds is not None:
769
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
770
+ elif input_ids is not None:
771
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
772
+ input_shape = input_ids.size()
773
+ elif inputs_embeds is not None:
774
+ input_shape = inputs_embeds.size()[:-1]
775
+ else:
776
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
777
+
778
+ batch_size, seq_length = input_shape
779
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
780
+
781
+ # past_key_values_length
782
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
783
+
784
+ if attention_mask is None:
785
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
786
+
787
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
788
+ # ourselves in which case we just need to make it broadcastable to all heads.
789
+ extended_attention_mask = None
790
+ if not use_cache:
791
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
792
+
793
+ # If a 2D or 3D attention mask is provided for the cross-attention
794
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
795
+ if self.config.is_decoder and encoder_hidden_states is not None:
796
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
797
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
798
+ if encoder_attention_mask is None:
799
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
800
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
801
+ else:
802
+ encoder_extended_attention_mask = None
803
+
804
+ # Prepare head mask if needed
805
+ # 1.0 in head_mask indicate we keep the head
806
+ # attention_probs has shape bsz x n_heads x N x N
807
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
808
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
809
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
810
+
811
+ embedding_output = self.embeddings(
812
+ input_ids=input_ids,
813
+ position_ids=position_ids,
814
+ inputs_embeds=inputs_embeds,
815
+ past_key_values_length=past_key_values_length,
816
+ )
817
+
818
+ encoder_outputs = self.encoder(
819
+ embedding_output,
820
+ attention_mask=extended_attention_mask,
821
+ head_mask=head_mask,
822
+ encoder_hidden_states=encoder_hidden_states,
823
+ encoder_attention_mask=encoder_extended_attention_mask,
824
+ past_key_values=past_key_values,
825
+ use_cache=use_cache,
826
+ output_attentions=output_attentions,
827
+ output_hidden_states=output_hidden_states,
828
+ return_dict=return_dict,
829
+ )
830
+ sequence_output = encoder_outputs[0]
831
+
832
+ if not return_dict:
833
+ return (sequence_output,) + encoder_outputs[1:]
834
+
835
+ return BaseModelOutputWithPastAndCrossAttentions(
836
+ last_hidden_state=sequence_output,
837
+ past_key_values=encoder_outputs.past_key_values,
838
+ hidden_states=encoder_outputs.hidden_states,
839
+ attentions=encoder_outputs.attentions,
840
+ cross_attentions=encoder_outputs.cross_attentions,
841
+ )
842
+
843
+
844
+ class BertGenerationOnlyLMHead(nn.Module):
845
+ def __init__(self, config):
846
+ super().__init__()
847
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
848
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
849
+ self.decoder.bias = self.bias
850
+
851
+ def forward(self, hidden_states):
852
+ logits = self.decoder(hidden_states)
853
+ return logits
854
+
855
+ def _tie_weights(self):
856
+ # To tie those two weights if they get disconnected (on TPU or when the bias is resized)
857
+ self.bias = self.decoder.bias
858
+
859
+
860
+ @add_start_docstrings(
861
+ """BertGeneration Model with a `language modeling` head on top for CLM fine-tuning.""",
862
+ BERT_GENERATION_START_DOCSTRING,
863
+ )
864
+ class BertGenerationDecoder(BertGenerationPreTrainedModel):
865
+ _tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
866
+
867
+ def __init__(self, config):
868
+ super().__init__(config)
869
+
870
+ if not config.is_decoder:
871
+ logger.warning("If you want to use `BertGenerationDecoder` as a standalone, add `is_decoder=True.`")
872
+
873
+ self.bert = BertGenerationEncoder(config)
874
+ self.lm_head = BertGenerationOnlyLMHead(config)
875
+
876
+ # Initialize weights and apply final processing
877
+ self.post_init()
878
+
879
+ def get_output_embeddings(self):
880
+ return self.lm_head.decoder
881
+
882
+ def set_output_embeddings(self, new_embeddings):
883
+ self.lm_head.decoder = new_embeddings
884
+
885
+ @add_start_docstrings_to_model_forward(BERT_GENERATION_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
886
+ @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
887
+ def forward(
888
+ self,
889
+ input_ids: Optional[torch.Tensor] = None,
890
+ attention_mask: Optional[torch.Tensor] = None,
891
+ position_ids: Optional[torch.Tensor] = None,
892
+ head_mask: Optional[torch.Tensor] = None,
893
+ inputs_embeds: Optional[torch.Tensor] = None,
894
+ encoder_hidden_states: Optional[torch.Tensor] = None,
895
+ encoder_attention_mask: Optional[torch.Tensor] = None,
896
+ labels: Optional[torch.Tensor] = None,
897
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
898
+ use_cache: Optional[bool] = None,
899
+ output_attentions: Optional[bool] = None,
900
+ output_hidden_states: Optional[bool] = None,
901
+ return_dict: Optional[bool] = None,
902
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
903
+ r"""
904
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
905
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
906
+ the model is configured as a decoder.
907
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
908
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
909
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
910
+
911
+ - 1 for tokens that are **not masked**,
912
+ - 0 for tokens that are **masked**.
913
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
914
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
915
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
916
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
917
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
918
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
919
+
920
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
921
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
922
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
923
+ use_cache (`bool`, *optional*):
924
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
925
+ `past_key_values`).
926
+
927
+ Returns:
928
+
929
+ Example:
930
+
931
+ ```python
932
+ >>> from transformers import AutoTokenizer, BertGenerationDecoder, BertGenerationConfig
933
+ >>> import torch
934
+
935
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder")
936
+ >>> config = BertGenerationConfig.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder")
937
+ >>> config.is_decoder = True
938
+ >>> model = BertGenerationDecoder.from_pretrained(
939
+ ... "google/bert_for_seq_generation_L-24_bbc_encoder", config=config
940
+ ... )
941
+
942
+ >>> inputs = tokenizer("Hello, my dog is cute", return_token_type_ids=False, return_tensors="pt")
943
+ >>> outputs = model(**inputs)
944
+
945
+ >>> prediction_logits = outputs.logits
946
+ ```"""
947
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
948
+ if labels is not None:
949
+ use_cache = False
950
+
951
+ outputs = self.bert(
952
+ input_ids,
953
+ attention_mask=attention_mask,
954
+ position_ids=position_ids,
955
+ head_mask=head_mask,
956
+ inputs_embeds=inputs_embeds,
957
+ encoder_hidden_states=encoder_hidden_states,
958
+ encoder_attention_mask=encoder_attention_mask,
959
+ past_key_values=past_key_values,
960
+ use_cache=use_cache,
961
+ output_attentions=output_attentions,
962
+ output_hidden_states=output_hidden_states,
963
+ return_dict=return_dict,
964
+ )
965
+
966
+ sequence_output = outputs[0]
967
+ prediction_scores = self.lm_head(sequence_output)
968
+
969
+ lm_loss = None
970
+ if labels is not None:
971
+ # we are doing next-token prediction; shift prediction scores and input ids by one
972
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
973
+ labels = labels[:, 1:].contiguous()
974
+ loss_fct = CrossEntropyLoss()
975
+ lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
976
+
977
+ if not return_dict:
978
+ output = (prediction_scores,) + outputs[1:]
979
+ return ((lm_loss,) + output) if lm_loss is not None else output
980
+
981
+ return CausalLMOutputWithCrossAttentions(
982
+ loss=lm_loss,
983
+ logits=prediction_scores,
984
+ past_key_values=outputs.past_key_values,
985
+ hidden_states=outputs.hidden_states,
986
+ attentions=outputs.attentions,
987
+ cross_attentions=outputs.cross_attentions,
988
+ )
989
+
990
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
991
+ input_shape = input_ids.shape
992
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
993
+ if attention_mask is None:
994
+ attention_mask = input_ids.new_ones(input_shape)
995
+
996
+ # cut decoder_input_ids if past is used
997
+ if past_key_values is not None:
998
+ input_ids = input_ids[:, -1:]
999
+
1000
+ return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values}
1001
+
1002
+ def _reorder_cache(self, past_key_values, beam_idx):
1003
+ reordered_past = ()
1004
+ for layer_past in past_key_values:
1005
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
1006
+ return reordered_past
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/__init__.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import (
17
+ OptionalDependencyNotAvailable,
18
+ _LazyModule,
19
+ is_flax_available,
20
+ is_tf_available,
21
+ is_tokenizers_available,
22
+ is_torch_available,
23
+ )
24
+
25
+
26
+ _import_structure = {
27
+ "configuration_blenderbot_small": [
28
+ "BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP",
29
+ "BlenderbotSmallConfig",
30
+ "BlenderbotSmallOnnxConfig",
31
+ ],
32
+ "tokenization_blenderbot_small": ["BlenderbotSmallTokenizer"],
33
+ }
34
+
35
+ try:
36
+ if not is_tokenizers_available():
37
+ raise OptionalDependencyNotAvailable()
38
+ except OptionalDependencyNotAvailable:
39
+ pass
40
+ else:
41
+ _import_structure["tokenization_blenderbot_small_fast"] = ["BlenderbotSmallTokenizerFast"]
42
+
43
+ try:
44
+ if not is_torch_available():
45
+ raise OptionalDependencyNotAvailable()
46
+ except OptionalDependencyNotAvailable:
47
+ pass
48
+ else:
49
+ _import_structure["modeling_blenderbot_small"] = [
50
+ "BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST",
51
+ "BlenderbotSmallForCausalLM",
52
+ "BlenderbotSmallForConditionalGeneration",
53
+ "BlenderbotSmallModel",
54
+ "BlenderbotSmallPreTrainedModel",
55
+ ]
56
+
57
+ try:
58
+ if not is_tf_available():
59
+ raise OptionalDependencyNotAvailable()
60
+ except OptionalDependencyNotAvailable:
61
+ pass
62
+ else:
63
+ _import_structure["modeling_tf_blenderbot_small"] = [
64
+ "TFBlenderbotSmallForConditionalGeneration",
65
+ "TFBlenderbotSmallModel",
66
+ "TFBlenderbotSmallPreTrainedModel",
67
+ ]
68
+
69
+ try:
70
+ if not is_flax_available():
71
+ raise OptionalDependencyNotAvailable()
72
+ except OptionalDependencyNotAvailable:
73
+ pass
74
+ else:
75
+ _import_structure["modeling_flax_blenderbot_small"] = [
76
+ "FlaxBlenderbotSmallForConditionalGeneration",
77
+ "FlaxBlenderbotSmallModel",
78
+ "FlaxBlenderbotSmallPreTrainedModel",
79
+ ]
80
+
81
+ if TYPE_CHECKING:
82
+ from .configuration_blenderbot_small import (
83
+ BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP,
84
+ BlenderbotSmallConfig,
85
+ BlenderbotSmallOnnxConfig,
86
+ )
87
+ from .tokenization_blenderbot_small import BlenderbotSmallTokenizer
88
+
89
+ try:
90
+ if not is_tokenizers_available():
91
+ raise OptionalDependencyNotAvailable()
92
+ except OptionalDependencyNotAvailable:
93
+ pass
94
+ else:
95
+ from .tokenization_blenderbot_small_fast import BlenderbotSmallTokenizerFast
96
+
97
+ try:
98
+ if not is_torch_available():
99
+ raise OptionalDependencyNotAvailable()
100
+ except OptionalDependencyNotAvailable:
101
+ pass
102
+ else:
103
+ from .modeling_blenderbot_small import (
104
+ BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST,
105
+ BlenderbotSmallForCausalLM,
106
+ BlenderbotSmallForConditionalGeneration,
107
+ BlenderbotSmallModel,
108
+ BlenderbotSmallPreTrainedModel,
109
+ )
110
+
111
+ try:
112
+ if not is_tf_available():
113
+ raise OptionalDependencyNotAvailable()
114
+ except OptionalDependencyNotAvailable:
115
+ pass
116
+ else:
117
+ from .modeling_tf_blenderbot_small import (
118
+ TFBlenderbotSmallForConditionalGeneration,
119
+ TFBlenderbotSmallModel,
120
+ TFBlenderbotSmallPreTrainedModel,
121
+ )
122
+
123
+ try:
124
+ if not is_flax_available():
125
+ raise OptionalDependencyNotAvailable()
126
+ except OptionalDependencyNotAvailable:
127
+ pass
128
+ else:
129
+ from .modeling_flax_blenderbot_small import (
130
+ FlaxBlenderbotSmallForConditionalGeneration,
131
+ FlaxBlenderbotSmallModel,
132
+ FlaxBlenderbotSmallPreTrainedModel,
133
+ )
134
+
135
+ else:
136
+ import sys
137
+
138
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.04 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/configuration_blenderbot_small.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_blenderbot_small.cpython-310.pyc ADDED
Binary file (54.4 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_flax_blenderbot_small.cpython-310.pyc ADDED
Binary file (43.2 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_tf_blenderbot_small.cpython-310.pyc ADDED
Binary file (45.2 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small.cpython-310.pyc ADDED
Binary file (7.92 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small_fast.cpython-310.pyc ADDED
Binary file (3.33 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/configuration_blenderbot_small.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Facebook, Inc. and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ BlenderbotSmall model configuration"""
16
+
17
+ from collections import OrderedDict
18
+ from typing import Any, Mapping, Optional
19
+
20
+ from ... import PreTrainedTokenizer
21
+ from ...configuration_utils import PretrainedConfig
22
+ from ...file_utils import TensorType, is_torch_available
23
+ from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeq2SeqConfigWithPast
24
+ from ...onnx.utils import compute_effective_axis_dimension
25
+ from ...utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP = {
31
+ "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json",
32
+ # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small
33
+ }
34
+
35
+
36
+ class BlenderbotSmallConfig(PretrainedConfig):
37
+ r"""
38
+ This is the configuration class to store the configuration of a [`BlenderbotSmallModel`]. It is used to instantiate
39
+ an BlenderbotSmall model according to the specified arguments, defining the model architecture. Instantiating a
40
+ configuration with the defaults will yield a similar configuration to that of the BlenderbotSmall
41
+ [facebook/blenderbot_small-90M](https://huggingface.co/facebook/blenderbot_small-90M) architecture.
42
+
43
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
44
+ documentation from [`PretrainedConfig`] for more information.
45
+
46
+
47
+ Args:
48
+ vocab_size (`int`, *optional*, defaults to 50265):
49
+ Vocabulary size of the BlenderbotSmall model. Defines the number of different tokens that can be
50
+ represented by the `inputs_ids` passed when calling [`BlenderbotSmallModel`] or [`TFBlenderbotSmallModel`].
51
+ d_model (`int`, *optional*, defaults to 512):
52
+ Dimensionality of the layers and the pooler layer.
53
+ encoder_layers (`int`, *optional*, defaults to 8):
54
+ Number of encoder layers.
55
+ decoder_layers (`int`, *optional*, defaults to 8):
56
+ Number of decoder layers.
57
+ encoder_attention_heads (`int`, *optional*, defaults to 16):
58
+ Number of attention heads for each attention layer in the Transformer encoder.
59
+ decoder_attention_heads (`int`, *optional*, defaults to 16):
60
+ Number of attention heads for each attention layer in the Transformer decoder.
61
+ decoder_ffn_dim (`int`, *optional*, defaults to 2048):
62
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
63
+ encoder_ffn_dim (`int`, *optional*, defaults to 2048):
64
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
65
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
66
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
67
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
68
+ dropout (`float`, *optional*, defaults to 0.1):
69
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
70
+ attention_dropout (`float`, *optional*, defaults to 0.0):
71
+ The dropout ratio for the attention probabilities.
72
+ activation_dropout (`float`, *optional*, defaults to 0.0):
73
+ The dropout ratio for activations inside the fully connected layer.
74
+ max_position_embeddings (`int`, *optional*, defaults to 512):
75
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
76
+ just in case (e.g., 512 or 1024 or 2048).
77
+ init_std (`float`, *optional*, defaults to 0.02):
78
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
79
+ encoder_layerdrop (`float`, *optional*, defaults to 0.0):
80
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
81
+ for more details.
82
+ decoder_layerdrop (`float`, *optional*, defaults to 0.0):
83
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
84
+ for more details.
85
+ scale_embedding (`bool`, *optional*, defaults to `False`):
86
+ Scale embeddings by diving by sqrt(d_model).
87
+ use_cache (`bool`, *optional*, defaults to `True`):
88
+ Whether or not the model should return the last key/values attentions (not used by all models)
89
+ forced_eos_token_id (`int`, *optional*, defaults to 2):
90
+ The id of the token to force as the last generated token when `max_length` is reached. Usually set to
91
+ `eos_token_id`.
92
+
93
+ Example:
94
+
95
+ ```python
96
+ >>> from transformers import BlenderbotSmallConfig, BlenderbotSmallModel
97
+
98
+ >>> # Initializing a BlenderbotSmall facebook/blenderbot_small-90M style configuration
99
+ >>> configuration = BlenderbotSmallConfig()
100
+
101
+ >>> # Initializing a model (with random weights) from the facebook/blenderbot_small-90M style configuration
102
+ >>> model = BlenderbotSmallModel(configuration)
103
+
104
+ >>> # Accessing the model configuration
105
+ >>> configuration = model.config
106
+ ```"""
107
+ model_type = "blenderbot-small"
108
+ keys_to_ignore_at_inference = ["past_key_values"]
109
+ attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
110
+
111
+ def __init__(
112
+ self,
113
+ vocab_size=50265,
114
+ max_position_embeddings=512,
115
+ encoder_layers=8,
116
+ encoder_ffn_dim=2048,
117
+ encoder_attention_heads=16,
118
+ decoder_layers=8,
119
+ decoder_ffn_dim=2048,
120
+ decoder_attention_heads=16,
121
+ encoder_layerdrop=0.0,
122
+ decoder_layerdrop=0.0,
123
+ use_cache=True,
124
+ is_encoder_decoder=True,
125
+ activation_function="gelu",
126
+ d_model=512,
127
+ dropout=0.1,
128
+ attention_dropout=0.0,
129
+ activation_dropout=0.0,
130
+ init_std=0.02,
131
+ decoder_start_token_id=1,
132
+ scale_embedding=False,
133
+ pad_token_id=0,
134
+ bos_token_id=1,
135
+ eos_token_id=2,
136
+ forced_eos_token_id=2,
137
+ **kwargs,
138
+ ):
139
+ self.vocab_size = vocab_size
140
+ self.max_position_embeddings = max_position_embeddings
141
+ self.d_model = d_model
142
+ self.encoder_ffn_dim = encoder_ffn_dim
143
+ self.encoder_layers = encoder_layers
144
+ self.encoder_attention_heads = encoder_attention_heads
145
+ self.decoder_ffn_dim = decoder_ffn_dim
146
+ self.decoder_layers = decoder_layers
147
+ self.decoder_attention_heads = decoder_attention_heads
148
+ self.dropout = dropout
149
+ self.attention_dropout = attention_dropout
150
+ self.activation_dropout = activation_dropout
151
+ self.activation_function = activation_function
152
+ self.init_std = init_std
153
+ self.encoder_layerdrop = encoder_layerdrop
154
+ self.decoder_layerdrop = decoder_layerdrop
155
+ self.use_cache = use_cache
156
+ self.num_hidden_layers = encoder_layers
157
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
158
+
159
+ super().__init__(
160
+ pad_token_id=pad_token_id,
161
+ bos_token_id=bos_token_id,
162
+ eos_token_id=eos_token_id,
163
+ is_encoder_decoder=is_encoder_decoder,
164
+ decoder_start_token_id=decoder_start_token_id,
165
+ forced_eos_token_id=forced_eos_token_id,
166
+ **kwargs,
167
+ )
168
+
169
+
170
+ # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig
171
+ class BlenderbotSmallOnnxConfig(OnnxSeq2SeqConfigWithPast):
172
+ @property
173
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
174
+ if self.task in ["default", "seq2seq-lm"]:
175
+ common_inputs = OrderedDict(
176
+ [
177
+ ("input_ids", {0: "batch", 1: "encoder_sequence"}),
178
+ ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
179
+ ]
180
+ )
181
+
182
+ if self.use_past:
183
+ common_inputs["decoder_input_ids"] = {0: "batch"}
184
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
185
+ else:
186
+ common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
187
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
188
+
189
+ if self.use_past:
190
+ self.fill_with_past_key_values_(common_inputs, direction="inputs")
191
+ elif self.task == "causal-lm":
192
+ # TODO: figure this case out.
193
+ common_inputs = OrderedDict(
194
+ [
195
+ ("input_ids", {0: "batch", 1: "encoder_sequence"}),
196
+ ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
197
+ ]
198
+ )
199
+ if self.use_past:
200
+ num_encoder_layers, _ = self.num_layers
201
+ for i in range(num_encoder_layers):
202
+ common_inputs[f"past_key_values.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
203
+ common_inputs[f"past_key_values.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
204
+ else:
205
+ common_inputs = OrderedDict(
206
+ [
207
+ ("input_ids", {0: "batch", 1: "encoder_sequence"}),
208
+ ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
209
+ ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}),
210
+ ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}),
211
+ ]
212
+ )
213
+
214
+ return common_inputs
215
+
216
+ @property
217
+ def outputs(self) -> Mapping[str, Mapping[int, str]]:
218
+ if self.task in ["default", "seq2seq-lm"]:
219
+ common_outputs = super().outputs
220
+ else:
221
+ common_outputs = super(OnnxConfigWithPast, self).outputs
222
+ if self.use_past:
223
+ num_encoder_layers, _ = self.num_layers
224
+ for i in range(num_encoder_layers):
225
+ common_outputs[f"present.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
226
+ common_outputs[f"present.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
227
+ return common_outputs
228
+
229
+ def _generate_dummy_inputs_for_default_and_seq2seq_lm(
230
+ self,
231
+ tokenizer: PreTrainedTokenizer,
232
+ batch_size: int = -1,
233
+ seq_length: int = -1,
234
+ is_pair: bool = False,
235
+ framework: Optional[TensorType] = None,
236
+ ) -> Mapping[str, Any]:
237
+ encoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
238
+ tokenizer, batch_size, seq_length, is_pair, framework
239
+ )
240
+
241
+ # Generate decoder inputs
242
+ decoder_seq_length = seq_length if not self.use_past else 1
243
+ decoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
244
+ tokenizer, batch_size, decoder_seq_length, is_pair, framework
245
+ )
246
+ decoder_inputs = {f"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
247
+ common_inputs = dict(**encoder_inputs, **decoder_inputs)
248
+
249
+ if self.use_past:
250
+ if not is_torch_available():
251
+ raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
252
+ else:
253
+ import torch
254
+ batch, encoder_seq_length = common_inputs["input_ids"].shape
255
+ decoder_seq_length = common_inputs["decoder_input_ids"].shape[1]
256
+ num_encoder_attention_heads, num_decoder_attention_heads = self.num_attention_heads
257
+ encoder_shape = (
258
+ batch,
259
+ num_encoder_attention_heads,
260
+ encoder_seq_length,
261
+ self._config.hidden_size // num_encoder_attention_heads,
262
+ )
263
+ decoder_past_length = decoder_seq_length + 3
264
+ decoder_shape = (
265
+ batch,
266
+ num_decoder_attention_heads,
267
+ decoder_past_length,
268
+ self._config.hidden_size // num_decoder_attention_heads,
269
+ )
270
+
271
+ common_inputs["decoder_attention_mask"] = torch.cat(
272
+ [common_inputs["decoder_attention_mask"], torch.ones(batch, decoder_past_length)], dim=1
273
+ )
274
+
275
+ common_inputs["past_key_values"] = []
276
+ # If the number of encoder and decoder layers are present in the model configuration, both are considered
277
+ num_encoder_layers, num_decoder_layers = self.num_layers
278
+ min_num_layers = min(num_encoder_layers, num_decoder_layers)
279
+ max_num_layers = max(num_encoder_layers, num_decoder_layers) - min_num_layers
280
+ remaining_side_name = "encoder" if num_encoder_layers > num_decoder_layers else "decoder"
281
+
282
+ for _ in range(min_num_layers):
283
+ common_inputs["past_key_values"].append(
284
+ (
285
+ torch.zeros(decoder_shape),
286
+ torch.zeros(decoder_shape),
287
+ torch.zeros(encoder_shape),
288
+ torch.zeros(encoder_shape),
289
+ )
290
+ )
291
+ # TODO: test this.
292
+ shape = encoder_shape if remaining_side_name == "encoder" else decoder_shape
293
+ for _ in range(min_num_layers, max_num_layers):
294
+ common_inputs["past_key_values"].append((torch.zeros(shape), torch.zeros(shape)))
295
+ return common_inputs
296
+
297
+ def _generate_dummy_inputs_for_causal_lm(
298
+ self,
299
+ tokenizer: PreTrainedTokenizer,
300
+ batch_size: int = -1,
301
+ seq_length: int = -1,
302
+ is_pair: bool = False,
303
+ framework: Optional[TensorType] = None,
304
+ ) -> Mapping[str, Any]:
305
+ common_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
306
+ tokenizer, batch_size, seq_length, is_pair, framework
307
+ )
308
+
309
+ if self.use_past:
310
+ if not is_torch_available():
311
+ raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
312
+ else:
313
+ import torch
314
+ batch, seqlen = common_inputs["input_ids"].shape
315
+ # Not using the same length for past_key_values
316
+ past_key_values_length = seqlen + 2
317
+ num_encoder_layers, _ = self.num_layers
318
+ num_encoder_attention_heads, _ = self.num_attention_heads
319
+ past_shape = (
320
+ batch,
321
+ num_encoder_attention_heads,
322
+ past_key_values_length,
323
+ self._config.hidden_size // num_encoder_attention_heads,
324
+ )
325
+
326
+ mask_dtype = common_inputs["attention_mask"].dtype
327
+ common_inputs["attention_mask"] = torch.cat(
328
+ [common_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
329
+ )
330
+ common_inputs["past_key_values"] = [
331
+ (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(num_encoder_layers)
332
+ ]
333
+ return common_inputs
334
+
335
+ def _generate_dummy_inputs_for_sequence_classification_and_question_answering(
336
+ self,
337
+ tokenizer: PreTrainedTokenizer,
338
+ batch_size: int = -1,
339
+ seq_length: int = -1,
340
+ is_pair: bool = False,
341
+ framework: Optional[TensorType] = None,
342
+ ) -> Mapping[str, Any]:
343
+ # Copied from OnnxConfig.generate_dummy_inputs
344
+ # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
345
+ # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
346
+ batch_size = compute_effective_axis_dimension(
347
+ batch_size, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0
348
+ )
349
+
350
+ # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
351
+ token_to_add = tokenizer.num_special_tokens_to_add(is_pair)
352
+ seq_length = compute_effective_axis_dimension(
353
+ seq_length, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=token_to_add
354
+ )
355
+
356
+ # Generate dummy inputs according to compute batch and sequence
357
+ dummy_input = [" ".join([tokenizer.unk_token]) * seq_length] * batch_size
358
+ common_inputs = dict(tokenizer(dummy_input, return_tensors=framework))
359
+ return common_inputs
360
+
361
+ def generate_dummy_inputs(
362
+ self,
363
+ tokenizer: PreTrainedTokenizer,
364
+ batch_size: int = -1,
365
+ seq_length: int = -1,
366
+ is_pair: bool = False,
367
+ framework: Optional[TensorType] = None,
368
+ ) -> Mapping[str, Any]:
369
+ if self.task in ["default", "seq2seq-lm"]:
370
+ common_inputs = self._generate_dummy_inputs_for_default_and_seq2seq_lm(
371
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
372
+ )
373
+
374
+ elif self.task == "causal-lm":
375
+ common_inputs = self._generate_dummy_inputs_for_causal_lm(
376
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
377
+ )
378
+ else:
379
+ common_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
380
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
381
+ )
382
+
383
+ return common_inputs
384
+
385
+ def _flatten_past_key_values_(self, flattened_output, name, idx, t):
386
+ if self.task in ["default", "seq2seq-lm"]:
387
+ flattened_output = super()._flatten_past_key_values_(flattened_output, name, idx, t)
388
+ else:
389
+ flattened_output = super(OnnxSeq2SeqConfigWithPast, self)._flatten_past_key_values_(
390
+ flattened_output, name, idx, t
391
+ )
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/modeling_blenderbot_small.py ADDED
@@ -0,0 +1,1605 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Facebook, Inc. and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ PyTorch BlenderbotSmall model."""
16
+
17
+
18
+ import copy
19
+ import math
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import CrossEntropyLoss
26
+
27
+ from ...activations import ACT2FN
28
+ from ...modeling_outputs import (
29
+ BaseModelOutput,
30
+ BaseModelOutputWithPastAndCrossAttentions,
31
+ CausalLMOutputWithCrossAttentions,
32
+ Seq2SeqLMOutput,
33
+ Seq2SeqModelOutput,
34
+ )
35
+ from ...modeling_utils import PreTrainedModel
36
+ from ...utils import (
37
+ add_end_docstrings,
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ logging,
41
+ replace_return_docstrings,
42
+ )
43
+ from .configuration_blenderbot_small import BlenderbotSmallConfig
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+ _CONFIG_FOR_DOC = "BlenderbotSmallConfig"
49
+
50
+
51
+ BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST = [
52
+ "facebook/blenderbot_small-90M",
53
+ # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small
54
+ ]
55
+
56
+
57
+ # Copied from transformers.models.bart.modeling_bart.shift_tokens_right
58
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
59
+ """
60
+ Shift input ids one token to the right.
61
+ """
62
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
63
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
64
+ shifted_input_ids[:, 0] = decoder_start_token_id
65
+
66
+ if pad_token_id is None:
67
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
68
+ # replace possible -100 values in labels by `pad_token_id`
69
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
70
+
71
+ return shifted_input_ids
72
+
73
+
74
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
75
+ def _make_causal_mask(
76
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
77
+ ):
78
+ """
79
+ Make causal mask used for bi-directional self-attention.
80
+ """
81
+ bsz, tgt_len = input_ids_shape
82
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
83
+ mask_cond = torch.arange(mask.size(-1), device=device)
84
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
85
+ mask = mask.to(dtype)
86
+
87
+ if past_key_values_length > 0:
88
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
89
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
90
+
91
+
92
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
93
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
94
+ """
95
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
96
+ """
97
+ bsz, src_len = mask.size()
98
+ tgt_len = tgt_len if tgt_len is not None else src_len
99
+
100
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
101
+
102
+ inverted_mask = 1.0 - expanded_mask
103
+
104
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
105
+
106
+
107
+ # Copied from transformers.models.blenderbot.modeling_blenderbot.BlenderbotLearnedPositionalEmbedding with Blenderbot->BlenderbotSmall
108
+ class BlenderbotSmallLearnedPositionalEmbedding(nn.Embedding):
109
+ """
110
+ This module learns positional embeddings up to a fixed maximum size.
111
+ """
112
+
113
+ def __init__(self, num_embeddings: int, embedding_dim: int):
114
+ super().__init__(num_embeddings, embedding_dim)
115
+
116
+ def forward(self, input_ids_shape: torch.Size, past_key_values_length: int = 0):
117
+ """`input_ids_shape` is expected to be [bsz x seqlen]."""
118
+ bsz, seq_len = input_ids_shape[:2]
119
+ positions = torch.arange(
120
+ past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
121
+ )
122
+ return super().forward(positions)
123
+
124
+
125
+ # Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->BlenderbotSmall
126
+ class BlenderbotSmallAttention(nn.Module):
127
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
128
+
129
+ def __init__(
130
+ self,
131
+ embed_dim: int,
132
+ num_heads: int,
133
+ dropout: float = 0.0,
134
+ is_decoder: bool = False,
135
+ bias: bool = True,
136
+ ):
137
+ super().__init__()
138
+ self.embed_dim = embed_dim
139
+ self.num_heads = num_heads
140
+ self.dropout = dropout
141
+ self.head_dim = embed_dim // num_heads
142
+
143
+ if (self.head_dim * num_heads) != self.embed_dim:
144
+ raise ValueError(
145
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
146
+ f" and `num_heads`: {num_heads})."
147
+ )
148
+ self.scaling = self.head_dim**-0.5
149
+ self.is_decoder = is_decoder
150
+
151
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
152
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
153
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
154
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
155
+
156
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
157
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
158
+
159
+ def forward(
160
+ self,
161
+ hidden_states: torch.Tensor,
162
+ key_value_states: Optional[torch.Tensor] = None,
163
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
164
+ attention_mask: Optional[torch.Tensor] = None,
165
+ layer_head_mask: Optional[torch.Tensor] = None,
166
+ output_attentions: bool = False,
167
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
168
+ """Input shape: Batch x Time x Channel"""
169
+
170
+ # if key_value_states are provided this layer is used as a cross-attention layer
171
+ # for the decoder
172
+ is_cross_attention = key_value_states is not None
173
+
174
+ bsz, tgt_len, _ = hidden_states.size()
175
+
176
+ # get query proj
177
+ query_states = self.q_proj(hidden_states) * self.scaling
178
+ # get key, value proj
179
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
180
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
181
+ # the provided `key_value_states` to support prefix tuning
182
+ if (
183
+ is_cross_attention
184
+ and past_key_value is not None
185
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
186
+ ):
187
+ # reuse k,v, cross_attentions
188
+ key_states = past_key_value[0]
189
+ value_states = past_key_value[1]
190
+ elif is_cross_attention:
191
+ # cross_attentions
192
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
193
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
194
+ elif past_key_value is not None:
195
+ # reuse k, v, self_attention
196
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
197
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
198
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
199
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
200
+ else:
201
+ # self_attention
202
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
203
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
204
+
205
+ if self.is_decoder:
206
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
207
+ # Further calls to cross_attention layer can then reuse all cross-attention
208
+ # key/value_states (first "if" case)
209
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
210
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
211
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
212
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
213
+ past_key_value = (key_states, value_states)
214
+
215
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
216
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
217
+ key_states = key_states.reshape(*proj_shape)
218
+ value_states = value_states.reshape(*proj_shape)
219
+
220
+ src_len = key_states.size(1)
221
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
222
+
223
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
224
+ raise ValueError(
225
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
226
+ f" {attn_weights.size()}"
227
+ )
228
+
229
+ if attention_mask is not None:
230
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
231
+ raise ValueError(
232
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
233
+ )
234
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
235
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
236
+
237
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
238
+
239
+ if layer_head_mask is not None:
240
+ if layer_head_mask.size() != (self.num_heads,):
241
+ raise ValueError(
242
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
243
+ f" {layer_head_mask.size()}"
244
+ )
245
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
246
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
247
+
248
+ if output_attentions:
249
+ # this operation is a bit awkward, but it's required to
250
+ # make sure that attn_weights keeps its gradient.
251
+ # In order to do so, attn_weights have to be reshaped
252
+ # twice and have to be reused in the following
253
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
254
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
255
+ else:
256
+ attn_weights_reshaped = None
257
+
258
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
259
+
260
+ attn_output = torch.bmm(attn_probs, value_states)
261
+
262
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
263
+ raise ValueError(
264
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
265
+ f" {attn_output.size()}"
266
+ )
267
+
268
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
269
+ attn_output = attn_output.transpose(1, 2)
270
+
271
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
272
+ # partitioned across GPUs when using tensor-parallelism.
273
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
274
+
275
+ attn_output = self.out_proj(attn_output)
276
+
277
+ return attn_output, attn_weights_reshaped, past_key_value
278
+
279
+
280
+ # Copied from transformers.models.bart.modeling_bart.BartEncoderLayer with Bart->BlenderbotSmall
281
+ class BlenderbotSmallEncoderLayer(nn.Module):
282
+ def __init__(self, config: BlenderbotSmallConfig):
283
+ super().__init__()
284
+ self.embed_dim = config.d_model
285
+ self.self_attn = BlenderbotSmallAttention(
286
+ embed_dim=self.embed_dim,
287
+ num_heads=config.encoder_attention_heads,
288
+ dropout=config.attention_dropout,
289
+ )
290
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
291
+ self.dropout = config.dropout
292
+ self.activation_fn = ACT2FN[config.activation_function]
293
+ self.activation_dropout = config.activation_dropout
294
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
295
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
296
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
297
+
298
+ def forward(
299
+ self,
300
+ hidden_states: torch.FloatTensor,
301
+ attention_mask: torch.FloatTensor,
302
+ layer_head_mask: torch.FloatTensor,
303
+ output_attentions: Optional[bool] = False,
304
+ ) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]:
305
+ """
306
+ Args:
307
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
308
+ attention_mask (`torch.FloatTensor`): attention mask of size
309
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
310
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
311
+ `(encoder_attention_heads,)`.
312
+ output_attentions (`bool`, *optional*):
313
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
314
+ returned tensors for more detail.
315
+ """
316
+ residual = hidden_states
317
+ hidden_states, attn_weights, _ = self.self_attn(
318
+ hidden_states=hidden_states,
319
+ attention_mask=attention_mask,
320
+ layer_head_mask=layer_head_mask,
321
+ output_attentions=output_attentions,
322
+ )
323
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
324
+ hidden_states = residual + hidden_states
325
+ hidden_states = self.self_attn_layer_norm(hidden_states)
326
+
327
+ residual = hidden_states
328
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
329
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
330
+ hidden_states = self.fc2(hidden_states)
331
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
332
+ hidden_states = residual + hidden_states
333
+ hidden_states = self.final_layer_norm(hidden_states)
334
+
335
+ if hidden_states.dtype == torch.float16 and (
336
+ torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
337
+ ):
338
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
339
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
340
+
341
+ outputs = (hidden_states,)
342
+
343
+ if output_attentions:
344
+ outputs += (attn_weights,)
345
+
346
+ return outputs
347
+
348
+
349
+ # Copied from transformers.models.bart.modeling_bart.BartDecoderLayer with Bart->BlenderbotSmall
350
+ class BlenderbotSmallDecoderLayer(nn.Module):
351
+ def __init__(self, config: BlenderbotSmallConfig):
352
+ super().__init__()
353
+ self.embed_dim = config.d_model
354
+
355
+ self.self_attn = BlenderbotSmallAttention(
356
+ embed_dim=self.embed_dim,
357
+ num_heads=config.decoder_attention_heads,
358
+ dropout=config.attention_dropout,
359
+ is_decoder=True,
360
+ )
361
+ self.dropout = config.dropout
362
+ self.activation_fn = ACT2FN[config.activation_function]
363
+ self.activation_dropout = config.activation_dropout
364
+
365
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
366
+ self.encoder_attn = BlenderbotSmallAttention(
367
+ self.embed_dim,
368
+ config.decoder_attention_heads,
369
+ dropout=config.attention_dropout,
370
+ is_decoder=True,
371
+ )
372
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
373
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
374
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
375
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
376
+
377
+ def forward(
378
+ self,
379
+ hidden_states: torch.Tensor,
380
+ attention_mask: Optional[torch.Tensor] = None,
381
+ encoder_hidden_states: Optional[torch.Tensor] = None,
382
+ encoder_attention_mask: Optional[torch.Tensor] = None,
383
+ layer_head_mask: Optional[torch.Tensor] = None,
384
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
385
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
386
+ output_attentions: Optional[bool] = False,
387
+ use_cache: Optional[bool] = True,
388
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
389
+ """
390
+ Args:
391
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
392
+ attention_mask (`torch.FloatTensor`): attention mask of size
393
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
394
+ encoder_hidden_states (`torch.FloatTensor`):
395
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
396
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
397
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
398
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
399
+ `(encoder_attention_heads,)`.
400
+ cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
401
+ size `(decoder_attention_heads,)`.
402
+ past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
403
+ output_attentions (`bool`, *optional*):
404
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
405
+ returned tensors for more detail.
406
+ """
407
+ residual = hidden_states
408
+
409
+ # Self Attention
410
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
411
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
412
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
413
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
414
+ hidden_states=hidden_states,
415
+ past_key_value=self_attn_past_key_value,
416
+ attention_mask=attention_mask,
417
+ layer_head_mask=layer_head_mask,
418
+ output_attentions=output_attentions,
419
+ )
420
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
421
+ hidden_states = residual + hidden_states
422
+ hidden_states = self.self_attn_layer_norm(hidden_states)
423
+
424
+ # Cross-Attention Block
425
+ cross_attn_present_key_value = None
426
+ cross_attn_weights = None
427
+ if encoder_hidden_states is not None:
428
+ residual = hidden_states
429
+
430
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
431
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
432
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
433
+ hidden_states=hidden_states,
434
+ key_value_states=encoder_hidden_states,
435
+ attention_mask=encoder_attention_mask,
436
+ layer_head_mask=cross_attn_layer_head_mask,
437
+ past_key_value=cross_attn_past_key_value,
438
+ output_attentions=output_attentions,
439
+ )
440
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
441
+ hidden_states = residual + hidden_states
442
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
443
+
444
+ # add cross-attn to positions 3,4 of present_key_value tuple
445
+ present_key_value = present_key_value + cross_attn_present_key_value
446
+
447
+ # Fully Connected
448
+ residual = hidden_states
449
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
450
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
451
+ hidden_states = self.fc2(hidden_states)
452
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
453
+ hidden_states = residual + hidden_states
454
+ hidden_states = self.final_layer_norm(hidden_states)
455
+
456
+ outputs = (hidden_states,)
457
+
458
+ if output_attentions:
459
+ outputs += (self_attn_weights, cross_attn_weights)
460
+
461
+ if use_cache:
462
+ outputs += (present_key_value,)
463
+
464
+ return outputs
465
+
466
+
467
+ class BlenderbotSmallPreTrainedModel(PreTrainedModel):
468
+ config_class = BlenderbotSmallConfig
469
+ base_model_prefix = "model"
470
+ supports_gradient_checkpointing = True
471
+
472
+ def _init_weights(self, module):
473
+ std = self.config.init_std
474
+ if isinstance(module, nn.Linear):
475
+ module.weight.data.normal_(mean=0.0, std=std)
476
+ if module.bias is not None:
477
+ module.bias.data.zero_()
478
+ elif isinstance(module, nn.Embedding):
479
+ module.weight.data.normal_(mean=0.0, std=std)
480
+ if module.padding_idx is not None:
481
+ module.weight.data[module.padding_idx].zero_()
482
+
483
+ def _set_gradient_checkpointing(self, module, value=False):
484
+ if isinstance(module, (BlenderbotSmallDecoder, BlenderbotSmallEncoder)):
485
+ module.gradient_checkpointing = value
486
+
487
+ @property
488
+ def dummy_inputs(self):
489
+ pad_token = self.config.pad_token_id
490
+ input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
491
+ dummy_inputs = {
492
+ "attention_mask": input_ids.ne(pad_token),
493
+ "input_ids": input_ids,
494
+ "decoder_input_ids": input_ids,
495
+ }
496
+ return dummy_inputs
497
+
498
+
499
+ BLENDERBOT_SMALL_START_DOCSTRING = r"""
500
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
501
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
502
+ etc.)
503
+
504
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
505
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
506
+ and behavior.
507
+
508
+ Parameters:
509
+ config ([`BlenderbotSmallConfig`]):
510
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
511
+ load the weights associated with the model, only the configuration. Check out the
512
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
513
+ """
514
+
515
+ BLENDERBOT_SMALL_GENERATION_EXAMPLE = r"""
516
+ Conversation example:
517
+
518
+ ```python
519
+ >>> from transformers import AutoTokenizer, BlenderbotSmallForConditionalGeneration
520
+
521
+ >>> mname = "facebook/blenderbot_small-90M"
522
+ >>> model = BlenderbotSmallForConditionalGeneration.from_pretrained(mname)
523
+ >>> tokenizer = AutoTokenizer.from_pretrained(mname)
524
+ >>> UTTERANCE = "My friends are cool but they eat too many carbs."
525
+ >>> print("Human: ", UTTERANCE)
526
+ Human: My friends are cool but they eat too many carbs.
527
+
528
+ >>> inputs = tokenizer([UTTERANCE], return_tensors="pt")
529
+ >>> reply_ids = model.generate(**inputs)
530
+ >>> print("Bot: ", tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0])
531
+ Bot: what kind of carbs do they eat? i don't know much about carbs.
532
+
533
+ >>> REPLY = "I'm not sure"
534
+ >>> print("Human: ", REPLY)
535
+ Human: I'm not sure
536
+
537
+ >>> NEXT_UTTERANCE = (
538
+ ... "My friends are cool but they eat too many carbs.__end__ __start__what kind of carbs do they eat? "
539
+ ... "i don't know much about carbs__end__ "
540
+ ... "__start__ I'm not sure."
541
+ ... )
542
+ >>> inputs = tokenizer([NEXT_UTTERANCE], return_tensors="pt")
543
+ >>> next_reply_ids = model.generate(**inputs)
544
+ >>> print("Bot: ", tokenizer.batch_decode(next_reply_ids, skip_special_tokens=True)[0])
545
+ Bot: they eat a lot of carbs. carbs are high in fat, protein, and fats.
546
+ ```
547
+ """
548
+
549
+ BLENDERBOT_SMALL_INPUTS_DOCSTRING = r"""
550
+ Args:
551
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
552
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
553
+ it.
554
+
555
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
556
+ [`PreTrainedTokenizer.__call__`] for details.
557
+
558
+ [What are input IDs?](../glossary#input-ids)
559
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
560
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
561
+
562
+ - 1 for tokens that are **not masked**,
563
+ - 0 for tokens that are **masked**.
564
+
565
+ [What are attention masks?](../glossary#attention-mask)
566
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
567
+ Indices of decoder input sequence tokens in the vocabulary.
568
+
569
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
570
+ [`PreTrainedTokenizer.__call__`] for details.
571
+
572
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
573
+
574
+ BlenderbotSmall uses the `bos_token_id` as the starting token for `decoder_input_ids` generation. If
575
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
576
+ `past_key_values`).
577
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
578
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
579
+ be used by default.
580
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
581
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
582
+
583
+ - 1 indicates the head is **not masked**,
584
+ - 0 indicates the head is **masked**.
585
+
586
+ decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
587
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
588
+
589
+ - 1 indicates the head is **not masked**,
590
+ - 0 indicates the head is **masked**.
591
+
592
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
593
+ Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
594
+ 1]`:
595
+
596
+ - 1 indicates the head is **not masked**,
597
+ - 0 indicates the head is **masked**.
598
+
599
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
600
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
601
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
602
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
603
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
604
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
605
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
606
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
607
+
608
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
609
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
610
+
611
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
612
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
613
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of shape
614
+ `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you
615
+ can choose to directly pass an embedded representation. This is useful if you want more control over how to
616
+ convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
617
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
618
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
619
+ representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
620
+ input (see `past_key_values`). This is useful if you want more control over how to convert
621
+ `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
622
+
623
+ If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
624
+ of `inputs_embeds`.
625
+ use_cache (`bool`, *optional*):
626
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
627
+ `past_key_values`).
628
+ output_attentions (`bool`, *optional*):
629
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
630
+ tensors for more detail.
631
+ output_hidden_states (`bool`, *optional*):
632
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
633
+ more detail.
634
+ return_dict (`bool`, *optional*):
635
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
636
+ """
637
+
638
+
639
+ class BlenderbotSmallEncoder(BlenderbotSmallPreTrainedModel):
640
+ """
641
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
642
+ [`BlenderbotSmallEncoderLayer`].
643
+
644
+ Args:
645
+ config: BlenderbotSmallConfig
646
+ embed_tokens (nn.Embedding): output embedding
647
+ """
648
+
649
+ def __init__(self, config: BlenderbotSmallConfig, embed_tokens: Optional[nn.Embedding] = None):
650
+ super().__init__(config)
651
+
652
+ self.dropout = config.dropout
653
+ self.layerdrop = config.encoder_layerdrop
654
+
655
+ embed_dim = config.d_model
656
+ self.padding_idx = config.pad_token_id
657
+ self.max_source_positions = config.max_position_embeddings
658
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
659
+
660
+ if embed_tokens is not None:
661
+ self.embed_tokens = embed_tokens
662
+ else:
663
+ self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
664
+
665
+ self.embed_positions = BlenderbotSmallLearnedPositionalEmbedding(
666
+ config.max_position_embeddings,
667
+ embed_dim,
668
+ )
669
+ self.layers = nn.ModuleList([BlenderbotSmallEncoderLayer(config) for _ in range(config.encoder_layers)])
670
+ self.layernorm_embedding = nn.LayerNorm(embed_dim)
671
+
672
+ self.gradient_checkpointing = False
673
+ # Initialize weights and apply final processing
674
+ self.post_init()
675
+
676
+ def forward(
677
+ self,
678
+ input_ids=None,
679
+ attention_mask=None,
680
+ head_mask=None,
681
+ inputs_embeds=None,
682
+ output_attentions=None,
683
+ output_hidden_states=None,
684
+ return_dict=None,
685
+ ):
686
+ r"""
687
+ Args:
688
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
689
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
690
+ provide it.
691
+
692
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
693
+ [`PreTrainedTokenizer.__call__`] for details.
694
+
695
+ [What are input IDs?](../glossary#input-ids)
696
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
697
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
698
+
699
+ - 1 for tokens that are **not masked**,
700
+ - 0 for tokens that are **masked**.
701
+
702
+ [What are attention masks?](../glossary#attention-mask)
703
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
704
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
705
+
706
+ - 1 indicates the head is **not masked**,
707
+ - 0 indicates the head is **masked**.
708
+
709
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
710
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
711
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
712
+ than the model's internal embedding lookup matrix.
713
+ output_attentions (`bool`, *optional*):
714
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
715
+ returned tensors for more detail.
716
+ output_hidden_states (`bool`, *optional*):
717
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
718
+ for more detail.
719
+ return_dict (`bool`, *optional*):
720
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
721
+ """
722
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
723
+ output_hidden_states = (
724
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
725
+ )
726
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
727
+
728
+ # retrieve input_ids and inputs_embeds
729
+ if input_ids is not None and inputs_embeds is not None:
730
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
731
+ elif input_ids is not None:
732
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
733
+ input_shape = input_ids.size()
734
+ input_ids = input_ids.view(-1, input_shape[-1])
735
+ elif inputs_embeds is not None:
736
+ input_shape = inputs_embeds.size()[:-1]
737
+ else:
738
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
739
+
740
+ if inputs_embeds is None:
741
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
742
+
743
+ embed_pos = self.embed_positions(input_shape)
744
+
745
+ hidden_states = inputs_embeds + embed_pos
746
+ hidden_states = self.layernorm_embedding(hidden_states)
747
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
748
+
749
+ # expand attention_mask
750
+ if attention_mask is not None:
751
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
752
+ attention_mask = _expand_mask(attention_mask, inputs_embeds.dtype)
753
+
754
+ encoder_states = () if output_hidden_states else None
755
+ all_attentions = () if output_attentions else None
756
+
757
+ # check if head_mask has a correct number of layers specified if desired
758
+ if head_mask is not None:
759
+ if head_mask.size()[0] != len(self.layers):
760
+ raise ValueError(
761
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
762
+ f" {head_mask.size()[0]}."
763
+ )
764
+ for idx, encoder_layer in enumerate(self.layers):
765
+ if output_hidden_states:
766
+ encoder_states = encoder_states + (hidden_states,)
767
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
768
+ to_drop = False
769
+ if self.training:
770
+ dropout_probability = torch.rand([])
771
+ if dropout_probability < self.layerdrop: # skip the layer
772
+ to_drop = True
773
+
774
+ if to_drop:
775
+ layer_outputs = (None, None)
776
+ else:
777
+ if self.gradient_checkpointing and self.training:
778
+
779
+ def create_custom_forward(module):
780
+ def custom_forward(*inputs):
781
+ return module(*inputs, output_attentions)
782
+
783
+ return custom_forward
784
+
785
+ layer_outputs = torch.utils.checkpoint.checkpoint(
786
+ create_custom_forward(encoder_layer),
787
+ hidden_states,
788
+ attention_mask,
789
+ (head_mask[idx] if head_mask is not None else None),
790
+ )
791
+ else:
792
+ layer_outputs = encoder_layer(
793
+ hidden_states,
794
+ attention_mask,
795
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
796
+ output_attentions=output_attentions,
797
+ )
798
+
799
+ hidden_states = layer_outputs[0]
800
+
801
+ if output_attentions:
802
+ all_attentions = all_attentions + (layer_outputs[1],)
803
+
804
+ if output_hidden_states:
805
+ encoder_states = encoder_states + (hidden_states,)
806
+
807
+ if not return_dict:
808
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
809
+ return BaseModelOutput(
810
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
811
+ )
812
+
813
+
814
+ class BlenderbotSmallDecoder(BlenderbotSmallPreTrainedModel):
815
+ """
816
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`BlenderbotSmallDecoderLayer`]
817
+
818
+ Args:
819
+ config: BlenderbotSmallConfig
820
+ embed_tokens (nn.Embedding): output embedding
821
+ """
822
+
823
+ def __init__(self, config: BlenderbotSmallConfig, embed_tokens: Optional[nn.Embedding] = None):
824
+ super().__init__(config)
825
+ self.dropout = config.dropout
826
+ self.layerdrop = config.decoder_layerdrop
827
+ self.padding_idx = config.pad_token_id
828
+ self.max_target_positions = config.max_position_embeddings
829
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
830
+
831
+ if embed_tokens is not None:
832
+ self.embed_tokens = embed_tokens
833
+ else:
834
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
835
+
836
+ self.embed_positions = BlenderbotSmallLearnedPositionalEmbedding(
837
+ config.max_position_embeddings,
838
+ config.d_model,
839
+ )
840
+ self.layers = nn.ModuleList([BlenderbotSmallDecoderLayer(config) for _ in range(config.decoder_layers)])
841
+ self.layernorm_embedding = nn.LayerNorm(config.d_model)
842
+
843
+ self.gradient_checkpointing = False
844
+ # Initialize weights and apply final processing
845
+ self.post_init()
846
+
847
+ def get_input_embeddings(self):
848
+ return self.embed_tokens
849
+
850
+ def set_input_embeddings(self, value):
851
+ self.embed_tokens = value
852
+
853
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
854
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
855
+ # create causal mask
856
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
857
+ combined_attention_mask = None
858
+ if input_shape[-1] > 1:
859
+ combined_attention_mask = _make_causal_mask(
860
+ input_shape,
861
+ inputs_embeds.dtype,
862
+ device=inputs_embeds.device,
863
+ past_key_values_length=past_key_values_length,
864
+ )
865
+
866
+ if attention_mask is not None:
867
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
868
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
869
+ inputs_embeds.device
870
+ )
871
+ combined_attention_mask = (
872
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
873
+ )
874
+
875
+ return combined_attention_mask
876
+
877
+ def forward(
878
+ self,
879
+ input_ids=None,
880
+ attention_mask=None,
881
+ encoder_hidden_states=None,
882
+ encoder_attention_mask=None,
883
+ head_mask=None,
884
+ cross_attn_head_mask=None,
885
+ past_key_values=None,
886
+ inputs_embeds=None,
887
+ use_cache=None,
888
+ output_attentions=None,
889
+ output_hidden_states=None,
890
+ return_dict=None,
891
+ ):
892
+ r"""
893
+ Args:
894
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
895
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
896
+ provide it.
897
+
898
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
899
+ [`PreTrainedTokenizer.__call__`] for details.
900
+
901
+ [What are input IDs?](../glossary#input-ids)
902
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
903
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
904
+
905
+ - 1 for tokens that are **not masked**,
906
+ - 0 for tokens that are **masked**.
907
+
908
+ [What are attention masks?](../glossary#attention-mask)
909
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
910
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
911
+ of the decoder.
912
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
913
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
914
+ selected in `[0, 1]`:
915
+
916
+ - 1 for tokens that are **not masked**,
917
+ - 0 for tokens that are **masked**.
918
+
919
+ [What are attention masks?](../glossary#attention-mask)
920
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
921
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
922
+
923
+ - 1 indicates the head is **not masked**,
924
+ - 0 indicates the head is **masked**.
925
+
926
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
927
+ Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
928
+ cross-attention on hidden heads. Mask values selected in `[0, 1]`:
929
+
930
+ - 1 indicates the head is **not masked**,
931
+ - 0 indicates the head is **masked**.
932
+
933
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
934
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
935
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
936
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
937
+
938
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
939
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
940
+
941
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
942
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
943
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of
944
+ shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing
945
+ `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more
946
+ control over how to convert `input_ids` indices into associated vectors than the model's internal
947
+ embedding lookup matrix.
948
+ output_attentions (`bool`, *optional*):
949
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
950
+ returned tensors for more detail.
951
+ output_hidden_states (`bool`, *optional*):
952
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
953
+ for more detail.
954
+ return_dict (`bool`, *optional*):
955
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
956
+ """
957
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
958
+ output_hidden_states = (
959
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
960
+ )
961
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
962
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
963
+
964
+ # retrieve input_ids and inputs_embeds
965
+ if input_ids is not None and inputs_embeds is not None:
966
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
967
+ elif input_ids is not None:
968
+ input_shape = input_ids.size()
969
+ input_ids = input_ids.view(-1, input_shape[-1])
970
+ elif inputs_embeds is not None:
971
+ input_shape = inputs_embeds.size()[:-1]
972
+ else:
973
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
974
+
975
+ # past_key_values_length
976
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
977
+
978
+ if inputs_embeds is None:
979
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
980
+
981
+ attention_mask = self._prepare_decoder_attention_mask(
982
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
983
+ )
984
+
985
+ # expand encoder attention mask
986
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
987
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
988
+ encoder_attention_mask = _expand_mask(encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1])
989
+
990
+ # embed positions
991
+ positions = self.embed_positions(input_shape, past_key_values_length)
992
+
993
+ # BlenderbotSmall applies layer norm on hidden_states
994
+ inputs_embeds = self.layernorm_embedding(inputs_embeds)
995
+ hidden_states = inputs_embeds + positions
996
+
997
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
998
+
999
+ if self.gradient_checkpointing and self.training:
1000
+ if use_cache:
1001
+ logger.warning_once(
1002
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1003
+ )
1004
+ use_cache = False
1005
+
1006
+ # decoder layers
1007
+ all_hidden_states = () if output_hidden_states else None
1008
+ all_self_attns = () if output_attentions else None
1009
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
1010
+ next_decoder_cache = () if use_cache else None
1011
+
1012
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
1013
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
1014
+ if attn_mask is not None:
1015
+ if attn_mask.size()[0] != len(self.layers):
1016
+ raise ValueError(
1017
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
1018
+ f" {head_mask.size()[0]}."
1019
+ )
1020
+ for idx, decoder_layer in enumerate(self.layers):
1021
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1022
+ if output_hidden_states:
1023
+ all_hidden_states += (hidden_states,)
1024
+ if self.training:
1025
+ dropout_probability = torch.rand([])
1026
+ if dropout_probability < self.layerdrop:
1027
+ continue
1028
+
1029
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1030
+
1031
+ if self.gradient_checkpointing and self.training:
1032
+
1033
+ def create_custom_forward(module):
1034
+ def custom_forward(*inputs):
1035
+ # None for past_key_value
1036
+ return module(*inputs, output_attentions, use_cache)
1037
+
1038
+ return custom_forward
1039
+
1040
+ layer_outputs = torch.utils.checkpoint.checkpoint(
1041
+ create_custom_forward(decoder_layer),
1042
+ hidden_states,
1043
+ attention_mask,
1044
+ encoder_hidden_states,
1045
+ encoder_attention_mask,
1046
+ head_mask[idx] if head_mask is not None else None,
1047
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
1048
+ None,
1049
+ )
1050
+ else:
1051
+ layer_outputs = decoder_layer(
1052
+ hidden_states,
1053
+ attention_mask=attention_mask,
1054
+ encoder_hidden_states=encoder_hidden_states,
1055
+ encoder_attention_mask=encoder_attention_mask,
1056
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
1057
+ cross_attn_layer_head_mask=(
1058
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
1059
+ ),
1060
+ past_key_value=past_key_value,
1061
+ output_attentions=output_attentions,
1062
+ use_cache=use_cache,
1063
+ )
1064
+ hidden_states = layer_outputs[0]
1065
+
1066
+ if use_cache:
1067
+ next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
1068
+
1069
+ if output_attentions:
1070
+ all_self_attns += (layer_outputs[1],)
1071
+
1072
+ if encoder_hidden_states is not None:
1073
+ all_cross_attentions += (layer_outputs[2],)
1074
+
1075
+ # add hidden states from the last decoder layer
1076
+ if output_hidden_states:
1077
+ all_hidden_states += (hidden_states,)
1078
+
1079
+ next_cache = next_decoder_cache if use_cache else None
1080
+ if not return_dict:
1081
+ return tuple(
1082
+ v
1083
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
1084
+ if v is not None
1085
+ )
1086
+ return BaseModelOutputWithPastAndCrossAttentions(
1087
+ last_hidden_state=hidden_states,
1088
+ past_key_values=next_cache,
1089
+ hidden_states=all_hidden_states,
1090
+ attentions=all_self_attns,
1091
+ cross_attentions=all_cross_attentions,
1092
+ )
1093
+
1094
+
1095
+ @add_start_docstrings(
1096
+ "The bare BlenderbotSmall Model outputting raw hidden-states without any specific head on top.",
1097
+ BLENDERBOT_SMALL_START_DOCSTRING,
1098
+ )
1099
+ class BlenderbotSmallModel(BlenderbotSmallPreTrainedModel):
1100
+ _tied_weights_keys = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight"]
1101
+
1102
+ def __init__(self, config: BlenderbotSmallConfig):
1103
+ super().__init__(config)
1104
+
1105
+ padding_idx, vocab_size = config.pad_token_id, config.vocab_size
1106
+ self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
1107
+
1108
+ self.encoder = BlenderbotSmallEncoder(config, self.shared)
1109
+ self.decoder = BlenderbotSmallDecoder(config, self.shared)
1110
+
1111
+ # Initialize weights and apply final processing
1112
+ self.post_init()
1113
+
1114
+ def get_input_embeddings(self):
1115
+ return self.shared
1116
+
1117
+ def set_input_embeddings(self, value):
1118
+ self.shared = value
1119
+ self.encoder.embed_tokens = self.shared
1120
+ self.decoder.embed_tokens = self.shared
1121
+
1122
+ def get_encoder(self):
1123
+ return self.encoder
1124
+
1125
+ def get_decoder(self):
1126
+ return self.decoder
1127
+
1128
+ @add_start_docstrings_to_model_forward(BLENDERBOT_SMALL_INPUTS_DOCSTRING)
1129
+ @replace_return_docstrings(output_type=Seq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)
1130
+ def forward(
1131
+ self,
1132
+ input_ids: Optional[torch.LongTensor] = None,
1133
+ attention_mask: Optional[torch.Tensor] = None,
1134
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1135
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1136
+ head_mask: Optional[torch.Tensor] = None,
1137
+ decoder_head_mask: Optional[torch.Tensor] = None,
1138
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1139
+ encoder_outputs: Optional[Union[Tuple, BaseModelOutput]] = None,
1140
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1141
+ inputs_embeds: Optional[torch.Tensor] = None,
1142
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1143
+ use_cache: Optional[bool] = None,
1144
+ output_attentions: Optional[bool] = None,
1145
+ output_hidden_states: Optional[bool] = None,
1146
+ return_dict: Optional[bool] = None,
1147
+ ) -> Union[Tuple[torch.FloatTensor], Seq2SeqModelOutput]:
1148
+ r"""
1149
+ Returns:
1150
+
1151
+ Example:
1152
+
1153
+ ```python
1154
+ >>> from transformers import AutoTokenizer, BlenderbotSmallModel
1155
+
1156
+ >>> model = BlenderbotSmallModel.from_pretrained("facebook/blenderbot_small-90M")
1157
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
1158
+
1159
+ >>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
1160
+ >>> decoder_inputs = tokenizer("Studies show that", return_tensors="pt") # Batch size 1
1161
+ >>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)
1162
+
1163
+ >>> last_hidden_states = outputs.last_hidden_state
1164
+ >>> list(last_hidden_states.shape)
1165
+ [1, 3, 512]
1166
+ ```"""
1167
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1168
+ output_hidden_states = (
1169
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1170
+ )
1171
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1172
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1173
+
1174
+ if encoder_outputs is None:
1175
+ encoder_outputs = self.encoder(
1176
+ input_ids=input_ids,
1177
+ attention_mask=attention_mask,
1178
+ head_mask=head_mask,
1179
+ inputs_embeds=inputs_embeds,
1180
+ output_attentions=output_attentions,
1181
+ output_hidden_states=output_hidden_states,
1182
+ return_dict=return_dict,
1183
+ )
1184
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
1185
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1186
+ encoder_outputs = BaseModelOutput(
1187
+ last_hidden_state=encoder_outputs[0],
1188
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1189
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1190
+ )
1191
+
1192
+ # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
1193
+ decoder_outputs = self.decoder(
1194
+ input_ids=decoder_input_ids,
1195
+ attention_mask=decoder_attention_mask,
1196
+ encoder_hidden_states=encoder_outputs[0],
1197
+ encoder_attention_mask=attention_mask,
1198
+ head_mask=decoder_head_mask,
1199
+ cross_attn_head_mask=cross_attn_head_mask,
1200
+ past_key_values=past_key_values,
1201
+ inputs_embeds=decoder_inputs_embeds,
1202
+ use_cache=use_cache,
1203
+ output_attentions=output_attentions,
1204
+ output_hidden_states=output_hidden_states,
1205
+ return_dict=return_dict,
1206
+ )
1207
+
1208
+ if not return_dict:
1209
+ return decoder_outputs + encoder_outputs
1210
+
1211
+ return Seq2SeqModelOutput(
1212
+ last_hidden_state=decoder_outputs.last_hidden_state,
1213
+ past_key_values=decoder_outputs.past_key_values,
1214
+ decoder_hidden_states=decoder_outputs.hidden_states,
1215
+ decoder_attentions=decoder_outputs.attentions,
1216
+ cross_attentions=decoder_outputs.cross_attentions,
1217
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1218
+ encoder_hidden_states=encoder_outputs.hidden_states,
1219
+ encoder_attentions=encoder_outputs.attentions,
1220
+ )
1221
+
1222
+
1223
+ @add_start_docstrings(
1224
+ "The BlenderbotSmall Model with a language modeling head. Can be used for summarization.",
1225
+ BLENDERBOT_SMALL_START_DOCSTRING,
1226
+ )
1227
+ class BlenderbotSmallForConditionalGeneration(BlenderbotSmallPreTrainedModel):
1228
+ base_model_prefix = "model"
1229
+ _keys_to_ignore_on_load_missing = ["final_logits_bias"]
1230
+ _tied_weights_keys = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight", "lm_head.weight"]
1231
+
1232
+ def __init__(self, config: BlenderbotSmallConfig):
1233
+ super().__init__(config)
1234
+ self.model = BlenderbotSmallModel(config)
1235
+ self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
1236
+ self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
1237
+
1238
+ # Initialize weights and apply final processing
1239
+ self.post_init()
1240
+
1241
+ def get_encoder(self):
1242
+ return self.model.get_encoder()
1243
+
1244
+ def get_decoder(self):
1245
+ return self.model.get_decoder()
1246
+
1247
+ def resize_token_embeddings(self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None) -> nn.Embedding:
1248
+ new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
1249
+ self._resize_final_logits_bias(new_embeddings.weight.shape[0])
1250
+ return new_embeddings
1251
+
1252
+ def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
1253
+ old_num_tokens = self.final_logits_bias.shape[-1]
1254
+ if new_num_tokens <= old_num_tokens:
1255
+ new_bias = self.final_logits_bias[:, :new_num_tokens]
1256
+ else:
1257
+ extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
1258
+ new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
1259
+ self.register_buffer("final_logits_bias", new_bias)
1260
+
1261
+ def get_output_embeddings(self):
1262
+ return self.lm_head
1263
+
1264
+ def set_output_embeddings(self, new_embeddings):
1265
+ self.lm_head = new_embeddings
1266
+
1267
+ @add_start_docstrings_to_model_forward(BLENDERBOT_SMALL_INPUTS_DOCSTRING)
1268
+ @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1269
+ @add_end_docstrings(BLENDERBOT_SMALL_GENERATION_EXAMPLE)
1270
+ def forward(
1271
+ self,
1272
+ input_ids: Optional[torch.LongTensor] = None,
1273
+ attention_mask: Optional[torch.Tensor] = None,
1274
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1275
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1276
+ head_mask: Optional[torch.Tensor] = None,
1277
+ decoder_head_mask: Optional[torch.Tensor] = None,
1278
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1279
+ encoder_outputs: Optional[Union[Tuple, BaseModelOutput]] = None,
1280
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1281
+ inputs_embeds: Optional[torch.Tensor] = None,
1282
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1283
+ labels: Optional[torch.LongTensor] = None,
1284
+ use_cache: Optional[bool] = None,
1285
+ output_attentions: Optional[bool] = None,
1286
+ output_hidden_states: Optional[bool] = None,
1287
+ return_dict: Optional[bool] = None,
1288
+ ) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:
1289
+ r"""
1290
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1291
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1292
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1293
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1294
+
1295
+ Returns:
1296
+ """
1297
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1298
+
1299
+ if labels is not None:
1300
+ if use_cache:
1301
+ logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
1302
+ use_cache = False
1303
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1304
+ decoder_input_ids = shift_tokens_right(
1305
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1306
+ )
1307
+
1308
+ outputs = self.model(
1309
+ input_ids,
1310
+ attention_mask=attention_mask,
1311
+ decoder_input_ids=decoder_input_ids,
1312
+ encoder_outputs=encoder_outputs,
1313
+ decoder_attention_mask=decoder_attention_mask,
1314
+ head_mask=head_mask,
1315
+ decoder_head_mask=decoder_head_mask,
1316
+ cross_attn_head_mask=cross_attn_head_mask,
1317
+ past_key_values=past_key_values,
1318
+ inputs_embeds=inputs_embeds,
1319
+ decoder_inputs_embeds=decoder_inputs_embeds,
1320
+ use_cache=use_cache,
1321
+ output_attentions=output_attentions,
1322
+ output_hidden_states=output_hidden_states,
1323
+ return_dict=return_dict,
1324
+ )
1325
+ lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
1326
+
1327
+ masked_lm_loss = None
1328
+ if labels is not None:
1329
+ loss_fct = CrossEntropyLoss()
1330
+ masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
1331
+
1332
+ if not return_dict:
1333
+ output = (lm_logits,) + outputs[1:]
1334
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1335
+
1336
+ return Seq2SeqLMOutput(
1337
+ loss=masked_lm_loss,
1338
+ logits=lm_logits,
1339
+ past_key_values=outputs.past_key_values,
1340
+ decoder_hidden_states=outputs.decoder_hidden_states,
1341
+ decoder_attentions=outputs.decoder_attentions,
1342
+ cross_attentions=outputs.cross_attentions,
1343
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1344
+ encoder_hidden_states=outputs.encoder_hidden_states,
1345
+ encoder_attentions=outputs.encoder_attentions,
1346
+ )
1347
+
1348
+ def prepare_inputs_for_generation(
1349
+ self,
1350
+ decoder_input_ids,
1351
+ past_key_values=None,
1352
+ attention_mask=None,
1353
+ head_mask=None,
1354
+ decoder_head_mask=None,
1355
+ cross_attn_head_mask=None,
1356
+ use_cache=None,
1357
+ encoder_outputs=None,
1358
+ **kwargs,
1359
+ ):
1360
+ # cut decoder_input_ids if past is used
1361
+ if past_key_values is not None:
1362
+ decoder_input_ids = decoder_input_ids[:, -1:]
1363
+
1364
+ return {
1365
+ "input_ids": None, # encoder_outputs is defined. input_ids not needed
1366
+ "encoder_outputs": encoder_outputs,
1367
+ "past_key_values": past_key_values,
1368
+ "decoder_input_ids": decoder_input_ids,
1369
+ "attention_mask": attention_mask,
1370
+ "head_mask": head_mask,
1371
+ "decoder_head_mask": decoder_head_mask,
1372
+ "cross_attn_head_mask": cross_attn_head_mask,
1373
+ "use_cache": use_cache, # change this to avoid caching (presumably for debugging)
1374
+ }
1375
+
1376
+ @staticmethod
1377
+ def _reorder_cache(past_key_values, beam_idx):
1378
+ reordered_past = ()
1379
+ for layer_past in past_key_values:
1380
+ # cached cross_attention states don't have to be reordered -> they are always the same
1381
+ reordered_past += (
1382
+ tuple(past_state.index_select(0, beam_idx) for past_state in layer_past[:2]) + layer_past[2:],
1383
+ )
1384
+ return reordered_past
1385
+
1386
+
1387
+ # Copied from transformers.models.bart.modeling_bart.BartDecoderWrapper with Bart->BlenderbotSmall
1388
+ class BlenderbotSmallDecoderWrapper(BlenderbotSmallPreTrainedModel):
1389
+ """
1390
+ This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
1391
+ used in combination with the [`EncoderDecoderModel`] framework.
1392
+ """
1393
+
1394
+ def __init__(self, config):
1395
+ super().__init__(config)
1396
+ self.decoder = BlenderbotSmallDecoder(config)
1397
+
1398
+ def forward(self, *args, **kwargs):
1399
+ return self.decoder(*args, **kwargs)
1400
+
1401
+
1402
+ # Copied from transformers.models.bart.modeling_bart.BartForCausalLM with Bart->BlenderbotSmall, facebook/bart-base->facebook/blenderbot_small-90M
1403
+ class BlenderbotSmallForCausalLM(BlenderbotSmallPreTrainedModel):
1404
+ _tied_weights_keys = ["lm_head.weight"]
1405
+
1406
+ def __init__(self, config):
1407
+ config = copy.deepcopy(config)
1408
+ config.is_decoder = True
1409
+ config.is_encoder_decoder = False
1410
+ super().__init__(config)
1411
+ self.model = BlenderbotSmallDecoderWrapper(config)
1412
+
1413
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1414
+
1415
+ # Initialize weights and apply final processing
1416
+ self.post_init()
1417
+
1418
+ def get_input_embeddings(self):
1419
+ return self.model.decoder.embed_tokens
1420
+
1421
+ def set_input_embeddings(self, value):
1422
+ self.model.decoder.embed_tokens = value
1423
+
1424
+ def get_output_embeddings(self):
1425
+ return self.lm_head
1426
+
1427
+ def set_output_embeddings(self, new_embeddings):
1428
+ self.lm_head = new_embeddings
1429
+
1430
+ def set_decoder(self, decoder):
1431
+ self.model.decoder = decoder
1432
+
1433
+ def get_decoder(self):
1434
+ return self.model.decoder
1435
+
1436
+ @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
1437
+ def forward(
1438
+ self,
1439
+ input_ids: torch.LongTensor = None,
1440
+ attention_mask: Optional[torch.Tensor] = None,
1441
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1442
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1443
+ head_mask: Optional[torch.Tensor] = None,
1444
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1445
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1446
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1447
+ labels: Optional[torch.LongTensor] = None,
1448
+ use_cache: Optional[bool] = None,
1449
+ output_attentions: Optional[bool] = None,
1450
+ output_hidden_states: Optional[bool] = None,
1451
+ return_dict: Optional[bool] = None,
1452
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1453
+ r"""
1454
+ Args:
1455
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1456
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
1457
+ provide it.
1458
+
1459
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1460
+ [`PreTrainedTokenizer.__call__`] for details.
1461
+
1462
+ [What are input IDs?](../glossary#input-ids)
1463
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1464
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1465
+
1466
+ - 1 for tokens that are **not masked**,
1467
+ - 0 for tokens that are **masked**.
1468
+
1469
+ [What are attention masks?](../glossary#attention-mask)
1470
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1471
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1472
+ if the model is configured as a decoder.
1473
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1474
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
1475
+ in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1476
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1477
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1478
+
1479
+ - 1 indicates the head is **not masked**,
1480
+ - 0 indicates the head is **masked**.
1481
+
1482
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1483
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
1484
+
1485
+ - 1 indicates the head is **not masked**,
1486
+ - 0 indicates the head is **masked**.
1487
+
1488
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1489
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1490
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
1491
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
1492
+ tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
1493
+
1494
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
1495
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1496
+
1497
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
1498
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
1499
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1500
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1501
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1502
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1503
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1504
+ use_cache (`bool`, *optional*):
1505
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1506
+ (see `past_key_values`).
1507
+
1508
+ - 1 for tokens that are **not masked**,
1509
+ - 0 for tokens that are **masked**.
1510
+ output_attentions (`bool`, *optional*):
1511
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1512
+ returned tensors for more detail.
1513
+ output_hidden_states (`bool`, *optional*):
1514
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1515
+ for more detail.
1516
+ return_dict (`bool`, *optional*):
1517
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1518
+
1519
+ Returns:
1520
+
1521
+ Example:
1522
+
1523
+ ```python
1524
+ >>> from transformers import AutoTokenizer, BlenderbotSmallForCausalLM
1525
+
1526
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
1527
+ >>> model = BlenderbotSmallForCausalLM.from_pretrained(
1528
+ ... "facebook/blenderbot_small-90M", add_cross_attention=False
1529
+ ... )
1530
+ >>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
1531
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1532
+ >>> outputs = model(**inputs)
1533
+
1534
+ >>> logits = outputs.logits
1535
+ >>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
1536
+ >>> list(logits.shape) == expected_shape
1537
+ True
1538
+ ```"""
1539
+
1540
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1541
+ output_hidden_states = (
1542
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1543
+ )
1544
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1545
+
1546
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1547
+ outputs = self.model.decoder(
1548
+ input_ids=input_ids,
1549
+ attention_mask=attention_mask,
1550
+ encoder_hidden_states=encoder_hidden_states,
1551
+ encoder_attention_mask=encoder_attention_mask,
1552
+ head_mask=head_mask,
1553
+ cross_attn_head_mask=cross_attn_head_mask,
1554
+ past_key_values=past_key_values,
1555
+ inputs_embeds=inputs_embeds,
1556
+ use_cache=use_cache,
1557
+ output_attentions=output_attentions,
1558
+ output_hidden_states=output_hidden_states,
1559
+ return_dict=return_dict,
1560
+ )
1561
+
1562
+ logits = self.lm_head(outputs[0])
1563
+
1564
+ loss = None
1565
+ if labels is not None:
1566
+ labels = labels.to(logits.device)
1567
+ loss_fct = CrossEntropyLoss()
1568
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
1569
+
1570
+ if not return_dict:
1571
+ output = (logits,) + outputs[1:]
1572
+ return (loss,) + output if loss is not None else output
1573
+
1574
+ return CausalLMOutputWithCrossAttentions(
1575
+ loss=loss,
1576
+ logits=logits,
1577
+ past_key_values=outputs.past_key_values,
1578
+ hidden_states=outputs.hidden_states,
1579
+ attentions=outputs.attentions,
1580
+ cross_attentions=outputs.cross_attentions,
1581
+ )
1582
+
1583
+ def prepare_inputs_for_generation(
1584
+ self, input_ids, past_key_values=None, attention_mask=None, use_cache=None, **kwargs
1585
+ ):
1586
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
1587
+ if attention_mask is None:
1588
+ attention_mask = input_ids.new_ones(input_ids.shape)
1589
+
1590
+ if past_key_values:
1591
+ input_ids = input_ids[:, -1:]
1592
+ # first step, decoder_cached_states are empty
1593
+ return {
1594
+ "input_ids": input_ids, # encoder_outputs is defined. input_ids not needed
1595
+ "attention_mask": attention_mask,
1596
+ "past_key_values": past_key_values,
1597
+ "use_cache": use_cache,
1598
+ }
1599
+
1600
+ @staticmethod
1601
+ def _reorder_cache(past_key_values, beam_idx):
1602
+ reordered_past = ()
1603
+ for layer_past in past_key_values:
1604
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
1605
+ return reordered_past
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/modeling_flax_blenderbot_small.py ADDED
@@ -0,0 +1,1522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Facebook, Inc. and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ Flax BlenderbotSmall model."""
16
+
17
+
18
+ import math
19
+ import random
20
+ from functools import partial
21
+ from typing import Callable, Optional, Tuple
22
+
23
+ import flax.linen as nn
24
+ import jax
25
+ import jax.numpy as jnp
26
+ from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
27
+ from flax.linen import combine_masks, make_causal_mask
28
+ from flax.linen.attention import dot_product_attention_weights
29
+ from flax.traverse_util import flatten_dict, unflatten_dict
30
+ from jax import lax
31
+ from jax.random import PRNGKey
32
+
33
+ from ...modeling_flax_outputs import (
34
+ FlaxBaseModelOutput,
35
+ FlaxBaseModelOutputWithPastAndCrossAttentions,
36
+ FlaxCausalLMOutputWithCrossAttentions,
37
+ FlaxSeq2SeqLMOutput,
38
+ FlaxSeq2SeqModelOutput,
39
+ )
40
+ from ...modeling_flax_utils import (
41
+ ACT2FN,
42
+ FlaxPreTrainedModel,
43
+ append_call_sample_docstring,
44
+ append_replace_return_docstrings,
45
+ overwrite_call_docstring,
46
+ )
47
+ from ...utils import add_start_docstrings, logging, replace_return_docstrings
48
+ from .configuration_blenderbot_small import BlenderbotSmallConfig
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ _CHECKPOINT_FOR_DOC = "facebook/blenderbot_small-90M"
54
+ _CONFIG_FOR_DOC = "BlenderbotSmallConfig"
55
+
56
+ BLENDERBOT_SMALL_START_DOCSTRING = r"""
57
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
58
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
59
+ etc.)
60
+
61
+ This model is also a Flax Linen
62
+ [flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
63
+ regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
64
+
65
+ Finally, this model supports inherent JAX features such as:
66
+
67
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
68
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
69
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
70
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
71
+
72
+ Parameters:
73
+ config ([`BlenderbotSmallConfig`]): Model configuration class with all the parameters of the model.
74
+ Initializing with a config file does not load the weights associated with the model, only the
75
+ configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
76
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
77
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
78
+ `jax.numpy.bfloat16` (on TPUs).
79
+
80
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
81
+ specified all the computation will be performed with the given `dtype`.
82
+
83
+ **Note that this only specifies the dtype of the computation and does not influence the dtype of model
84
+ parameters.**
85
+
86
+ If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
87
+ [`~FlaxPreTrainedModel.to_bf16`].
88
+ """
89
+
90
+ BLENDERBOT_SMALL_INPUTS_DOCSTRING = r"""
91
+ Args:
92
+ input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
93
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
94
+ it.
95
+
96
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
97
+ [`PreTrainedTokenizer.__call__`] for details.
98
+
99
+ [What are input IDs?](../glossary#input-ids)
100
+ attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
101
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
102
+
103
+ - 1 for tokens that are **not masked**,
104
+ - 0 for tokens that are **masked**.
105
+
106
+ [What are attention masks?](../glossary#attention-mask)
107
+ decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
108
+ Indices of decoder input sequence tokens in the vocabulary.
109
+
110
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
111
+ [`PreTrainedTokenizer.__call__`] for details.
112
+
113
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
114
+
115
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
116
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
117
+ for denoising pre-training following the paper.
118
+ decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
119
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
120
+ be used by default.
121
+
122
+ If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
123
+ paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
124
+ position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
125
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
126
+ config.max_position_embeddings - 1]`.
127
+ decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
128
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
129
+ range `[0, config.max_position_embeddings - 1]`.
130
+ output_attentions (`bool`, *optional*):
131
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
132
+ tensors for more detail.
133
+ output_hidden_states (`bool`, *optional*):
134
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
135
+ more detail.
136
+ return_dict (`bool`, *optional*):
137
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
138
+ """
139
+
140
+
141
+ BLENDERBOT_SMALL_ENCODE_INPUTS_DOCSTRING = r"""
142
+ Args:
143
+ input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
144
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
145
+ it.
146
+
147
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
148
+ [`PreTrainedTokenizer.__call__`] for details.
149
+
150
+ [What are input IDs?](../glossary#input-ids)
151
+ attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
152
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
153
+
154
+ - 1 for tokens that are **not masked**,
155
+ - 0 for tokens that are **masked**.
156
+
157
+ [What are attention masks?](../glossary#attention-mask)
158
+ position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
159
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
160
+ config.max_position_embeddings - 1]`.
161
+ output_attentions (`bool`, *optional*):
162
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
163
+ tensors for more detail.
164
+ output_hidden_states (`bool`, *optional*):
165
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
166
+ more detail.
167
+ return_dict (`bool`, *optional*):
168
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
169
+ """
170
+
171
+ BLENDERBOT_SMALL_DECODE_INPUTS_DOCSTRING = r"""
172
+ Args:
173
+ decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`):
174
+ Indices of decoder input sequence tokens in the vocabulary.
175
+
176
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
177
+ [`PreTrainedTokenizer.__call__`] for details.
178
+
179
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
180
+
181
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
182
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
183
+ for denoising pre-training following the paper.
184
+ encoder_outputs (`tuple(tuple(jnp.ndarray)`):
185
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
186
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
187
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
188
+ encoder_attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
189
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
190
+
191
+ - 1 for tokens that are **not masked**,
192
+ - 0 for tokens that are **masked**.
193
+
194
+ [What are attention masks?](../glossary#attention-mask)
195
+ decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
196
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
197
+ be used by default.
198
+
199
+ If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
200
+ paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
201
+ decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
202
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
203
+ range `[0, config.max_position_embeddings - 1]`.
204
+ past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
205
+ Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
206
+ auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
207
+ output_attentions (`bool`, *optional*):
208
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
209
+ tensors for more detail.
210
+ output_hidden_states (`bool`, *optional*):
211
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
212
+ more detail.
213
+ return_dict (`bool`, *optional*):
214
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
215
+ """
216
+
217
+
218
+ # Copied from transformers.models.bart.modeling_flax_bart.shift_tokens_right
219
+ def shift_tokens_right(input_ids: jnp.array, pad_token_id: int, decoder_start_token_id: int) -> jnp.ndarray:
220
+ """
221
+ Shift input ids one token to the right.
222
+ """
223
+ shifted_input_ids = jnp.zeros_like(input_ids)
224
+ shifted_input_ids = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1])
225
+ shifted_input_ids = shifted_input_ids.at[:, 0].set(decoder_start_token_id)
226
+
227
+ shifted_input_ids = jnp.where(shifted_input_ids == -100, pad_token_id, shifted_input_ids)
228
+ return shifted_input_ids
229
+
230
+
231
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartAttention with Bart->BlenderbotSmall
232
+ class FlaxBlenderbotSmallAttention(nn.Module):
233
+ config: BlenderbotSmallConfig
234
+ embed_dim: int
235
+ num_heads: int
236
+ dropout: float = 0.0
237
+ causal: bool = False
238
+ bias: bool = True
239
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
240
+
241
+ def setup(self) -> None:
242
+ self.head_dim = self.embed_dim // self.num_heads
243
+ if self.head_dim * self.num_heads != self.embed_dim:
244
+ raise ValueError(
245
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
246
+ f" and `num_heads`: {self.num_heads})."
247
+ )
248
+
249
+ dense = partial(
250
+ nn.Dense,
251
+ self.embed_dim,
252
+ use_bias=self.bias,
253
+ dtype=self.dtype,
254
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
255
+ )
256
+
257
+ self.q_proj, self.k_proj, self.v_proj = dense(), dense(), dense()
258
+ self.out_proj = dense()
259
+
260
+ self.dropout_layer = nn.Dropout(rate=self.dropout)
261
+
262
+ if self.causal:
263
+ self.causal_mask = make_causal_mask(
264
+ jnp.ones((1, self.config.max_position_embeddings), dtype="bool"), dtype="bool"
265
+ )
266
+
267
+ def _split_heads(self, hidden_states):
268
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.num_heads, self.head_dim))
269
+
270
+ def _merge_heads(self, hidden_states):
271
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
272
+
273
+ @nn.compact
274
+ def _concatenate_to_cache(self, key, value, query, attention_mask):
275
+ """
276
+ This function takes projected key, value states from a single input token and concatenates the states to cached
277
+ states from previous steps. This function is slighly adapted from the official Flax repository:
278
+ https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
279
+ """
280
+ # detect if we're initializing by absence of existing cache data.
281
+ is_initialized = self.has_variable("cache", "cached_key")
282
+ cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
283
+ cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
284
+ cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
285
+
286
+ if is_initialized:
287
+ *batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
288
+ # update key, value caches with our new 1d spatial slices
289
+ cur_index = cache_index.value
290
+ indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
291
+ key = lax.dynamic_update_slice(cached_key.value, key, indices)
292
+ value = lax.dynamic_update_slice(cached_value.value, value, indices)
293
+ cached_key.value = key
294
+ cached_value.value = value
295
+ num_updated_cache_vectors = query.shape[1]
296
+ cache_index.value = cache_index.value + num_updated_cache_vectors
297
+ # causal mask for cached decoder self-attention: our single query position should only attend to those key positions that have already been generated and cached, not the remaining zero elements.
298
+ pad_mask = jnp.broadcast_to(
299
+ jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
300
+ tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
301
+ )
302
+ attention_mask = combine_masks(pad_mask, attention_mask)
303
+ return key, value, attention_mask
304
+
305
+ def __call__(
306
+ self,
307
+ hidden_states: jnp.ndarray,
308
+ key_value_states: Optional[jnp.ndarray] = None,
309
+ attention_mask: Optional[jnp.ndarray] = None,
310
+ init_cache: bool = False,
311
+ deterministic: bool = True,
312
+ ) -> Tuple[jnp.ndarray]:
313
+ """Input shape: Batch x Time x Channel"""
314
+
315
+ # if key_value_states are provided this layer is used as a cross-attention layer
316
+ # for the decoder
317
+ is_cross_attention = key_value_states is not None
318
+ batch_size = hidden_states.shape[0]
319
+
320
+ # get query proj
321
+ query_states = self.q_proj(hidden_states)
322
+ # get key, value proj
323
+ if is_cross_attention:
324
+ # cross_attentions
325
+ key_states = self.k_proj(key_value_states)
326
+ value_states = self.v_proj(key_value_states)
327
+ else:
328
+ # self_attention
329
+ key_states = self.k_proj(hidden_states)
330
+ value_states = self.v_proj(hidden_states)
331
+
332
+ query_states = self._split_heads(query_states)
333
+ key_states = self._split_heads(key_states)
334
+ value_states = self._split_heads(value_states)
335
+
336
+ # handle cache prepare causal attention mask
337
+ if self.causal:
338
+ query_length, key_length = query_states.shape[1], key_states.shape[1]
339
+ if self.has_variable("cache", "cached_key"):
340
+ mask_shift = self.variables["cache"]["cache_index"]
341
+ max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
342
+ causal_mask = lax.dynamic_slice(
343
+ self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
344
+ )
345
+ else:
346
+ causal_mask = self.causal_mask[:, :, :query_length, :key_length]
347
+ causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
348
+
349
+ # combine masks if needed
350
+ if attention_mask is not None and self.causal:
351
+ attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
352
+ attention_mask = combine_masks(attention_mask, causal_mask)
353
+ elif self.causal:
354
+ attention_mask = causal_mask
355
+ elif attention_mask is not None:
356
+ attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
357
+
358
+ # During fast autoregressive decoding, we feed one position at a time,
359
+ # and cache the keys and values step by step.
360
+ if self.causal and (self.has_variable("cache", "cached_key") or init_cache):
361
+ key_states, value_states, attention_mask = self._concatenate_to_cache(
362
+ key_states, value_states, query_states, attention_mask
363
+ )
364
+
365
+ # Convert the boolean attention mask to an attention bias.
366
+ if attention_mask is not None:
367
+ # attention mask in the form of attention bias
368
+ attention_bias = lax.select(
369
+ attention_mask > 0,
370
+ jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
371
+ jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
372
+ )
373
+ else:
374
+ attention_bias = None
375
+
376
+ dropout_rng = None
377
+ if not deterministic and self.dropout > 0.0:
378
+ dropout_rng = self.make_rng("dropout")
379
+
380
+ attn_weights = dot_product_attention_weights(
381
+ query_states,
382
+ key_states,
383
+ bias=attention_bias,
384
+ dropout_rng=dropout_rng,
385
+ dropout_rate=self.dropout,
386
+ broadcast_dropout=True,
387
+ deterministic=deterministic,
388
+ dtype=self.dtype,
389
+ precision=None,
390
+ )
391
+
392
+ attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
393
+ attn_output = self._merge_heads(attn_output)
394
+ attn_output = self.out_proj(attn_output)
395
+
396
+ return attn_output, attn_weights
397
+
398
+
399
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartEncoderLayer with Bart->BlenderbotSmall
400
+ class FlaxBlenderbotSmallEncoderLayer(nn.Module):
401
+ config: BlenderbotSmallConfig
402
+ dtype: jnp.dtype = jnp.float32
403
+
404
+ def setup(self) -> None:
405
+ self.embed_dim = self.config.d_model
406
+ self.self_attn = FlaxBlenderbotSmallAttention(
407
+ config=self.config,
408
+ embed_dim=self.embed_dim,
409
+ num_heads=self.config.encoder_attention_heads,
410
+ dropout=self.config.attention_dropout,
411
+ dtype=self.dtype,
412
+ )
413
+ self.self_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
414
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
415
+ self.activation_fn = ACT2FN[self.config.activation_function]
416
+ self.activation_dropout_layer = nn.Dropout(rate=self.config.activation_dropout)
417
+ self.fc1 = nn.Dense(
418
+ self.config.encoder_ffn_dim,
419
+ dtype=self.dtype,
420
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
421
+ )
422
+ self.fc2 = nn.Dense(
423
+ self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)
424
+ )
425
+ self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
426
+
427
+ def __call__(
428
+ self,
429
+ hidden_states: jnp.ndarray,
430
+ attention_mask: jnp.ndarray,
431
+ output_attentions: bool = True,
432
+ deterministic: bool = True,
433
+ ) -> Tuple[jnp.ndarray]:
434
+ residual = hidden_states
435
+ hidden_states, attn_weights = self.self_attn(hidden_states=hidden_states, attention_mask=attention_mask)
436
+
437
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
438
+ hidden_states = residual + hidden_states
439
+ hidden_states = self.self_attn_layer_norm(hidden_states)
440
+
441
+ residual = hidden_states
442
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
443
+ hidden_states = self.activation_dropout_layer(hidden_states, deterministic=deterministic)
444
+ hidden_states = self.fc2(hidden_states)
445
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
446
+ hidden_states = residual + hidden_states
447
+ hidden_states = self.final_layer_norm(hidden_states)
448
+
449
+ outputs = (hidden_states,)
450
+
451
+ if output_attentions:
452
+ outputs += (attn_weights,)
453
+
454
+ return outputs
455
+
456
+
457
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartEncoderLayerCollection with Bart->BlenderbotSmall
458
+ class FlaxBlenderbotSmallEncoderLayerCollection(nn.Module):
459
+ config: BlenderbotSmallConfig
460
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
461
+
462
+ def setup(self):
463
+ self.layers = [
464
+ FlaxBlenderbotSmallEncoderLayer(self.config, name=str(i), dtype=self.dtype)
465
+ for i in range(self.config.encoder_layers)
466
+ ]
467
+ self.layerdrop = self.config.encoder_layerdrop
468
+
469
+ def __call__(
470
+ self,
471
+ hidden_states,
472
+ attention_mask,
473
+ deterministic: bool = True,
474
+ output_attentions: bool = False,
475
+ output_hidden_states: bool = False,
476
+ return_dict: bool = True,
477
+ ):
478
+ all_attentions = () if output_attentions else None
479
+ all_hidden_states = () if output_hidden_states else None
480
+
481
+ for encoder_layer in self.layers:
482
+ if output_hidden_states:
483
+ all_hidden_states = all_hidden_states + (hidden_states,)
484
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
485
+ dropout_probability = random.uniform(0, 1)
486
+ if not deterministic and (dropout_probability < self.layerdrop): # skip the layer
487
+ layer_outputs = (None, None)
488
+ else:
489
+ layer_outputs = encoder_layer(
490
+ hidden_states,
491
+ attention_mask,
492
+ output_attentions,
493
+ deterministic,
494
+ )
495
+ hidden_states = layer_outputs[0]
496
+ if output_attentions:
497
+ all_attentions = all_attentions + (layer_outputs[1],)
498
+
499
+ if output_hidden_states:
500
+ all_hidden_states += (hidden_states,)
501
+
502
+ outputs = (hidden_states, all_hidden_states, all_attentions)
503
+
504
+ if not return_dict:
505
+ return tuple(v for v in outputs if v is not None)
506
+
507
+ return FlaxBaseModelOutput(
508
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
509
+ )
510
+
511
+
512
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderLayer with Bart->BlenderbotSmall
513
+ class FlaxBlenderbotSmallDecoderLayer(nn.Module):
514
+ config: BlenderbotSmallConfig
515
+ dtype: jnp.dtype = jnp.float32
516
+
517
+ def setup(self) -> None:
518
+ self.embed_dim = self.config.d_model
519
+ self.self_attn = FlaxBlenderbotSmallAttention(
520
+ config=self.config,
521
+ embed_dim=self.embed_dim,
522
+ num_heads=self.config.decoder_attention_heads,
523
+ dropout=self.config.attention_dropout,
524
+ causal=True,
525
+ dtype=self.dtype,
526
+ )
527
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
528
+ self.activation_fn = ACT2FN[self.config.activation_function]
529
+ self.activation_dropout_layer = nn.Dropout(rate=self.config.activation_dropout)
530
+
531
+ self.self_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
532
+ self.encoder_attn = FlaxBlenderbotSmallAttention(
533
+ config=self.config,
534
+ embed_dim=self.embed_dim,
535
+ num_heads=self.config.decoder_attention_heads,
536
+ dropout=self.config.attention_dropout,
537
+ dtype=self.dtype,
538
+ )
539
+ self.encoder_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
540
+ self.fc1 = nn.Dense(
541
+ self.config.decoder_ffn_dim,
542
+ dtype=self.dtype,
543
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
544
+ )
545
+ self.fc2 = nn.Dense(
546
+ self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)
547
+ )
548
+ self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
549
+
550
+ def __call__(
551
+ self,
552
+ hidden_states: jnp.ndarray,
553
+ attention_mask: jnp.ndarray,
554
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
555
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
556
+ init_cache: bool = False,
557
+ output_attentions: bool = True,
558
+ deterministic: bool = True,
559
+ ) -> Tuple[jnp.ndarray]:
560
+ residual = hidden_states
561
+
562
+ # Self Attention
563
+ hidden_states, self_attn_weights = self.self_attn(
564
+ hidden_states=hidden_states, attention_mask=attention_mask, init_cache=init_cache
565
+ )
566
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
567
+ hidden_states = residual + hidden_states
568
+ hidden_states = self.self_attn_layer_norm(hidden_states)
569
+
570
+ # Cross-Attention Block
571
+ cross_attn_weights = None
572
+ if encoder_hidden_states is not None:
573
+ residual = hidden_states
574
+
575
+ hidden_states, cross_attn_weights = self.encoder_attn(
576
+ hidden_states=hidden_states,
577
+ key_value_states=encoder_hidden_states,
578
+ attention_mask=encoder_attention_mask,
579
+ )
580
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
581
+ hidden_states = residual + hidden_states
582
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
583
+
584
+ # Fully Connected
585
+ residual = hidden_states
586
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
587
+ hidden_states = self.activation_dropout_layer(hidden_states, deterministic=deterministic)
588
+ hidden_states = self.fc2(hidden_states)
589
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
590
+ hidden_states = residual + hidden_states
591
+ hidden_states = self.final_layer_norm(hidden_states)
592
+
593
+ outputs = (hidden_states,)
594
+
595
+ if output_attentions:
596
+ outputs += (self_attn_weights, cross_attn_weights)
597
+
598
+ return outputs
599
+
600
+
601
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderLayerCollection with Bart->BlenderbotSmall
602
+ class FlaxBlenderbotSmallDecoderLayerCollection(nn.Module):
603
+ config: BlenderbotSmallConfig
604
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
605
+
606
+ def setup(self):
607
+ self.layers = [
608
+ FlaxBlenderbotSmallDecoderLayer(self.config, name=str(i), dtype=self.dtype)
609
+ for i in range(self.config.decoder_layers)
610
+ ]
611
+ self.layerdrop = self.config.decoder_layerdrop
612
+
613
+ def __call__(
614
+ self,
615
+ hidden_states,
616
+ attention_mask,
617
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
618
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
619
+ deterministic: bool = True,
620
+ init_cache: bool = False,
621
+ output_attentions: bool = False,
622
+ output_hidden_states: bool = False,
623
+ return_dict: bool = True,
624
+ ):
625
+ # decoder layers
626
+ all_hidden_states = () if output_hidden_states else None
627
+ all_self_attns = () if output_attentions else None
628
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
629
+
630
+ for decoder_layer in self.layers:
631
+ if output_hidden_states:
632
+ all_hidden_states += (hidden_states,)
633
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
634
+ dropout_probability = random.uniform(0, 1)
635
+ if not deterministic and (dropout_probability < self.layerdrop):
636
+ layer_outputs = (None, None, None)
637
+ else:
638
+ layer_outputs = decoder_layer(
639
+ hidden_states,
640
+ attention_mask=attention_mask,
641
+ encoder_hidden_states=encoder_hidden_states,
642
+ encoder_attention_mask=encoder_attention_mask,
643
+ init_cache=init_cache,
644
+ output_attentions=output_attentions,
645
+ deterministic=deterministic,
646
+ )
647
+
648
+ hidden_states = layer_outputs[0]
649
+ if output_attentions:
650
+ all_self_attns += (layer_outputs[1],)
651
+
652
+ if encoder_hidden_states is not None:
653
+ all_cross_attentions += (layer_outputs[2],)
654
+
655
+ # add hidden states from the last decoder layer
656
+ if output_hidden_states:
657
+ all_hidden_states += (hidden_states,)
658
+
659
+ outputs = [hidden_states, all_hidden_states, all_self_attns, all_cross_attentions]
660
+
661
+ if not return_dict:
662
+ return tuple(v for v in outputs if v is not None)
663
+
664
+ return FlaxBaseModelOutputWithPastAndCrossAttentions(
665
+ last_hidden_state=hidden_states,
666
+ hidden_states=all_hidden_states,
667
+ attentions=all_self_attns,
668
+ cross_attentions=all_cross_attentions,
669
+ )
670
+
671
+
672
+ class FlaxBlenderbotSmallEncoder(nn.Module):
673
+ config: BlenderbotSmallConfig
674
+ embed_tokens: nn.Embed
675
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
676
+
677
+ def setup(self):
678
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
679
+
680
+ embed_dim = self.config.d_model
681
+ self.padding_idx = self.config.pad_token_id
682
+ self.max_source_positions = self.config.max_position_embeddings
683
+ self.embed_scale = math.sqrt(embed_dim) if self.config.scale_embedding else 1.0
684
+
685
+ self.embed_positions = nn.Embed(
686
+ self.config.max_position_embeddings,
687
+ embed_dim,
688
+ embedding_init=jax.nn.initializers.normal(self.config.init_std),
689
+ )
690
+ self.layers = FlaxBlenderbotSmallEncoderLayerCollection(self.config, self.dtype)
691
+ self.layernorm_embedding = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
692
+
693
+ def __call__(
694
+ self,
695
+ input_ids,
696
+ attention_mask,
697
+ position_ids,
698
+ output_attentions: bool = False,
699
+ output_hidden_states: bool = False,
700
+ return_dict: bool = True,
701
+ deterministic: bool = True,
702
+ ):
703
+ input_shape = input_ids.shape
704
+ input_ids = input_ids.reshape(-1, input_shape[-1])
705
+
706
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
707
+
708
+ embed_pos = self.embed_positions(position_ids)
709
+
710
+ hidden_states = inputs_embeds + embed_pos
711
+ hidden_states = self.layernorm_embedding(hidden_states)
712
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
713
+
714
+ outputs = self.layers(
715
+ hidden_states,
716
+ attention_mask,
717
+ deterministic=deterministic,
718
+ output_attentions=output_attentions,
719
+ output_hidden_states=output_hidden_states,
720
+ return_dict=return_dict,
721
+ )
722
+
723
+ if not return_dict:
724
+ return outputs
725
+
726
+ return FlaxBaseModelOutput(
727
+ last_hidden_state=outputs.last_hidden_state,
728
+ hidden_states=outputs.hidden_states,
729
+ attentions=outputs.attentions,
730
+ )
731
+
732
+
733
+ class FlaxBlenderbotSmallDecoder(nn.Module):
734
+ config: BlenderbotSmallConfig
735
+ embed_tokens: nn.Embed
736
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
737
+
738
+ def setup(self):
739
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
740
+
741
+ embed_dim = self.config.d_model
742
+ self.padding_idx = self.config.pad_token_id
743
+ self.max_target_positions = self.config.max_position_embeddings
744
+ self.embed_scale = math.sqrt(self.config.d_model) if self.config.scale_embedding else 1.0
745
+
746
+ self.embed_positions = nn.Embed(
747
+ self.config.max_position_embeddings,
748
+ embed_dim,
749
+ embedding_init=jax.nn.initializers.normal(self.config.init_std),
750
+ )
751
+
752
+ self.layers = FlaxBlenderbotSmallDecoderLayerCollection(self.config, self.dtype)
753
+ self.layernorm_embedding = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
754
+
755
+ def __call__(
756
+ self,
757
+ input_ids,
758
+ attention_mask,
759
+ position_ids,
760
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
761
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
762
+ init_cache: bool = False,
763
+ output_attentions: bool = False,
764
+ output_hidden_states: bool = False,
765
+ return_dict: bool = True,
766
+ deterministic: bool = True,
767
+ ):
768
+ input_shape = input_ids.shape
769
+ input_ids = input_ids.reshape(-1, input_shape[-1])
770
+
771
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
772
+
773
+ # embed positions
774
+ positions = self.embed_positions(position_ids)
775
+
776
+ # BlenderbotSmall applies layer norm on inputs_embeds in decoder
777
+ inputs_embeds = self.layernorm_embedding(inputs_embeds)
778
+ hidden_states = inputs_embeds + positions
779
+
780
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
781
+
782
+ outputs = self.layers(
783
+ hidden_states,
784
+ attention_mask,
785
+ encoder_hidden_states,
786
+ encoder_attention_mask,
787
+ deterministic=deterministic,
788
+ init_cache=init_cache,
789
+ output_attentions=output_attentions,
790
+ output_hidden_states=output_hidden_states,
791
+ return_dict=return_dict,
792
+ )
793
+
794
+ if not return_dict:
795
+ return outputs
796
+
797
+ return FlaxBaseModelOutputWithPastAndCrossAttentions(
798
+ last_hidden_state=outputs.last_hidden_state,
799
+ hidden_states=outputs.hidden_states,
800
+ attentions=outputs.attentions,
801
+ cross_attentions=outputs.cross_attentions,
802
+ )
803
+
804
+
805
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartModule with Bart->BlenderbotSmall
806
+ class FlaxBlenderbotSmallModule(nn.Module):
807
+ config: BlenderbotSmallConfig
808
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
809
+
810
+ def setup(self):
811
+ self.shared = nn.Embed(
812
+ self.config.vocab_size,
813
+ self.config.d_model,
814
+ embedding_init=jax.nn.initializers.normal(self.config.init_std),
815
+ dtype=self.dtype,
816
+ )
817
+
818
+ self.encoder = FlaxBlenderbotSmallEncoder(self.config, dtype=self.dtype, embed_tokens=self.shared)
819
+ self.decoder = FlaxBlenderbotSmallDecoder(self.config, dtype=self.dtype, embed_tokens=self.shared)
820
+
821
+ def _get_encoder_module(self):
822
+ return self.encoder
823
+
824
+ def _get_decoder_module(self):
825
+ return self.decoder
826
+
827
+ def __call__(
828
+ self,
829
+ input_ids,
830
+ attention_mask,
831
+ decoder_input_ids,
832
+ decoder_attention_mask,
833
+ position_ids,
834
+ decoder_position_ids,
835
+ output_attentions: bool = False,
836
+ output_hidden_states: bool = False,
837
+ return_dict: bool = True,
838
+ deterministic: bool = True,
839
+ ):
840
+ encoder_outputs = self.encoder(
841
+ input_ids=input_ids,
842
+ attention_mask=attention_mask,
843
+ position_ids=position_ids,
844
+ output_attentions=output_attentions,
845
+ output_hidden_states=output_hidden_states,
846
+ return_dict=return_dict,
847
+ deterministic=deterministic,
848
+ )
849
+
850
+ decoder_outputs = self.decoder(
851
+ input_ids=decoder_input_ids,
852
+ attention_mask=decoder_attention_mask,
853
+ position_ids=decoder_position_ids,
854
+ encoder_hidden_states=encoder_outputs[0],
855
+ encoder_attention_mask=attention_mask,
856
+ output_attentions=output_attentions,
857
+ output_hidden_states=output_hidden_states,
858
+ return_dict=return_dict,
859
+ deterministic=deterministic,
860
+ )
861
+
862
+ if not return_dict:
863
+ return decoder_outputs + encoder_outputs
864
+
865
+ return FlaxSeq2SeqModelOutput(
866
+ last_hidden_state=decoder_outputs.last_hidden_state,
867
+ decoder_hidden_states=decoder_outputs.hidden_states,
868
+ decoder_attentions=decoder_outputs.attentions,
869
+ cross_attentions=decoder_outputs.cross_attentions,
870
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
871
+ encoder_hidden_states=encoder_outputs.hidden_states,
872
+ encoder_attentions=encoder_outputs.attentions,
873
+ )
874
+
875
+
876
+ class FlaxBlenderbotSmallPreTrainedModel(FlaxPreTrainedModel):
877
+ config_class = BlenderbotSmallConfig
878
+ base_model_prefix: str = "model"
879
+ module_class: nn.Module = None
880
+
881
+ def __init__(
882
+ self,
883
+ config: BlenderbotSmallConfig,
884
+ input_shape: Tuple[int] = (1, 1),
885
+ seed: int = 0,
886
+ dtype: jnp.dtype = jnp.float32,
887
+ _do_init: bool = True,
888
+ **kwargs,
889
+ ):
890
+ module = self.module_class(config=config, dtype=dtype, **kwargs)
891
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
892
+
893
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
894
+ # init input tensors
895
+ input_ids = jnp.zeros(input_shape, dtype="i4")
896
+ # make sure initialization pass will work for FlaxBlenderbotSmallForSequenceClassificationModule
897
+ input_ids = input_ids.at[(..., -1)].set(self.config.eos_token_id)
898
+ attention_mask = jnp.ones_like(input_ids)
899
+ decoder_input_ids = input_ids
900
+ decoder_attention_mask = jnp.ones_like(input_ids)
901
+
902
+ batch_size, sequence_length = input_ids.shape
903
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
904
+ decoder_position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
905
+
906
+ params_rng, dropout_rng = jax.random.split(rng)
907
+ rngs = {"params": params_rng, "dropout": dropout_rng}
908
+
909
+ random_params = self.module.init(
910
+ rngs,
911
+ input_ids,
912
+ attention_mask,
913
+ decoder_input_ids,
914
+ decoder_attention_mask,
915
+ position_ids,
916
+ decoder_position_ids,
917
+ )["params"]
918
+
919
+ if params is not None:
920
+ random_params = flatten_dict(unfreeze(random_params))
921
+ params = flatten_dict(unfreeze(params))
922
+ for missing_key in self._missing_keys:
923
+ params[missing_key] = random_params[missing_key]
924
+ self._missing_keys = set()
925
+ return freeze(unflatten_dict(params))
926
+ else:
927
+ return random_params
928
+
929
+ def init_cache(self, batch_size, max_length, encoder_outputs):
930
+ r"""
931
+ Args:
932
+ batch_size (`int`):
933
+ batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
934
+ max_length (`int`):
935
+ maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
936
+ cache.
937
+ encoder_outputs (`Union[FlaxBaseModelOutput, tuple(tuple(jnp.ndarray)]`):
938
+ `encoder_outputs` consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*:
939
+ `attentions`). `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*)
940
+ is a sequence of hidden-states at the output of the last layer of the encoder. Used in the
941
+ cross-attention of the decoder.
942
+ """
943
+ # init input variables to retrieve cache
944
+ decoder_input_ids = jnp.ones((batch_size, max_length), dtype="i4")
945
+ decoder_attention_mask = jnp.ones_like(decoder_input_ids)
946
+ decoder_position_ids = jnp.broadcast_to(
947
+ jnp.arange(jnp.atleast_2d(decoder_input_ids).shape[-1]), decoder_input_ids.shape
948
+ )
949
+
950
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
951
+ decoder_module = module._get_decoder_module()
952
+ return decoder_module(
953
+ decoder_input_ids,
954
+ decoder_attention_mask,
955
+ decoder_position_ids,
956
+ **kwargs,
957
+ )
958
+
959
+ init_variables = self.module.init(
960
+ jax.random.PRNGKey(0),
961
+ decoder_input_ids=decoder_input_ids,
962
+ decoder_attention_mask=decoder_attention_mask,
963
+ decoder_position_ids=decoder_position_ids,
964
+ encoder_hidden_states=encoder_outputs[0],
965
+ init_cache=True,
966
+ method=_decoder_forward, # we only need to call the decoder to init the cache
967
+ )
968
+ return unfreeze(init_variables["cache"])
969
+
970
+ @add_start_docstrings(BLENDERBOT_SMALL_ENCODE_INPUTS_DOCSTRING)
971
+ @replace_return_docstrings(output_type=FlaxBaseModelOutput, config_class=BlenderbotSmallConfig)
972
+ def encode(
973
+ self,
974
+ input_ids: jnp.ndarray,
975
+ attention_mask: Optional[jnp.ndarray] = None,
976
+ position_ids: Optional[jnp.ndarray] = None,
977
+ output_attentions: Optional[bool] = None,
978
+ output_hidden_states: Optional[bool] = None,
979
+ return_dict: Optional[bool] = None,
980
+ train: bool = False,
981
+ params: dict = None,
982
+ dropout_rng: PRNGKey = None,
983
+ ):
984
+ r"""
985
+ Returns:
986
+
987
+ Example:
988
+
989
+ ```python
990
+ >>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
991
+
992
+ >>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
993
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
994
+
995
+ >>> text = "My friends are cool but they eat too many carbs."
996
+ >>> inputs = tokenizer(text, max_length=1024, return_tensors="np")
997
+ >>> encoder_outputs = model.encode(**inputs)
998
+ ```"""
999
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1000
+ output_hidden_states = (
1001
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1002
+ )
1003
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1004
+
1005
+ if attention_mask is None:
1006
+ attention_mask = jnp.ones_like(input_ids)
1007
+ if position_ids is None:
1008
+ batch_size, sequence_length = input_ids.shape
1009
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
1010
+
1011
+ # Handle any PRNG if needed
1012
+ rngs = {}
1013
+ if dropout_rng is not None:
1014
+ rngs["dropout"] = dropout_rng
1015
+
1016
+ def _encoder_forward(module, input_ids, attention_mask, position_ids, **kwargs):
1017
+ encode_module = module._get_encoder_module()
1018
+ return encode_module(input_ids, attention_mask, position_ids, **kwargs)
1019
+
1020
+ return self.module.apply(
1021
+ {"params": params or self.params},
1022
+ input_ids=jnp.array(input_ids, dtype="i4"),
1023
+ attention_mask=jnp.array(attention_mask, dtype="i4"),
1024
+ position_ids=jnp.array(position_ids, dtype="i4"),
1025
+ output_attentions=output_attentions,
1026
+ output_hidden_states=output_hidden_states,
1027
+ return_dict=return_dict,
1028
+ deterministic=not train,
1029
+ rngs=rngs,
1030
+ method=_encoder_forward,
1031
+ )
1032
+
1033
+ @add_start_docstrings(BLENDERBOT_SMALL_DECODE_INPUTS_DOCSTRING)
1034
+ @replace_return_docstrings(
1035
+ output_type=FlaxBaseModelOutputWithPastAndCrossAttentions, config_class=BlenderbotSmallConfig
1036
+ )
1037
+ def decode(
1038
+ self,
1039
+ decoder_input_ids,
1040
+ encoder_outputs,
1041
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1042
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1043
+ decoder_position_ids: Optional[jnp.ndarray] = None,
1044
+ past_key_values: dict = None,
1045
+ output_attentions: Optional[bool] = None,
1046
+ output_hidden_states: Optional[bool] = None,
1047
+ return_dict: Optional[bool] = None,
1048
+ train: bool = False,
1049
+ params: dict = None,
1050
+ dropout_rng: PRNGKey = None,
1051
+ ):
1052
+ r"""
1053
+ Returns:
1054
+
1055
+ Example:
1056
+
1057
+ ```python
1058
+ >>> import jax.numpy as jnp
1059
+ >>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
1060
+
1061
+ >>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
1062
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
1063
+
1064
+ >>> text = "My friends are cool but they eat too many carbs."
1065
+ >>> inputs = tokenizer(text, max_length=1024, return_tensors="np")
1066
+ >>> encoder_outputs = model.encode(**inputs)
1067
+
1068
+ >>> decoder_start_token_id = model.config.decoder_start_token_id
1069
+ >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
1070
+
1071
+ >>> outputs = model.decode(decoder_input_ids, encoder_outputs)
1072
+ >>> last_decoder_hidden_states = outputs.last_hidden_state
1073
+ ```"""
1074
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1075
+ output_hidden_states = (
1076
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1077
+ )
1078
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1079
+
1080
+ encoder_hidden_states = encoder_outputs[0]
1081
+ if encoder_attention_mask is None:
1082
+ batch_size, sequence_length = encoder_hidden_states.shape[:2]
1083
+ encoder_attention_mask = jnp.ones((batch_size, sequence_length))
1084
+
1085
+ batch_size, sequence_length = decoder_input_ids.shape
1086
+ if decoder_attention_mask is None:
1087
+ decoder_attention_mask = jnp.ones((batch_size, sequence_length))
1088
+
1089
+ if decoder_position_ids is None:
1090
+ if past_key_values is not None:
1091
+ raise ValueError("Make sure to provide `decoder_position_ids` when passing `past_key_values`.")
1092
+
1093
+ decoder_position_ids = jnp.broadcast_to(
1094
+ jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
1095
+ )
1096
+
1097
+ # Handle any PRNG if needed
1098
+ rngs = {}
1099
+ if dropout_rng is not None:
1100
+ rngs["dropout"] = dropout_rng
1101
+
1102
+ inputs = {"params": params or self.params}
1103
+
1104
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be
1105
+ # passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
1106
+ # it can be changed by FlaxBlenderbotSmallAttention module
1107
+ if past_key_values:
1108
+ inputs["cache"] = past_key_values
1109
+ mutable = ["cache"]
1110
+ else:
1111
+ mutable = False
1112
+
1113
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
1114
+ decoder_module = module._get_decoder_module()
1115
+ return decoder_module(
1116
+ decoder_input_ids,
1117
+ decoder_attention_mask,
1118
+ decoder_position_ids,
1119
+ **kwargs,
1120
+ )
1121
+
1122
+ outputs = self.module.apply(
1123
+ inputs,
1124
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1125
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1126
+ decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
1127
+ encoder_hidden_states=encoder_hidden_states,
1128
+ encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
1129
+ output_attentions=output_attentions,
1130
+ output_hidden_states=output_hidden_states,
1131
+ return_dict=return_dict,
1132
+ deterministic=not train,
1133
+ rngs=rngs,
1134
+ mutable=mutable,
1135
+ method=_decoder_forward,
1136
+ )
1137
+
1138
+ # add updated cache to model output
1139
+ if past_key_values is not None and return_dict:
1140
+ outputs, past = outputs
1141
+ outputs["past_key_values"] = unfreeze(past["cache"])
1142
+ return outputs
1143
+ elif past_key_values is not None and not return_dict:
1144
+ outputs, past = outputs
1145
+ outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
1146
+
1147
+ return outputs
1148
+
1149
+ def __call__(
1150
+ self,
1151
+ input_ids: jnp.ndarray,
1152
+ attention_mask: Optional[jnp.ndarray] = None,
1153
+ decoder_input_ids: Optional[jnp.ndarray] = None,
1154
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1155
+ position_ids: Optional[jnp.ndarray] = None,
1156
+ decoder_position_ids: Optional[jnp.ndarray] = None,
1157
+ output_attentions: Optional[bool] = None,
1158
+ output_hidden_states: Optional[bool] = None,
1159
+ return_dict: Optional[bool] = None,
1160
+ train: bool = False,
1161
+ params: dict = None,
1162
+ dropout_rng: PRNGKey = None,
1163
+ ):
1164
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1165
+ output_hidden_states = (
1166
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1167
+ )
1168
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1169
+
1170
+ # prepare encoder inputs
1171
+ if attention_mask is None:
1172
+ attention_mask = jnp.ones_like(input_ids)
1173
+ if position_ids is None:
1174
+ batch_size, sequence_length = input_ids.shape
1175
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
1176
+
1177
+ # prepare decoder inputs
1178
+ if decoder_input_ids is None:
1179
+ decoder_input_ids = shift_tokens_right(
1180
+ input_ids, self.config.pad_token_id, decoder_start_token_id=self.config.decoder_start_token_id
1181
+ )
1182
+ if decoder_attention_mask is None:
1183
+ decoder_attention_mask = jnp.ones_like(decoder_input_ids)
1184
+ if decoder_position_ids is None:
1185
+ batch_size, sequence_length = decoder_input_ids.shape
1186
+ decoder_position_ids = jnp.broadcast_to(
1187
+ jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
1188
+ )
1189
+
1190
+ # Handle any PRNG if needed
1191
+ rngs = {"dropout": dropout_rng} if dropout_rng is not None else {}
1192
+
1193
+ return self.module.apply(
1194
+ {"params": params or self.params},
1195
+ input_ids=jnp.array(input_ids, dtype="i4"),
1196
+ attention_mask=jnp.array(attention_mask, dtype="i4"),
1197
+ position_ids=jnp.array(position_ids, dtype="i4"),
1198
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1199
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1200
+ decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
1201
+ output_attentions=output_attentions,
1202
+ output_hidden_states=output_hidden_states,
1203
+ return_dict=return_dict,
1204
+ deterministic=not train,
1205
+ rngs=rngs,
1206
+ )
1207
+
1208
+
1209
+ @add_start_docstrings(
1210
+ "The bare BlenderbotSmall Model transformer outputting raw hidden-states without any specific head on top.",
1211
+ BLENDERBOT_SMALL_START_DOCSTRING,
1212
+ )
1213
+ class FlaxBlenderbotSmallModel(FlaxBlenderbotSmallPreTrainedModel):
1214
+ config: BlenderbotSmallConfig
1215
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
1216
+ module_class = FlaxBlenderbotSmallModule
1217
+
1218
+
1219
+ append_call_sample_docstring(FlaxBlenderbotSmallModel, _CHECKPOINT_FOR_DOC, FlaxSeq2SeqModelOutput, _CONFIG_FOR_DOC)
1220
+
1221
+
1222
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartForConditionalGenerationModule with Bart->BlenderbotSmall
1223
+ class FlaxBlenderbotSmallForConditionalGenerationModule(nn.Module):
1224
+ config: BlenderbotSmallConfig
1225
+ dtype: jnp.dtype = jnp.float32
1226
+ bias_init: Callable[..., jnp.ndarray] = jax.nn.initializers.zeros
1227
+
1228
+ def setup(self):
1229
+ self.model = FlaxBlenderbotSmallModule(config=self.config, dtype=self.dtype)
1230
+ self.lm_head = nn.Dense(
1231
+ self.model.shared.num_embeddings,
1232
+ use_bias=False,
1233
+ dtype=self.dtype,
1234
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
1235
+ )
1236
+ self.final_logits_bias = self.param("final_logits_bias", self.bias_init, (1, self.model.shared.num_embeddings))
1237
+
1238
+ def _get_encoder_module(self):
1239
+ return self.model.encoder
1240
+
1241
+ def _get_decoder_module(self):
1242
+ return self.model.decoder
1243
+
1244
+ def __call__(
1245
+ self,
1246
+ input_ids,
1247
+ attention_mask,
1248
+ decoder_input_ids,
1249
+ decoder_attention_mask,
1250
+ position_ids,
1251
+ decoder_position_ids,
1252
+ output_attentions: bool = False,
1253
+ output_hidden_states: bool = False,
1254
+ return_dict: bool = True,
1255
+ deterministic: bool = True,
1256
+ ):
1257
+ outputs = self.model(
1258
+ input_ids=input_ids,
1259
+ attention_mask=attention_mask,
1260
+ decoder_input_ids=decoder_input_ids,
1261
+ decoder_attention_mask=decoder_attention_mask,
1262
+ position_ids=position_ids,
1263
+ decoder_position_ids=decoder_position_ids,
1264
+ output_attentions=output_attentions,
1265
+ output_hidden_states=output_hidden_states,
1266
+ return_dict=return_dict,
1267
+ deterministic=deterministic,
1268
+ )
1269
+
1270
+ hidden_states = outputs[0]
1271
+
1272
+ if self.config.tie_word_embeddings:
1273
+ shared_embedding = self.model.variables["params"]["shared"]["embedding"]
1274
+ lm_logits = self.lm_head.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
1275
+ else:
1276
+ lm_logits = self.lm_head(hidden_states)
1277
+
1278
+ lm_logits += jax.lax.stop_gradient(self.final_logits_bias.astype(self.dtype))
1279
+
1280
+ if not return_dict:
1281
+ output = (lm_logits,) + outputs[1:]
1282
+ return output
1283
+
1284
+ return FlaxSeq2SeqLMOutput(
1285
+ logits=lm_logits,
1286
+ decoder_hidden_states=outputs.decoder_hidden_states,
1287
+ decoder_attentions=outputs.decoder_attentions,
1288
+ cross_attentions=outputs.cross_attentions,
1289
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1290
+ encoder_hidden_states=outputs.encoder_hidden_states,
1291
+ encoder_attentions=outputs.encoder_attentions,
1292
+ )
1293
+
1294
+
1295
+ @add_start_docstrings(
1296
+ "The BLENDERBOT_SMALL Model with a language modeling head. Can be used for summarization.",
1297
+ BLENDERBOT_SMALL_START_DOCSTRING,
1298
+ )
1299
+ class FlaxBlenderbotSmallForConditionalGeneration(FlaxBlenderbotSmallPreTrainedModel):
1300
+ module_class = FlaxBlenderbotSmallForConditionalGenerationModule
1301
+ dtype: jnp.dtype = jnp.float32
1302
+
1303
+ @add_start_docstrings(BLENDERBOT_SMALL_DECODE_INPUTS_DOCSTRING)
1304
+ @replace_return_docstrings(output_type=FlaxCausalLMOutputWithCrossAttentions, config_class=BlenderbotSmallConfig)
1305
+ def decode(
1306
+ self,
1307
+ decoder_input_ids,
1308
+ encoder_outputs,
1309
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1310
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1311
+ decoder_position_ids: Optional[jnp.ndarray] = None,
1312
+ past_key_values: dict = None,
1313
+ output_attentions: Optional[bool] = None,
1314
+ output_hidden_states: Optional[bool] = None,
1315
+ return_dict: Optional[bool] = None,
1316
+ deterministic: bool = True,
1317
+ params: dict = None,
1318
+ dropout_rng: PRNGKey = None,
1319
+ ):
1320
+ r"""
1321
+ Returns:
1322
+
1323
+ Example:
1324
+
1325
+ ```python
1326
+ >>> import jax.numpy as jnp
1327
+ >>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
1328
+
1329
+ >>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
1330
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
1331
+
1332
+ >>> text = "My friends are cool but they eat too many carbs."
1333
+ >>> inputs = tokenizer(text, max_length=1024, return_tensors="np")
1334
+ >>> encoder_outputs = model.encode(**inputs)
1335
+
1336
+ >>> decoder_start_token_id = model.config.decoder_start_token_id
1337
+ >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
1338
+
1339
+ >>> outputs = model.decode(decoder_input_ids, encoder_outputs)
1340
+ >>> logits = outputs.logits
1341
+ ```"""
1342
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1343
+ output_hidden_states = (
1344
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1345
+ )
1346
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1347
+
1348
+ encoder_hidden_states = encoder_outputs[0]
1349
+ if encoder_attention_mask is None:
1350
+ batch_size, sequence_length = encoder_hidden_states.shape[:2]
1351
+ encoder_attention_mask = jnp.ones((batch_size, sequence_length))
1352
+
1353
+ batch_size, sequence_length = decoder_input_ids.shape
1354
+ if decoder_attention_mask is None:
1355
+ decoder_attention_mask = jnp.ones((batch_size, sequence_length))
1356
+
1357
+ if decoder_position_ids is None:
1358
+ if past_key_values is not None:
1359
+ raise ValueError("Make sure to provide `decoder_position_ids` when passing `past_key_values`.")
1360
+
1361
+ decoder_position_ids = jnp.broadcast_to(
1362
+ jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
1363
+ )
1364
+
1365
+ # Handle any PRNG if needed
1366
+ rngs = {}
1367
+ if dropout_rng is not None:
1368
+ rngs["dropout"] = dropout_rng
1369
+
1370
+ inputs = {"params": params or self.params}
1371
+
1372
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be
1373
+ # passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
1374
+ # it can be changed by FlaxBlenderbotSmallAttention module
1375
+ if past_key_values:
1376
+ inputs["cache"] = past_key_values
1377
+ mutable = ["cache"]
1378
+ else:
1379
+ mutable = False
1380
+
1381
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
1382
+ decoder_module = module._get_decoder_module()
1383
+ outputs = decoder_module(
1384
+ decoder_input_ids,
1385
+ decoder_attention_mask,
1386
+ decoder_position_ids,
1387
+ **kwargs,
1388
+ )
1389
+ hidden_states = outputs[0]
1390
+
1391
+ if self.config.tie_word_embeddings:
1392
+ shared_embedding = module.model.variables["params"]["shared"]["embedding"]
1393
+ lm_logits = module.lm_head.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
1394
+ else:
1395
+ lm_logits = module.lm_head(hidden_states)
1396
+
1397
+ lm_logits += module.final_logits_bias.astype(self.dtype)
1398
+ return lm_logits, outputs
1399
+
1400
+ outputs = self.module.apply(
1401
+ inputs,
1402
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1403
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1404
+ decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
1405
+ encoder_hidden_states=encoder_hidden_states,
1406
+ encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
1407
+ output_attentions=output_attentions,
1408
+ output_hidden_states=output_hidden_states,
1409
+ return_dict=return_dict,
1410
+ deterministic=deterministic,
1411
+ rngs=rngs,
1412
+ mutable=mutable,
1413
+ method=_decoder_forward,
1414
+ )
1415
+
1416
+ if past_key_values is None:
1417
+ lm_logits, decoder_outputs = outputs
1418
+ else:
1419
+ (lm_logits, decoder_outputs), past = outputs
1420
+
1421
+ if return_dict:
1422
+ outputs = FlaxCausalLMOutputWithCrossAttentions(
1423
+ logits=lm_logits,
1424
+ hidden_states=decoder_outputs.hidden_states,
1425
+ attentions=decoder_outputs.attentions,
1426
+ cross_attentions=decoder_outputs.cross_attentions,
1427
+ )
1428
+ else:
1429
+ outputs = (lm_logits,) + decoder_outputs[1:]
1430
+
1431
+ # add updated cache to model output
1432
+ if past_key_values is not None and return_dict:
1433
+ outputs["past_key_values"] = unfreeze(past["cache"])
1434
+ return outputs
1435
+ elif past_key_values is not None and not return_dict:
1436
+ outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
1437
+
1438
+ return outputs
1439
+
1440
+ def prepare_inputs_for_generation(
1441
+ self,
1442
+ decoder_input_ids,
1443
+ max_length,
1444
+ attention_mask: Optional[jax.Array] = None,
1445
+ decoder_attention_mask: Optional[jax.Array] = None,
1446
+ encoder_outputs=None,
1447
+ **kwargs,
1448
+ ):
1449
+ # initializing the cache
1450
+ batch_size, seq_length = decoder_input_ids.shape
1451
+
1452
+ past_key_values = self.init_cache(batch_size, max_length, encoder_outputs)
1453
+ # Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
1454
+ # But since the decoder uses a causal mask, those positions are masked anyways.
1455
+ # Thus we can create a single static attention_mask here, which is more efficient for compilation
1456
+ extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
1457
+ if decoder_attention_mask is not None:
1458
+ position_ids = decoder_attention_mask.cumsum(axis=-1) - 1
1459
+ extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, decoder_attention_mask, (0, 0))
1460
+ else:
1461
+ position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
1462
+
1463
+ return {
1464
+ "past_key_values": past_key_values,
1465
+ "encoder_outputs": encoder_outputs,
1466
+ "encoder_attention_mask": attention_mask,
1467
+ "decoder_attention_mask": extended_attention_mask,
1468
+ "decoder_position_ids": position_ids,
1469
+ }
1470
+
1471
+ def update_inputs_for_generation(self, model_outputs, model_kwargs):
1472
+ model_kwargs["past_key_values"] = model_outputs.past_key_values
1473
+ model_kwargs["decoder_position_ids"] = model_kwargs["decoder_position_ids"][:, -1:] + 1
1474
+ return model_kwargs
1475
+
1476
+
1477
+ FLAX_BLENDERBOT_SMALL_CONDITIONAL_GENERATION_DOCSTRING = """
1478
+ Returns:
1479
+
1480
+ Summarization example:
1481
+
1482
+ ```py
1483
+ >>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
1484
+
1485
+ >>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
1486
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
1487
+
1488
+ >>> ARTICLE_TO_SUMMARIZE = "My friends are cool but they eat too many carbs."
1489
+ >>> inputs = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=1024, return_tensors="np")
1490
+
1491
+ >>> # Generate Summary
1492
+ >>> summary_ids = model.generate(inputs["input_ids"]).sequences
1493
+ >>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False))
1494
+ ```
1495
+
1496
+ Mask filling example:
1497
+
1498
+ ```py
1499
+ >>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
1500
+
1501
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
1502
+ >>> TXT = "My friends are <mask> but they eat too many carbs."
1503
+
1504
+ >>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
1505
+ >>> input_ids = tokenizer([TXT], return_tensors="np")["input_ids"]
1506
+ >>> logits = model(input_ids).logits
1507
+
1508
+ >>> masked_index = (input_ids[0] == tokenizer.mask_token_id).nonzero().item()
1509
+ >>> probs = jax.nn.softmax(logits[0, masked_index], axis=0)
1510
+ >>> values, predictions = jax.lax.top_k(probs)
1511
+
1512
+ >>> tokenizer.decode(predictions).split()
1513
+ ```
1514
+ """
1515
+
1516
+ overwrite_call_docstring(
1517
+ FlaxBlenderbotSmallForConditionalGeneration,
1518
+ BLENDERBOT_SMALL_INPUTS_DOCSTRING + FLAX_BLENDERBOT_SMALL_CONDITIONAL_GENERATION_DOCSTRING,
1519
+ )
1520
+ append_replace_return_docstrings(
1521
+ FlaxBlenderbotSmallForConditionalGeneration, output_type=FlaxSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC
1522
+ )
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/modeling_tf_blenderbot_small.py ADDED
@@ -0,0 +1,1415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Facebook, Inc and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ TF 2.0 BlenderbotSmall model."""
16
+
17
+
18
+ from __future__ import annotations
19
+
20
+ import random
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import numpy as np
24
+ import tensorflow as tf
25
+
26
+ from ...activations_tf import get_tf_activation
27
+ from ...modeling_tf_outputs import (
28
+ TFBaseModelOutput,
29
+ TFBaseModelOutputWithPastAndCrossAttentions,
30
+ TFSeq2SeqLMOutput,
31
+ TFSeq2SeqModelOutput,
32
+ )
33
+
34
+ # Public API
35
+ from ...modeling_tf_utils import (
36
+ TFCausalLanguageModelingLoss,
37
+ TFPreTrainedModel,
38
+ keras_serializable,
39
+ unpack_inputs,
40
+ )
41
+ from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
42
+ from ...utils import (
43
+ ContextManagers,
44
+ add_code_sample_docstrings,
45
+ add_end_docstrings,
46
+ add_start_docstrings,
47
+ add_start_docstrings_to_model_forward,
48
+ logging,
49
+ replace_return_docstrings,
50
+ )
51
+ from .configuration_blenderbot_small import BlenderbotSmallConfig
52
+
53
+
54
+ logger = logging.get_logger(__name__)
55
+
56
+ _CHECKPOINT_FOR_DOC = "facebook/blenderbot_small-90M"
57
+ _CONFIG_FOR_DOC = "BlenderbotSmallConfig"
58
+
59
+
60
+ LARGE_NEGATIVE = -1e8
61
+
62
+
63
+ # Copied from transformers.models.bart.modeling_tf_bart.shift_tokens_right
64
+ def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int):
65
+ pad_token_id = tf.cast(pad_token_id, input_ids.dtype)
66
+ decoder_start_token_id = tf.cast(decoder_start_token_id, input_ids.dtype)
67
+ start_tokens = tf.fill(
68
+ (shape_list(input_ids)[0], 1), tf.convert_to_tensor(decoder_start_token_id, input_ids.dtype)
69
+ )
70
+ shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1)
71
+ # replace possible -100 values in labels by `pad_token_id`
72
+ shifted_input_ids = tf.where(
73
+ shifted_input_ids == -100,
74
+ tf.fill(shape_list(shifted_input_ids), tf.convert_to_tensor(pad_token_id, input_ids.dtype)),
75
+ shifted_input_ids,
76
+ )
77
+
78
+ # "Verify that `labels` has only positive values and -100"
79
+ assert_gte0 = tf.debugging.assert_greater_equal(shifted_input_ids, tf.constant(0, dtype=input_ids.dtype))
80
+
81
+ # Make sure the assertion op is called by wrapping the result in an identity no-op
82
+ with tf.control_dependencies([assert_gte0]):
83
+ shifted_input_ids = tf.identity(shifted_input_ids)
84
+
85
+ return shifted_input_ids
86
+
87
+
88
+ # Copied from transformers.models.bart.modeling_tf_bart._make_causal_mask
89
+ def _make_causal_mask(input_ids_shape: tf.TensorShape, past_key_values_length: int = 0):
90
+ """
91
+ Make causal mask used for bi-directional self-attention.
92
+ """
93
+ bsz = input_ids_shape[0]
94
+ tgt_len = input_ids_shape[1]
95
+ mask = tf.ones((tgt_len, tgt_len)) * LARGE_NEGATIVE
96
+ mask_cond = tf.range(shape_list(mask)[-1])
97
+
98
+ mask = tf.where(mask_cond < tf.reshape(mask_cond + 1, (shape_list(mask)[-1], 1)), 0.0, mask)
99
+
100
+ if past_key_values_length > 0:
101
+ mask = tf.concat([tf.zeros((tgt_len, past_key_values_length)), mask], axis=-1)
102
+
103
+ return tf.tile(mask[None, None, :, :], (bsz, 1, 1, 1))
104
+
105
+
106
+ # Copied from transformers.models.bart.modeling_tf_bart._expand_mask
107
+ def _expand_mask(mask: tf.Tensor, tgt_len: Optional[int] = None):
108
+ """
109
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
110
+ """
111
+ src_len = shape_list(mask)[1]
112
+ tgt_len = tgt_len if tgt_len is not None else src_len
113
+ one_cst = tf.constant(1.0)
114
+ mask = tf.cast(mask, dtype=one_cst.dtype)
115
+ expanded_mask = tf.tile(mask[:, None, None, :], (1, 1, tgt_len, 1))
116
+
117
+ return (one_cst - expanded_mask) * LARGE_NEGATIVE
118
+
119
+
120
+ # Copied from transformers.models.blenderbot.modeling_tf_blenderbot.TFBlenderbotLearnedPositionalEmbedding with Blenderbot->BlenderbotSmall
121
+ class TFBlenderbotSmallLearnedPositionalEmbedding(tf.keras.layers.Embedding):
122
+ """
123
+ This module learns positional embeddings up to a fixed maximum size.
124
+ """
125
+
126
+ def __init__(self, num_embeddings: int, embedding_dim: int, **kwargs):
127
+ super().__init__(num_embeddings, embedding_dim, **kwargs)
128
+
129
+ def call(
130
+ self, input_shape: tf.TensorShape, past_key_values_length: int = 0, position_ids: tf.Tensor | None = None
131
+ ):
132
+ """Input is expected to be of size [bsz x seqlen]."""
133
+ if position_ids is None:
134
+ seq_len = input_shape[1]
135
+ position_ids = tf.range(seq_len, delta=1, name="range")
136
+ position_ids += past_key_values_length
137
+
138
+ return super().call(tf.cast(position_ids, dtype=tf.int32))
139
+
140
+
141
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartAttention with Bart->BlenderbotSmall
142
+ class TFBlenderbotSmallAttention(tf.keras.layers.Layer):
143
+ """Multi-headed attention from "Attention Is All You Need"""
144
+
145
+ def __init__(
146
+ self,
147
+ embed_dim: int,
148
+ num_heads: int,
149
+ dropout: float = 0.0,
150
+ is_decoder: bool = False,
151
+ bias: bool = True,
152
+ **kwargs,
153
+ ):
154
+ super().__init__(**kwargs)
155
+ self.embed_dim = embed_dim
156
+
157
+ self.num_heads = num_heads
158
+ self.dropout = tf.keras.layers.Dropout(dropout)
159
+ self.head_dim = embed_dim // num_heads
160
+ if (self.head_dim * num_heads) != self.embed_dim:
161
+ raise ValueError(
162
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
163
+ f" and `num_heads`: {num_heads})."
164
+ )
165
+ self.scaling = self.head_dim**-0.5
166
+ self.is_decoder = is_decoder
167
+
168
+ self.k_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name="k_proj")
169
+ self.q_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name="q_proj")
170
+ self.v_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name="v_proj")
171
+ self.out_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name="out_proj")
172
+
173
+ def _shape(self, tensor: tf.Tensor, seq_len: int, bsz: int):
174
+ return tf.transpose(tf.reshape(tensor, (bsz, seq_len, self.num_heads, self.head_dim)), (0, 2, 1, 3))
175
+
176
+ def call(
177
+ self,
178
+ hidden_states: tf.Tensor,
179
+ key_value_states: tf.Tensor | None = None,
180
+ past_key_value: Tuple[Tuple[tf.Tensor]] | None = None,
181
+ attention_mask: tf.Tensor | None = None,
182
+ layer_head_mask: tf.Tensor | None = None,
183
+ training: Optional[bool] = False,
184
+ ) -> Tuple[tf.Tensor, tf.Tensor | None]:
185
+ """Input shape: Batch x Time x Channel"""
186
+
187
+ # if key_value_states are provided this layer is used as a cross-attention layer
188
+ # for the decoder
189
+ is_cross_attention = key_value_states is not None
190
+ bsz, tgt_len, embed_dim = shape_list(hidden_states)
191
+
192
+ # get query proj
193
+ query_states = self.q_proj(hidden_states) * self.scaling
194
+ # get key, value proj
195
+ if is_cross_attention and past_key_value is not None:
196
+ # reuse k,v, cross_attentions
197
+ key_states = past_key_value[0]
198
+ value_states = past_key_value[1]
199
+ elif is_cross_attention:
200
+ # cross_attentions
201
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
202
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
203
+ elif past_key_value is not None:
204
+ # reuse k, v, self_attention
205
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
206
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
207
+ key_states = tf.concat([past_key_value[0], key_states], axis=2)
208
+ value_states = tf.concat([past_key_value[1], value_states], axis=2)
209
+ else:
210
+ # self_attention
211
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
212
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
213
+
214
+ if self.is_decoder:
215
+ # if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
216
+ # Further calls to cross_attention layer can then reuse all cross-attention
217
+ # key/value_states (first "if" case)
218
+ # if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
219
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
220
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
221
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
222
+ past_key_value = (key_states, value_states)
223
+
224
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
225
+ query_states = tf.reshape(self._shape(query_states, tgt_len, bsz), proj_shape)
226
+ key_states = tf.reshape(key_states, proj_shape)
227
+ value_states = tf.reshape(value_states, proj_shape)
228
+
229
+ src_len = shape_list(key_states)[1]
230
+ attn_weights = tf.matmul(query_states, key_states, transpose_b=True)
231
+
232
+ tf.debugging.assert_equal(
233
+ shape_list(attn_weights),
234
+ [bsz * self.num_heads, tgt_len, src_len],
235
+ message=(
236
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
237
+ f" {shape_list(attn_weights)}"
238
+ ),
239
+ )
240
+
241
+ if attention_mask is not None:
242
+ tf.debugging.assert_equal(
243
+ shape_list(attention_mask),
244
+ [bsz, 1, tgt_len, src_len],
245
+ message=(
246
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
247
+ f" {shape_list(attention_mask)}"
248
+ ),
249
+ )
250
+
251
+ attention_mask = tf.cast(attention_mask, dtype=attn_weights.dtype)
252
+ attn_weights = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) + attention_mask
253
+ attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
254
+
255
+ attn_weights = stable_softmax(attn_weights, axis=-1)
256
+
257
+ if layer_head_mask is not None:
258
+ tf.debugging.assert_equal(
259
+ shape_list(layer_head_mask),
260
+ [self.num_heads],
261
+ message=(
262
+ f"Head mask for a single layer should be of size {(self.num_heads)}, but is"
263
+ f" {shape_list(layer_head_mask)}"
264
+ ),
265
+ )
266
+
267
+ attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape(
268
+ attn_weights, (bsz, self.num_heads, tgt_len, src_len)
269
+ )
270
+ attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
271
+
272
+ attn_probs = self.dropout(attn_weights, training=training)
273
+ attn_output = tf.matmul(attn_probs, value_states)
274
+
275
+ tf.debugging.assert_equal(
276
+ shape_list(attn_output),
277
+ [bsz * self.num_heads, tgt_len, self.head_dim],
278
+ message=(
279
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
280
+ f" {shape_list(attn_output)}"
281
+ ),
282
+ )
283
+
284
+ attn_output = tf.transpose(
285
+ tf.reshape(attn_output, (bsz, self.num_heads, tgt_len, self.head_dim)), (0, 2, 1, 3)
286
+ )
287
+ attn_output = tf.reshape(attn_output, (bsz, tgt_len, embed_dim))
288
+
289
+ attn_output = self.out_proj(attn_output)
290
+ attn_weights: tf.Tensor = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len))
291
+
292
+ return attn_output, attn_weights, past_key_value
293
+
294
+
295
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartEncoderLayer with Bart->BlenderbotSmall
296
+ class TFBlenderbotSmallEncoderLayer(tf.keras.layers.Layer):
297
+ def __init__(self, config: BlenderbotSmallConfig, **kwargs):
298
+ super().__init__(**kwargs)
299
+ self.embed_dim = config.d_model
300
+ self.self_attn = TFBlenderbotSmallAttention(
301
+ self.embed_dim, config.encoder_attention_heads, dropout=config.attention_dropout, name="self_attn"
302
+ )
303
+ self.self_attn_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
304
+ self.dropout = tf.keras.layers.Dropout(config.dropout)
305
+ self.activation_fn = get_tf_activation(config.activation_function)
306
+ self.activation_dropout = tf.keras.layers.Dropout(config.activation_dropout)
307
+ self.fc1 = tf.keras.layers.Dense(config.encoder_ffn_dim, name="fc1")
308
+ self.fc2 = tf.keras.layers.Dense(self.embed_dim, name="fc2")
309
+ self.final_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
310
+
311
+ def call(
312
+ self,
313
+ hidden_states: tf.Tensor,
314
+ attention_mask: np.ndarray | tf.Tensor | None,
315
+ layer_head_mask: tf.Tensor | None,
316
+ training: Optional[bool] = False,
317
+ ) -> tf.Tensor:
318
+ """
319
+ Args:
320
+ hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
321
+ attention_mask (`tf.Tensor`): attention mask of size
322
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
323
+ layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
324
+ `(encoder_attention_heads,)`
325
+ """
326
+ residual = hidden_states
327
+ hidden_states, self_attn_weights, _ = self.self_attn(
328
+ hidden_states=hidden_states, attention_mask=attention_mask, layer_head_mask=layer_head_mask
329
+ )
330
+
331
+ tf.debugging.assert_equal(
332
+ shape_list(hidden_states),
333
+ shape_list(residual),
334
+ message=f"Self attn modified the shape of query {shape_list(residual)} to {shape_list(hidden_states)}",
335
+ )
336
+
337
+ hidden_states = self.dropout(hidden_states, training=training)
338
+ hidden_states = residual + hidden_states
339
+ hidden_states = self.self_attn_layer_norm(hidden_states)
340
+
341
+ residual = hidden_states
342
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
343
+ hidden_states = self.activation_dropout(hidden_states, training=training)
344
+ hidden_states = self.fc2(hidden_states)
345
+ hidden_states = self.dropout(hidden_states, training=training)
346
+ hidden_states = residual + hidden_states
347
+ hidden_states = self.final_layer_norm(hidden_states)
348
+
349
+ return hidden_states, self_attn_weights
350
+
351
+
352
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartDecoderLayer with Bart->BlenderbotSmall
353
+ class TFBlenderbotSmallDecoderLayer(tf.keras.layers.Layer):
354
+ def __init__(self, config: BlenderbotSmallConfig, **kwargs):
355
+ super().__init__(**kwargs)
356
+ self.embed_dim = config.d_model
357
+ self.self_attn = TFBlenderbotSmallAttention(
358
+ embed_dim=self.embed_dim,
359
+ num_heads=config.decoder_attention_heads,
360
+ dropout=config.attention_dropout,
361
+ name="self_attn",
362
+ is_decoder=True,
363
+ )
364
+ self.dropout = tf.keras.layers.Dropout(config.dropout)
365
+ self.activation_fn = get_tf_activation(config.activation_function)
366
+ self.activation_dropout = tf.keras.layers.Dropout(config.activation_dropout)
367
+
368
+ self.self_attn_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
369
+ self.encoder_attn = TFBlenderbotSmallAttention(
370
+ self.embed_dim,
371
+ config.decoder_attention_heads,
372
+ dropout=config.attention_dropout,
373
+ name="encoder_attn",
374
+ is_decoder=True,
375
+ )
376
+ self.encoder_attn_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="encoder_attn_layer_norm")
377
+ self.fc1 = tf.keras.layers.Dense(config.decoder_ffn_dim, name="fc1")
378
+ self.fc2 = tf.keras.layers.Dense(self.embed_dim, name="fc2")
379
+ self.final_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
380
+
381
+ def call(
382
+ self,
383
+ hidden_states: tf.Tensor,
384
+ attention_mask: np.ndarray | tf.Tensor | None = None,
385
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
386
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
387
+ layer_head_mask: tf.Tensor | None = None,
388
+ cross_attn_layer_head_mask: tf.Tensor | None = None,
389
+ past_key_value: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
390
+ training: Optional[bool] = False,
391
+ ) -> Tuple[tf.Tensor, tf.Tensor, Tuple[Tuple[tf.Tensor]]]:
392
+ """
393
+ Args:
394
+ hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
395
+ attention_mask (`tf.Tensor`): attention mask of size
396
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
397
+ encoder_hidden_states (`tf.Tensor`):
398
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
399
+ encoder_attention_mask (`tf.Tensor`): encoder attention mask of size
400
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
401
+ layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
402
+ `(decoder_attention_heads,)`
403
+ cross_attn_layer_head_mask (`tf.Tensor`): mask for heads of the cross-attention module.
404
+ `(decoder_attention_heads,)`
405
+ past_key_value (`Tuple(tf.Tensor)`): cached past key and value projection states
406
+ """
407
+ residual = hidden_states
408
+
409
+ # Self Attention
410
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
411
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
412
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
413
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
414
+ hidden_states=hidden_states,
415
+ past_key_value=self_attn_past_key_value,
416
+ attention_mask=attention_mask,
417
+ layer_head_mask=layer_head_mask,
418
+ )
419
+ hidden_states = self.dropout(hidden_states, training=training)
420
+ hidden_states = residual + hidden_states
421
+ hidden_states = self.self_attn_layer_norm(hidden_states)
422
+
423
+ # Cross-Attention Block
424
+ cross_attn_present_key_value = None
425
+ cross_attn_weights = None
426
+ if encoder_hidden_states is not None:
427
+ residual = hidden_states
428
+
429
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
430
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
431
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
432
+ hidden_states=hidden_states,
433
+ key_value_states=encoder_hidden_states,
434
+ attention_mask=encoder_attention_mask,
435
+ layer_head_mask=cross_attn_layer_head_mask,
436
+ past_key_value=cross_attn_past_key_value,
437
+ )
438
+ hidden_states = self.dropout(hidden_states, training=training)
439
+ hidden_states = residual + hidden_states
440
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
441
+
442
+ # add cross-attn to positions 3,4 of present_key_value tuple
443
+ present_key_value = present_key_value + cross_attn_present_key_value
444
+
445
+ # Fully Connected
446
+ residual = hidden_states
447
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
448
+ hidden_states = self.activation_dropout(hidden_states, training=training)
449
+ hidden_states = self.fc2(hidden_states)
450
+ hidden_states = self.dropout(hidden_states, training=training)
451
+ hidden_states = residual + hidden_states
452
+ hidden_states = self.final_layer_norm(hidden_states)
453
+
454
+ return (
455
+ hidden_states,
456
+ self_attn_weights,
457
+ cross_attn_weights,
458
+ present_key_value,
459
+ )
460
+
461
+
462
+ class TFBlenderbotSmallPreTrainedModel(TFPreTrainedModel):
463
+ config_class = BlenderbotSmallConfig
464
+ base_model_prefix = "model"
465
+
466
+
467
+ BLENDERBOT_SMALL_START_DOCSTRING = r"""
468
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
469
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
470
+ etc.)
471
+
472
+ This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
473
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
474
+ behavior.
475
+
476
+ <Tip>
477
+
478
+ TensorFlow models and layers in `transformers` accept two formats as input:
479
+
480
+ - having all inputs as keyword arguments (like PyTorch models), or
481
+ - having all inputs as a list, tuple or dict in the first positional argument.
482
+
483
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
484
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
485
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
486
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
487
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
488
+ positional argument:
489
+
490
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
491
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
492
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
493
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
494
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
495
+
496
+ Note that when creating models and layers with
497
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
498
+ about any of this, as you can just pass inputs like you would to any other Python function!
499
+
500
+ </Tip>
501
+
502
+ Args:
503
+ config ([`BlenderbotSmallConfig`]): Model configuration class with all the parameters of the model.
504
+ Initializing with a config file does not load the weights associated with the model, only the
505
+ configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
506
+ """
507
+
508
+ BLENDERBOT_SMALL_GENERATION_EXAMPLE = r"""
509
+ Conversation example::
510
+
511
+ ```py
512
+ >>> from transformers import AutoTokenizer, TFBlenderbotSmallForConditionalGeneration
513
+
514
+ >>> mname = "facebook/blenderbot_small-90M"
515
+ >>> model = BlenderbotSmallForConditionalGeneration.from_pretrained(mname)
516
+ >>> tokenizer = AutoTokenizer.from_pretrained(mname)
517
+
518
+ >>> UTTERANCE = "My friends are cool but they eat too many carbs."
519
+ >>> print("Human: ", UTTERANCE)
520
+ >>> inputs = tokenizer([UTTERANCE], return_tensors="tf")
521
+
522
+ >>> reply_ids = model.generate(**inputs)
523
+ >>> print("Bot: ", tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0])
524
+ what kind of carbs do they eat? i don't know much about carbs.
525
+
526
+ >>> REPLY = "I'm not sure"
527
+ >>> print("Human: ", REPLY)
528
+ >>> NEXT_UTTERANCE = (
529
+ ... "My friends are cool but they eat too many carbs.</s> "
530
+ ... "<s>what kind of carbs do they eat? i don't know much about carbs.</s> "
531
+ ... "<s>I'm not sure."
532
+ ... )
533
+
534
+ >>> inputs = tokenizer([NEXT_UTTERANCE], return_tensors="tf")
535
+ >>> inputs.pop("token_type_ids")
536
+ >>> next_reply_ids = model.generate(**inputs)
537
+ >>> print("Bot: ", tokenizer.batch_decode(next_reply_ids, skip_special_tokens=True)[0])
538
+ ```
539
+ """
540
+
541
+ BLENDERBOT_SMALL_INPUTS_DOCSTRING = r"""
542
+ Args:
543
+ input_ids (`tf.Tensor` of shape `({0})`):
544
+ Indices of input sequence tokens in the vocabulary.
545
+
546
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
547
+ [`PreTrainedTokenizer.__call__`] for details.
548
+
549
+ [What are input IDs?](../glossary#input-ids)
550
+ attention_mask (`tf.Tensor` of shape `({0})`, *optional*):
551
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
552
+
553
+ - 1 for tokens that are **not masked**,
554
+ - 0 for tokens that are **masked**.
555
+
556
+ [What are attention masks?](../glossary#attention-mask)
557
+ decoder_input_ids (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
558
+ Indices of decoder input sequence tokens in the vocabulary.
559
+
560
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
561
+ [`PreTrainedTokenizer.__call__`] for details.
562
+
563
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
564
+
565
+ BlenderbotSmall uses the `bos_token_id` as the starting token for `decoder_input_ids` generation. If
566
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
567
+ `past_key_values`).
568
+ decoder_attention_mask (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
569
+ will be made by default and ignore pad tokens. It is not recommended to set this for most use cases.
570
+ decoder_position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
571
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
572
+ range `[0, config.max_position_embeddings - 1]`.
573
+ head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
574
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
575
+
576
+ - 1 indicates the head is **not masked**,
577
+ - 0 indicates the head is **masked**.
578
+
579
+ decoder_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
580
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
581
+
582
+ - 1 indicates the head is **not masked**,
583
+ - 0 indicates the head is **masked**.
584
+
585
+ cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
586
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
587
+
588
+ - 1 indicates the head is **not masked**,
589
+ - 0 indicates the head is **masked**.
590
+
591
+ encoder_outputs (`tf.FloatTensor`, *optional*):
592
+ hidden states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
593
+ of shape `(batch_size, sequence_length, hidden_size)` is a sequence of
594
+ past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
595
+ contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
596
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
597
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
598
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
599
+ use_cache (`bool`, *optional*, defaults to `True`):
600
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
601
+ `past_key_values`). Set to `False` during training, `True` during generation
602
+ output_attentions (`bool`, *optional*):
603
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
604
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
605
+ config will be used instead.
606
+ output_hidden_states (`bool`, *optional*):
607
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
608
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
609
+ used instead.
610
+ return_dict (`bool`, *optional*):
611
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
612
+ eager mode, in graph mode the value will always be set to True.
613
+ training (`bool`, *optional*, defaults to `False`):
614
+ Whether or not to use the model in training mode (some modules like dropout modules have different
615
+ behaviors between training and evaluation).
616
+ """
617
+
618
+
619
+ @keras_serializable
620
+ class TFBlenderbotSmallEncoder(tf.keras.layers.Layer):
621
+ config_class = BlenderbotSmallConfig
622
+ """
623
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
624
+ [`TFBlenderbotSmallEncoderLayer`].
625
+
626
+ Args:
627
+ config: BlenderbotSmallConfig
628
+ """
629
+
630
+ def __init__(
631
+ self, config: BlenderbotSmallConfig, embed_tokens: Optional[tf.keras.layers.Embedding] = None, **kwargs
632
+ ):
633
+ super().__init__(**kwargs)
634
+ self.config = config
635
+ self.dropout = tf.keras.layers.Dropout(config.dropout)
636
+ self.layerdrop = config.encoder_layerdrop
637
+ self.padding_idx = config.pad_token_id
638
+ self.max_source_positions = config.max_position_embeddings
639
+ self.embed_scale = tf.math.sqrt(float(config.d_model)) if config.scale_embedding else 1.0
640
+
641
+ self.embed_tokens = embed_tokens
642
+ self.embed_positions = TFBlenderbotSmallLearnedPositionalEmbedding(
643
+ config.max_position_embeddings,
644
+ config.d_model,
645
+ name="embed_positions",
646
+ )
647
+ self.layers = [TFBlenderbotSmallEncoderLayer(config, name=f"layers.{i}") for i in range(config.encoder_layers)]
648
+ self.layernorm_embedding = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm_embedding")
649
+
650
+ def get_embed_tokens(self):
651
+ return self.embed_tokens
652
+
653
+ def set_embed_tokens(self, embed_tokens):
654
+ self.embed_tokens = embed_tokens
655
+
656
+ @unpack_inputs
657
+ def call(
658
+ self,
659
+ input_ids=None,
660
+ inputs_embeds=None,
661
+ attention_mask=None,
662
+ head_mask=None,
663
+ output_attentions=None,
664
+ output_hidden_states=None,
665
+ return_dict=None,
666
+ training=False,
667
+ ):
668
+ """
669
+ Args:
670
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
671
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
672
+ provide it.
673
+
674
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
675
+ [`PreTrainedTokenizer.__call__`] for details.
676
+
677
+ [What are input IDs?](../glossary#input-ids)
678
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
679
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
680
+
681
+ - 1 for tokens that are **not masked**,
682
+ - 0 for tokens that are **masked**.
683
+
684
+ [What are attention masks?](../glossary#attention-mask)
685
+ head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, `optional):
686
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
687
+
688
+ - 1 indicates the head is **not masked**,
689
+ - 0 indicates the head is **masked**.
690
+
691
+ inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
692
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
693
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
694
+ than the model's internal embedding lookup matrix.
695
+ output_attentions (`bool`, *optional*):
696
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
697
+ returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value
698
+ in the config will be used instead.
699
+ output_hidden_states (`bool`, *optional*):
700
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
701
+ for more detail. This argument can be used only in eager mode, in graph mode the value in the config
702
+ will be used instead.
703
+ return_dict (`bool`, *optional*):
704
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used
705
+ in eager mode, in graph mode the value will always be set to True.
706
+ training (`bool`, *optional*, defaults to `False`):
707
+ Whether or not to use the model in training mode (some modules like dropout modules have different
708
+ behaviors between training and evaluation).
709
+ """
710
+ if input_ids is not None and inputs_embeds is not None:
711
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
712
+ elif input_ids is not None:
713
+ input_shape = shape_list(input_ids)
714
+ elif inputs_embeds is not None:
715
+ input_shape = shape_list(inputs_embeds)[:-1]
716
+ else:
717
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
718
+
719
+ if inputs_embeds is None:
720
+ # if `self.embed_tokens.load_weight_prefix` is set, runs the embedding operation with the correct name
721
+ # scope, so that its weights are registered with the desired name for loading/storing. When `tf.name_scope`
722
+ # is used with a name ending in `/`, that name replaces the current name scope.
723
+ # (embeddings with tf.name_scope: self.embed_tokens.load_weight_prefix/self.embed_tokens.name/embeddings:0)
724
+ context = []
725
+ if hasattr(self.embed_tokens, "load_weight_prefix"):
726
+ context.append(tf.name_scope(self.embed_tokens.load_weight_prefix + "/"))
727
+ with ContextManagers(context):
728
+ check_embeddings_within_bounds(input_ids, self.embed_tokens.input_dim)
729
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
730
+
731
+ embed_pos = self.embed_positions(input_shape)
732
+ hidden_states = inputs_embeds + embed_pos
733
+ hidden_states = self.layernorm_embedding(hidden_states)
734
+ hidden_states = self.dropout(hidden_states, training=training)
735
+
736
+ # check attention mask and invert
737
+ if attention_mask is not None:
738
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
739
+ attention_mask = _expand_mask(attention_mask)
740
+ else:
741
+ attention_mask = None
742
+
743
+ encoder_states = () if output_hidden_states else None
744
+ all_attentions = () if output_attentions else None
745
+
746
+ # check if head_mask has a correct number of layers specified if desired
747
+ if head_mask is not None:
748
+ tf.debugging.assert_equal(
749
+ shape_list(head_mask)[0],
750
+ len(self.layers),
751
+ message=(
752
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
753
+ f" {shape_list(head_mask)[0]}."
754
+ ),
755
+ )
756
+
757
+ # encoder layers
758
+ for idx, encoder_layer in enumerate(self.layers):
759
+ if output_hidden_states:
760
+ encoder_states = encoder_states + (hidden_states,)
761
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
762
+ dropout_probability = random.uniform(0, 1)
763
+ if training and (dropout_probability < self.layerdrop): # skip the layer
764
+ continue
765
+
766
+ hidden_states, attn = encoder_layer(
767
+ hidden_states,
768
+ attention_mask,
769
+ head_mask[idx] if head_mask is not None else None,
770
+ )
771
+
772
+ if output_attentions:
773
+ all_attentions += (attn,)
774
+
775
+ if output_hidden_states:
776
+ encoder_states = encoder_states + (hidden_states,)
777
+
778
+ if not return_dict:
779
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
780
+ return TFBaseModelOutput(
781
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
782
+ )
783
+
784
+
785
+ @keras_serializable
786
+ class TFBlenderbotSmallDecoder(tf.keras.layers.Layer):
787
+ config_class = BlenderbotSmallConfig
788
+ """
789
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TFBlenderbotSmallDecoderLayer`]
790
+
791
+ Args:
792
+ config: BlenderbotSmallConfig
793
+ embed_tokens: output embedding
794
+ """
795
+
796
+ def __init__(
797
+ self, config: BlenderbotSmallConfig, embed_tokens: Optional[tf.keras.layers.Embedding] = None, **kwargs
798
+ ):
799
+ super().__init__(**kwargs)
800
+ self.config = config
801
+ self.padding_idx = config.pad_token_id
802
+ self.embed_tokens = embed_tokens
803
+ self.layerdrop = config.decoder_layerdrop
804
+ self.embed_positions = TFBlenderbotSmallLearnedPositionalEmbedding(
805
+ config.max_position_embeddings,
806
+ config.d_model,
807
+ name="embed_positions",
808
+ )
809
+ self.embed_scale = tf.math.sqrt(float(config.d_model)) if config.scale_embedding else 1.0
810
+ self.layers = [TFBlenderbotSmallDecoderLayer(config, name=f"layers.{i}") for i in range(config.decoder_layers)]
811
+ self.layernorm_embedding = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm_embedding")
812
+
813
+ self.dropout = tf.keras.layers.Dropout(config.dropout)
814
+
815
+ def get_embed_tokens(self):
816
+ return self.embed_tokens
817
+
818
+ def set_embed_tokens(self, embed_tokens):
819
+ self.embed_tokens = embed_tokens
820
+
821
+ @unpack_inputs
822
+ def call(
823
+ self,
824
+ input_ids=None,
825
+ inputs_embeds=None,
826
+ attention_mask=None,
827
+ position_ids=None,
828
+ encoder_hidden_states=None,
829
+ encoder_attention_mask=None,
830
+ head_mask=None,
831
+ cross_attn_head_mask=None,
832
+ past_key_values=None,
833
+ use_cache=None,
834
+ output_attentions=None,
835
+ output_hidden_states=None,
836
+ return_dict=None,
837
+ training=False,
838
+ ):
839
+ r"""
840
+ Args:
841
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
842
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
843
+ provide it.
844
+
845
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
846
+ [`PreTrainedTokenizer.__call__`] for details.
847
+
848
+ [What are input IDs?](../glossary#input-ids)
849
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
850
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
851
+
852
+ - 1 for tokens that are **not masked**,
853
+ - 0 for tokens that are **masked**.
854
+
855
+ [What are attention masks?](../glossary#attention-mask)
856
+ position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
857
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
858
+ range `[0, config.max_position_embeddings - 1]`.
859
+ encoder_hidden_states (`tf.Tensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
860
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
861
+ of the decoder.
862
+ encoder_attention_mask (`tf.Tensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
863
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
864
+ selected in `[0, 1]`:
865
+
866
+ - 1 for tokens that are **not masked**,
867
+ - 0 for tokens that are **masked**.
868
+
869
+ [What are attention masks?](../glossary#attention-mask)
870
+ head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
871
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
872
+
873
+ - 1 indicates the head is **not masked**,
874
+ - 0 indicates the head is **masked**.
875
+
876
+ cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
877
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
878
+
879
+ - 1 indicates the head is **not masked**,
880
+ - 0 indicates the head is **masked**.
881
+
882
+ past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
883
+ Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up
884
+ decoding.
885
+
886
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
887
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
888
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`tf.Tensor` of shape
889
+ `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids`
890
+ you can choose to directly pass an embedded representation. This is useful if you want more control
891
+ over how to convert `input_ids` indices into associated vectors than the model's internal embedding
892
+ lookup matrix.
893
+ output_attentions (`bool`, *optional*):
894
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
895
+ returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value
896
+ in the config will be used instead.
897
+ output_hidden_states (`bool`, *optional*):
898
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
899
+ for more detail. This argument can be used only in eager mode, in graph mode the value in the config
900
+ will be used instead.
901
+ return_dict (`bool`, *optional*):
902
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used
903
+ in eager mode, in graph mode the value will always be set to True.
904
+ training (`bool`, *optional*, defaults to `False`):
905
+ Whether or not to use the model in training mode (some modules like dropout modules have different
906
+ behaviors between training and evaluation).
907
+ """
908
+ if input_ids is not None and inputs_embeds is not None:
909
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
910
+ elif input_ids is not None:
911
+ input_shape = shape_list(input_ids)
912
+ elif inputs_embeds is not None:
913
+ input_shape = shape_list(inputs_embeds)[:-1]
914
+ else:
915
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
916
+
917
+ past_key_values_length = shape_list(past_key_values[0][0])[2] if past_key_values is not None else 0
918
+
919
+ if inputs_embeds is None:
920
+ # if `self.embed_tokens.load_weight_prefix` is set, runs the embedding operation with the correct name
921
+ # scope, so that its weights are registered with the desired name for loading/storing. When `tf.name_scope`
922
+ # is used with a name ending in `/`, that name replaces the current name scope.
923
+ # (embeddings with tf.name_scope: self.embed_tokens.load_weight_prefix/self.embed_tokens.name/embeddings:0)
924
+ context = []
925
+ if hasattr(self.embed_tokens, "load_weight_prefix"):
926
+ context.append(tf.name_scope(self.embed_tokens.load_weight_prefix + "/"))
927
+ with ContextManagers(context):
928
+ check_embeddings_within_bounds(input_ids, self.embed_tokens.input_dim)
929
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
930
+
931
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
932
+ if input_shape[-1] > 1:
933
+ combined_attention_mask = _make_causal_mask(input_shape, past_key_values_length=past_key_values_length)
934
+ else:
935
+ combined_attention_mask = _expand_mask(
936
+ tf.ones((input_shape[0], input_shape[1] + past_key_values_length)), tgt_len=input_shape[-1]
937
+ )
938
+
939
+ if attention_mask is not None:
940
+ combined_attention_mask = combined_attention_mask + _expand_mask(attention_mask, tgt_len=input_shape[-1])
941
+
942
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
943
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
944
+ encoder_attention_mask = _expand_mask(encoder_attention_mask, tgt_len=input_shape[-1])
945
+
946
+ # embed positions
947
+ if position_ids is None:
948
+ positions = self.embed_positions(input_shape, past_key_values_length)
949
+ else:
950
+ positions = self.embed_positions(input_shape, position_ids=position_ids)
951
+
952
+ hidden_states = self.layernorm_embedding(inputs_embeds) + positions
953
+ hidden_states = self.dropout(hidden_states, training=training)
954
+
955
+ # decoder layers
956
+ all_hidden_states = () if output_hidden_states else None
957
+ all_self_attns = () if output_attentions else None
958
+ all_cross_attns = () if (output_attentions and encoder_hidden_states is not None) else None
959
+ present_key_values = () if use_cache else None
960
+
961
+ # check if head_mask and cross_attn_head_mask have a correct number of layers specified if desired
962
+ for attn_mask_name, attn_mask in [("head_mask", head_mask), ("cross_attn_head_mask", cross_attn_head_mask)]:
963
+ if attn_mask is not None:
964
+ tf.debugging.assert_equal(
965
+ shape_list(attn_mask)[0],
966
+ len(self.layers),
967
+ message=(
968
+ f"The {attn_mask_name} should be specified for {len(self.layers)} layers, but it is for"
969
+ f" {shape_list(attn_mask)[0]}."
970
+ ),
971
+ )
972
+
973
+ for idx, decoder_layer in enumerate(self.layers):
974
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
975
+ if output_hidden_states:
976
+ all_hidden_states += (hidden_states,)
977
+ dropout_probability = random.uniform(0, 1)
978
+
979
+ if training and (dropout_probability < self.layerdrop):
980
+ continue
981
+
982
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
983
+
984
+ hidden_states, layer_self_attn, layer_cross_attn, present_key_value = decoder_layer(
985
+ hidden_states,
986
+ attention_mask=combined_attention_mask,
987
+ encoder_hidden_states=encoder_hidden_states,
988
+ encoder_attention_mask=encoder_attention_mask,
989
+ layer_head_mask=head_mask[idx] if head_mask is not None else None,
990
+ cross_attn_layer_head_mask=cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
991
+ past_key_value=past_key_value,
992
+ )
993
+
994
+ if use_cache:
995
+ present_key_values += (present_key_value,)
996
+
997
+ if output_attentions:
998
+ all_self_attns += (layer_self_attn,)
999
+
1000
+ if encoder_hidden_states is not None:
1001
+ all_cross_attns += (layer_cross_attn,)
1002
+
1003
+ if output_hidden_states:
1004
+ all_hidden_states += (hidden_states,)
1005
+
1006
+ if not return_dict:
1007
+ return hidden_states, present_key_values, all_hidden_states, all_self_attns, all_cross_attns
1008
+ else:
1009
+ return TFBaseModelOutputWithPastAndCrossAttentions(
1010
+ last_hidden_state=hidden_states,
1011
+ past_key_values=present_key_values,
1012
+ hidden_states=all_hidden_states,
1013
+ attentions=all_self_attns,
1014
+ cross_attentions=all_cross_attns,
1015
+ )
1016
+
1017
+
1018
+ @keras_serializable
1019
+ class TFBlenderbotSmallMainLayer(tf.keras.layers.Layer):
1020
+ config_class = BlenderbotSmallConfig
1021
+
1022
+ def __init__(self, config: BlenderbotSmallConfig, **kwargs):
1023
+ super().__init__(**kwargs)
1024
+
1025
+ self.config = config
1026
+ self.shared = tf.keras.layers.Embedding(
1027
+ input_dim=config.vocab_size,
1028
+ output_dim=config.d_model,
1029
+ embeddings_initializer=tf.keras.initializers.TruncatedNormal(stddev=self.config.init_std),
1030
+ name="model.shared",
1031
+ )
1032
+ # Additional attribute to specify the expected name scope of the layer (for loading/storing weights)
1033
+ self.shared.load_weight_prefix = "model.shared"
1034
+
1035
+ self.encoder = TFBlenderbotSmallEncoder(config, self.shared, name="encoder")
1036
+ self.decoder = TFBlenderbotSmallDecoder(config, self.shared, name="decoder")
1037
+
1038
+ def get_input_embeddings(self):
1039
+ return self.shared
1040
+
1041
+ def set_input_embeddings(self, new_embeddings):
1042
+ self.shared = new_embeddings
1043
+ self.encoder.embed_tokens = self.shared
1044
+ self.decoder.embed_tokens = self.shared
1045
+
1046
+ @unpack_inputs
1047
+ def call(
1048
+ self,
1049
+ input_ids=None,
1050
+ attention_mask=None,
1051
+ decoder_input_ids=None,
1052
+ decoder_attention_mask=None,
1053
+ decoder_position_ids=None,
1054
+ head_mask=None,
1055
+ decoder_head_mask=None,
1056
+ cross_attn_head_mask=None,
1057
+ encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,
1058
+ past_key_values=None,
1059
+ inputs_embeds=None,
1060
+ decoder_inputs_embeds=None,
1061
+ use_cache=None,
1062
+ output_attentions=None,
1063
+ output_hidden_states=None,
1064
+ return_dict=None,
1065
+ training=False,
1066
+ **kwargs,
1067
+ ):
1068
+ output_hidden_states = (
1069
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1070
+ )
1071
+
1072
+ if encoder_outputs is None:
1073
+ encoder_outputs = self.encoder(
1074
+ input_ids=input_ids,
1075
+ attention_mask=attention_mask,
1076
+ head_mask=head_mask,
1077
+ inputs_embeds=inputs_embeds,
1078
+ output_attentions=output_attentions,
1079
+ output_hidden_states=output_hidden_states,
1080
+ return_dict=return_dict,
1081
+ training=training,
1082
+ )
1083
+ # If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True
1084
+ elif return_dict and not isinstance(encoder_outputs, TFBaseModelOutput):
1085
+ encoder_outputs = TFBaseModelOutput(
1086
+ last_hidden_state=encoder_outputs[0],
1087
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1088
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1089
+ )
1090
+ # If the user passed a TFBaseModelOutput for encoder_outputs, we wrap it in a tuple when return_dict=False
1091
+ elif not return_dict and not isinstance(encoder_outputs, tuple):
1092
+ encoder_outputs = encoder_outputs.to_tuple()
1093
+
1094
+ decoder_outputs = self.decoder(
1095
+ decoder_input_ids,
1096
+ attention_mask=decoder_attention_mask,
1097
+ position_ids=decoder_position_ids,
1098
+ encoder_hidden_states=encoder_outputs[0],
1099
+ encoder_attention_mask=attention_mask,
1100
+ head_mask=decoder_head_mask,
1101
+ cross_attn_head_mask=cross_attn_head_mask,
1102
+ past_key_values=past_key_values,
1103
+ inputs_embeds=decoder_inputs_embeds,
1104
+ use_cache=use_cache,
1105
+ output_attentions=output_attentions,
1106
+ output_hidden_states=output_hidden_states,
1107
+ return_dict=return_dict,
1108
+ training=training,
1109
+ )
1110
+
1111
+ if not return_dict:
1112
+ return decoder_outputs + encoder_outputs
1113
+
1114
+ return TFSeq2SeqModelOutput(
1115
+ last_hidden_state=decoder_outputs.last_hidden_state,
1116
+ past_key_values=decoder_outputs.past_key_values,
1117
+ decoder_hidden_states=decoder_outputs.hidden_states,
1118
+ decoder_attentions=decoder_outputs.attentions,
1119
+ cross_attentions=decoder_outputs.cross_attentions,
1120
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1121
+ encoder_hidden_states=encoder_outputs.hidden_states,
1122
+ encoder_attentions=encoder_outputs.attentions,
1123
+ )
1124
+
1125
+
1126
+ @add_start_docstrings(
1127
+ "The bare BLENDERBOT_SMALL Model outputting raw hidden-states without any specific head on top.",
1128
+ BLENDERBOT_SMALL_START_DOCSTRING,
1129
+ )
1130
+ class TFBlenderbotSmallModel(TFBlenderbotSmallPreTrainedModel):
1131
+ def __init__(self, config: BlenderbotSmallConfig, *inputs, **kwargs):
1132
+ super().__init__(config, *inputs, **kwargs)
1133
+
1134
+ self.model = TFBlenderbotSmallMainLayer(config, name="model")
1135
+
1136
+ def get_encoder(self):
1137
+ return self.model.encoder
1138
+
1139
+ def get_decoder(self):
1140
+ return self.model.decoder
1141
+
1142
+ @unpack_inputs
1143
+ @add_start_docstrings_to_model_forward(BLENDERBOT_SMALL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1144
+ @add_code_sample_docstrings(
1145
+ checkpoint=_CHECKPOINT_FOR_DOC,
1146
+ output_type=TFSeq2SeqModelOutput,
1147
+ config_class=_CONFIG_FOR_DOC,
1148
+ )
1149
+ def call(
1150
+ self,
1151
+ input_ids: tf.Tensor | None = None,
1152
+ attention_mask: tf.Tensor | None = None,
1153
+ decoder_input_ids: tf.Tensor | None = None,
1154
+ decoder_attention_mask: tf.Tensor | None = None,
1155
+ decoder_position_ids: tf.Tensor | None = None,
1156
+ head_mask: tf.Tensor | None = None,
1157
+ decoder_head_mask: tf.Tensor | None = None,
1158
+ cross_attn_head_mask: tf.Tensor | None = None,
1159
+ encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,
1160
+ past_key_values: List[tf.Tensor] | None = None,
1161
+ inputs_embeds: tf.Tensor | None = None,
1162
+ decoder_inputs_embeds: tf.Tensor | None = None,
1163
+ use_cache: Optional[bool] = None,
1164
+ output_attentions: Optional[bool] = None,
1165
+ output_hidden_states: Optional[bool] = None,
1166
+ return_dict: Optional[bool] = None,
1167
+ training: Optional[bool] = False,
1168
+ **kwargs,
1169
+ ) -> Union[Tuple[tf.Tensor], TFSeq2SeqModelOutput]:
1170
+ outputs = self.model(
1171
+ input_ids=input_ids,
1172
+ attention_mask=attention_mask,
1173
+ decoder_input_ids=decoder_input_ids,
1174
+ decoder_attention_mask=decoder_attention_mask,
1175
+ decoder_position_ids=decoder_position_ids,
1176
+ head_mask=head_mask,
1177
+ decoder_head_mask=decoder_head_mask,
1178
+ cross_attn_head_mask=cross_attn_head_mask,
1179
+ encoder_outputs=encoder_outputs,
1180
+ past_key_values=past_key_values,
1181
+ inputs_embeds=inputs_embeds,
1182
+ decoder_inputs_embeds=decoder_inputs_embeds,
1183
+ use_cache=use_cache,
1184
+ output_attentions=output_attentions,
1185
+ output_hidden_states=output_hidden_states,
1186
+ return_dict=return_dict,
1187
+ training=training,
1188
+ )
1189
+
1190
+ return outputs
1191
+
1192
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartModel.serving_output
1193
+ def serving_output(self, output):
1194
+ pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
1195
+ dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
1196
+ dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
1197
+ cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
1198
+ enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
1199
+ enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
1200
+
1201
+ return TFSeq2SeqModelOutput(
1202
+ last_hidden_state=output.last_hidden_state,
1203
+ past_key_values=pkv,
1204
+ decoder_hidden_states=dec_hs,
1205
+ decoder_attentions=dec_attns,
1206
+ cross_attentions=cross_attns,
1207
+ encoder_last_hidden_state=output.encoder_last_hidden_state,
1208
+ encoder_hidden_states=enc_hs,
1209
+ encoder_attentions=enc_attns,
1210
+ )
1211
+
1212
+
1213
+ # Copied from transformers.models.bart.modeling_tf_bart.BiasLayer
1214
+ class BiasLayer(tf.keras.layers.Layer):
1215
+ """
1216
+ Bias as a layer. It is used for serialization purposes: `tf.keras.Model.save_weights` stores on a per-layer basis,
1217
+ so all weights have to be registered in a layer.
1218
+ """
1219
+
1220
+ def __init__(self, shape, initializer, trainable, name, **kwargs):
1221
+ super().__init__(name=name, **kwargs)
1222
+ # Note: the name of this variable will NOT be scoped when serialized, i.e. it will not be in the format of
1223
+ # "outer_layer/inner_layer/.../name:0". Instead, it will be "name:0". For further details, see:
1224
+ # https://github.com/huggingface/transformers/pull/18833#issuecomment-1233090214
1225
+ self.bias = self.add_weight(name=name, shape=shape, initializer=initializer, trainable=trainable)
1226
+
1227
+ def call(self, x):
1228
+ return x + self.bias
1229
+
1230
+
1231
+ @add_start_docstrings(
1232
+ "The BLENDERBOT_SMALL Model with a language modeling head. Can be used for summarization.",
1233
+ BLENDERBOT_SMALL_START_DOCSTRING,
1234
+ )
1235
+ class TFBlenderbotSmallForConditionalGeneration(TFBlenderbotSmallPreTrainedModel, TFCausalLanguageModelingLoss):
1236
+ _keys_to_ignore_on_load_unexpected = [
1237
+ r"model.encoder.embed_tokens.weight",
1238
+ r"model.decoder.embed_tokens.weight",
1239
+ ]
1240
+
1241
+ def __init__(self, config, *inputs, **kwargs):
1242
+ super().__init__(config, *inputs, **kwargs)
1243
+ self.model = TFBlenderbotSmallMainLayer(config, name="model")
1244
+ self.use_cache = config.use_cache
1245
+ # final_bias_logits is registered as a buffer in pytorch, so not trainable for the sake of consistency.
1246
+ self.bias_layer = BiasLayer(
1247
+ name="final_logits_bias", shape=[1, config.vocab_size], initializer="zeros", trainable=False
1248
+ )
1249
+
1250
+ def get_decoder(self):
1251
+ return self.model.decoder
1252
+
1253
+ def get_encoder(self):
1254
+ return self.model.encoder
1255
+
1256
+ def get_output_embeddings(self):
1257
+ return self.get_input_embeddings()
1258
+
1259
+ def set_output_embeddings(self, value):
1260
+ self.set_input_embeddings(value)
1261
+
1262
+ def get_bias(self):
1263
+ return {"final_logits_bias": self.bias_layer.bias}
1264
+
1265
+ def set_bias(self, value):
1266
+ # Replaces the existing layers containing bias for correct (de)serialization.
1267
+ vocab_size = value["final_logits_bias"].shape[-1]
1268
+ self.bias_layer = BiasLayer(
1269
+ name="final_logits_bias", shape=[1, vocab_size], initializer="zeros", trainable=False
1270
+ )
1271
+ self.bias_layer.bias.assign(value["final_logits_bias"])
1272
+
1273
+ @unpack_inputs
1274
+ @add_start_docstrings_to_model_forward(BLENDERBOT_SMALL_INPUTS_DOCSTRING)
1275
+ @replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1276
+ @add_end_docstrings(BLENDERBOT_SMALL_GENERATION_EXAMPLE)
1277
+ def call(
1278
+ self,
1279
+ input_ids: tf.Tensor | None = None,
1280
+ attention_mask: tf.Tensor | None = None,
1281
+ decoder_input_ids: tf.Tensor | None = None,
1282
+ decoder_attention_mask: tf.Tensor | None = None,
1283
+ decoder_position_ids: tf.Tensor | None = None,
1284
+ head_mask: tf.Tensor | None = None,
1285
+ decoder_head_mask: tf.Tensor | None = None,
1286
+ cross_attn_head_mask: tf.Tensor | None = None,
1287
+ encoder_outputs: Optional[TFBaseModelOutput] = None,
1288
+ past_key_values: List[tf.Tensor] | None = None,
1289
+ inputs_embeds: tf.Tensor | None = None,
1290
+ decoder_inputs_embeds: tf.Tensor | None = None,
1291
+ use_cache: Optional[bool] = None,
1292
+ output_attentions: Optional[bool] = None,
1293
+ output_hidden_states: Optional[bool] = None,
1294
+ return_dict: Optional[bool] = None,
1295
+ labels: tf.Tensor | None = None,
1296
+ training: Optional[bool] = False,
1297
+ ) -> Union[Tuple[tf.Tensor], TFSeq2SeqLMOutput]:
1298
+ r"""
1299
+ labels (`tf.tensor` of shape `(batch_size, sequence_length)`, *optional*):
1300
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1301
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1302
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1303
+
1304
+ Returns:
1305
+
1306
+ """
1307
+
1308
+ if labels is not None:
1309
+ labels = tf.where(
1310
+ labels == self.config.pad_token_id,
1311
+ tf.cast(tf.fill(shape_list(labels), -100), labels.dtype),
1312
+ labels,
1313
+ )
1314
+ use_cache = False
1315
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1316
+ decoder_input_ids = shift_tokens_right(
1317
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1318
+ )
1319
+
1320
+ outputs = self.model(
1321
+ input_ids,
1322
+ attention_mask=attention_mask,
1323
+ decoder_input_ids=decoder_input_ids,
1324
+ decoder_attention_mask=decoder_attention_mask,
1325
+ decoder_position_ids=decoder_position_ids,
1326
+ head_mask=head_mask,
1327
+ decoder_head_mask=decoder_head_mask,
1328
+ cross_attn_head_mask=cross_attn_head_mask,
1329
+ encoder_outputs=encoder_outputs,
1330
+ past_key_values=past_key_values,
1331
+ inputs_embeds=inputs_embeds,
1332
+ decoder_inputs_embeds=decoder_inputs_embeds,
1333
+ use_cache=use_cache,
1334
+ output_attentions=output_attentions,
1335
+ output_hidden_states=output_hidden_states,
1336
+ return_dict=return_dict,
1337
+ training=training,
1338
+ )
1339
+ lm_logits = tf.matmul(outputs[0], self.model.shared.weights, transpose_b=True)
1340
+ lm_logits = self.bias_layer(lm_logits)
1341
+ masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits)
1342
+
1343
+ if not return_dict:
1344
+ output = (lm_logits,) + outputs[1:]
1345
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1346
+ return TFSeq2SeqLMOutput(
1347
+ loss=masked_lm_loss,
1348
+ logits=lm_logits,
1349
+ past_key_values=outputs.past_key_values, # index 1 of d outputs
1350
+ decoder_hidden_states=outputs.decoder_hidden_states, # index 2 of d outputs
1351
+ decoder_attentions=outputs.decoder_attentions, # index 3 of d outputs
1352
+ cross_attentions=outputs.cross_attentions, # index 4 of d outputs
1353
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state, # index 0 of encoder outputs
1354
+ encoder_hidden_states=outputs.encoder_hidden_states, # 1 of e out
1355
+ encoder_attentions=outputs.encoder_attentions, # 2 of e out
1356
+ )
1357
+
1358
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartForConditionalGeneration.serving_output
1359
+ def serving_output(self, output):
1360
+ pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
1361
+ dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
1362
+ dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
1363
+ cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
1364
+ enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
1365
+ enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
1366
+
1367
+ return TFSeq2SeqLMOutput(
1368
+ logits=output.logits,
1369
+ past_key_values=pkv,
1370
+ decoder_hidden_states=dec_hs,
1371
+ decoder_attentions=dec_attns,
1372
+ cross_attentions=cross_attns,
1373
+ encoder_last_hidden_state=output.encoder_last_hidden_state,
1374
+ encoder_hidden_states=enc_hs,
1375
+ encoder_attentions=enc_attns,
1376
+ )
1377
+
1378
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartForConditionalGeneration.prepare_inputs_for_generation
1379
+ def prepare_inputs_for_generation(
1380
+ self,
1381
+ decoder_input_ids,
1382
+ past_key_values=None,
1383
+ attention_mask=None,
1384
+ decoder_attention_mask=None,
1385
+ head_mask=None,
1386
+ decoder_head_mask=None,
1387
+ cross_attn_head_mask=None,
1388
+ use_cache=None,
1389
+ encoder_outputs=None,
1390
+ **kwargs,
1391
+ ):
1392
+ # cut decoder_input_ids if past_key_values is used
1393
+ if past_key_values is not None:
1394
+ decoder_input_ids = decoder_input_ids[:, -1:]
1395
+
1396
+ if decoder_attention_mask is not None: # xla
1397
+ decoder_position_ids = tf.math.cumsum(decoder_attention_mask, axis=-1, exclusive=True)[:, -1:]
1398
+ elif past_key_values is not None: # no xla + past_key_values
1399
+ decoder_position_ids = past_key_values[0][0].shape[2]
1400
+ else: # no xla + no past_key_values
1401
+ decoder_position_ids = tf.range(decoder_input_ids.shape[1])
1402
+
1403
+ return {
1404
+ "input_ids": None, # encoder_outputs is defined. input_ids not needed
1405
+ "encoder_outputs": encoder_outputs,
1406
+ "past_key_values": past_key_values,
1407
+ "decoder_input_ids": decoder_input_ids,
1408
+ "attention_mask": attention_mask,
1409
+ "decoder_attention_mask": decoder_attention_mask,
1410
+ "decoder_position_ids": decoder_position_ids,
1411
+ "head_mask": head_mask,
1412
+ "decoder_head_mask": decoder_head_mask,
1413
+ "cross_attn_head_mask": cross_attn_head_mask,
1414
+ "use_cache": use_cache, # change this to avoid caching (presumably for debugging)
1415
+ }
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/tokenization_blenderbot_small.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Facebook Inc. and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Tokenization class for BlenderbotSmall."""
16
+
17
+ import json
18
+ import os
19
+ from typing import Dict, List, Optional, Tuple
20
+
21
+ import regex as re
22
+
23
+ from ...tokenization_utils import PreTrainedTokenizer
24
+ from ...utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ VOCAB_FILES_NAMES = {
31
+ "vocab_file": "vocab.json",
32
+ "merges_file": "merges.txt",
33
+ "tokenizer_config_file": "tokenizer_config.json",
34
+ }
35
+
36
+ PRETRAINED_VOCAB_FILES_MAP = {
37
+ "vocab_file": {
38
+ "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json"
39
+ },
40
+ "merges_file": {
41
+ "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt"
42
+ },
43
+ "tokenizer_config_file": {
44
+ "facebook/blenderbot_small-90M": (
45
+ "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json"
46
+ )
47
+ },
48
+ }
49
+
50
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {"facebook/blenderbot_small-90M": 512}
51
+
52
+
53
+ def get_pairs(word):
54
+ """
55
+ Return set of symbol pairs in a word.
56
+
57
+ Word is represented as tuple of symbols (symbols being variable-length strings).
58
+ """
59
+ pairs = set()
60
+ prev_char = word[0]
61
+ for char in word[1:]:
62
+ pairs.add((prev_char, char))
63
+ prev_char = char
64
+
65
+ pairs = set(pairs)
66
+ return pairs
67
+
68
+
69
+ class BlenderbotSmallTokenizer(PreTrainedTokenizer):
70
+ """
71
+ Constructs a Blenderbot-90M tokenizer based on BPE (Byte-Pair-Encoding)
72
+
73
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
74
+ the superclass for more information regarding methods.
75
+
76
+ Args:
77
+ vocab_file (`str`):
78
+ File containing the vocabulary.
79
+ merges_file (`str`):
80
+ Path to the merges file.
81
+ bos_token (`str`, *optional*, defaults to `"__start__"`):
82
+ The beginning of sentence token.
83
+ eos_token (`str`, *optional*, defaults to `"__end__"`):
84
+ The end of sentence token.
85
+ unk_token (`str`, *optional*, defaults to `"__unk__"`):
86
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
87
+ token instead.
88
+ pad_token (`str`, *optional*, defaults to `"__pad__"`):
89
+ The token used for padding, for example when batching sequences of different lengths.
90
+ **kwargs
91
+ Additional keyword arguments passed along to [`PreTrainedTokenizer`]
92
+ """
93
+
94
+ vocab_files_names = VOCAB_FILES_NAMES
95
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
96
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
97
+ model_input_names = ["input_ids", "attention_mask"]
98
+
99
+ def __init__(
100
+ self,
101
+ vocab_file,
102
+ merges_file,
103
+ bos_token="__start__",
104
+ eos_token="__end__",
105
+ unk_token="__unk__",
106
+ pad_token="__null__",
107
+ **kwargs,
108
+ ):
109
+ super().__init__(unk_token=unk_token, bos_token=bos_token, eos_token=eos_token, pad_token=pad_token, **kwargs)
110
+
111
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
112
+ self.encoder = json.load(vocab_handle)
113
+ self.decoder = {v: k for k, v in self.encoder.items()}
114
+ with open(merges_file, encoding="utf-8") as merges_handle:
115
+ merges = merges_handle.read().split("\n")[1:-1]
116
+ merges = [tuple(merge.split()) for merge in merges]
117
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
118
+ self.cache = {}
119
+
120
+ @property
121
+ def vocab_size(self) -> int:
122
+ return len(self.encoder)
123
+
124
+ def get_vocab(self) -> Dict:
125
+ return dict(self.encoder, **self.added_tokens_encoder)
126
+
127
+ def bpe(self, token: str) -> str:
128
+ if token in self.cache:
129
+ return self.cache[token]
130
+ token = re.sub("([.,!?()])", r" \1", token)
131
+ token = re.sub("(')", r" \1 ", token)
132
+ token = re.sub(r"\s{2,}", " ", token)
133
+ if "\n" in token:
134
+ token = token.replace("\n", " __newln__")
135
+
136
+ tokens = token.split(" ")
137
+ words = []
138
+ for token in tokens:
139
+ if not len(token):
140
+ continue
141
+
142
+ token = token.lower()
143
+ word = tuple(token)
144
+ word = tuple(list(word[:-1]) + [word[-1] + "</w>"])
145
+ pairs = get_pairs(word)
146
+
147
+ if not pairs:
148
+ words.append(token)
149
+ continue
150
+
151
+ while True:
152
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
153
+ if bigram not in self.bpe_ranks:
154
+ break
155
+ first, second = bigram
156
+ new_word = []
157
+ i = 0
158
+
159
+ while i < len(word):
160
+ try:
161
+ j = word.index(first, i)
162
+ new_word.extend(word[i:j])
163
+ i = j
164
+ except ValueError:
165
+ new_word.extend(word[i:])
166
+ break
167
+
168
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
169
+ new_word.append(first + second)
170
+ i += 2
171
+ else:
172
+ new_word.append(word[i])
173
+ i += 1
174
+ new_word = tuple(new_word)
175
+ word = new_word
176
+ if len(word) == 1:
177
+ break
178
+ else:
179
+ pairs = get_pairs(word)
180
+ word = "@@ ".join(word)
181
+ word = word[:-4]
182
+
183
+ self.cache[token] = word
184
+ words.append(word)
185
+ return " ".join(words)
186
+
187
+ def _tokenize(self, text: str) -> List[str]:
188
+ """Split a string into tokens using BPE."""
189
+ split_tokens = []
190
+
191
+ words = re.findall(r"\S+\n?", text)
192
+
193
+ for token in words:
194
+ split_tokens.extend(list(self.bpe(token).split(" ")))
195
+ return split_tokens
196
+
197
+ def _convert_token_to_id(self, token: str) -> int:
198
+ """Converts a token to an id using the vocab."""
199
+ token = token.lower()
200
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
201
+
202
+ def _convert_id_to_token(self, index: int) -> str:
203
+ """Converts an index (integer) in a token (str) using the vocab."""
204
+ return self.decoder.get(index, self.unk_token)
205
+
206
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
207
+ """Converts a sequence of tokens in a single string."""
208
+ out_string = " ".join(tokens).replace("@@ ", "").strip()
209
+ return out_string
210
+
211
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
212
+ if not os.path.isdir(save_directory):
213
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
214
+ return
215
+ vocab_file = os.path.join(
216
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
217
+ )
218
+ merge_file = os.path.join(
219
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
220
+ )
221
+
222
+ with open(vocab_file, "w", encoding="utf-8") as f:
223
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
224
+
225
+ index = 0
226
+ with open(merge_file, "w", encoding="utf-8") as writer:
227
+ writer.write("#version: 0.2\n")
228
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
229
+ if index != token_index:
230
+ logger.warning(
231
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
232
+ " Please check that the tokenizer is not corrupted!"
233
+ )
234
+ index = token_index
235
+ writer.write(" ".join(bpe_tokens) + "\n")
236
+ index += 1
237
+
238
+ return vocab_file, merge_file
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blenderbot_small/tokenization_blenderbot_small_fast.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021, The Facebook, Inc. and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Fast tokenization class for BlenderbotSmall."""
16
+ from typing import List, Optional
17
+
18
+ from tokenizers import ByteLevelBPETokenizer
19
+
20
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
21
+ from ...utils import logging
22
+ from .tokenization_blenderbot_small import BlenderbotSmallTokenizer
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+ VOCAB_FILES_NAMES = {
28
+ "vocab_file": "vocab.json",
29
+ "merges_file": "merges.txt",
30
+ "tokenizer_config_file": "tokenizer_config.json",
31
+ }
32
+
33
+ PRETRAINED_VOCAB_FILES_MAP = {
34
+ "vocab_file": {
35
+ "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json"
36
+ },
37
+ "merges_file": {
38
+ "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt"
39
+ },
40
+ "tokenizer_config_file": {
41
+ "facebook/blenderbot_small-90M": (
42
+ "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json"
43
+ )
44
+ },
45
+ }
46
+
47
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
48
+ "facebook/blenderbot_small-90M": 512,
49
+ }
50
+
51
+
52
+ class BlenderbotSmallTokenizerFast(PreTrainedTokenizerFast):
53
+ """
54
+ Construct a "fast" BlenderbotSmall tokenizer (backed by HuggingFace's *tokenizers* library).
55
+
56
+ Args:
57
+ vocab_file (`str`):
58
+ Path to the vocabulary file.
59
+ """
60
+
61
+ vocab_files_names = VOCAB_FILES_NAMES
62
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
63
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
64
+ slow_tokenizer_class = BlenderbotSmallTokenizer
65
+
66
+ def __init__(
67
+ self,
68
+ vocab_file=None,
69
+ merges_file=None,
70
+ unk_token="<|endoftext|>",
71
+ bos_token="<|endoftext|>",
72
+ eos_token="<|endoftext|>",
73
+ add_prefix_space=False,
74
+ trim_offsets=True,
75
+ **kwargs,
76
+ ):
77
+ super().__init__(
78
+ ByteLevelBPETokenizer(
79
+ vocab=vocab_file,
80
+ merges=merges_file,
81
+ add_prefix_space=add_prefix_space,
82
+ trim_offsets=trim_offsets,
83
+ ),
84
+ bos_token=bos_token,
85
+ eos_token=eos_token,
86
+ unk_token=unk_token,
87
+ **kwargs,
88
+ )
89
+ self.add_prefix_space = add_prefix_space
90
+
91
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
92
+ output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
93
+ if token_ids_1 is None:
94
+ return output
95
+
96
+ return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
97
+
98
+ def create_token_type_ids_from_sequences(
99
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
100
+ ) -> List[int]:
101
+ """
102
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. BlenderbotSmall
103
+ does not make use of token type ids, therefore a list of zeros is returned.
104
+
105
+ Args:
106
+ token_ids_0 (`List[int]`):
107
+ List of IDs.
108
+ token_ids_1 (`List[int]`, *optional*):
109
+ Optional second list of IDs for sequence pairs.
110
+
111
+ Returns:
112
+ `List[int]`: List of zeros.
113
+ """
114
+ sep = [self.sep_token_id]
115
+ cls = [self.cls_token_id]
116
+
117
+ if token_ids_1 is None:
118
+ return len(cls + token_ids_0 + sep) * [0]
119
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blip_2/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.12 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blip_2/__pycache__/convert_blip_2_original_to_pytorch.cpython-310.pyc ADDED
Binary file (8.14 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blip_2/__pycache__/modeling_blip_2.cpython-310.pyc ADDED
Binary file (55.8 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blip_2/__pycache__/processing_blip_2.cpython-310.pyc ADDED
Binary file (4.34 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blip_2/configuration_blip_2.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ BLIP-2 model configuration"""
16
+
17
+ import os
18
+ from typing import Union
19
+
20
+ from ...configuration_utils import PretrainedConfig
21
+ from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
22
+ from ...utils import logging
23
+ from ..auto import CONFIG_MAPPING
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP = {
29
+ "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json",
30
+ }
31
+
32
+
33
+ class Blip2VisionConfig(PretrainedConfig):
34
+ r"""
35
+ This is the configuration class to store the configuration of a [`Blip2VisionModel`]. It is used to instantiate a
36
+ BLIP-2 vision encoder according to the specified arguments, defining the model architecture. Instantiating a
37
+ configuration defaults will yield a similar configuration to that of the BLIP-2
38
+ [Salesforce/blip2-opt-2.7b](https://huggingface.co/Salesforce/blip2-opt-2.7b) architecture.
39
+
40
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
41
+ documentation from [`PretrainedConfig`] for more information.
42
+
43
+ Args:
44
+ hidden_size (`int`, *optional*, defaults to 1408):
45
+ Dimensionality of the encoder layers and the pooler layer.
46
+ intermediate_size (`int`, *optional*, defaults to 6144):
47
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
48
+ num_hidden_layers (`int`, *optional*, defaults to 39):
49
+ Number of hidden layers in the Transformer encoder.
50
+ num_attention_heads (`int`, *optional*, defaults to 16):
51
+ Number of attention heads for each attention layer in the Transformer encoder.
52
+ image_size (`int`, *optional*, defaults to 224):
53
+ The size (resolution) of each image.
54
+ patch_size (`int`, *optional*, defaults to 14):
55
+ The size (resolution) of each patch.
56
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
57
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
58
+ `"relu"`, `"selu"` and `"gelu_new"` ``"gelu"` are supported. layer_norm_eps (`float`, *optional*, defaults
59
+ to 1e-5): The epsilon used by the layer normalization layers.
60
+ attention_dropout (`float`, *optional*, defaults to 0.0):
61
+ The dropout ratio for the attention probabilities.
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ qkv_bias (`bool`, *optional*, defaults to `True`):
65
+ Whether to add a bias to the queries and values in the self-attention layers.
66
+
67
+ Example:
68
+
69
+ ```python
70
+ >>> from transformers import Blip2VisionConfig, Blip2VisionModel
71
+
72
+ >>> # Initializing a Blip2VisionConfig with Salesforce/blip2-opt-2.7b style configuration
73
+ >>> configuration = Blip2VisionConfig()
74
+
75
+ >>> # Initializing a Blip2VisionModel (with random weights) from the Salesforce/blip2-opt-2.7b style configuration
76
+ >>> model = Blip2VisionModel(configuration)
77
+
78
+ >>> # Accessing the model configuration
79
+ >>> configuration = model.config
80
+ ```"""
81
+
82
+ model_type = "blip_2_vision_model"
83
+
84
+ def __init__(
85
+ self,
86
+ hidden_size=1408,
87
+ intermediate_size=6144,
88
+ num_hidden_layers=39,
89
+ num_attention_heads=16,
90
+ image_size=224,
91
+ patch_size=14,
92
+ hidden_act="gelu",
93
+ layer_norm_eps=0.00001,
94
+ attention_dropout=0.0,
95
+ initializer_range=1e-10,
96
+ qkv_bias=True,
97
+ **kwargs,
98
+ ):
99
+ super().__init__(**kwargs)
100
+
101
+ self.hidden_size = hidden_size
102
+ self.intermediate_size = intermediate_size
103
+ self.num_hidden_layers = num_hidden_layers
104
+ self.num_attention_heads = num_attention_heads
105
+ self.patch_size = patch_size
106
+ self.image_size = image_size
107
+ self.initializer_range = initializer_range
108
+ self.attention_dropout = attention_dropout
109
+ self.layer_norm_eps = layer_norm_eps
110
+ self.hidden_act = hidden_act
111
+ self.qkv_bias = qkv_bias
112
+
113
+ @classmethod
114
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
115
+ cls._set_token_in_kwargs(kwargs)
116
+
117
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
118
+
119
+ # get the vision config dict if we are loading from Blip2Config
120
+ if config_dict.get("model_type") == "blip-2":
121
+ config_dict = config_dict["vision_config"]
122
+
123
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
124
+ logger.warning(
125
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
126
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
127
+ )
128
+
129
+ return cls.from_dict(config_dict, **kwargs)
130
+
131
+
132
+ class Blip2QFormerConfig(PretrainedConfig):
133
+ r"""
134
+ This is the configuration class to store the configuration of a [`Blip2QFormerModel`]. It is used to instantiate a
135
+ BLIP-2 Querying Transformer (Q-Former) model according to the specified arguments, defining the model architecture.
136
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the BLIP-2
137
+ [Salesforce/blip2-opt-2.7b](https://huggingface.co/Salesforce/blip2-opt-2.7b) architecture. Configuration objects
138
+ inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from
139
+ [`PretrainedConfig`] for more information.
140
+
141
+ Note that [`Blip2QFormerModel`] is very similar to [`BertLMHeadModel`] with interleaved cross-attention.
142
+
143
+ Args:
144
+ vocab_size (`int`, *optional*, defaults to 30522):
145
+ Vocabulary size of the Q-Former model. Defines the number of different tokens that can be represented by
146
+ the `inputs_ids` passed when calling the model.
147
+ hidden_size (`int`, *optional*, defaults to 768):
148
+ Dimensionality of the encoder layers and the pooler layer.
149
+ num_hidden_layers (`int`, *optional*, defaults to 12):
150
+ Number of hidden layers in the Transformer encoder.
151
+ num_attention_heads (`int`, *optional*, defaults to 12):
152
+ Number of attention heads for each attention layer in the Transformer encoder.
153
+ intermediate_size (`int`, *optional*, defaults to 3072):
154
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
155
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
156
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
157
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
158
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
159
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
160
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
161
+ The dropout ratio for the attention probabilities.
162
+ max_position_embeddings (`int`, *optional*, defaults to 512):
163
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
164
+ just in case (e.g., 512 or 1024 or 2048).
165
+ initializer_range (`float`, *optional*, defaults to 0.02):
166
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
167
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
168
+ The epsilon used by the layer normalization layers.
169
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
170
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
171
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
172
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
173
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
174
+ with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
175
+ cross_attention_frequency (`int`, *optional*, defaults to 2):
176
+ The frequency of adding cross-attention to the Transformer layers.
177
+ encoder_hidden_size (`int`, *optional*, defaults to 1408):
178
+ The hidden size of the hidden states for cross-attention.
179
+
180
+ Examples:
181
+
182
+ ```python
183
+ >>> from transformers import Blip2QFormerConfig, Blip2QFormerModel
184
+
185
+ >>> # Initializing a BLIP-2 Salesforce/blip2-opt-2.7b style configuration
186
+ >>> configuration = Blip2QFormerConfig()
187
+
188
+ >>> # Initializing a model (with random weights) from the Salesforce/blip2-opt-2.7b style configuration
189
+ >>> model = Blip2QFormerModel(configuration)
190
+ >>> # Accessing the model configuration
191
+ >>> configuration = model.config
192
+ ```"""
193
+ model_type = "blip_2_qformer"
194
+
195
+ def __init__(
196
+ self,
197
+ vocab_size=30522,
198
+ hidden_size=768,
199
+ num_hidden_layers=12,
200
+ num_attention_heads=12,
201
+ intermediate_size=3072,
202
+ hidden_act="gelu",
203
+ hidden_dropout_prob=0.1,
204
+ attention_probs_dropout_prob=0.1,
205
+ max_position_embeddings=512,
206
+ initializer_range=0.02,
207
+ layer_norm_eps=1e-12,
208
+ pad_token_id=0,
209
+ position_embedding_type="absolute",
210
+ cross_attention_frequency=2,
211
+ encoder_hidden_size=1408,
212
+ **kwargs,
213
+ ):
214
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
215
+
216
+ self.vocab_size = vocab_size
217
+ self.hidden_size = hidden_size
218
+ self.num_hidden_layers = num_hidden_layers
219
+ self.num_attention_heads = num_attention_heads
220
+ self.hidden_act = hidden_act
221
+ self.intermediate_size = intermediate_size
222
+ self.hidden_dropout_prob = hidden_dropout_prob
223
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
224
+ self.max_position_embeddings = max_position_embeddings
225
+ self.initializer_range = initializer_range
226
+ self.layer_norm_eps = layer_norm_eps
227
+ self.position_embedding_type = position_embedding_type
228
+ self.cross_attention_frequency = cross_attention_frequency
229
+ self.encoder_hidden_size = encoder_hidden_size
230
+
231
+ @classmethod
232
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
233
+ cls._set_token_in_kwargs(kwargs)
234
+
235
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
236
+
237
+ # get the qformer config dict if we are loading from Blip2Config
238
+ if config_dict.get("model_type") == "blip-2":
239
+ config_dict = config_dict["qformer_config"]
240
+
241
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
242
+ logger.warning(
243
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
244
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
245
+ )
246
+
247
+ return cls.from_dict(config_dict, **kwargs)
248
+
249
+
250
+ class Blip2Config(PretrainedConfig):
251
+ r"""
252
+ [`Blip2Config`] is the configuration class to store the configuration of a [`Blip2ForConditionalGeneration`]. It is
253
+ used to instantiate a BLIP-2 model according to the specified arguments, defining the vision model, Q-Former model
254
+ and language model configs. Instantiating a configuration with the defaults will yield a similar configuration to
255
+ that of the BLIP-2 [Salesforce/blip2-opt-2.7b](https://huggingface.co/Salesforce/blip2-opt-2.7b) architecture.
256
+
257
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
258
+ documentation from [`PretrainedConfig`] for more information.
259
+
260
+ Args:
261
+ vision_config (`dict`, *optional*):
262
+ Dictionary of configuration options used to initialize [`Blip2VisionConfig`].
263
+ qformer_config (`dict`, *optional*):
264
+ Dictionary of configuration options used to initialize [`Blip2QFormerConfig`].
265
+ text_config (`dict`, *optional*):
266
+ Dictionary of configuration options used to initialize any [`PretrainedConfig`].
267
+ num_query_tokens (`int`, *optional*, defaults to 32):
268
+ The number of query tokens passed through the Transformer.
269
+
270
+ kwargs (*optional*):
271
+ Dictionary of keyword arguments.
272
+
273
+ Example:
274
+
275
+ ```python
276
+ >>> from transformers import (
277
+ ... Blip2VisionConfig,
278
+ ... Blip2QFormerConfig,
279
+ ... OPTConfig,
280
+ ... Blip2Config,
281
+ ... Blip2ForConditionalGeneration,
282
+ ... )
283
+
284
+ >>> # Initializing a Blip2Config with Salesforce/blip2-opt-2.7b style configuration
285
+ >>> configuration = Blip2Config()
286
+
287
+ >>> # Initializing a Blip2ForConditionalGeneration (with random weights) from the Salesforce/blip2-opt-2.7b style configuration
288
+ >>> model = Blip2ForConditionalGeneration(configuration)
289
+
290
+ >>> # Accessing the model configuration
291
+ >>> configuration = model.config
292
+
293
+ >>> # We can also initialize a Blip2Config from a Blip2VisionConfig, Blip2QFormerConfig and any PretrainedConfig
294
+
295
+ >>> # Initializing BLIP-2 vision, BLIP-2 Q-Former and language model configurations
296
+ >>> vision_config = Blip2VisionConfig()
297
+ >>> qformer_config = Blip2QFormerConfig()
298
+ >>> text_config = OPTConfig()
299
+
300
+ >>> config = Blip2Config.from_text_vision_configs(vision_config, qformer_config, text_config)
301
+ ```"""
302
+
303
+ model_type = "blip-2"
304
+
305
+ def __init__(self, vision_config=None, qformer_config=None, text_config=None, num_query_tokens=32, **kwargs):
306
+ super().__init__(**kwargs)
307
+
308
+ if vision_config is None:
309
+ vision_config = {}
310
+ logger.info("vision_config is None. initializing the Blip2VisionConfig with default values.")
311
+
312
+ if qformer_config is None:
313
+ qformer_config = {}
314
+ logger.info("qformer_config is None. Initializing the Blip2QFormerConfig with default values.")
315
+
316
+ if text_config is None:
317
+ text_config = {}
318
+ logger.info("text_config is None. Initializing the text config with default values (`OPTConfig`).")
319
+
320
+ self.vision_config = Blip2VisionConfig(**vision_config)
321
+ self.qformer_config = Blip2QFormerConfig(**qformer_config)
322
+ text_model_type = text_config["model_type"] if "model_type" in text_config else "opt"
323
+ self.text_config = CONFIG_MAPPING[text_model_type](**text_config)
324
+
325
+ self.tie_word_embeddings = self.text_config.tie_word_embeddings
326
+ self.is_encoder_decoder = self.text_config.is_encoder_decoder
327
+
328
+ self.num_query_tokens = num_query_tokens
329
+ self.qformer_config.encoder_hidden_size = self.vision_config.hidden_size
330
+ self.use_decoder_only_language_model = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
331
+ self.initializer_factor = 1.0
332
+ self.initializer_range = 0.02
333
+
334
+ @classmethod
335
+ def from_vision_qformer_text_configs(
336
+ cls,
337
+ vision_config: Blip2VisionConfig,
338
+ qformer_config: Blip2QFormerConfig,
339
+ text_config: PretrainedConfig,
340
+ **kwargs,
341
+ ):
342
+ r"""
343
+ Instantiate a [`Blip2Config`] (or a derived class) from a BLIP-2 vision model, Q-Former and language model
344
+ configurations.
345
+
346
+ Returns:
347
+ [`Blip2Config`]: An instance of a configuration object
348
+ """
349
+
350
+ return cls(
351
+ vision_config=vision_config.to_dict(),
352
+ qformer_config=qformer_config.to_dict(),
353
+ text_config=text_config.to_dict(),
354
+ **kwargs,
355
+ )
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blip_2/convert_blip_2_original_to_pytorch.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Convert BLIP-2 checkpoints from the original repository.
17
+
18
+ URL: https://github.com/salesforce/LAVIS/tree/main/projects/blip2
19
+ """
20
+
21
+ import argparse
22
+
23
+ import requests
24
+ import torch
25
+
26
+ # pip3 install salesforce-lavis
27
+ # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis
28
+ from lavis.models import load_model_and_preprocess
29
+ from PIL import Image
30
+
31
+ from transformers import (
32
+ AutoTokenizer,
33
+ Blip2Config,
34
+ Blip2ForConditionalGeneration,
35
+ Blip2Processor,
36
+ Blip2VisionConfig,
37
+ BlipImageProcessor,
38
+ OPTConfig,
39
+ T5Config,
40
+ )
41
+ from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD
42
+
43
+
44
+ def load_demo_image():
45
+ url = "https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png"
46
+ image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
47
+
48
+ return image
49
+
50
+
51
+ # here we list all keys to be renamed (original name on the left, our name on the right)
52
+ def create_rename_keys(config):
53
+ rename_keys = []
54
+ # fmt: off
55
+
56
+ # vision encoder
57
+ rename_keys.append(("visual_encoder.cls_token", "vision_model.embeddings.class_embedding"))
58
+ rename_keys.append(("visual_encoder.pos_embed", "vision_model.embeddings.position_embedding"))
59
+ rename_keys.append(("visual_encoder.patch_embed.proj.weight", "vision_model.embeddings.patch_embedding.weight"))
60
+ rename_keys.append(("visual_encoder.patch_embed.proj.bias", "vision_model.embeddings.patch_embedding.bias"))
61
+ rename_keys.append(("ln_vision.weight", "vision_model.post_layernorm.weight"))
62
+ rename_keys.append(("ln_vision.bias", "vision_model.post_layernorm.bias"))
63
+
64
+ for i in range(config.vision_config.num_hidden_layers):
65
+ rename_keys.append((f"visual_encoder.blocks.{i}.norm1.weight", f"vision_model.encoder.layers.{i}.layer_norm1.weight"))
66
+ rename_keys.append((f"visual_encoder.blocks.{i}.norm1.bias", f"vision_model.encoder.layers.{i}.layer_norm1.bias"))
67
+ rename_keys.append((f"visual_encoder.blocks.{i}.norm2.weight", f"vision_model.encoder.layers.{i}.layer_norm2.weight"))
68
+ rename_keys.append((f"visual_encoder.blocks.{i}.norm2.bias", f"vision_model.encoder.layers.{i}.layer_norm2.bias"))
69
+ rename_keys.append((f"visual_encoder.blocks.{i}.attn.qkv.weight", f"vision_model.encoder.layers.{i}.self_attn.qkv.weight"))
70
+ rename_keys.append((f"visual_encoder.blocks.{i}.attn.proj.weight", f"vision_model.encoder.layers.{i}.self_attn.projection.weight",))
71
+ rename_keys.append((f"visual_encoder.blocks.{i}.attn.proj.bias", f"vision_model.encoder.layers.{i}.self_attn.projection.bias"))
72
+ rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc1.weight", f"vision_model.encoder.layers.{i}.mlp.fc1.weight"))
73
+ rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc1.bias", f"vision_model.encoder.layers.{i}.mlp.fc1.bias"))
74
+ rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc2.weight", f"vision_model.encoder.layers.{i}.mlp.fc2.weight"))
75
+ rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc2.bias", f"vision_model.encoder.layers.{i}.mlp.fc2.bias"))
76
+
77
+ # QFormer
78
+ rename_keys.append(("Qformer.bert.embeddings.LayerNorm.weight", "qformer.layernorm.weight"))
79
+ rename_keys.append(("Qformer.bert.embeddings.LayerNorm.bias", "qformer.layernorm.bias"))
80
+
81
+ # fmt: on
82
+ return rename_keys
83
+
84
+
85
+ def rename_key(dct, old, new):
86
+ val = dct.pop(old)
87
+ dct[new] = val
88
+
89
+
90
+ def read_in_q_v_bias(state_dict, config):
91
+ for i in range(config.vision_config.num_hidden_layers):
92
+ # read in original q and v biases
93
+ q_bias = state_dict.pop(f"visual_encoder.blocks.{i}.attn.q_bias")
94
+ v_bias = state_dict.pop(f"visual_encoder.blocks.{i}.attn.v_bias")
95
+
96
+ # next, set bias in the state dict
97
+ qkv_bias = torch.cat((q_bias, torch.zeros_like(v_bias, requires_grad=False), v_bias))
98
+ state_dict[f"vision_model.encoder.layers.{i}.self_attn.qkv.bias"] = qkv_bias
99
+
100
+
101
+ def get_blip2_config(model_name, eos_token_id):
102
+ image_size = 364 if "coco" in model_name else 224
103
+ vision_config = Blip2VisionConfig(image_size=image_size).to_dict()
104
+
105
+ # make sure the models have proper bos_token_id and eos_token_id set (important for generation)
106
+ # seems like flan-T5 models don't have bos_token_id properly set?
107
+ if "opt-2.7b" in model_name:
108
+ text_config = OPTConfig.from_pretrained("facebook/opt-2.7b", eos_token_id=eos_token_id).to_dict()
109
+ elif "opt-6.7b" in model_name:
110
+ text_config = OPTConfig.from_pretrained("facebook/opt-6.7b", eos_token_id=eos_token_id).to_dict()
111
+ elif "t5-xl" in model_name:
112
+ text_config = T5Config.from_pretrained("google/flan-t5-xl", dense_act_fn="gelu", bos_token_id=1).to_dict()
113
+ elif "t5-xxl" in model_name:
114
+ text_config = T5Config.from_pretrained("google/flan-t5-xxl", dense_act_fn="gelu", bos_token_id=1).to_dict()
115
+
116
+ config = Blip2Config(vision_config=vision_config, text_config=text_config)
117
+
118
+ return config, image_size
119
+
120
+
121
+ @torch.no_grad()
122
+ def convert_blip2_checkpoint(model_name, pytorch_dump_folder_path=None, push_to_hub=False):
123
+ """
124
+ Copy/paste/tweak model's weights to Transformers design.
125
+ """
126
+ tokenizer = (
127
+ AutoTokenizer.from_pretrained("facebook/opt-2.7b")
128
+ if "opt" in model_name
129
+ else AutoTokenizer.from_pretrained("google/flan-t5-xl")
130
+ )
131
+ eos_token_id = tokenizer("\n", add_special_tokens=False).input_ids[0]
132
+ config, image_size = get_blip2_config(model_name, eos_token_id=eos_token_id)
133
+
134
+ hf_model = Blip2ForConditionalGeneration(config).eval()
135
+
136
+ model_name_to_original = {
137
+ "blip2-opt-2.7b": ("blip2_opt", "pretrain_opt2.7b"),
138
+ "blip2-opt-6.7b": ("blip2_opt", "pretrain_opt6.7b"),
139
+ "blip2-opt-2.7b-coco": ("blip2_opt", "caption_coco_opt2.7b"),
140
+ "blip2-opt-6.7b-coco": ("blip2_opt", "caption_coco_opt6.7b"),
141
+ "blip2-flan-t5-xl": ("blip2_t5", "pretrain_flant5xl"),
142
+ "blip2-flan-t5-xl-coco": ("blip2_t5", "caption_coco_flant5xl"),
143
+ "blip2-flan-t5-xxl": ("blip2_t5", "pretrain_flant5xxl"),
144
+ }
145
+
146
+ name, type = model_name_to_original[model_name]
147
+
148
+ # load original model
149
+ print("Loading original model...")
150
+ device = "cuda" if torch.cuda.is_available() else "cpu"
151
+ original_model, vis_processors, _ = load_model_and_preprocess(
152
+ name=name, model_type=type, is_eval=True, device=device
153
+ )
154
+ original_model.eval()
155
+ print("Done!")
156
+
157
+ # update state dict keys
158
+ state_dict = original_model.state_dict()
159
+ rename_keys = create_rename_keys(config)
160
+ for src, dest in rename_keys:
161
+ rename_key(state_dict, src, dest)
162
+
163
+ # some keys can be renamed efficiently
164
+ for key, val in state_dict.copy().items():
165
+ val = state_dict.pop(key)
166
+ if key.startswith("Qformer.bert"):
167
+ key = key.replace("Qformer.bert", "qformer")
168
+ if "attention.self" in key:
169
+ key = key.replace("self", "attention")
170
+ if "opt_proj" in key:
171
+ key = key.replace("opt_proj", "language_projection")
172
+ if "t5_proj" in key:
173
+ key = key.replace("t5_proj", "language_projection")
174
+ if key.startswith("opt"):
175
+ key = key.replace("opt", "language")
176
+ if key.startswith("t5"):
177
+ key = key.replace("t5", "language")
178
+ state_dict[key] = val
179
+
180
+ # read in qv biases
181
+ read_in_q_v_bias(state_dict, config)
182
+
183
+ missing_keys, unexpected_keys = hf_model.load_state_dict(state_dict, strict=False)
184
+ assert len(missing_keys) == 0
185
+ assert unexpected_keys == ["qformer.embeddings.position_ids"]
186
+
187
+ image = load_demo_image()
188
+ original_pixel_values = vis_processors["eval"](image).unsqueeze(0).to(device)
189
+ input_ids = tokenizer(["\n"], return_tensors="pt").input_ids.to(device)
190
+
191
+ # create processor
192
+ image_processor = BlipImageProcessor(
193
+ size={"height": image_size, "width": image_size}, image_mean=OPENAI_CLIP_MEAN, image_std=OPENAI_CLIP_STD
194
+ )
195
+ processor = Blip2Processor(image_processor=image_processor, tokenizer=tokenizer)
196
+ pixel_values = processor(images=image, return_tensors="pt").pixel_values.to(device)
197
+
198
+ # make sure processor creates exact same pixel values
199
+ assert torch.allclose(pixel_values, original_pixel_values)
200
+
201
+ original_model.to(device)
202
+ hf_model.to(device)
203
+ with torch.no_grad():
204
+ if "opt" in model_name:
205
+ original_logits = original_model({"image": original_pixel_values, "text_input": [""]}).logits
206
+ logits = hf_model(original_pixel_values, input_ids).logits
207
+ else:
208
+ original_logits = original_model(
209
+ {"image": original_pixel_values, "text_input": ["\n"], "text_output": ["\n"]}
210
+ ).logits
211
+ labels = input_ids.masked_fill(input_ids == tokenizer.pad_token_id, -100)
212
+ logits = hf_model(original_pixel_values, input_ids, labels=labels).logits
213
+
214
+ assert original_logits.shape == logits.shape
215
+ print("First values of original logits:", original_logits[0, :3, :3])
216
+ print("First values of HF logits:", logits[0, :3, :3])
217
+
218
+ # assert values
219
+ if model_name == "blip2-flan-t5-xl":
220
+ expected_slice_logits = torch.tensor(
221
+ [[-41.5850, -4.4440, -8.9922], [-47.4322, -5.9143, -1.7340]], device=device
222
+ )
223
+ assert torch.allclose(logits[0, :3, :3], expected_slice_logits, atol=1e-4)
224
+ elif model_name == "blip2-flan-t5-xl-coco":
225
+ expected_slice_logits = torch.tensor(
226
+ [[-57.0109, -9.8967, -12.6280], [-68.6578, -12.7191, -10.5065]], device=device
227
+ )
228
+ else:
229
+ # cast to same type
230
+ target_dtype = logits.dtype
231
+ assert torch.allclose(original_logits.to(target_dtype), logits, atol=1e-2)
232
+ print("Looks ok!")
233
+
234
+ print("Generating a caption...")
235
+ prompt = ""
236
+ input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
237
+
238
+ original_outputs = original_model.generate({"image": original_pixel_values})
239
+ outputs = hf_model.generate(
240
+ original_pixel_values,
241
+ input_ids,
242
+ do_sample=False,
243
+ num_beams=5,
244
+ max_length=30,
245
+ min_length=1,
246
+ top_p=0.9,
247
+ repetition_penalty=1.0,
248
+ length_penalty=1.0,
249
+ temperature=1,
250
+ )
251
+ print("Original generation:", original_outputs)
252
+ prompt_length = input_ids.shape[1]
253
+ output_text = processor.batch_decode(outputs[:, prompt_length:], skip_special_tokens=True)
254
+ output_text = [text.strip() for text in output_text]
255
+ print("HF generation:", output_text)
256
+
257
+ if pytorch_dump_folder_path is not None:
258
+ processor.save_pretrained(pytorch_dump_folder_path)
259
+ hf_model.save_pretrained(pytorch_dump_folder_path)
260
+
261
+ if push_to_hub:
262
+ processor.push_to_hub(f"nielsr/{model_name}")
263
+ hf_model.push_to_hub(f"nielsr/{model_name}")
264
+
265
+
266
+ if __name__ == "__main__":
267
+ parser = argparse.ArgumentParser()
268
+ choices = [
269
+ "blip2-opt-2.7b",
270
+ "blip2-opt-6.7b",
271
+ "blip2-opt-2.7b-coco",
272
+ "blip2-opt-6.7b-coco",
273
+ "blip2-flan-t5-xl",
274
+ "blip2-flan-t5-xl-coco",
275
+ "blip2-flan-t5-xxl",
276
+ ]
277
+ parser.add_argument(
278
+ "--model_name",
279
+ default="blip2-opt-2.7b",
280
+ choices=choices,
281
+ type=str,
282
+ help="Path to hf config.json of model to convert",
283
+ )
284
+ parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
285
+ parser.add_argument(
286
+ "--push_to_hub",
287
+ action="store_true",
288
+ help="Whether to push the model and processor to the hub after converting",
289
+ )
290
+
291
+ args = parser.parse_args()
292
+
293
+ convert_blip2_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
evalkit_tf433/lib/python3.10/site-packages/transformers/models/blip_2/processing_blip_2.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Processor class for BLIP-2.
17
+ """
18
+
19
+ from typing import List, Optional, Union
20
+
21
+ from ...image_utils import ImageInput
22
+ from ...processing_utils import ProcessorMixin
23
+ from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
24
+ from ...utils import TensorType
25
+
26
+
27
+ class Blip2Processor(ProcessorMixin):
28
+ r"""
29
+ Constructs a BLIP-2 processor which wraps a BLIP image processor and an OPT/T5 tokenizer into a single processor.
30
+
31
+ [`BlipProcessor`] offers all the functionalities of [`BlipImageProcessor`] and [`AutoTokenizer`]. See the docstring
32
+ of [`~BlipProcessor.__call__`] and [`~BlipProcessor.decode`] for more information.
33
+
34
+ Args:
35
+ image_processor (`BlipImageProcessor`):
36
+ An instance of [`BlipImageProcessor`]. The image processor is a required input.
37
+ tokenizer (`AutoTokenizer`):
38
+ An instance of ['PreTrainedTokenizer`]. The tokenizer is a required input.
39
+ """
40
+ attributes = ["image_processor", "tokenizer"]
41
+ image_processor_class = "BlipImageProcessor"
42
+ tokenizer_class = "AutoTokenizer"
43
+
44
+ # Copied from transformers.models.blip.processing_blip.BlipProcessor.__init__
45
+ def __init__(self, image_processor, tokenizer):
46
+ tokenizer.return_token_type_ids = False
47
+ super().__init__(image_processor, tokenizer)
48
+ self.current_processor = self.image_processor
49
+
50
+ # Copied from transformers.models.blip.processing_blip.BlipProcessor.__call__
51
+ def __call__(
52
+ self,
53
+ images: ImageInput = None,
54
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
55
+ add_special_tokens: bool = True,
56
+ padding: Union[bool, str, PaddingStrategy] = False,
57
+ truncation: Union[bool, str, TruncationStrategy] = None,
58
+ max_length: Optional[int] = None,
59
+ stride: int = 0,
60
+ pad_to_multiple_of: Optional[int] = None,
61
+ return_attention_mask: Optional[bool] = None,
62
+ return_overflowing_tokens: bool = False,
63
+ return_special_tokens_mask: bool = False,
64
+ return_offsets_mapping: bool = False,
65
+ return_token_type_ids: bool = False,
66
+ return_length: bool = False,
67
+ verbose: bool = True,
68
+ return_tensors: Optional[Union[str, TensorType]] = None,
69
+ **kwargs,
70
+ ) -> BatchEncoding:
71
+ """
72
+ This method uses [`BlipImageProcessor.__call__`] method to prepare image(s) for the model, and
73
+ [`BertTokenizerFast.__call__`] to prepare text for the model.
74
+
75
+ Please refer to the docstring of the above two methods for more information.
76
+ """
77
+ if images is None and text is None:
78
+ raise ValueError("You have to specify either images or text.")
79
+
80
+ # Get only text
81
+ if images is None:
82
+ self.current_processor = self.tokenizer
83
+ text_encoding = self.tokenizer(
84
+ text=text,
85
+ add_special_tokens=add_special_tokens,
86
+ padding=padding,
87
+ truncation=truncation,
88
+ max_length=max_length,
89
+ stride=stride,
90
+ pad_to_multiple_of=pad_to_multiple_of,
91
+ return_attention_mask=return_attention_mask,
92
+ return_overflowing_tokens=return_overflowing_tokens,
93
+ return_special_tokens_mask=return_special_tokens_mask,
94
+ return_offsets_mapping=return_offsets_mapping,
95
+ return_token_type_ids=return_token_type_ids,
96
+ return_length=return_length,
97
+ verbose=verbose,
98
+ return_tensors=return_tensors,
99
+ **kwargs,
100
+ )
101
+ return text_encoding
102
+
103
+ # add pixel_values
104
+ encoding_image_processor = self.image_processor(images, return_tensors=return_tensors)
105
+
106
+ if text is not None:
107
+ text_encoding = self.tokenizer(
108
+ text=text,
109
+ add_special_tokens=add_special_tokens,
110
+ padding=padding,
111
+ truncation=truncation,
112
+ max_length=max_length,
113
+ stride=stride,
114
+ pad_to_multiple_of=pad_to_multiple_of,
115
+ return_attention_mask=return_attention_mask,
116
+ return_overflowing_tokens=return_overflowing_tokens,
117
+ return_special_tokens_mask=return_special_tokens_mask,
118
+ return_offsets_mapping=return_offsets_mapping,
119
+ return_token_type_ids=return_token_type_ids,
120
+ return_length=return_length,
121
+ verbose=verbose,
122
+ return_tensors=return_tensors,
123
+ **kwargs,
124
+ )
125
+ else:
126
+ text_encoding = None
127
+
128
+ if text_encoding is not None:
129
+ encoding_image_processor.update(text_encoding)
130
+
131
+ return encoding_image_processor
132
+
133
+ # Copied from transformers.models.blip.processing_blip.BlipProcessor.batch_decode with BertTokenizerFast->PreTrainedTokenizer
134
+ def batch_decode(self, *args, **kwargs):
135
+ """
136
+ This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
137
+ refer to the docstring of this method for more information.
138
+ """
139
+ return self.tokenizer.batch_decode(*args, **kwargs)
140
+
141
+ # Copied from transformers.models.blip.processing_blip.BlipProcessor.decode with BertTokenizerFast->PreTrainedTokenizer
142
+ def decode(self, *args, **kwargs):
143
+ """
144
+ This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer
145
+ to the docstring of this method for more information.
146
+ """
147
+ return self.tokenizer.decode(*args, **kwargs)
148
+
149
+ @property
150
+ # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
151
+ def model_input_names(self):
152
+ tokenizer_input_names = self.tokenizer.model_input_names
153
+ image_processor_input_names = self.image_processor.model_input_names
154
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
evalkit_tf433/lib/python3.10/site-packages/transformers/models/byt5/__pycache__/convert_byt5_original_tf_checkpoint_to_pytorch.cpython-310.pyc ADDED
Binary file (1.38 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/cvt/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.19 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/cvt/__pycache__/configuration_cvt.cpython-310.pyc ADDED
Binary file (6.04 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/cvt/__pycache__/modeling_cvt.cpython-310.pyc ADDED
Binary file (22.1 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/cvt/convert_cvt_original_pytorch_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Convert CvT checkpoints from the original repository.
16
+
17
+ URL: https://github.com/microsoft/CvT"""
18
+
19
+
20
+ import argparse
21
+ import json
22
+ from collections import OrderedDict
23
+
24
+ import torch
25
+ from huggingface_hub import cached_download, hf_hub_url
26
+
27
+ from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification
28
+
29
+
30
+ def embeddings(idx):
31
+ """
32
+ The function helps in renaming embedding layer weights.
33
+
34
+ Args:
35
+ idx: stage number in original model
36
+ """
37
+ embed = []
38
+ embed.append(
39
+ (
40
+ f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight",
41
+ f"stage{idx}.patch_embed.proj.weight",
42
+ )
43
+ )
44
+ embed.append(
45
+ (
46
+ f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias",
47
+ f"stage{idx}.patch_embed.proj.bias",
48
+ )
49
+ )
50
+ embed.append(
51
+ (
52
+ f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight",
53
+ f"stage{idx}.patch_embed.norm.weight",
54
+ )
55
+ )
56
+ embed.append(
57
+ (
58
+ f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias",
59
+ f"stage{idx}.patch_embed.norm.bias",
60
+ )
61
+ )
62
+ return embed
63
+
64
+
65
+ def attention(idx, cnt):
66
+ """
67
+ The function helps in renaming attention block layers weights.
68
+
69
+ Args:
70
+ idx: stage number in original model
71
+ cnt: count of blocks in each stage
72
+ """
73
+ attention_weights = []
74
+ attention_weights.append(
75
+ (
76
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight",
77
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight",
78
+ )
79
+ )
80
+ attention_weights.append(
81
+ (
82
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight",
83
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight",
84
+ )
85
+ )
86
+ attention_weights.append(
87
+ (
88
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias",
89
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias",
90
+ )
91
+ )
92
+ attention_weights.append(
93
+ (
94
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean",
95
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean",
96
+ )
97
+ )
98
+ attention_weights.append(
99
+ (
100
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var",
101
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var",
102
+ )
103
+ )
104
+ attention_weights.append(
105
+ (
106
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked",
107
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked",
108
+ )
109
+ )
110
+ attention_weights.append(
111
+ (
112
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight",
113
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight",
114
+ )
115
+ )
116
+ attention_weights.append(
117
+ (
118
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight",
119
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight",
120
+ )
121
+ )
122
+ attention_weights.append(
123
+ (
124
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias",
125
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias",
126
+ )
127
+ )
128
+ attention_weights.append(
129
+ (
130
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean",
131
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean",
132
+ )
133
+ )
134
+ attention_weights.append(
135
+ (
136
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var",
137
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var",
138
+ )
139
+ )
140
+ attention_weights.append(
141
+ (
142
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked",
143
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked",
144
+ )
145
+ )
146
+ attention_weights.append(
147
+ (
148
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight",
149
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight",
150
+ )
151
+ )
152
+ attention_weights.append(
153
+ (
154
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight",
155
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight",
156
+ )
157
+ )
158
+ attention_weights.append(
159
+ (
160
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias",
161
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias",
162
+ )
163
+ )
164
+ attention_weights.append(
165
+ (
166
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean",
167
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean",
168
+ )
169
+ )
170
+ attention_weights.append(
171
+ (
172
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var",
173
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var",
174
+ )
175
+ )
176
+ attention_weights.append(
177
+ (
178
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked",
179
+ f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked",
180
+ )
181
+ )
182
+ attention_weights.append(
183
+ (
184
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight",
185
+ f"stage{idx}.blocks.{cnt}.attn.proj_q.weight",
186
+ )
187
+ )
188
+ attention_weights.append(
189
+ (
190
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias",
191
+ f"stage{idx}.blocks.{cnt}.attn.proj_q.bias",
192
+ )
193
+ )
194
+ attention_weights.append(
195
+ (
196
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight",
197
+ f"stage{idx}.blocks.{cnt}.attn.proj_k.weight",
198
+ )
199
+ )
200
+ attention_weights.append(
201
+ (
202
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias",
203
+ f"stage{idx}.blocks.{cnt}.attn.proj_k.bias",
204
+ )
205
+ )
206
+ attention_weights.append(
207
+ (
208
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight",
209
+ f"stage{idx}.blocks.{cnt}.attn.proj_v.weight",
210
+ )
211
+ )
212
+ attention_weights.append(
213
+ (
214
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias",
215
+ f"stage{idx}.blocks.{cnt}.attn.proj_v.bias",
216
+ )
217
+ )
218
+ attention_weights.append(
219
+ (
220
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight",
221
+ f"stage{idx}.blocks.{cnt}.attn.proj.weight",
222
+ )
223
+ )
224
+ attention_weights.append(
225
+ (
226
+ f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias",
227
+ f"stage{idx}.blocks.{cnt}.attn.proj.bias",
228
+ )
229
+ )
230
+ attention_weights.append(
231
+ (f"cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight", f"stage{idx}.blocks.{cnt}.mlp.fc1.weight")
232
+ )
233
+ attention_weights.append(
234
+ (f"cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias", f"stage{idx}.blocks.{cnt}.mlp.fc1.bias")
235
+ )
236
+ attention_weights.append(
237
+ (f"cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight", f"stage{idx}.blocks.{cnt}.mlp.fc2.weight")
238
+ )
239
+ attention_weights.append(
240
+ (f"cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias", f"stage{idx}.blocks.{cnt}.mlp.fc2.bias")
241
+ )
242
+ attention_weights.append(
243
+ (f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight", f"stage{idx}.blocks.{cnt}.norm1.weight")
244
+ )
245
+ attention_weights.append(
246
+ (f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias", f"stage{idx}.blocks.{cnt}.norm1.bias")
247
+ )
248
+ attention_weights.append(
249
+ (f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight", f"stage{idx}.blocks.{cnt}.norm2.weight")
250
+ )
251
+ attention_weights.append(
252
+ (f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias", f"stage{idx}.blocks.{cnt}.norm2.bias")
253
+ )
254
+ return attention_weights
255
+
256
+
257
+ def cls_token(idx):
258
+ """
259
+ Function helps in renaming cls_token weights
260
+ """
261
+ token = []
262
+ token.append((f"cvt.encoder.stages.{idx}.cls_token", "stage2.cls_token"))
263
+ return token
264
+
265
+
266
+ def final():
267
+ """
268
+ Function helps in renaming final classification layer
269
+ """
270
+ head = []
271
+ head.append(("layernorm.weight", "norm.weight"))
272
+ head.append(("layernorm.bias", "norm.bias"))
273
+ head.append(("classifier.weight", "head.weight"))
274
+ head.append(("classifier.bias", "head.bias"))
275
+ return head
276
+
277
+
278
+ def convert_cvt_checkpoint(cvt_model, image_size, cvt_file_name, pytorch_dump_folder):
279
+ """
280
+ Fucntion to convert the microsoft cvt checkpoint to huggingface checkpoint
281
+ """
282
+ img_labels_file = "imagenet-1k-id2label.json"
283
+ num_labels = 1000
284
+
285
+ repo_id = "huggingface/label-files"
286
+ num_labels = num_labels
287
+ id2label = json.load(open(cached_download(hf_hub_url(repo_id, img_labels_file, repo_type="dataset")), "r"))
288
+ id2label = {int(k): v for k, v in id2label.items()}
289
+
290
+ id2label = id2label
291
+ label2id = {v: k for k, v in id2label.items()}
292
+
293
+ config = config = CvtConfig(num_labels=num_labels, id2label=id2label, label2id=label2id)
294
+
295
+ # For depth size 13 (13 = 1+2+10)
296
+ if cvt_model.rsplit("/", 1)[-1][4:6] == "13":
297
+ config.depth = [1, 2, 10]
298
+
299
+ # For depth size 21 (21 = 1+4+16)
300
+ elif cvt_model.rsplit("/", 1)[-1][4:6] == "21":
301
+ config.depth = [1, 4, 16]
302
+
303
+ # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20)
304
+ else:
305
+ config.depth = [2, 2, 20]
306
+ config.num_heads = [3, 12, 16]
307
+ config.embed_dim = [192, 768, 1024]
308
+
309
+ model = CvtForImageClassification(config)
310
+ image_processor = AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k")
311
+ image_processor.size["shortest_edge"] = image_size
312
+ original_weights = torch.load(cvt_file_name, map_location=torch.device("cpu"))
313
+
314
+ huggingface_weights = OrderedDict()
315
+ list_of_state_dict = []
316
+
317
+ for idx in range(len(config.depth)):
318
+ if config.cls_token[idx]:
319
+ list_of_state_dict = list_of_state_dict + cls_token(idx)
320
+ list_of_state_dict = list_of_state_dict + embeddings(idx)
321
+ for cnt in range(config.depth[idx]):
322
+ list_of_state_dict = list_of_state_dict + attention(idx, cnt)
323
+
324
+ list_of_state_dict = list_of_state_dict + final()
325
+ for gg in list_of_state_dict:
326
+ print(gg)
327
+ for i in range(len(list_of_state_dict)):
328
+ huggingface_weights[list_of_state_dict[i][0]] = original_weights[list_of_state_dict[i][1]]
329
+
330
+ model.load_state_dict(huggingface_weights)
331
+ model.save_pretrained(pytorch_dump_folder)
332
+ image_processor.save_pretrained(pytorch_dump_folder)
333
+
334
+
335
+ # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al
336
+
337
+ if __name__ == "__main__":
338
+ parser = argparse.ArgumentParser()
339
+ parser.add_argument(
340
+ "--cvt_model",
341
+ default="cvt-w24",
342
+ type=str,
343
+ help="Name of the cvt model you'd like to convert.",
344
+ )
345
+ parser.add_argument(
346
+ "--image_size",
347
+ default=384,
348
+ type=int,
349
+ help="Input Image Size",
350
+ )
351
+ parser.add_argument(
352
+ "--cvt_file_name",
353
+ default=r"cvtmodels\CvT-w24-384x384-IN-22k.pth",
354
+ type=str,
355
+ help="Input Image Size",
356
+ )
357
+ parser.add_argument(
358
+ "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
359
+ )
360
+
361
+ args = parser.parse_args()
362
+ convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/__init__.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
17
+
18
+
19
+ _import_structure = {
20
+ "configuration_graphormer": ["GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "GraphormerConfig"],
21
+ }
22
+
23
+ try:
24
+ if not is_torch_available():
25
+ raise OptionalDependencyNotAvailable()
26
+ except OptionalDependencyNotAvailable:
27
+ pass
28
+ else:
29
+ _import_structure["modeling_graphormer"] = [
30
+ "GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
31
+ "GraphormerForGraphClassification",
32
+ "GraphormerModel",
33
+ "GraphormerPreTrainedModel",
34
+ ]
35
+
36
+
37
+ if TYPE_CHECKING:
38
+ from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig
39
+
40
+ try:
41
+ if not is_torch_available():
42
+ raise OptionalDependencyNotAvailable()
43
+ except OptionalDependencyNotAvailable:
44
+ pass
45
+ else:
46
+ from .modeling_graphormer import (
47
+ GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
48
+ GraphormerForGraphClassification,
49
+ GraphormerModel,
50
+ GraphormerPreTrainedModel,
51
+ )
52
+
53
+
54
+ else:
55
+ import sys
56
+
57
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (982 Bytes). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/__pycache__/collating_graphormer.cpython-310.pyc ADDED
Binary file (4.73 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/__pycache__/configuration_graphormer.cpython-310.pyc ADDED
Binary file (8.98 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/__pycache__/modeling_graphormer.cpython-310.pyc ADDED
Binary file (25.7 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/algos_graphormer.pyx ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation and HuggingFace
2
+ # Licensed under the MIT License.
3
+
4
+ import cython
5
+
6
+ cimport numpy
7
+ from cython.parallel cimport parallel, prange
8
+
9
+ import numpy as np
10
+
11
+
12
+ # Reduce this number if matrices are too big for large graphs
13
+ UNREACHABLE_NODE_DISTANCE = 510
14
+
15
+ def floyd_warshall(adjacency_matrix):
16
+ """
17
+ Applies the Floyd-Warshall algorithm to the adjacency matrix, to compute the
18
+ shortest paths distance between all nodes, up to UNREACHABLE_NODE_DISTANCE.
19
+ """
20
+ (nrows, ncols) = adjacency_matrix.shape
21
+ assert nrows == ncols
22
+ cdef unsigned int n = nrows
23
+
24
+ adj_mat_copy = adjacency_matrix.astype(np.int32, order='C', casting='safe', copy=True)
25
+ assert adj_mat_copy.flags['C_CONTIGUOUS']
26
+ cdef numpy.ndarray[numpy.int32_t, ndim=2, mode='c'] M = adj_mat_copy
27
+ cdef numpy.ndarray[numpy.int32_t, ndim=2, mode='c'] path = -1 * np.ones([n, n], dtype=np.int32)
28
+
29
+ cdef unsigned int i, j, k
30
+ cdef numpy.int32_t M_ij, M_ik, cost_ikkj
31
+ cdef numpy.int32_t* M_ptr = &M[0,0]
32
+ cdef numpy.int32_t* M_i_ptr
33
+ cdef numpy.int32_t* M_k_ptr
34
+
35
+ # set unreachable nodes distance to UNREACHABLE_NODE_DISTANCE
36
+ for i in range(n):
37
+ for j in range(n):
38
+ if i == j:
39
+ M[i][j] = 0
40
+ elif M[i][j] == 0:
41
+ M[i][j] = UNREACHABLE_NODE_DISTANCE
42
+
43
+ # floyed algo
44
+ for k in range(n):
45
+ M_k_ptr = M_ptr + n*k
46
+ for i in range(n):
47
+ M_i_ptr = M_ptr + n*i
48
+ M_ik = M_i_ptr[k]
49
+ for j in range(n):
50
+ cost_ikkj = M_ik + M_k_ptr[j]
51
+ M_ij = M_i_ptr[j]
52
+ if M_ij > cost_ikkj:
53
+ M_i_ptr[j] = cost_ikkj
54
+ path[i][j] = k
55
+
56
+ # set unreachable path to UNREACHABLE_NODE_DISTANCE
57
+ for i in range(n):
58
+ for j in range(n):
59
+ if M[i][j] >= UNREACHABLE_NODE_DISTANCE:
60
+ path[i][j] = UNREACHABLE_NODE_DISTANCE
61
+ M[i][j] = UNREACHABLE_NODE_DISTANCE
62
+
63
+ return M, path
64
+
65
+
66
+ def get_all_edges(path, i, j):
67
+ """
68
+ Recursive function to compute all possible paths between two nodes from the graph adjacency matrix.
69
+ """
70
+ cdef int k = path[i][j]
71
+ if k == -1:
72
+ return []
73
+ else:
74
+ return get_all_edges(path, i, k) + [k] + get_all_edges(path, k, j)
75
+
76
+
77
+ def gen_edge_input(max_dist, path, edge_feat):
78
+ """
79
+ Generates the full edge feature and adjacency matrix.
80
+ Shape: num_nodes * num_nodes * max_distance_between_nodes * num_edge_features
81
+ Dim 1 is the input node, dim 2 the output node of the edge, dim 3 the depth of the edge, dim 4 the feature
82
+ """
83
+ (nrows, ncols) = path.shape
84
+ assert nrows == ncols
85
+ cdef unsigned int n = nrows
86
+ cdef unsigned int max_dist_copy = max_dist
87
+
88
+ path_copy = path.astype(long, order='C', casting='safe', copy=True)
89
+ edge_feat_copy = edge_feat.astype(long, order='C', casting='safe', copy=True)
90
+ assert path_copy.flags['C_CONTIGUOUS']
91
+ assert edge_feat_copy.flags['C_CONTIGUOUS']
92
+
93
+ cdef numpy.ndarray[numpy.int32_t, ndim=4, mode='c'] edge_fea_all = -1 * np.ones([n, n, max_dist_copy, edge_feat.shape[-1]], dtype=np.int32)
94
+ cdef unsigned int i, j, k, num_path, cur
95
+
96
+ for i in range(n):
97
+ for j in range(n):
98
+ if i == j:
99
+ continue
100
+ if path_copy[i][j] == UNREACHABLE_NODE_DISTANCE:
101
+ continue
102
+ path = [i] + get_all_edges(path_copy, i, j) + [j]
103
+ num_path = len(path) - 1
104
+ for k in range(num_path):
105
+ edge_fea_all[i, j, k, :] = edge_feat_copy[path[k], path[k+1], :]
106
+
107
+ return edge_fea_all
evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/collating_graphormer.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation and HuggingFace
2
+ # Licensed under the MIT License.
3
+
4
+ from typing import Any, Dict, List, Mapping
5
+
6
+ import numpy as np
7
+ import torch
8
+
9
+ from ...utils import is_cython_available, requires_backends
10
+
11
+
12
+ if is_cython_available():
13
+ import pyximport
14
+
15
+ pyximport.install(setup_args={"include_dirs": np.get_include()})
16
+ from . import algos_graphormer # noqa E402
17
+
18
+
19
+ def convert_to_single_emb(x, offset: int = 512):
20
+ feature_num = x.shape[1] if len(x.shape) > 1 else 1
21
+ feature_offset = 1 + np.arange(0, feature_num * offset, offset, dtype=np.int64)
22
+ x = x + feature_offset
23
+ return x
24
+
25
+
26
+ def preprocess_item(item, keep_features=True):
27
+ requires_backends(preprocess_item, ["cython"])
28
+
29
+ if keep_features and "edge_attr" in item.keys(): # edge_attr
30
+ edge_attr = np.asarray(item["edge_attr"], dtype=np.int64)
31
+ else:
32
+ edge_attr = np.ones((len(item["edge_index"][0]), 1), dtype=np.int64) # same embedding for all
33
+
34
+ if keep_features and "node_feat" in item.keys(): # input_nodes
35
+ node_feature = np.asarray(item["node_feat"], dtype=np.int64)
36
+ else:
37
+ node_feature = np.ones((item["num_nodes"], 1), dtype=np.int64) # same embedding for all
38
+
39
+ edge_index = np.asarray(item["edge_index"], dtype=np.int64)
40
+
41
+ input_nodes = convert_to_single_emb(node_feature) + 1
42
+ num_nodes = item["num_nodes"]
43
+
44
+ if len(edge_attr.shape) == 1:
45
+ edge_attr = edge_attr[:, None]
46
+ attn_edge_type = np.zeros([num_nodes, num_nodes, edge_attr.shape[-1]], dtype=np.int64)
47
+ attn_edge_type[edge_index[0], edge_index[1]] = convert_to_single_emb(edge_attr) + 1
48
+
49
+ # node adj matrix [num_nodes, num_nodes] bool
50
+ adj = np.zeros([num_nodes, num_nodes], dtype=bool)
51
+ adj[edge_index[0], edge_index[1]] = True
52
+
53
+ shortest_path_result, path = algos_graphormer.floyd_warshall(adj)
54
+ max_dist = np.amax(shortest_path_result)
55
+
56
+ input_edges = algos_graphormer.gen_edge_input(max_dist, path, attn_edge_type)
57
+ attn_bias = np.zeros([num_nodes + 1, num_nodes + 1], dtype=np.single) # with graph token
58
+
59
+ # combine
60
+ item["input_nodes"] = input_nodes + 1 # we shift all indices by one for padding
61
+ item["attn_bias"] = attn_bias
62
+ item["attn_edge_type"] = attn_edge_type
63
+ item["spatial_pos"] = shortest_path_result.astype(np.int64) + 1 # we shift all indices by one for padding
64
+ item["in_degree"] = np.sum(adj, axis=1).reshape(-1) + 1 # we shift all indices by one for padding
65
+ item["out_degree"] = item["in_degree"] # for undirected graph
66
+ item["input_edges"] = input_edges + 1 # we shift all indices by one for padding
67
+ if "labels" not in item:
68
+ item["labels"] = item["y"]
69
+
70
+ return item
71
+
72
+
73
+ class GraphormerDataCollator:
74
+ def __init__(self, spatial_pos_max=20, on_the_fly_processing=False):
75
+ if not is_cython_available():
76
+ raise ImportError("Graphormer preprocessing needs Cython (pyximport)")
77
+
78
+ self.spatial_pos_max = spatial_pos_max
79
+ self.on_the_fly_processing = on_the_fly_processing
80
+
81
+ def __call__(self, features: List[dict]) -> Dict[str, Any]:
82
+ if self.on_the_fly_processing:
83
+ features = [preprocess_item(i) for i in features]
84
+
85
+ if not isinstance(features[0], Mapping):
86
+ features = [vars(f) for f in features]
87
+ batch = {}
88
+
89
+ max_node_num = max(len(i["input_nodes"]) for i in features)
90
+ node_feat_size = len(features[0]["input_nodes"][0])
91
+ edge_feat_size = len(features[0]["attn_edge_type"][0][0])
92
+ max_dist = max(len(i["input_edges"][0][0]) for i in features)
93
+ edge_input_size = len(features[0]["input_edges"][0][0][0])
94
+ batch_size = len(features)
95
+
96
+ batch["attn_bias"] = torch.zeros(batch_size, max_node_num + 1, max_node_num + 1, dtype=torch.float)
97
+ batch["attn_edge_type"] = torch.zeros(batch_size, max_node_num, max_node_num, edge_feat_size, dtype=torch.long)
98
+ batch["spatial_pos"] = torch.zeros(batch_size, max_node_num, max_node_num, dtype=torch.long)
99
+ batch["in_degree"] = torch.zeros(batch_size, max_node_num, dtype=torch.long)
100
+ batch["input_nodes"] = torch.zeros(batch_size, max_node_num, node_feat_size, dtype=torch.long)
101
+ batch["input_edges"] = torch.zeros(
102
+ batch_size, max_node_num, max_node_num, max_dist, edge_input_size, dtype=torch.long
103
+ )
104
+
105
+ for ix, f in enumerate(features):
106
+ for k in ["attn_bias", "attn_edge_type", "spatial_pos", "in_degree", "input_nodes", "input_edges"]:
107
+ f[k] = torch.tensor(f[k])
108
+
109
+ if len(f["attn_bias"][1:, 1:][f["spatial_pos"] >= self.spatial_pos_max]) > 0:
110
+ f["attn_bias"][1:, 1:][f["spatial_pos"] >= self.spatial_pos_max] = float("-inf")
111
+
112
+ batch["attn_bias"][ix, : f["attn_bias"].shape[0], : f["attn_bias"].shape[1]] = f["attn_bias"]
113
+ batch["attn_edge_type"][ix, : f["attn_edge_type"].shape[0], : f["attn_edge_type"].shape[1], :] = f[
114
+ "attn_edge_type"
115
+ ]
116
+ batch["spatial_pos"][ix, : f["spatial_pos"].shape[0], : f["spatial_pos"].shape[1]] = f["spatial_pos"]
117
+ batch["in_degree"][ix, : f["in_degree"].shape[0]] = f["in_degree"]
118
+ batch["input_nodes"][ix, : f["input_nodes"].shape[0], :] = f["input_nodes"]
119
+ batch["input_edges"][
120
+ ix, : f["input_edges"].shape[0], : f["input_edges"].shape[1], : f["input_edges"].shape[2], :
121
+ ] = f["input_edges"]
122
+
123
+ batch["out_degree"] = batch["in_degree"]
124
+
125
+ sample = features[0]["labels"]
126
+ if len(sample) == 1: # one task
127
+ if isinstance(sample[0], float): # regression
128
+ batch["labels"] = torch.from_numpy(np.concatenate([i["labels"] for i in features]))
129
+ else: # binary classification
130
+ batch["labels"] = torch.from_numpy(np.concatenate([i["labels"] for i in features]))
131
+ else: # multi task classification, left to float to keep the NaNs
132
+ batch["labels"] = torch.from_numpy(np.stack([i["labels"] for i in features], axis=0))
133
+
134
+ return batch
evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/configuration_graphormer.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Microsoft, clefourrier and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ Graphormer model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ # pcqm4mv1 now deprecated
25
+ "graphormer-base": "https://huggingface.co/clefourrier/graphormer-base-pcqm4mv2/resolve/main/config.json",
26
+ # See all Graphormer models at https://huggingface.co/models?filter=graphormer
27
+ }
28
+
29
+
30
+ class GraphormerConfig(PretrainedConfig):
31
+ r"""
32
+ This is the configuration class to store the configuration of a [`~GraphormerModel`]. It is used to instantiate an
33
+ Graphormer model according to the specified arguments, defining the model architecture. Instantiating a
34
+ configuration with the defaults will yield a similar configuration to that of the Graphormer
35
+ [graphormer-base-pcqm4mv1](https://huggingface.co/graphormer-base-pcqm4mv1) architecture.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ num_classes (`int`, *optional*, defaults to 1):
43
+ Number of target classes or labels, set to n for binary classification of n tasks.
44
+ num_atoms (`int`, *optional*, defaults to 512*9):
45
+ Number of node types in the graphs.
46
+ num_edges (`int`, *optional*, defaults to 512*3):
47
+ Number of edges types in the graph.
48
+ num_in_degree (`int`, *optional*, defaults to 512):
49
+ Number of in degrees types in the input graphs.
50
+ num_out_degree (`int`, *optional*, defaults to 512):
51
+ Number of out degrees types in the input graphs.
52
+ num_edge_dis (`int`, *optional*, defaults to 128):
53
+ Number of edge dis in the input graphs.
54
+ multi_hop_max_dist (`int`, *optional*, defaults to 20):
55
+ Maximum distance of multi hop edges between two nodes.
56
+ spatial_pos_max (`int`, *optional*, defaults to 1024):
57
+ Maximum distance between nodes in the graph attention bias matrices, used during preprocessing and
58
+ collation.
59
+ edge_type (`str`, *optional*, defaults to multihop):
60
+ Type of edge relation chosen.
61
+ max_nodes (`int`, *optional*, defaults to 512):
62
+ Maximum number of nodes which can be parsed for the input graphs.
63
+ share_input_output_embed (`bool`, *optional*, defaults to `False`):
64
+ Shares the embedding layer between encoder and decoder - careful, True is not implemented.
65
+ num_layers (`int`, *optional*, defaults to 12):
66
+ Number of layers.
67
+ embedding_dim (`int`, *optional*, defaults to 768):
68
+ Dimension of the embedding layer in encoder.
69
+ ffn_embedding_dim (`int`, *optional*, defaults to 768):
70
+ Dimension of the "intermediate" (often named feed-forward) layer in encoder.
71
+ num_attention_heads (`int`, *optional*, defaults to 32):
72
+ Number of attention heads in the encoder.
73
+ self_attention (`bool`, *optional*, defaults to `True`):
74
+ Model is self attentive (False not implemented).
75
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
76
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
77
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
78
+ dropout (`float`, *optional*, defaults to 0.1):
79
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
80
+ attention_dropout (`float`, *optional*, defaults to 0.1):
81
+ The dropout probability for the attention weights.
82
+ layerdrop (`float`, *optional*, defaults to 0.0):
83
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
84
+ for more details.
85
+ bias (`bool`, *optional*, defaults to `True`):
86
+ Uses bias in the attention module - unsupported at the moment.
87
+ embed_scale(`float`, *optional*, defaults to None):
88
+ Scaling factor for the node embeddings.
89
+ num_trans_layers_to_freeze (`int`, *optional*, defaults to 0):
90
+ Number of transformer layers to freeze.
91
+ encoder_normalize_before (`bool`, *optional*, defaults to `False`):
92
+ Normalize features before encoding the graph.
93
+ pre_layernorm (`bool`, *optional*, defaults to `False`):
94
+ Apply layernorm before self attention and the feed forward network. Without this, post layernorm will be
95
+ used.
96
+ apply_graphormer_init (`bool`, *optional*, defaults to `False`):
97
+ Apply a custom graphormer initialisation to the model before training.
98
+ freeze_embeddings (`bool`, *optional*, defaults to `False`):
99
+ Freeze the embedding layer, or train it along the model.
100
+ encoder_normalize_before (`bool`, *optional*, defaults to `False`):
101
+ Apply the layer norm before each encoder block.
102
+ q_noise (`float`, *optional*, defaults to 0.0):
103
+ Amount of quantization noise (see "Training with Quantization Noise for Extreme Model Compression"). (For
104
+ more detail, see fairseq's documentation on quant_noise).
105
+ qn_block_size (`int`, *optional*, defaults to 8):
106
+ Size of the blocks for subsequent quantization with iPQ (see q_noise).
107
+ kdim (`int`, *optional*, defaults to None):
108
+ Dimension of the key in the attention, if different from the other values.
109
+ vdim (`int`, *optional*, defaults to None):
110
+ Dimension of the value in the attention, if different from the other values.
111
+ use_cache (`bool`, *optional*, defaults to `True`):
112
+ Whether or not the model should return the last key/values attentions (not used by all models).
113
+ traceable (`bool`, *optional*, defaults to `False`):
114
+ Changes return value of the encoder's inner_state to stacked tensors.
115
+
116
+ Example:
117
+ ```python
118
+ >>> from transformers import GraphormerForGraphClassification, GraphormerConfig
119
+
120
+ >>> # Initializing a Graphormer graphormer-base-pcqm4mv2 style configuration
121
+ >>> configuration = GraphormerConfig()
122
+
123
+ >>> # Initializing a model from the graphormer-base-pcqm4mv1 style configuration
124
+ >>> model = GraphormerForGraphClassification(configuration)
125
+
126
+ >>> # Accessing the model configuration
127
+ >>> configuration = model.config
128
+ ```
129
+ """
130
+ model_type = "graphormer"
131
+ keys_to_ignore_at_inference = ["past_key_values"]
132
+
133
+ def __init__(
134
+ self,
135
+ num_classes: int = 1,
136
+ num_atoms: int = 512 * 9,
137
+ num_edges: int = 512 * 3,
138
+ num_in_degree: int = 512,
139
+ num_out_degree: int = 512,
140
+ num_spatial: int = 512,
141
+ num_edge_dis: int = 128,
142
+ multi_hop_max_dist: int = 5, # sometimes is 20
143
+ spatial_pos_max: int = 1024,
144
+ edge_type: str = "multi_hop",
145
+ max_nodes: int = 512,
146
+ share_input_output_embed: bool = False,
147
+ num_hidden_layers: int = 12,
148
+ embedding_dim: int = 768,
149
+ ffn_embedding_dim: int = 768,
150
+ num_attention_heads: int = 32,
151
+ dropout: float = 0.1,
152
+ attention_dropout: float = 0.1,
153
+ layerdrop: float = 0.0,
154
+ encoder_normalize_before: bool = False,
155
+ pre_layernorm: bool = False,
156
+ apply_graphormer_init: bool = False,
157
+ activation_fn: str = "gelu",
158
+ embed_scale: float = None,
159
+ freeze_embeddings: bool = False,
160
+ num_trans_layers_to_freeze: int = 0,
161
+ traceable: bool = False,
162
+ q_noise: float = 0.0,
163
+ qn_block_size: int = 8,
164
+ kdim: int = None,
165
+ vdim: int = None,
166
+ bias: bool = True,
167
+ self_attention: bool = True,
168
+ pad_token_id=0,
169
+ bos_token_id=1,
170
+ eos_token_id=2,
171
+ **kwargs,
172
+ ):
173
+ self.num_classes = num_classes
174
+ self.num_atoms = num_atoms
175
+ self.num_in_degree = num_in_degree
176
+ self.num_out_degree = num_out_degree
177
+ self.num_edges = num_edges
178
+ self.num_spatial = num_spatial
179
+ self.num_edge_dis = num_edge_dis
180
+ self.edge_type = edge_type
181
+ self.multi_hop_max_dist = multi_hop_max_dist
182
+ self.spatial_pos_max = spatial_pos_max
183
+ self.max_nodes = max_nodes
184
+ self.num_hidden_layers = num_hidden_layers
185
+ self.embedding_dim = embedding_dim
186
+ self.hidden_size = embedding_dim
187
+ self.ffn_embedding_dim = ffn_embedding_dim
188
+ self.num_attention_heads = num_attention_heads
189
+ self.dropout = dropout
190
+ self.attention_dropout = attention_dropout
191
+ self.layerdrop = layerdrop
192
+ self.encoder_normalize_before = encoder_normalize_before
193
+ self.pre_layernorm = pre_layernorm
194
+ self.apply_graphormer_init = apply_graphormer_init
195
+ self.activation_fn = activation_fn
196
+ self.embed_scale = embed_scale
197
+ self.freeze_embeddings = freeze_embeddings
198
+ self.num_trans_layers_to_freeze = num_trans_layers_to_freeze
199
+ self.share_input_output_embed = share_input_output_embed
200
+ self.traceable = traceable
201
+ self.q_noise = q_noise
202
+ self.qn_block_size = qn_block_size
203
+
204
+ # These parameters are here for future extensions
205
+ # atm, the model only supports self attention
206
+ self.kdim = kdim
207
+ self.vdim = vdim
208
+ self.self_attention = self_attention
209
+ self.bias = bias
210
+
211
+ super().__init__(
212
+ pad_token_id=pad_token_id,
213
+ bos_token_id=bos_token_id,
214
+ eos_token_id=eos_token_id,
215
+ **kwargs,
216
+ )
evalkit_tf433/lib/python3.10/site-packages/transformers/models/graphormer/modeling_graphormer.py ADDED
@@ -0,0 +1,921 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Microsoft, clefourrier The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ PyTorch Graphormer model."""
16
+
17
+ import math
18
+ from typing import Iterable, Iterator, List, Optional, Tuple, Union
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
23
+
24
+ from ...activations import ACT2FN
25
+ from ...modeling_outputs import (
26
+ BaseModelOutputWithNoAttention,
27
+ SequenceClassifierOutput,
28
+ )
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...utils import logging
31
+ from .configuration_graphormer import GraphormerConfig
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+ _CHECKPOINT_FOR_DOC = "graphormer-base-pcqm4mv1"
37
+ _CONFIG_FOR_DOC = "GraphormerConfig"
38
+
39
+
40
+ GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST = [
41
+ "clefourrier/graphormer-base-pcqm4mv1",
42
+ "clefourrier/graphormer-base-pcqm4mv2",
43
+ # See all Graphormer models at https://huggingface.co/models?filter=graphormer
44
+ ]
45
+
46
+
47
+ def quant_noise(module: nn.Module, p: float, block_size: int):
48
+ """
49
+ From:
50
+ https://github.com/facebookresearch/fairseq/blob/dd0079bde7f678b0cd0715cbd0ae68d661b7226d/fairseq/modules/quant_noise.py
51
+
52
+ Wraps modules and applies quantization noise to the weights for subsequent quantization with Iterative Product
53
+ Quantization as described in "Training with Quantization Noise for Extreme Model Compression"
54
+
55
+ Args:
56
+ - module: nn.Module
57
+ - p: amount of Quantization Noise
58
+ - block_size: size of the blocks for subsequent quantization with iPQ
59
+
60
+ Remarks:
61
+ - Module weights must have the right sizes wrt the block size
62
+ - Only Linear, Embedding and Conv2d modules are supported for the moment
63
+ - For more detail on how to quantize by blocks with convolutional weights, see "And the Bit Goes Down:
64
+ Revisiting the Quantization of Neural Networks"
65
+ - We implement the simplest form of noise here as stated in the paper which consists in randomly dropping
66
+ blocks
67
+ """
68
+
69
+ # if no quantization noise, don't register hook
70
+ if p <= 0:
71
+ return module
72
+
73
+ # supported modules
74
+ if not isinstance(module, (nn.Linear, nn.Embedding, nn.Conv2d)):
75
+ raise NotImplementedError("Module unsupported for quant_noise.")
76
+
77
+ # test whether module.weight has the right sizes wrt block_size
78
+ is_conv = module.weight.ndim == 4
79
+
80
+ # 2D matrix
81
+ if not is_conv:
82
+ if module.weight.size(1) % block_size != 0:
83
+ raise AssertionError("Input features must be a multiple of block sizes")
84
+
85
+ # 4D matrix
86
+ else:
87
+ # 1x1 convolutions
88
+ if module.kernel_size == (1, 1):
89
+ if module.in_channels % block_size != 0:
90
+ raise AssertionError("Input channels must be a multiple of block sizes")
91
+ # regular convolutions
92
+ else:
93
+ k = module.kernel_size[0] * module.kernel_size[1]
94
+ if k % block_size != 0:
95
+ raise AssertionError("Kernel size must be a multiple of block size")
96
+
97
+ def _forward_pre_hook(mod, input):
98
+ # no noise for evaluation
99
+ if mod.training:
100
+ if not is_conv:
101
+ # gather weight and sizes
102
+ weight = mod.weight
103
+ in_features = weight.size(1)
104
+ out_features = weight.size(0)
105
+
106
+ # split weight matrix into blocks and randomly drop selected blocks
107
+ mask = torch.zeros(in_features // block_size * out_features, device=weight.device)
108
+ mask.bernoulli_(p)
109
+ mask = mask.repeat_interleave(block_size, -1).view(-1, in_features)
110
+
111
+ else:
112
+ # gather weight and sizes
113
+ weight = mod.weight
114
+ in_channels = mod.in_channels
115
+ out_channels = mod.out_channels
116
+
117
+ # split weight matrix into blocks and randomly drop selected blocks
118
+ if mod.kernel_size == (1, 1):
119
+ mask = torch.zeros(
120
+ int(in_channels // block_size * out_channels),
121
+ device=weight.device,
122
+ )
123
+ mask.bernoulli_(p)
124
+ mask = mask.repeat_interleave(block_size, -1).view(-1, in_channels)
125
+ else:
126
+ mask = torch.zeros(weight.size(0), weight.size(1), device=weight.device)
127
+ mask.bernoulli_(p)
128
+ mask = mask.unsqueeze(2).unsqueeze(3).repeat(1, 1, mod.kernel_size[0], mod.kernel_size[1])
129
+
130
+ # scale weights and apply mask
131
+ mask = mask.to(torch.bool) # x.bool() is not currently supported in TorchScript
132
+ s = 1 / (1 - p)
133
+ mod.weight.data = s * weight.masked_fill(mask, 0)
134
+
135
+ module.register_forward_pre_hook(_forward_pre_hook)
136
+ return module
137
+
138
+
139
+ class LayerDropModuleList(nn.ModuleList):
140
+ """
141
+ From:
142
+ https://github.com/facebookresearch/fairseq/blob/dd0079bde7f678b0cd0715cbd0ae68d661b7226d/fairseq/modules/layer_drop.py
143
+ A LayerDrop implementation based on [`torch.nn.ModuleList`]. LayerDrop as described in
144
+ https://arxiv.org/abs/1909.11556.
145
+
146
+ We refresh the choice of which layers to drop every time we iterate over the LayerDropModuleList instance. During
147
+ evaluation we always iterate over all layers.
148
+
149
+ Usage:
150
+
151
+ ```python
152
+ layers = LayerDropList(p=0.5, modules=[layer1, layer2, layer3])
153
+ for layer in layers: # this might iterate over layers 1 and 3
154
+ x = layer(x)
155
+ for layer in layers: # this might iterate over all layers
156
+ x = layer(x)
157
+ for layer in layers: # this might not iterate over any layers
158
+ x = layer(x)
159
+ ```
160
+
161
+ Args:
162
+ p (float): probability of dropping out each layer
163
+ modules (iterable, optional): an iterable of modules to add
164
+ """
165
+
166
+ def __init__(self, p: float, modules: Optional[Iterable[nn.Module]] = None):
167
+ super().__init__(modules)
168
+ self.p = p
169
+
170
+ def __iter__(self) -> Iterator[nn.Module]:
171
+ dropout_probs = torch.empty(len(self)).uniform_()
172
+ for i, m in enumerate(super().__iter__()):
173
+ if not self.training or (dropout_probs[i] > self.p):
174
+ yield m
175
+
176
+
177
+ class GraphormerGraphNodeFeature(nn.Module):
178
+ """
179
+ Compute node features for each node in the graph.
180
+ """
181
+
182
+ def __init__(self, config: GraphormerConfig):
183
+ super().__init__()
184
+ self.num_heads = config.num_attention_heads
185
+ self.num_atoms = config.num_atoms
186
+
187
+ self.atom_encoder = nn.Embedding(config.num_atoms + 1, config.hidden_size, padding_idx=config.pad_token_id)
188
+ self.in_degree_encoder = nn.Embedding(
189
+ config.num_in_degree, config.hidden_size, padding_idx=config.pad_token_id
190
+ )
191
+ self.out_degree_encoder = nn.Embedding(
192
+ config.num_out_degree, config.hidden_size, padding_idx=config.pad_token_id
193
+ )
194
+
195
+ self.graph_token = nn.Embedding(1, config.hidden_size)
196
+
197
+ def forward(
198
+ self,
199
+ input_nodes: torch.LongTensor,
200
+ in_degree: torch.LongTensor,
201
+ out_degree: torch.LongTensor,
202
+ ) -> torch.Tensor:
203
+ n_graph, n_node = input_nodes.size()[:2]
204
+
205
+ node_feature = ( # node feature + graph token
206
+ self.atom_encoder(input_nodes).sum(dim=-2) # [n_graph, n_node, n_hidden]
207
+ + self.in_degree_encoder(in_degree)
208
+ + self.out_degree_encoder(out_degree)
209
+ )
210
+
211
+ graph_token_feature = self.graph_token.weight.unsqueeze(0).repeat(n_graph, 1, 1)
212
+
213
+ graph_node_feature = torch.cat([graph_token_feature, node_feature], dim=1)
214
+
215
+ return graph_node_feature
216
+
217
+
218
+ class GraphormerGraphAttnBias(nn.Module):
219
+ """
220
+ Compute attention bias for each head.
221
+ """
222
+
223
+ def __init__(self, config: GraphormerConfig):
224
+ super().__init__()
225
+ self.num_heads = config.num_attention_heads
226
+ self.multi_hop_max_dist = config.multi_hop_max_dist
227
+
228
+ # We do not change edge feature embedding learning, as edge embeddings are represented as a combination of the original features
229
+ # + shortest path
230
+ self.edge_encoder = nn.Embedding(config.num_edges + 1, config.num_attention_heads, padding_idx=0)
231
+
232
+ self.edge_type = config.edge_type
233
+ if self.edge_type == "multi_hop":
234
+ self.edge_dis_encoder = nn.Embedding(
235
+ config.num_edge_dis * config.num_attention_heads * config.num_attention_heads,
236
+ 1,
237
+ )
238
+
239
+ self.spatial_pos_encoder = nn.Embedding(config.num_spatial, config.num_attention_heads, padding_idx=0)
240
+
241
+ self.graph_token_virtual_distance = nn.Embedding(1, config.num_attention_heads)
242
+
243
+ def forward(
244
+ self,
245
+ input_nodes: torch.LongTensor,
246
+ attn_bias: torch.Tensor,
247
+ spatial_pos: torch.LongTensor,
248
+ input_edges: torch.LongTensor,
249
+ attn_edge_type: torch.LongTensor,
250
+ ) -> torch.Tensor:
251
+ n_graph, n_node = input_nodes.size()[:2]
252
+ graph_attn_bias = attn_bias.clone()
253
+ graph_attn_bias = graph_attn_bias.unsqueeze(1).repeat(
254
+ 1, self.num_heads, 1, 1
255
+ ) # [n_graph, n_head, n_node+1, n_node+1]
256
+
257
+ # spatial pos
258
+ # [n_graph, n_node, n_node, n_head] -> [n_graph, n_head, n_node, n_node]
259
+ spatial_pos_bias = self.spatial_pos_encoder(spatial_pos).permute(0, 3, 1, 2)
260
+ graph_attn_bias[:, :, 1:, 1:] = graph_attn_bias[:, :, 1:, 1:] + spatial_pos_bias
261
+
262
+ # reset spatial pos here
263
+ t = self.graph_token_virtual_distance.weight.view(1, self.num_heads, 1)
264
+ graph_attn_bias[:, :, 1:, 0] = graph_attn_bias[:, :, 1:, 0] + t
265
+ graph_attn_bias[:, :, 0, :] = graph_attn_bias[:, :, 0, :] + t
266
+
267
+ # edge feature
268
+ if self.edge_type == "multi_hop":
269
+ spatial_pos_ = spatial_pos.clone()
270
+
271
+ spatial_pos_[spatial_pos_ == 0] = 1 # set pad to 1
272
+ # set 1 to 1, input_nodes > 1 to input_nodes - 1
273
+ spatial_pos_ = torch.where(spatial_pos_ > 1, spatial_pos_ - 1, spatial_pos_)
274
+ if self.multi_hop_max_dist > 0:
275
+ spatial_pos_ = spatial_pos_.clamp(0, self.multi_hop_max_dist)
276
+ input_edges = input_edges[:, :, :, : self.multi_hop_max_dist, :]
277
+ # [n_graph, n_node, n_node, max_dist, n_head]
278
+
279
+ input_edges = self.edge_encoder(input_edges).mean(-2)
280
+ max_dist = input_edges.size(-2)
281
+ edge_input_flat = input_edges.permute(3, 0, 1, 2, 4).reshape(max_dist, -1, self.num_heads)
282
+ edge_input_flat = torch.bmm(
283
+ edge_input_flat,
284
+ self.edge_dis_encoder.weight.reshape(-1, self.num_heads, self.num_heads)[:max_dist, :, :],
285
+ )
286
+ input_edges = edge_input_flat.reshape(max_dist, n_graph, n_node, n_node, self.num_heads).permute(
287
+ 1, 2, 3, 0, 4
288
+ )
289
+ input_edges = (input_edges.sum(-2) / (spatial_pos_.float().unsqueeze(-1))).permute(0, 3, 1, 2)
290
+ else:
291
+ # [n_graph, n_node, n_node, n_head] -> [n_graph, n_head, n_node, n_node]
292
+ input_edges = self.edge_encoder(attn_edge_type).mean(-2).permute(0, 3, 1, 2)
293
+
294
+ graph_attn_bias[:, :, 1:, 1:] = graph_attn_bias[:, :, 1:, 1:] + input_edges
295
+ graph_attn_bias = graph_attn_bias + attn_bias.unsqueeze(1) # reset
296
+
297
+ return graph_attn_bias
298
+
299
+
300
+ class GraphormerMultiheadAttention(nn.Module):
301
+ """Multi-headed attention.
302
+
303
+ See "Attention Is All You Need" for more details.
304
+ """
305
+
306
+ def __init__(self, config: GraphormerConfig):
307
+ super().__init__()
308
+ self.embedding_dim = config.embedding_dim
309
+ self.kdim = config.kdim if config.kdim is not None else config.embedding_dim
310
+ self.vdim = config.vdim if config.vdim is not None else config.embedding_dim
311
+ self.qkv_same_dim = self.kdim == config.embedding_dim and self.vdim == config.embedding_dim
312
+
313
+ self.num_heads = config.num_attention_heads
314
+ self.dropout_module = torch.nn.Dropout(p=config.dropout, inplace=False)
315
+
316
+ self.head_dim = config.embedding_dim // config.num_attention_heads
317
+ if not (self.head_dim * config.num_attention_heads == self.embedding_dim):
318
+ raise AssertionError("The embedding_dim must be divisible by num_heads.")
319
+ self.scaling = self.head_dim**-0.5
320
+
321
+ self.self_attention = True # config.self_attention
322
+ if not (self.self_attention):
323
+ raise NotImplementedError("The Graphormer model only supports self attention for now.")
324
+ if self.self_attention and not self.qkv_same_dim:
325
+ raise AssertionError("Self-attention requires query, key and value to be of the same size.")
326
+
327
+ self.k_proj = quant_noise(
328
+ nn.Linear(self.kdim, config.embedding_dim, bias=config.bias),
329
+ config.q_noise,
330
+ config.qn_block_size,
331
+ )
332
+ self.v_proj = quant_noise(
333
+ nn.Linear(self.vdim, config.embedding_dim, bias=config.bias),
334
+ config.q_noise,
335
+ config.qn_block_size,
336
+ )
337
+ self.q_proj = quant_noise(
338
+ nn.Linear(config.embedding_dim, config.embedding_dim, bias=config.bias),
339
+ config.q_noise,
340
+ config.qn_block_size,
341
+ )
342
+
343
+ self.out_proj = quant_noise(
344
+ nn.Linear(config.embedding_dim, config.embedding_dim, bias=config.bias),
345
+ config.q_noise,
346
+ config.qn_block_size,
347
+ )
348
+
349
+ self.onnx_trace = False
350
+
351
+ def reset_parameters(self):
352
+ if self.qkv_same_dim:
353
+ # Empirically observed the convergence to be much better with
354
+ # the scaled initialization
355
+ nn.init.xavier_uniform_(self.k_proj.weight, gain=1 / math.sqrt(2))
356
+ nn.init.xavier_uniform_(self.v_proj.weight, gain=1 / math.sqrt(2))
357
+ nn.init.xavier_uniform_(self.q_proj.weight, gain=1 / math.sqrt(2))
358
+ else:
359
+ nn.init.xavier_uniform_(self.k_proj.weight)
360
+ nn.init.xavier_uniform_(self.v_proj.weight)
361
+ nn.init.xavier_uniform_(self.q_proj.weight)
362
+
363
+ nn.init.xavier_uniform_(self.out_proj.weight)
364
+ if self.out_proj.bias is not None:
365
+ nn.init.constant_(self.out_proj.bias, 0.0)
366
+
367
+ def forward(
368
+ self,
369
+ query: torch.LongTensor,
370
+ key: Optional[torch.Tensor],
371
+ value: Optional[torch.Tensor],
372
+ attn_bias: Optional[torch.Tensor],
373
+ key_padding_mask: Optional[torch.Tensor] = None,
374
+ need_weights: bool = True,
375
+ attn_mask: Optional[torch.Tensor] = None,
376
+ before_softmax: bool = False,
377
+ need_head_weights: bool = False,
378
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
379
+ """
380
+ Args:
381
+ key_padding_mask (Bytetorch.Tensor, optional): mask to exclude
382
+ keys that are pads, of shape `(batch, src_len)`, where padding elements are indicated by 1s.
383
+ need_weights (bool, optional): return the attention weights,
384
+ averaged over heads (default: False).
385
+ attn_mask (Bytetorch.Tensor, optional): typically used to
386
+ implement causal attention, where the mask prevents the attention from looking forward in time
387
+ (default: None).
388
+ before_softmax (bool, optional): return the raw attention
389
+ weights and values before the attention softmax.
390
+ need_head_weights (bool, optional): return the attention
391
+ weights for each head. Implies *need_weights*. Default: return the average attention weights over all
392
+ heads.
393
+ """
394
+ if need_head_weights:
395
+ need_weights = True
396
+
397
+ tgt_len, bsz, embedding_dim = query.size()
398
+ src_len = tgt_len
399
+ if not (embedding_dim == self.embedding_dim):
400
+ raise AssertionError(
401
+ f"The query embedding dimension {embedding_dim} is not equal to the expected embedding_dim"
402
+ f" {self.embedding_dim}."
403
+ )
404
+ if not (list(query.size()) == [tgt_len, bsz, embedding_dim]):
405
+ raise AssertionError("Query size incorrect in Graphormer, compared to model dimensions.")
406
+
407
+ if key is not None:
408
+ src_len, key_bsz, _ = key.size()
409
+ if not torch.jit.is_scripting():
410
+ if (key_bsz != bsz) or (value is None) or not (src_len, bsz == value.shape[:2]):
411
+ raise AssertionError(
412
+ "The batch shape does not match the key or value shapes provided to the attention."
413
+ )
414
+
415
+ q = self.q_proj(query)
416
+ k = self.k_proj(query)
417
+ v = self.v_proj(query)
418
+
419
+ q *= self.scaling
420
+
421
+ q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim).transpose(0, 1)
422
+ if k is not None:
423
+ k = k.contiguous().view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1)
424
+ if v is not None:
425
+ v = v.contiguous().view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1)
426
+
427
+ if (k is None) or not (k.size(1) == src_len):
428
+ raise AssertionError("The shape of the key generated in the attention is incorrect")
429
+
430
+ # This is part of a workaround to get around fork/join parallelism
431
+ # not supporting Optional types.
432
+ if key_padding_mask is not None and key_padding_mask.dim() == 0:
433
+ key_padding_mask = None
434
+
435
+ if key_padding_mask is not None:
436
+ if key_padding_mask.size(0) != bsz or key_padding_mask.size(1) != src_len:
437
+ raise AssertionError(
438
+ "The shape of the generated padding mask for the key does not match expected dimensions."
439
+ )
440
+ attn_weights = torch.bmm(q, k.transpose(1, 2))
441
+ attn_weights = self.apply_sparse_mask(attn_weights, tgt_len, src_len, bsz)
442
+
443
+ if list(attn_weights.size()) != [bsz * self.num_heads, tgt_len, src_len]:
444
+ raise AssertionError("The attention weights generated do not match the expected dimensions.")
445
+
446
+ if attn_bias is not None:
447
+ attn_weights += attn_bias.view(bsz * self.num_heads, tgt_len, src_len)
448
+
449
+ if attn_mask is not None:
450
+ attn_mask = attn_mask.unsqueeze(0)
451
+ attn_weights += attn_mask
452
+
453
+ if key_padding_mask is not None:
454
+ # don't attend to padding symbols
455
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
456
+ attn_weights = attn_weights.masked_fill(
457
+ key_padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool), float("-inf")
458
+ )
459
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
460
+
461
+ if before_softmax:
462
+ return attn_weights, v
463
+
464
+ attn_weights_float = torch.nn.functional.softmax(attn_weights, dim=-1)
465
+ attn_weights = attn_weights_float.type_as(attn_weights)
466
+ attn_probs = self.dropout_module(attn_weights)
467
+
468
+ if v is None:
469
+ raise AssertionError("No value generated")
470
+ attn = torch.bmm(attn_probs, v)
471
+ if list(attn.size()) != [bsz * self.num_heads, tgt_len, self.head_dim]:
472
+ raise AssertionError("The attention generated do not match the expected dimensions.")
473
+
474
+ attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embedding_dim)
475
+ attn: torch.Tensor = self.out_proj(attn)
476
+
477
+ attn_weights = None
478
+ if need_weights:
479
+ attn_weights = attn_weights_float.contiguous().view(bsz, self.num_heads, tgt_len, src_len).transpose(1, 0)
480
+ if not need_head_weights:
481
+ # average attention weights over heads
482
+ attn_weights = attn_weights.mean(dim=0)
483
+
484
+ return attn, attn_weights
485
+
486
+ def apply_sparse_mask(self, attn_weights: torch.Tensor, tgt_len: int, src_len: int, bsz: int) -> torch.Tensor:
487
+ return attn_weights
488
+
489
+
490
+ class GraphormerGraphEncoderLayer(nn.Module):
491
+ def __init__(self, config: GraphormerConfig) -> None:
492
+ super().__init__()
493
+
494
+ # Initialize parameters
495
+ self.embedding_dim = config.embedding_dim
496
+ self.num_attention_heads = config.num_attention_heads
497
+ self.attention_dropout = config.attention_dropout
498
+ self.q_noise = config.q_noise
499
+ self.qn_block_size = config.qn_block_size
500
+ self.pre_layernorm = config.pre_layernorm
501
+
502
+ self.dropout_module = torch.nn.Dropout(p=config.dropout, inplace=False)
503
+
504
+ self.activation_dropout_module = torch.nn.Dropout(p=config.dropout, inplace=False)
505
+
506
+ # Initialize blocks
507
+ self.activation_fn = ACT2FN[config.activation_fn]
508
+ self.self_attn = GraphormerMultiheadAttention(config)
509
+
510
+ # layer norm associated with the self attention layer
511
+ self.self_attn_layer_norm = nn.LayerNorm(self.embedding_dim)
512
+
513
+ self.fc1 = self.build_fc(
514
+ self.embedding_dim,
515
+ config.ffn_embedding_dim,
516
+ q_noise=config.q_noise,
517
+ qn_block_size=config.qn_block_size,
518
+ )
519
+ self.fc2 = self.build_fc(
520
+ config.ffn_embedding_dim,
521
+ self.embedding_dim,
522
+ q_noise=config.q_noise,
523
+ qn_block_size=config.qn_block_size,
524
+ )
525
+
526
+ # layer norm associated with the position wise feed-forward NN
527
+ self.final_layer_norm = nn.LayerNorm(self.embedding_dim)
528
+
529
+ def build_fc(
530
+ self, input_dim: int, output_dim: int, q_noise: float, qn_block_size: int
531
+ ) -> Union[nn.Module, nn.Linear, nn.Embedding, nn.Conv2d]:
532
+ return quant_noise(nn.Linear(input_dim, output_dim), q_noise, qn_block_size)
533
+
534
+ def forward(
535
+ self,
536
+ input_nodes: torch.Tensor,
537
+ self_attn_bias: Optional[torch.Tensor] = None,
538
+ self_attn_mask: Optional[torch.Tensor] = None,
539
+ self_attn_padding_mask: Optional[torch.Tensor] = None,
540
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
541
+ """
542
+ nn.LayerNorm is applied either before or after the self-attention/ffn modules similar to the original
543
+ Transformer implementation.
544
+ """
545
+ residual = input_nodes
546
+ if self.pre_layernorm:
547
+ input_nodes = self.self_attn_layer_norm(input_nodes)
548
+
549
+ input_nodes, attn = self.self_attn(
550
+ query=input_nodes,
551
+ key=input_nodes,
552
+ value=input_nodes,
553
+ attn_bias=self_attn_bias,
554
+ key_padding_mask=self_attn_padding_mask,
555
+ need_weights=False,
556
+ attn_mask=self_attn_mask,
557
+ )
558
+ input_nodes = self.dropout_module(input_nodes)
559
+ input_nodes = residual + input_nodes
560
+ if not self.pre_layernorm:
561
+ input_nodes = self.self_attn_layer_norm(input_nodes)
562
+
563
+ residual = input_nodes
564
+ if self.pre_layernorm:
565
+ input_nodes = self.final_layer_norm(input_nodes)
566
+ input_nodes = self.activation_fn(self.fc1(input_nodes))
567
+ input_nodes = self.activation_dropout_module(input_nodes)
568
+ input_nodes = self.fc2(input_nodes)
569
+ input_nodes = self.dropout_module(input_nodes)
570
+ input_nodes = residual + input_nodes
571
+ if not self.pre_layernorm:
572
+ input_nodes = self.final_layer_norm(input_nodes)
573
+
574
+ return input_nodes, attn
575
+
576
+
577
+ class GraphormerGraphEncoder(nn.Module):
578
+ def __init__(self, config: GraphormerConfig):
579
+ super().__init__()
580
+
581
+ self.dropout_module = torch.nn.Dropout(p=config.dropout, inplace=False)
582
+ self.layerdrop = config.layerdrop
583
+ self.embedding_dim = config.embedding_dim
584
+ self.apply_graphormer_init = config.apply_graphormer_init
585
+ self.traceable = config.traceable
586
+
587
+ self.graph_node_feature = GraphormerGraphNodeFeature(config)
588
+ self.graph_attn_bias = GraphormerGraphAttnBias(config)
589
+
590
+ self.embed_scale = config.embed_scale
591
+
592
+ if config.q_noise > 0:
593
+ self.quant_noise = quant_noise(
594
+ nn.Linear(self.embedding_dim, self.embedding_dim, bias=False),
595
+ config.q_noise,
596
+ config.qn_block_size,
597
+ )
598
+ else:
599
+ self.quant_noise = None
600
+
601
+ if config.encoder_normalize_before:
602
+ self.emb_layer_norm = nn.LayerNorm(self.embedding_dim)
603
+ else:
604
+ self.emb_layer_norm = None
605
+
606
+ if config.pre_layernorm:
607
+ self.final_layer_norm = nn.LayerNorm(self.embedding_dim)
608
+
609
+ if self.layerdrop > 0.0:
610
+ self.layers = LayerDropModuleList(p=self.layerdrop)
611
+ else:
612
+ self.layers = nn.ModuleList([])
613
+ self.layers.extend([GraphormerGraphEncoderLayer(config) for _ in range(config.num_hidden_layers)])
614
+
615
+ # Apply initialization of model params after building the model
616
+ if config.freeze_embeddings:
617
+ raise NotImplementedError("Freezing embeddings is not implemented yet.")
618
+
619
+ for layer in range(config.num_trans_layers_to_freeze):
620
+ m = self.layers[layer]
621
+ if m is not None:
622
+ for p in m.parameters():
623
+ p.requires_grad = False
624
+
625
+ def forward(
626
+ self,
627
+ input_nodes: torch.LongTensor,
628
+ input_edges: torch.LongTensor,
629
+ attn_bias: torch.Tensor,
630
+ in_degree: torch.LongTensor,
631
+ out_degree: torch.LongTensor,
632
+ spatial_pos: torch.LongTensor,
633
+ attn_edge_type: torch.LongTensor,
634
+ perturb=None,
635
+ last_state_only: bool = False,
636
+ token_embeddings: Optional[torch.Tensor] = None,
637
+ attn_mask: Optional[torch.Tensor] = None,
638
+ ) -> Tuple[Union[torch.Tensor, List[torch.LongTensor]], torch.Tensor]:
639
+ # compute padding mask. This is needed for multi-head attention
640
+ data_x = input_nodes
641
+ n_graph, n_node = data_x.size()[:2]
642
+ padding_mask = (data_x[:, :, 0]).eq(0)
643
+ padding_mask_cls = torch.zeros(n_graph, 1, device=padding_mask.device, dtype=padding_mask.dtype)
644
+ padding_mask = torch.cat((padding_mask_cls, padding_mask), dim=1)
645
+
646
+ attn_bias = self.graph_attn_bias(input_nodes, attn_bias, spatial_pos, input_edges, attn_edge_type)
647
+
648
+ if token_embeddings is not None:
649
+ input_nodes = token_embeddings
650
+ else:
651
+ input_nodes = self.graph_node_feature(input_nodes, in_degree, out_degree)
652
+
653
+ if perturb is not None:
654
+ input_nodes[:, 1:, :] += perturb
655
+
656
+ if self.embed_scale is not None:
657
+ input_nodes = input_nodes * self.embed_scale
658
+
659
+ if self.quant_noise is not None:
660
+ input_nodes = self.quant_noise(input_nodes)
661
+
662
+ if self.emb_layer_norm is not None:
663
+ input_nodes = self.emb_layer_norm(input_nodes)
664
+
665
+ input_nodes = self.dropout_module(input_nodes)
666
+
667
+ input_nodes = input_nodes.transpose(0, 1)
668
+
669
+ inner_states = []
670
+ if not last_state_only:
671
+ inner_states.append(input_nodes)
672
+
673
+ for layer in self.layers:
674
+ input_nodes, _ = layer(
675
+ input_nodes,
676
+ self_attn_padding_mask=padding_mask,
677
+ self_attn_mask=attn_mask,
678
+ self_attn_bias=attn_bias,
679
+ )
680
+ if not last_state_only:
681
+ inner_states.append(input_nodes)
682
+
683
+ graph_rep = input_nodes[0, :, :]
684
+
685
+ if last_state_only:
686
+ inner_states = [input_nodes]
687
+
688
+ if self.traceable:
689
+ return torch.stack(inner_states), graph_rep
690
+ else:
691
+ return inner_states, graph_rep
692
+
693
+
694
+ class GraphormerDecoderHead(nn.Module):
695
+ def __init__(self, embedding_dim: int, num_classes: int):
696
+ super().__init__()
697
+ """num_classes should be 1 for regression, or the number of classes for classification"""
698
+ self.lm_output_learned_bias = nn.Parameter(torch.zeros(1))
699
+ self.classifier = nn.Linear(embedding_dim, num_classes, bias=False)
700
+ self.num_classes = num_classes
701
+
702
+ def forward(self, input_nodes: torch.Tensor, **unused) -> torch.Tensor:
703
+ input_nodes = self.classifier(input_nodes)
704
+ input_nodes = input_nodes + self.lm_output_learned_bias
705
+ return input_nodes
706
+
707
+
708
+ class GraphormerPreTrainedModel(PreTrainedModel):
709
+ """
710
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
711
+ models.
712
+ """
713
+
714
+ config_class = GraphormerConfig
715
+ base_model_prefix = "graphormer"
716
+ supports_gradient_checkpointing = True
717
+ main_input_name_nodes = "input_nodes"
718
+ main_input_name_edges = "input_edges"
719
+
720
+ def normal_(self, data: torch.Tensor):
721
+ # with FSDP, module params will be on CUDA, so we cast them back to CPU
722
+ # so that the RNG is consistent with and without FSDP
723
+ data.copy_(data.cpu().normal_(mean=0.0, std=0.02).to(data.device))
724
+
725
+ def init_graphormer_params(self, module: Union[nn.Linear, nn.Embedding, GraphormerMultiheadAttention]):
726
+ """
727
+ Initialize the weights specific to the Graphormer Model.
728
+ """
729
+ if isinstance(module, nn.Linear):
730
+ self.normal_(module.weight.data)
731
+ if module.bias is not None:
732
+ module.bias.data.zero_()
733
+ if isinstance(module, nn.Embedding):
734
+ self.normal_(module.weight.data)
735
+ if module.padding_idx is not None:
736
+ module.weight.data[module.padding_idx].zero_()
737
+ if isinstance(module, GraphormerMultiheadAttention):
738
+ self.normal_(module.q_proj.weight.data)
739
+ self.normal_(module.k_proj.weight.data)
740
+ self.normal_(module.v_proj.weight.data)
741
+
742
+ def _init_weights(
743
+ self,
744
+ module: Union[
745
+ nn.Linear, nn.Conv2d, nn.Embedding, nn.LayerNorm, GraphormerMultiheadAttention, GraphormerGraphEncoder
746
+ ],
747
+ ):
748
+ """
749
+ Initialize the weights
750
+ """
751
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
752
+ # We might be missing part of the Linear init, dependant on the layer num
753
+ module.weight.data.normal_(mean=0.0, std=0.02)
754
+ if module.bias is not None:
755
+ module.bias.data.zero_()
756
+ elif isinstance(module, nn.Embedding):
757
+ module.weight.data.normal_(mean=0.0, std=0.02)
758
+ if module.padding_idx is not None:
759
+ module.weight.data[module.padding_idx].zero_()
760
+ elif isinstance(module, GraphormerMultiheadAttention):
761
+ module.q_proj.weight.data.normal_(mean=0.0, std=0.02)
762
+ module.k_proj.weight.data.normal_(mean=0.0, std=0.02)
763
+ module.v_proj.weight.data.normal_(mean=0.0, std=0.02)
764
+ module.reset_parameters()
765
+ elif isinstance(module, nn.LayerNorm):
766
+ module.bias.data.zero_()
767
+ module.weight.data.fill_(1.0)
768
+ elif isinstance(module, GraphormerGraphEncoder):
769
+ if module.apply_graphormer_init:
770
+ module.apply(self.init_graphormer_params)
771
+
772
+ elif isinstance(module, nn.LayerNorm):
773
+ module.bias.data.zero_()
774
+ module.weight.data.fill_(1.0)
775
+
776
+ def _set_gradient_checkpointing(self, module, value=False):
777
+ if isinstance(module, GraphormerModel):
778
+ module.gradient_checkpointing = value
779
+
780
+
781
+ class GraphormerModel(GraphormerPreTrainedModel):
782
+ """The Graphormer model is a graph-encoder model.
783
+
784
+ It goes from a graph to its representation. If you want to use the model for a downstream classification task, use
785
+ GraphormerForGraphClassification instead. For any other downstream task, feel free to add a new class, or combine
786
+ this model with a downstream model of your choice, following the example in GraphormerForGraphClassification.
787
+ """
788
+
789
+ def __init__(self, config: GraphormerConfig):
790
+ super().__init__(config)
791
+ self.max_nodes = config.max_nodes
792
+
793
+ self.graph_encoder = GraphormerGraphEncoder(config)
794
+
795
+ self.share_input_output_embed = config.share_input_output_embed
796
+ self.lm_output_learned_bias = None
797
+
798
+ # Remove head is set to true during fine-tuning
799
+ self.load_softmax = not getattr(config, "remove_head", False)
800
+
801
+ self.lm_head_transform_weight = nn.Linear(config.embedding_dim, config.embedding_dim)
802
+ self.activation_fn = ACT2FN[config.activation_fn]
803
+ self.layer_norm = nn.LayerNorm(config.embedding_dim)
804
+
805
+ self.post_init()
806
+
807
+ def reset_output_layer_parameters(self):
808
+ self.lm_output_learned_bias = nn.Parameter(torch.zeros(1))
809
+
810
+ def forward(
811
+ self,
812
+ input_nodes: torch.LongTensor,
813
+ input_edges: torch.LongTensor,
814
+ attn_bias: torch.Tensor,
815
+ in_degree: torch.LongTensor,
816
+ out_degree: torch.LongTensor,
817
+ spatial_pos: torch.LongTensor,
818
+ attn_edge_type: torch.LongTensor,
819
+ perturb: Optional[torch.FloatTensor] = None,
820
+ masked_tokens: None = None,
821
+ return_dict: Optional[bool] = None,
822
+ **unused,
823
+ ) -> Union[Tuple[torch.LongTensor], BaseModelOutputWithNoAttention]:
824
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
825
+
826
+ inner_states, graph_rep = self.graph_encoder(
827
+ input_nodes, input_edges, attn_bias, in_degree, out_degree, spatial_pos, attn_edge_type, perturb=perturb
828
+ )
829
+
830
+ # last inner state, then revert Batch and Graph len
831
+ input_nodes = inner_states[-1].transpose(0, 1)
832
+
833
+ # project masked tokens only
834
+ if masked_tokens is not None:
835
+ raise NotImplementedError
836
+
837
+ input_nodes = self.layer_norm(self.activation_fn(self.lm_head_transform_weight(input_nodes)))
838
+
839
+ # project back to size of vocabulary
840
+ if self.share_input_output_embed and hasattr(self.graph_encoder.embed_tokens, "weight"):
841
+ input_nodes = torch.nn.functional.linear(input_nodes, self.graph_encoder.embed_tokens.weight)
842
+
843
+ if not return_dict:
844
+ return tuple(x for x in [input_nodes, inner_states] if x is not None)
845
+ return BaseModelOutputWithNoAttention(last_hidden_state=input_nodes, hidden_states=inner_states)
846
+
847
+ def max_nodes(self):
848
+ """Maximum output length supported by the encoder."""
849
+ return self.max_nodes
850
+
851
+
852
+ class GraphormerForGraphClassification(GraphormerPreTrainedModel):
853
+ """
854
+ This model can be used for graph-level classification or regression tasks.
855
+
856
+ It can be trained on
857
+ - regression (by setting config.num_classes to 1); there should be one float-type label per graph
858
+ - one task classification (by setting config.num_classes to the number of classes); there should be one integer
859
+ label per graph
860
+ - binary multi-task classification (by setting config.num_classes to the number of labels); there should be a list
861
+ of integer labels for each graph.
862
+ """
863
+
864
+ def __init__(self, config: GraphormerConfig):
865
+ super().__init__(config)
866
+ self.encoder = GraphormerModel(config)
867
+ self.embedding_dim = config.embedding_dim
868
+ self.num_classes = config.num_classes
869
+ self.classifier = GraphormerDecoderHead(self.embedding_dim, self.num_classes)
870
+ self.is_encoder_decoder = True
871
+
872
+ # Initialize weights and apply final processing
873
+ self.post_init()
874
+
875
+ def forward(
876
+ self,
877
+ input_nodes: torch.LongTensor,
878
+ input_edges: torch.LongTensor,
879
+ attn_bias: torch.Tensor,
880
+ in_degree: torch.LongTensor,
881
+ out_degree: torch.LongTensor,
882
+ spatial_pos: torch.LongTensor,
883
+ attn_edge_type: torch.LongTensor,
884
+ labels: Optional[torch.LongTensor] = None,
885
+ return_dict: Optional[bool] = None,
886
+ **unused,
887
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
888
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
889
+
890
+ encoder_outputs = self.encoder(
891
+ input_nodes,
892
+ input_edges,
893
+ attn_bias,
894
+ in_degree,
895
+ out_degree,
896
+ spatial_pos,
897
+ attn_edge_type,
898
+ return_dict=True,
899
+ )
900
+ outputs, hidden_states = encoder_outputs["last_hidden_state"], encoder_outputs["hidden_states"]
901
+
902
+ head_outputs = self.classifier(outputs)
903
+ logits = head_outputs[:, 0, :].contiguous()
904
+
905
+ loss = None
906
+ if labels is not None:
907
+ mask = ~torch.isnan(labels)
908
+
909
+ if self.num_classes == 1: # regression
910
+ loss_fct = MSELoss()
911
+ loss = loss_fct(logits[mask].squeeze(), labels[mask].squeeze().float())
912
+ elif self.num_classes > 1 and len(labels.shape) == 1: # One task classification
913
+ loss_fct = CrossEntropyLoss()
914
+ loss = loss_fct(logits[mask].view(-1, self.num_classes), labels[mask].view(-1))
915
+ else: # Binary multi-task classification
916
+ loss_fct = BCEWithLogitsLoss(reduction="sum")
917
+ loss = loss_fct(logits[mask], labels[mask])
918
+
919
+ if not return_dict:
920
+ return tuple(x for x in [loss, logits, hidden_states] if x is not None)
921
+ return SequenceClassifierOutput(loss=loss, logits=logits, hidden_states=hidden_states, attentions=None)
evalkit_tf433/lib/python3.10/site-packages/transformers/models/layoutlmv3/feature_extraction_layoutlmv3.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Feature extractor class for LayoutLMv3.
17
+ """
18
+
19
+ import warnings
20
+
21
+ from ...utils import logging
22
+ from .image_processing_layoutlmv3 import LayoutLMv3ImageProcessor
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class LayoutLMv3FeatureExtractor(LayoutLMv3ImageProcessor):
29
+ def __init__(self, *args, **kwargs) -> None:
30
+ warnings.warn(
31
+ "The class LayoutLMv3FeatureExtractor is deprecated and will be removed in version 5 of Transformers."
32
+ " Please use LayoutLMv3ImageProcessor instead.",
33
+ FutureWarning,
34
+ )
35
+ super().__init__(*args, **kwargs)
evalkit_tf433/lib/python3.10/site-packages/transformers/models/layoutlmv3/processing_layoutlmv3.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Processor class for LayoutLMv3.
17
+ """
18
+
19
+ import warnings
20
+ from typing import List, Optional, Union
21
+
22
+ from ...processing_utils import ProcessorMixin
23
+ from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
24
+ from ...utils import TensorType
25
+
26
+
27
+ class LayoutLMv3Processor(ProcessorMixin):
28
+ r"""
29
+ Constructs a LayoutLMv3 processor which combines a LayoutLMv3 image processor and a LayoutLMv3 tokenizer into a
30
+ single processor.
31
+
32
+ [`LayoutLMv3Processor`] offers all the functionalities you need to prepare data for the model.
33
+
34
+ It first uses [`LayoutLMv3ImageProcessor`] to resize and normalize document images, and optionally applies OCR to
35
+ get words and normalized bounding boxes. These are then provided to [`LayoutLMv3Tokenizer`] or
36
+ [`LayoutLMv3TokenizerFast`], which turns the words and bounding boxes into token-level `input_ids`,
37
+ `attention_mask`, `token_type_ids`, `bbox`. Optionally, one can provide integer `word_labels`, which are turned
38
+ into token-level `labels` for token classification tasks (such as FUNSD, CORD).
39
+
40
+ Args:
41
+ image_processor (`LayoutLMv3ImageProcessor`):
42
+ An instance of [`LayoutLMv3ImageProcessor`]. The image processor is a required input.
43
+ tokenizer (`LayoutLMv3Tokenizer` or `LayoutLMv3TokenizerFast`):
44
+ An instance of [`LayoutLMv3Tokenizer`] or [`LayoutLMv3TokenizerFast`]. The tokenizer is a required input.
45
+ """
46
+ attributes = ["image_processor", "tokenizer"]
47
+ image_processor_class = "LayoutLMv3ImageProcessor"
48
+ tokenizer_class = ("LayoutLMv3Tokenizer", "LayoutLMv3TokenizerFast")
49
+
50
+ def __init__(self, image_processor=None, tokenizer=None, **kwargs):
51
+ feature_extractor = None
52
+ if "feature_extractor" in kwargs:
53
+ warnings.warn(
54
+ "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
55
+ " instead.",
56
+ FutureWarning,
57
+ )
58
+ feature_extractor = kwargs.pop("feature_extractor")
59
+
60
+ image_processor = image_processor if image_processor is not None else feature_extractor
61
+ if image_processor is None:
62
+ raise ValueError("You need to specify an `image_processor`.")
63
+ if tokenizer is None:
64
+ raise ValueError("You need to specify a `tokenizer`.")
65
+
66
+ super().__init__(image_processor, tokenizer)
67
+
68
+ def __call__(
69
+ self,
70
+ images,
71
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
72
+ text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
73
+ boxes: Union[List[List[int]], List[List[List[int]]]] = None,
74
+ word_labels: Optional[Union[List[int], List[List[int]]]] = None,
75
+ add_special_tokens: bool = True,
76
+ padding: Union[bool, str, PaddingStrategy] = False,
77
+ truncation: Union[bool, str, TruncationStrategy] = None,
78
+ max_length: Optional[int] = None,
79
+ stride: int = 0,
80
+ pad_to_multiple_of: Optional[int] = None,
81
+ return_token_type_ids: Optional[bool] = None,
82
+ return_attention_mask: Optional[bool] = None,
83
+ return_overflowing_tokens: bool = False,
84
+ return_special_tokens_mask: bool = False,
85
+ return_offsets_mapping: bool = False,
86
+ return_length: bool = False,
87
+ verbose: bool = True,
88
+ return_tensors: Optional[Union[str, TensorType]] = None,
89
+ **kwargs,
90
+ ) -> BatchEncoding:
91
+ """
92
+ This method first forwards the `images` argument to [`~LayoutLMv3ImageProcessor.__call__`]. In case
93
+ [`LayoutLMv3ImageProcessor`] was initialized with `apply_ocr` set to `True`, it passes the obtained words and
94
+ bounding boxes along with the additional arguments to [`~LayoutLMv3Tokenizer.__call__`] and returns the output,
95
+ together with resized and normalized `pixel_values`. In case [`LayoutLMv3ImageProcessor`] was initialized with
96
+ `apply_ocr` set to `False`, it passes the words (`text`/``text_pair`) and `boxes` specified by the user along
97
+ with the additional arguments to [`~LayoutLMv3Tokenizer.__call__`] and returns the output, together with
98
+ resized and normalized `pixel_values`.
99
+
100
+ Please refer to the docstring of the above two methods for more information.
101
+ """
102
+ # verify input
103
+ if self.image_processor.apply_ocr and (boxes is not None):
104
+ raise ValueError(
105
+ "You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True."
106
+ )
107
+
108
+ if self.image_processor.apply_ocr and (word_labels is not None):
109
+ raise ValueError(
110
+ "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."
111
+ )
112
+
113
+ # first, apply the image processor
114
+ features = self.image_processor(images=images, return_tensors=return_tensors)
115
+
116
+ # second, apply the tokenizer
117
+ if text is not None and self.image_processor.apply_ocr and text_pair is None:
118
+ if isinstance(text, str):
119
+ text = [text] # add batch dimension (as the image processor always adds a batch dimension)
120
+ text_pair = features["words"]
121
+
122
+ encoded_inputs = self.tokenizer(
123
+ text=text if text is not None else features["words"],
124
+ text_pair=text_pair if text_pair is not None else None,
125
+ boxes=boxes if boxes is not None else features["boxes"],
126
+ word_labels=word_labels,
127
+ add_special_tokens=add_special_tokens,
128
+ padding=padding,
129
+ truncation=truncation,
130
+ max_length=max_length,
131
+ stride=stride,
132
+ pad_to_multiple_of=pad_to_multiple_of,
133
+ return_token_type_ids=return_token_type_ids,
134
+ return_attention_mask=return_attention_mask,
135
+ return_overflowing_tokens=return_overflowing_tokens,
136
+ return_special_tokens_mask=return_special_tokens_mask,
137
+ return_offsets_mapping=return_offsets_mapping,
138
+ return_length=return_length,
139
+ verbose=verbose,
140
+ return_tensors=return_tensors,
141
+ **kwargs,
142
+ )
143
+
144
+ # add pixel values
145
+ images = features.pop("pixel_values")
146
+ if return_overflowing_tokens is True:
147
+ images = self.get_overflowing_images(images, encoded_inputs["overflow_to_sample_mapping"])
148
+ encoded_inputs["pixel_values"] = images
149
+
150
+ return encoded_inputs
151
+
152
+ def get_overflowing_images(self, images, overflow_to_sample_mapping):
153
+ # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
154
+ images_with_overflow = []
155
+ for sample_idx in overflow_to_sample_mapping:
156
+ images_with_overflow.append(images[sample_idx])
157
+
158
+ if len(images_with_overflow) != len(overflow_to_sample_mapping):
159
+ raise ValueError(
160
+ "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
161
+ f" {len(images_with_overflow)} and {len(overflow_to_sample_mapping)}"
162
+ )
163
+
164
+ return images_with_overflow
165
+
166
+ def batch_decode(self, *args, **kwargs):
167
+ """
168
+ This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
169
+ refer to the docstring of this method for more information.
170
+ """
171
+ return self.tokenizer.batch_decode(*args, **kwargs)
172
+
173
+ def decode(self, *args, **kwargs):
174
+ """
175
+ This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer
176
+ to the docstring of this method for more information.
177
+ """
178
+ return self.tokenizer.decode(*args, **kwargs)
179
+
180
+ @property
181
+ def model_input_names(self):
182
+ return ["input_ids", "bbox", "attention_mask", "pixel_values"]
183
+
184
+ @property
185
+ def feature_extractor_class(self):
186
+ warnings.warn(
187
+ "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
188
+ FutureWarning,
189
+ )
190
+ return self.image_processor_class
191
+
192
+ @property
193
+ def feature_extractor(self):
194
+ warnings.warn(
195
+ "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
196
+ FutureWarning,
197
+ )
198
+ return self.image_processor
evalkit_tf433/lib/python3.10/site-packages/transformers/models/layoutlmv3/tokenization_layoutlmv3_fast.py ADDED
@@ -0,0 +1,855 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """
16
+ Fast tokenization class for LayoutLMv3. It overwrites 2 methods of the slow tokenizer class, namely _batch_encode_plus
17
+ and _encode_plus, in which the Rust tokenizer is used.
18
+ """
19
+
20
+ import json
21
+ from typing import Dict, List, Optional, Tuple, Union
22
+
23
+ from tokenizers import pre_tokenizers, processors
24
+
25
+ from ...tokenization_utils_base import (
26
+ BatchEncoding,
27
+ EncodedInput,
28
+ PaddingStrategy,
29
+ PreTokenizedInput,
30
+ TensorType,
31
+ TextInput,
32
+ TextInputPair,
33
+ TruncationStrategy,
34
+ )
35
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
36
+ from ...utils import add_end_docstrings, logging
37
+ from .tokenization_layoutlmv3 import (
38
+ LAYOUTLMV3_ENCODE_KWARGS_DOCSTRING,
39
+ LAYOUTLMV3_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING,
40
+ LayoutLMv3Tokenizer,
41
+ )
42
+
43
+
44
+ logger = logging.get_logger(__name__)
45
+
46
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
47
+
48
+ PRETRAINED_VOCAB_FILES_MAP = {
49
+ "vocab_file": {
50
+ "microsoft/layoutlmv3-base": "https://huggingface.co/microsoft/layoutlmv3-base/raw/main/vocab.json",
51
+ "microsoft/layoutlmv3-large": "https://huggingface.co/microsoft/layoutlmv3-large/raw/main/vocab.json",
52
+ },
53
+ "merges_file": {
54
+ "microsoft/layoutlmv3-base": "https://huggingface.co/microsoft/layoutlmv3-base/raw/main/merges.txt",
55
+ "microsoft/layoutlmv3-large": "https://huggingface.co/microsoft/layoutlmv3-large/raw/main/merges.txt",
56
+ },
57
+ }
58
+
59
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
60
+ "microsoft/layoutlmv3-base": 512,
61
+ "microsoft/layoutlmv3-large": 512,
62
+ }
63
+
64
+
65
+ class LayoutLMv3TokenizerFast(PreTrainedTokenizerFast):
66
+ r"""
67
+ Construct a "fast" LayoutLMv3 tokenizer (backed by HuggingFace's *tokenizers* library). Based on BPE.
68
+
69
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
70
+ refer to this superclass for more information regarding those methods.
71
+
72
+ Args:
73
+ vocab_file (`str`):
74
+ Path to the vocabulary file.
75
+ merges_file (`str`):
76
+ Path to the merges file.
77
+ errors (`str`, *optional*, defaults to `"replace"`):
78
+ Paradigm to follow when decoding bytes to UTF-8. See
79
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
80
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
81
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
82
+
83
+ <Tip>
84
+
85
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
86
+ sequence. The token used is the `cls_token`.
87
+
88
+ </Tip>
89
+
90
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
91
+ The end of sequence token.
92
+
93
+ <Tip>
94
+
95
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
96
+ The token used is the `sep_token`.
97
+
98
+ </Tip>
99
+
100
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
101
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
102
+ sequence classification or for a text and a question for question answering. It is also used as the last
103
+ token of a sequence built with special tokens.
104
+ cls_token (`str`, *optional*, defaults to `"<s>"`):
105
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
106
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
107
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
108
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
109
+ token instead.
110
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
111
+ The token used for padding, for example when batching sequences of different lengths.
112
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
113
+ The token used for masking values. This is the token used when training this model with masked language
114
+ modeling. This is the token which the model will try to predict.
115
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
116
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
117
+ other word. (RoBERTa tokenizer detect beginning of words by the preceding space).
118
+ trim_offsets (`bool`, *optional*, defaults to `True`):
119
+ Whether the post processing step should trim offsets to avoid including whitespaces.
120
+ cls_token_box (`List[int]`, *optional*, defaults to `[0, 0, 0, 0]`):
121
+ The bounding box to use for the special [CLS] token.
122
+ sep_token_box (`List[int]`, *optional*, defaults to `[0, 0, 0, 0]`):
123
+ The bounding box to use for the special [SEP] token.
124
+ pad_token_box (`List[int]`, *optional*, defaults to `[0, 0, 0, 0]`):
125
+ The bounding box to use for the special [PAD] token.
126
+ pad_token_label (`int`, *optional*, defaults to -100):
127
+ The label to use for padding tokens. Defaults to -100, which is the `ignore_index` of PyTorch's
128
+ CrossEntropyLoss.
129
+ only_label_first_subword (`bool`, *optional*, defaults to `True`):
130
+ Whether or not to only label the first subword, in case word labels are provided.
131
+ """
132
+
133
+ vocab_files_names = VOCAB_FILES_NAMES
134
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
135
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
136
+ model_input_names = ["input_ids", "attention_mask"]
137
+ slow_tokenizer_class = LayoutLMv3Tokenizer
138
+
139
+ def __init__(
140
+ self,
141
+ vocab_file=None,
142
+ merges_file=None,
143
+ tokenizer_file=None,
144
+ errors="replace",
145
+ bos_token="<s>",
146
+ eos_token="</s>",
147
+ sep_token="</s>",
148
+ cls_token="<s>",
149
+ unk_token="<unk>",
150
+ pad_token="<pad>",
151
+ mask_token="<mask>",
152
+ add_prefix_space=True,
153
+ trim_offsets=True,
154
+ cls_token_box=[0, 0, 0, 0],
155
+ sep_token_box=[0, 0, 0, 0],
156
+ pad_token_box=[0, 0, 0, 0],
157
+ pad_token_label=-100,
158
+ only_label_first_subword=True,
159
+ **kwargs,
160
+ ):
161
+ super().__init__(
162
+ vocab_file,
163
+ merges_file,
164
+ tokenizer_file=tokenizer_file,
165
+ errors=errors,
166
+ bos_token=bos_token,
167
+ eos_token=eos_token,
168
+ sep_token=sep_token,
169
+ cls_token=cls_token,
170
+ unk_token=unk_token,
171
+ pad_token=pad_token,
172
+ mask_token=mask_token,
173
+ add_prefix_space=add_prefix_space,
174
+ trim_offsets=trim_offsets,
175
+ cls_token_box=cls_token_box,
176
+ sep_token_box=sep_token_box,
177
+ pad_token_box=pad_token_box,
178
+ pad_token_label=pad_token_label,
179
+ only_label_first_subword=only_label_first_subword,
180
+ **kwargs,
181
+ )
182
+
183
+ pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
184
+ if pre_tok_state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
185
+ pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop("type"))
186
+ pre_tok_state["add_prefix_space"] = add_prefix_space
187
+ self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state)
188
+
189
+ self.add_prefix_space = add_prefix_space
190
+
191
+ tokenizer_component = "post_processor"
192
+ tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)
193
+ if tokenizer_component_instance:
194
+ state = json.loads(tokenizer_component_instance.__getstate__())
195
+
196
+ # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
197
+ if "sep" in state:
198
+ state["sep"] = tuple(state["sep"])
199
+ if "cls" in state:
200
+ state["cls"] = tuple(state["cls"])
201
+
202
+ changes_to_apply = False
203
+
204
+ if state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
205
+ state["add_prefix_space"] = add_prefix_space
206
+ changes_to_apply = True
207
+
208
+ if state.get("trim_offsets", trim_offsets) != trim_offsets:
209
+ state["trim_offsets"] = trim_offsets
210
+ changes_to_apply = True
211
+
212
+ if changes_to_apply:
213
+ component_class = getattr(processors, state.pop("type"))
214
+ new_value = component_class(**state)
215
+ setattr(self.backend_tokenizer, tokenizer_component, new_value)
216
+
217
+ # additional properties
218
+ self.cls_token_box = cls_token_box
219
+ self.sep_token_box = sep_token_box
220
+ self.pad_token_box = pad_token_box
221
+ self.pad_token_label = pad_token_label
222
+ self.only_label_first_subword = only_label_first_subword
223
+
224
+ @add_end_docstrings(LAYOUTLMV3_ENCODE_KWARGS_DOCSTRING, LAYOUTLMV3_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
225
+ # Copied from transformers.models.layoutlmv2.tokenization_layoutlmv2_fast.LayoutLMv2TokenizerFast.__call__
226
+ def __call__(
227
+ self,
228
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
229
+ text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
230
+ boxes: Union[List[List[int]], List[List[List[int]]]] = None,
231
+ word_labels: Optional[Union[List[int], List[List[int]]]] = None,
232
+ add_special_tokens: bool = True,
233
+ padding: Union[bool, str, PaddingStrategy] = False,
234
+ truncation: Union[bool, str, TruncationStrategy] = None,
235
+ max_length: Optional[int] = None,
236
+ stride: int = 0,
237
+ pad_to_multiple_of: Optional[int] = None,
238
+ return_tensors: Optional[Union[str, TensorType]] = None,
239
+ return_token_type_ids: Optional[bool] = None,
240
+ return_attention_mask: Optional[bool] = None,
241
+ return_overflowing_tokens: bool = False,
242
+ return_special_tokens_mask: bool = False,
243
+ return_offsets_mapping: bool = False,
244
+ return_length: bool = False,
245
+ verbose: bool = True,
246
+ **kwargs,
247
+ ) -> BatchEncoding:
248
+ """
249
+ Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
250
+ sequences with word-level normalized bounding boxes and optional labels.
251
+
252
+ Args:
253
+ text (`str`, `List[str]`, `List[List[str]]`):
254
+ The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
255
+ (words of a single example or questions of a batch of examples) or a list of list of strings (batch of
256
+ words).
257
+ text_pair (`List[str]`, `List[List[str]]`):
258
+ The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
259
+ (pretokenized string).
260
+ boxes (`List[List[int]]`, `List[List[List[int]]]`):
261
+ Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.
262
+ word_labels (`List[int]`, `List[List[int]]`, *optional*):
263
+ Word-level integer labels (for token classification tasks such as FUNSD, CORD).
264
+ """
265
+
266
+ # Input type checking for clearer error
267
+ def _is_valid_text_input(t):
268
+ if isinstance(t, str):
269
+ # Strings are fine
270
+ return True
271
+ elif isinstance(t, (list, tuple)):
272
+ # List are fine as long as they are...
273
+ if len(t) == 0:
274
+ # ... empty
275
+ return True
276
+ elif isinstance(t[0], str):
277
+ # ... list of strings
278
+ return True
279
+ elif isinstance(t[0], (list, tuple)):
280
+ # ... list with an empty list or with a list of strings
281
+ return len(t[0]) == 0 or isinstance(t[0][0], str)
282
+ else:
283
+ return False
284
+ else:
285
+ return False
286
+
287
+ if text_pair is not None:
288
+ # in case text + text_pair are provided, text = questions, text_pair = words
289
+ if not _is_valid_text_input(text):
290
+ raise ValueError("text input must of type `str` (single example) or `List[str]` (batch of examples). ")
291
+ if not isinstance(text_pair, (list, tuple)):
292
+ raise ValueError(
293
+ "Words must be of type `List[str]` (single pretokenized example), "
294
+ "or `List[List[str]]` (batch of pretokenized examples)."
295
+ )
296
+ else:
297
+ # in case only text is provided => must be words
298
+ if not isinstance(text, (list, tuple)):
299
+ raise ValueError(
300
+ "Words must be of type `List[str]` (single pretokenized example), "
301
+ "or `List[List[str]]` (batch of pretokenized examples)."
302
+ )
303
+
304
+ if text_pair is not None:
305
+ is_batched = isinstance(text, (list, tuple))
306
+ else:
307
+ is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))
308
+
309
+ words = text if text_pair is None else text_pair
310
+ if boxes is None:
311
+ raise ValueError("You must provide corresponding bounding boxes")
312
+ if is_batched:
313
+ if len(words) != len(boxes):
314
+ raise ValueError("You must provide words and boxes for an equal amount of examples")
315
+ for words_example, boxes_example in zip(words, boxes):
316
+ if len(words_example) != len(boxes_example):
317
+ raise ValueError("You must provide as many words as there are bounding boxes")
318
+ else:
319
+ if len(words) != len(boxes):
320
+ raise ValueError("You must provide as many words as there are bounding boxes")
321
+
322
+ if is_batched:
323
+ if text_pair is not None and len(text) != len(text_pair):
324
+ raise ValueError(
325
+ f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
326
+ f" {len(text_pair)}."
327
+ )
328
+ batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
329
+ is_pair = bool(text_pair is not None)
330
+ return self.batch_encode_plus(
331
+ batch_text_or_text_pairs=batch_text_or_text_pairs,
332
+ is_pair=is_pair,
333
+ boxes=boxes,
334
+ word_labels=word_labels,
335
+ add_special_tokens=add_special_tokens,
336
+ padding=padding,
337
+ truncation=truncation,
338
+ max_length=max_length,
339
+ stride=stride,
340
+ pad_to_multiple_of=pad_to_multiple_of,
341
+ return_tensors=return_tensors,
342
+ return_token_type_ids=return_token_type_ids,
343
+ return_attention_mask=return_attention_mask,
344
+ return_overflowing_tokens=return_overflowing_tokens,
345
+ return_special_tokens_mask=return_special_tokens_mask,
346
+ return_offsets_mapping=return_offsets_mapping,
347
+ return_length=return_length,
348
+ verbose=verbose,
349
+ **kwargs,
350
+ )
351
+ else:
352
+ return self.encode_plus(
353
+ text=text,
354
+ text_pair=text_pair,
355
+ boxes=boxes,
356
+ word_labels=word_labels,
357
+ add_special_tokens=add_special_tokens,
358
+ padding=padding,
359
+ truncation=truncation,
360
+ max_length=max_length,
361
+ stride=stride,
362
+ pad_to_multiple_of=pad_to_multiple_of,
363
+ return_tensors=return_tensors,
364
+ return_token_type_ids=return_token_type_ids,
365
+ return_attention_mask=return_attention_mask,
366
+ return_overflowing_tokens=return_overflowing_tokens,
367
+ return_special_tokens_mask=return_special_tokens_mask,
368
+ return_offsets_mapping=return_offsets_mapping,
369
+ return_length=return_length,
370
+ verbose=verbose,
371
+ **kwargs,
372
+ )
373
+
374
+ @add_end_docstrings(LAYOUTLMV3_ENCODE_KWARGS_DOCSTRING, LAYOUTLMV3_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
375
+ # Copied from transformers.models.layoutlmv2.tokenization_layoutlmv2_fast.LayoutLMv2TokenizerFast.batch_encode_plus
376
+ def batch_encode_plus(
377
+ self,
378
+ batch_text_or_text_pairs: Union[
379
+ List[TextInput],
380
+ List[TextInputPair],
381
+ List[PreTokenizedInput],
382
+ ],
383
+ is_pair: bool = None,
384
+ boxes: Optional[List[List[List[int]]]] = None,
385
+ word_labels: Optional[Union[List[int], List[List[int]]]] = None,
386
+ add_special_tokens: bool = True,
387
+ padding: Union[bool, str, PaddingStrategy] = False,
388
+ truncation: Union[bool, str, TruncationStrategy] = None,
389
+ max_length: Optional[int] = None,
390
+ stride: int = 0,
391
+ pad_to_multiple_of: Optional[int] = None,
392
+ return_tensors: Optional[Union[str, TensorType]] = None,
393
+ return_token_type_ids: Optional[bool] = None,
394
+ return_attention_mask: Optional[bool] = None,
395
+ return_overflowing_tokens: bool = False,
396
+ return_special_tokens_mask: bool = False,
397
+ return_offsets_mapping: bool = False,
398
+ return_length: bool = False,
399
+ verbose: bool = True,
400
+ **kwargs,
401
+ ) -> BatchEncoding:
402
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
403
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
404
+ padding=padding,
405
+ truncation=truncation,
406
+ max_length=max_length,
407
+ pad_to_multiple_of=pad_to_multiple_of,
408
+ verbose=verbose,
409
+ **kwargs,
410
+ )
411
+
412
+ return self._batch_encode_plus(
413
+ batch_text_or_text_pairs=batch_text_or_text_pairs,
414
+ is_pair=is_pair,
415
+ boxes=boxes,
416
+ word_labels=word_labels,
417
+ add_special_tokens=add_special_tokens,
418
+ padding_strategy=padding_strategy,
419
+ truncation_strategy=truncation_strategy,
420
+ max_length=max_length,
421
+ stride=stride,
422
+ pad_to_multiple_of=pad_to_multiple_of,
423
+ return_tensors=return_tensors,
424
+ return_token_type_ids=return_token_type_ids,
425
+ return_attention_mask=return_attention_mask,
426
+ return_overflowing_tokens=return_overflowing_tokens,
427
+ return_special_tokens_mask=return_special_tokens_mask,
428
+ return_offsets_mapping=return_offsets_mapping,
429
+ return_length=return_length,
430
+ verbose=verbose,
431
+ **kwargs,
432
+ )
433
+
434
+ # Copied from transformers.models.layoutlmv2.tokenization_layoutlmv2_fast.LayoutLMv2TokenizerFast.tokenize
435
+ def tokenize(self, text: str, pair: Optional[str] = None, add_special_tokens: bool = False, **kwargs) -> List[str]:
436
+ batched_input = [(text, pair)] if pair else [text]
437
+ encodings = self._tokenizer.encode_batch(
438
+ batched_input, add_special_tokens=add_special_tokens, is_pretokenized=False, **kwargs
439
+ )
440
+
441
+ return encodings[0].tokens
442
+
443
+ @add_end_docstrings(LAYOUTLMV3_ENCODE_KWARGS_DOCSTRING, LAYOUTLMV3_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
444
+ # Copied from transformers.models.layoutlmv2.tokenization_layoutlmv2_fast.LayoutLMv2TokenizerFast.encode_plus
445
+ def encode_plus(
446
+ self,
447
+ text: Union[TextInput, PreTokenizedInput],
448
+ text_pair: Optional[PreTokenizedInput] = None,
449
+ boxes: Optional[List[List[int]]] = None,
450
+ word_labels: Optional[List[int]] = None,
451
+ add_special_tokens: bool = True,
452
+ padding: Union[bool, str, PaddingStrategy] = False,
453
+ truncation: Union[bool, str, TruncationStrategy] = None,
454
+ max_length: Optional[int] = None,
455
+ stride: int = 0,
456
+ pad_to_multiple_of: Optional[int] = None,
457
+ return_tensors: Optional[Union[str, TensorType]] = None,
458
+ return_token_type_ids: Optional[bool] = None,
459
+ return_attention_mask: Optional[bool] = None,
460
+ return_overflowing_tokens: bool = False,
461
+ return_special_tokens_mask: bool = False,
462
+ return_offsets_mapping: bool = False,
463
+ return_length: bool = False,
464
+ verbose: bool = True,
465
+ **kwargs,
466
+ ) -> BatchEncoding:
467
+ """
468
+ Tokenize and prepare for the model a sequence or a pair of sequences. .. warning:: This method is deprecated,
469
+ `__call__` should be used instead.
470
+
471
+ Args:
472
+ text (`str`, `List[str]`, `List[List[str]]`):
473
+ The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
474
+ text_pair (`List[str]` or `List[int]`, *optional*):
475
+ Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a
476
+ list of list of strings (words of a batch of examples).
477
+ """
478
+
479
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
480
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
481
+ padding=padding,
482
+ truncation=truncation,
483
+ max_length=max_length,
484
+ pad_to_multiple_of=pad_to_multiple_of,
485
+ verbose=verbose,
486
+ **kwargs,
487
+ )
488
+
489
+ return self._encode_plus(
490
+ text=text,
491
+ boxes=boxes,
492
+ text_pair=text_pair,
493
+ word_labels=word_labels,
494
+ add_special_tokens=add_special_tokens,
495
+ padding_strategy=padding_strategy,
496
+ truncation_strategy=truncation_strategy,
497
+ max_length=max_length,
498
+ stride=stride,
499
+ pad_to_multiple_of=pad_to_multiple_of,
500
+ return_tensors=return_tensors,
501
+ return_token_type_ids=return_token_type_ids,
502
+ return_attention_mask=return_attention_mask,
503
+ return_overflowing_tokens=return_overflowing_tokens,
504
+ return_special_tokens_mask=return_special_tokens_mask,
505
+ return_offsets_mapping=return_offsets_mapping,
506
+ return_length=return_length,
507
+ verbose=verbose,
508
+ **kwargs,
509
+ )
510
+
511
+ def _batch_encode_plus(
512
+ self,
513
+ batch_text_or_text_pairs: Union[
514
+ List[TextInput],
515
+ List[TextInputPair],
516
+ List[PreTokenizedInput],
517
+ ],
518
+ is_pair: bool = None,
519
+ boxes: Optional[List[List[List[int]]]] = None,
520
+ word_labels: Optional[List[List[int]]] = None,
521
+ add_special_tokens: bool = True,
522
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
523
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
524
+ max_length: Optional[int] = None,
525
+ stride: int = 0,
526
+ pad_to_multiple_of: Optional[int] = None,
527
+ return_tensors: Optional[str] = None,
528
+ return_token_type_ids: Optional[bool] = None,
529
+ return_attention_mask: Optional[bool] = None,
530
+ return_overflowing_tokens: bool = False,
531
+ return_special_tokens_mask: bool = False,
532
+ return_offsets_mapping: bool = False,
533
+ return_length: bool = False,
534
+ verbose: bool = True,
535
+ ) -> BatchEncoding:
536
+ if not isinstance(batch_text_or_text_pairs, list):
537
+ raise TypeError(f"batch_text_or_text_pairs has to be a list (got {type(batch_text_or_text_pairs)})")
538
+
539
+ # Set the truncation and padding strategy and restore the initial configuration
540
+ self.set_truncation_and_padding(
541
+ padding_strategy=padding_strategy,
542
+ truncation_strategy=truncation_strategy,
543
+ max_length=max_length,
544
+ stride=stride,
545
+ pad_to_multiple_of=pad_to_multiple_of,
546
+ )
547
+
548
+ if is_pair:
549
+ batch_text_or_text_pairs = [(text.split(), text_pair) for text, text_pair in batch_text_or_text_pairs]
550
+
551
+ encodings = self._tokenizer.encode_batch(
552
+ batch_text_or_text_pairs,
553
+ add_special_tokens=add_special_tokens,
554
+ is_pretokenized=True, # we set this to True as LayoutLMv3 always expects pretokenized inputs
555
+ )
556
+
557
+ # Convert encoding to dict
558
+ # `Tokens` has type: Tuple[
559
+ # List[Dict[str, List[List[int]]]] or List[Dict[str, 2D-Tensor]],
560
+ # List[EncodingFast]
561
+ # ]
562
+ # with nested dimensions corresponding to batch, overflows, sequence length
563
+ tokens_and_encodings = [
564
+ self._convert_encoding(
565
+ encoding=encoding,
566
+ return_token_type_ids=return_token_type_ids,
567
+ return_attention_mask=return_attention_mask,
568
+ return_overflowing_tokens=return_overflowing_tokens,
569
+ return_special_tokens_mask=return_special_tokens_mask,
570
+ return_offsets_mapping=True
571
+ if word_labels is not None
572
+ else return_offsets_mapping, # we use offsets to create the labels
573
+ return_length=return_length,
574
+ verbose=verbose,
575
+ )
576
+ for encoding in encodings
577
+ ]
578
+
579
+ # Convert the output to have dict[list] from list[dict] and remove the additional overflows dimension
580
+ # From (variable) shape (batch, overflows, sequence length) to ~ (batch * overflows, sequence length)
581
+ # (we say ~ because the number of overflow varies with the example in the batch)
582
+ #
583
+ # To match each overflowing sample with the original sample in the batch
584
+ # we add an overflow_to_sample_mapping array (see below)
585
+ sanitized_tokens = {}
586
+ for key in tokens_and_encodings[0][0].keys():
587
+ stack = [e for item, _ in tokens_and_encodings for e in item[key]]
588
+ sanitized_tokens[key] = stack
589
+ sanitized_encodings = [e for _, item in tokens_and_encodings for e in item]
590
+
591
+ # If returning overflowing tokens, we need to return a mapping
592
+ # from the batch idx to the original sample
593
+ if return_overflowing_tokens:
594
+ overflow_to_sample_mapping = []
595
+ for i, (toks, _) in enumerate(tokens_and_encodings):
596
+ overflow_to_sample_mapping += [i] * len(toks["input_ids"])
597
+ sanitized_tokens["overflow_to_sample_mapping"] = overflow_to_sample_mapping
598
+
599
+ for input_ids in sanitized_tokens["input_ids"]:
600
+ self._eventual_warn_about_too_long_sequence(input_ids, max_length, verbose)
601
+
602
+ # create the token boxes
603
+ token_boxes = []
604
+ for batch_index in range(len(sanitized_tokens["input_ids"])):
605
+ if return_overflowing_tokens:
606
+ original_index = sanitized_tokens["overflow_to_sample_mapping"][batch_index]
607
+ else:
608
+ original_index = batch_index
609
+ token_boxes_example = []
610
+ for id, sequence_id, word_id in zip(
611
+ sanitized_tokens["input_ids"][batch_index],
612
+ sanitized_encodings[batch_index].sequence_ids,
613
+ sanitized_encodings[batch_index].word_ids,
614
+ ):
615
+ if word_id is not None:
616
+ if is_pair and sequence_id == 0:
617
+ token_boxes_example.append(self.pad_token_box)
618
+ else:
619
+ token_boxes_example.append(boxes[original_index][word_id])
620
+ else:
621
+ if id == self.cls_token_id:
622
+ token_boxes_example.append(self.cls_token_box)
623
+ elif id == self.sep_token_id:
624
+ token_boxes_example.append(self.sep_token_box)
625
+ elif id == self.pad_token_id:
626
+ token_boxes_example.append(self.pad_token_box)
627
+ else:
628
+ raise ValueError("Id not recognized")
629
+ token_boxes.append(token_boxes_example)
630
+
631
+ sanitized_tokens["bbox"] = token_boxes
632
+
633
+ # optionally, create the labels
634
+ if word_labels is not None:
635
+ labels = []
636
+ for batch_index in range(len(sanitized_tokens["input_ids"])):
637
+ if return_overflowing_tokens:
638
+ original_index = sanitized_tokens["overflow_to_sample_mapping"][batch_index]
639
+ else:
640
+ original_index = batch_index
641
+ labels_example = []
642
+ previous_token_empty = False
643
+ for id, offset, word_id in zip(
644
+ sanitized_tokens["input_ids"][batch_index],
645
+ sanitized_tokens["offset_mapping"][batch_index],
646
+ sanitized_encodings[batch_index].word_ids,
647
+ ):
648
+ if word_id is not None:
649
+ if self.only_label_first_subword:
650
+ if offset[0] == 0 and not previous_token_empty:
651
+ # Use the real label id for the first token of the word, and padding ids for the remaining tokens
652
+ labels_example.append(word_labels[original_index][word_id])
653
+ else:
654
+ labels_example.append(self.pad_token_label)
655
+ if offset == (0, 0):
656
+ previous_token_empty = True
657
+ else:
658
+ previous_token_empty = False
659
+ else:
660
+ labels_example.append(word_labels[original_index][word_id])
661
+ else:
662
+ labels_example.append(self.pad_token_label)
663
+ labels.append(labels_example)
664
+
665
+ sanitized_tokens["labels"] = labels
666
+ # finally, remove offsets if the user didn't want them
667
+ if not return_offsets_mapping:
668
+ del sanitized_tokens["offset_mapping"]
669
+
670
+ return BatchEncoding(sanitized_tokens, sanitized_encodings, tensor_type=return_tensors)
671
+
672
+ # Copied from transformers.models.layoutlmv2.tokenization_layoutlmv2_fast.LayoutLMv2TokenizerFast._encode_plus
673
+ def _encode_plus(
674
+ self,
675
+ text: Union[TextInput, PreTokenizedInput],
676
+ text_pair: Optional[PreTokenizedInput] = None,
677
+ boxes: Optional[List[List[int]]] = None,
678
+ word_labels: Optional[List[int]] = None,
679
+ add_special_tokens: bool = True,
680
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
681
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
682
+ max_length: Optional[int] = None,
683
+ stride: int = 0,
684
+ pad_to_multiple_of: Optional[int] = None,
685
+ return_tensors: Optional[bool] = None,
686
+ return_token_type_ids: Optional[bool] = None,
687
+ return_attention_mask: Optional[bool] = None,
688
+ return_overflowing_tokens: bool = False,
689
+ return_special_tokens_mask: bool = False,
690
+ return_offsets_mapping: bool = False,
691
+ return_length: bool = False,
692
+ verbose: bool = True,
693
+ **kwargs,
694
+ ) -> BatchEncoding:
695
+ # make it a batched input
696
+ # 2 options:
697
+ # 1) only text, in case text must be a list of str
698
+ # 2) text + text_pair, in which case text = str and text_pair a list of str
699
+ batched_input = [(text, text_pair)] if text_pair else [text]
700
+ batched_boxes = [boxes]
701
+ batched_word_labels = [word_labels] if word_labels is not None else None
702
+ batched_output = self._batch_encode_plus(
703
+ batched_input,
704
+ is_pair=bool(text_pair is not None),
705
+ boxes=batched_boxes,
706
+ word_labels=batched_word_labels,
707
+ add_special_tokens=add_special_tokens,
708
+ padding_strategy=padding_strategy,
709
+ truncation_strategy=truncation_strategy,
710
+ max_length=max_length,
711
+ stride=stride,
712
+ pad_to_multiple_of=pad_to_multiple_of,
713
+ return_tensors=return_tensors,
714
+ return_token_type_ids=return_token_type_ids,
715
+ return_attention_mask=return_attention_mask,
716
+ return_overflowing_tokens=return_overflowing_tokens,
717
+ return_special_tokens_mask=return_special_tokens_mask,
718
+ return_offsets_mapping=return_offsets_mapping,
719
+ return_length=return_length,
720
+ verbose=verbose,
721
+ **kwargs,
722
+ )
723
+
724
+ # Return tensor is None, then we can remove the leading batch axis
725
+ # Overflowing tokens are returned as a batch of output so we keep them in this case
726
+ if return_tensors is None and not return_overflowing_tokens:
727
+ batched_output = BatchEncoding(
728
+ {
729
+ key: value[0] if len(value) > 0 and isinstance(value[0], list) else value
730
+ for key, value in batched_output.items()
731
+ },
732
+ batched_output.encodings,
733
+ )
734
+
735
+ self._eventual_warn_about_too_long_sequence(batched_output["input_ids"], max_length, verbose)
736
+
737
+ return batched_output
738
+
739
+ # Copied from transformers.models.layoutlmv2.tokenization_layoutlmv2_fast.LayoutLMv2TokenizerFast._pad
740
+ def _pad(
741
+ self,
742
+ encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
743
+ max_length: Optional[int] = None,
744
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
745
+ pad_to_multiple_of: Optional[int] = None,
746
+ return_attention_mask: Optional[bool] = None,
747
+ ) -> dict:
748
+ """
749
+ Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
750
+
751
+ Args:
752
+ encoded_inputs:
753
+ Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
754
+ max_length: maximum length of the returned list and optionally padding length (see below).
755
+ Will truncate by taking into account the special tokens.
756
+ padding_strategy: PaddingStrategy to use for padding.
757
+
758
+ - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
759
+ - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
760
+ - PaddingStrategy.DO_NOT_PAD: Do not pad
761
+ The tokenizer padding sides are defined in self.padding_side:
762
+
763
+ - 'left': pads on the left of the sequences
764
+ - 'right': pads on the right of the sequences
765
+ pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
766
+ This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
767
+ `>= 7.5` (Volta).
768
+ return_attention_mask:
769
+ (optional) Set to False to avoid returning attention mask (default: set to model specifics)
770
+ """
771
+ # Load from model defaults
772
+ if return_attention_mask is None:
773
+ return_attention_mask = "attention_mask" in self.model_input_names
774
+
775
+ required_input = encoded_inputs[self.model_input_names[0]]
776
+
777
+ if padding_strategy == PaddingStrategy.LONGEST:
778
+ max_length = len(required_input)
779
+
780
+ if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
781
+ max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
782
+
783
+ needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
784
+
785
+ # Initialize attention mask if not present.
786
+ if return_attention_mask and "attention_mask" not in encoded_inputs:
787
+ encoded_inputs["attention_mask"] = [1] * len(required_input)
788
+
789
+ if needs_to_be_padded:
790
+ difference = max_length - len(required_input)
791
+ if self.padding_side == "right":
792
+ if return_attention_mask:
793
+ encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
794
+ if "token_type_ids" in encoded_inputs:
795
+ encoded_inputs["token_type_ids"] = (
796
+ encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
797
+ )
798
+ if "bbox" in encoded_inputs:
799
+ encoded_inputs["bbox"] = encoded_inputs["bbox"] + [self.pad_token_box] * difference
800
+ if "labels" in encoded_inputs:
801
+ encoded_inputs["labels"] = encoded_inputs["labels"] + [self.pad_token_label] * difference
802
+ if "special_tokens_mask" in encoded_inputs:
803
+ encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
804
+ encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
805
+ elif self.padding_side == "left":
806
+ if return_attention_mask:
807
+ encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
808
+ if "token_type_ids" in encoded_inputs:
809
+ encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
810
+ "token_type_ids"
811
+ ]
812
+ if "bbox" in encoded_inputs:
813
+ encoded_inputs["bbox"] = [self.pad_token_box] * difference + encoded_inputs["bbox"]
814
+ if "labels" in encoded_inputs:
815
+ encoded_inputs["labels"] = [self.pad_token_label] * difference + encoded_inputs["labels"]
816
+ if "special_tokens_mask" in encoded_inputs:
817
+ encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
818
+ encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
819
+ else:
820
+ raise ValueError("Invalid padding strategy:" + str(self.padding_side))
821
+
822
+ return encoded_inputs
823
+
824
+ # Copied from transformers.models.layoutlmv2.tokenization_layoutlmv2_fast.LayoutLMv2TokenizerFast.save_vocabulary
825
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
826
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
827
+ return tuple(files)
828
+
829
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
830
+ output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
831
+ if token_ids_1 is None:
832
+ return output
833
+
834
+ return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
835
+
836
+ def create_token_type_ids_from_sequences(
837
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
838
+ ) -> List[int]:
839
+ """
840
+ Args:
841
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. RoBERTa does not:
842
+ make use of token type ids, therefore a list of zeros is returned.
843
+ token_ids_0 (`List[int]`):
844
+ List of IDs.
845
+ token_ids_1 (`List[int]`, *optional*):
846
+ Optional second list of IDs for sequence pairs.
847
+ Returns:
848
+ `List[int]`: List of zeros.
849
+ """
850
+ sep = [self.sep_token_id]
851
+ cls = [self.cls_token_id]
852
+
853
+ if token_ids_1 is None:
854
+ return len(cls + token_ids_0 + sep) * [0]
855
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
evalkit_tf433/lib/python3.10/site-packages/transformers/models/reformer/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.54 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/reformer/__pycache__/configuration_reformer.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/reformer/__pycache__/convert_reformer_trax_checkpoint_to_pytorch.cpython-310.pyc ADDED
Binary file (4.94 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/reformer/__pycache__/modeling_reformer.cpython-310.pyc ADDED
Binary file (67 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/reformer/__pycache__/tokenization_reformer.cpython-310.pyc ADDED
Binary file (6.89 kB). View file
 
evalkit_tf433/lib/python3.10/site-packages/transformers/models/reformer/__pycache__/tokenization_reformer_fast.cpython-310.pyc ADDED
Binary file (4.13 kB). View file