AdithyaSK HF Staff commited on
Commit
ac77771
·
verified ·
1 Parent(s): 4960275

Stage Harbor release files 15001-15500

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fastspeech2_conformer/convert_hifigan.py +134 -0
  2. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fastspeech2_conformer/convert_model_with_hifigan.py +102 -0
  3. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fastspeech2_conformer/modeling_fastspeech2_conformer.py +1697 -0
  4. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fastspeech2_conformer/tokenization_fastspeech2_conformer.py +188 -0
  5. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flaubert/__init__.py +29 -0
  6. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flaubert/configuration_flaubert.py +235 -0
  7. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flaubert/modeling_flaubert.py +1314 -0
  8. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flaubert/modeling_tf_flaubert.py +1344 -0
  9. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flaubert/tokenization_flaubert.py +568 -0
  10. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flava/__init__.py +30 -0
  11. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flava/configuration_flava.py +701 -0
  12. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flava/convert_dalle_to_flava_codebook.py +102 -0
  13. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flava/convert_flava_original_pytorch_to_hf.py +99 -0
  14. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flava/feature_extraction_flava.py +36 -0
  15. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flava/image_processing_flava.py +703 -0
  16. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flava/modeling_flava.py +2115 -0
  17. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flava/processing_flava.py +168 -0
  18. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fnet/__init__.py +29 -0
  19. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fnet/configuration_fnet.py +119 -0
  20. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fnet/convert_fnet_original_flax_checkpoint_to_pytorch.py +156 -0
  21. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fnet/modeling_fnet.py +1199 -0
  22. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fnet/tokenization_fnet.py +341 -0
  23. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fnet/tokenization_fnet_fast.py +189 -0
  24. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/focalnet/__init__.py +27 -0
  25. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/focalnet/configuration_focalnet.py +164 -0
  26. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/focalnet/convert_focalnet_to_hf_format.py +237 -0
  27. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/focalnet/modeling_focalnet.py +1038 -0
  28. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fsmt/__init__.py +28 -0
  29. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fsmt/configuration_fsmt.py +218 -0
  30. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fsmt/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py +280 -0
  31. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fsmt/modeling_fsmt.py +1369 -0
  32. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fsmt/tokenization_fsmt.py +521 -0
  33. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/funnel/__init__.py +31 -0
  34. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/funnel/configuration_funnel.py +166 -0
  35. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/funnel/convert_funnel_original_tf_checkpoint_to_pytorch.py +67 -0
  36. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/funnel/modeling_funnel.py +1608 -0
  37. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/funnel/modeling_tf_funnel.py +1880 -0
  38. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/funnel/tokenization_funnel.py +542 -0
  39. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/funnel/tokenization_funnel_fast.py +203 -0
  40. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fuyu/__init__.py +29 -0
  41. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fuyu/configuration_fuyu.py +210 -0
  42. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fuyu/convert_fuyu_model_weights_to_hf.py +134 -0
  43. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fuyu/image_processing_fuyu.py +724 -0
  44. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fuyu/modeling_fuyu.py +391 -0
  45. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fuyu/processing_fuyu.py +726 -0
  46. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/gemma/__init__.py +30 -0
  47. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/gemma/configuration_gemma.py +147 -0
  48. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/gemma/convert_gemma_weights_to_hf.py +206 -0
  49. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/gemma/modeling_flax_gemma.py +777 -0
  50. tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/gemma/modeling_gemma.py +1068 -0
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fastspeech2_conformer/convert_hifigan.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Convert FastSpeech2Conformer HiFi-GAN checkpoint."""
16
+
17
+ import argparse
18
+ from pathlib import Path
19
+
20
+ import torch
21
+ import yaml
22
+
23
+ from transformers import FastSpeech2ConformerHifiGan, FastSpeech2ConformerHifiGanConfig, logging
24
+
25
+
26
+ logging.set_verbosity_info()
27
+ logger = logging.get_logger("transformers.models.FastSpeech2Conformer")
28
+
29
+
30
+ def load_weights(checkpoint, hf_model, config):
31
+ vocoder_key_prefix = "tts.generator.vocoder."
32
+ checkpoint = {k.replace(vocoder_key_prefix, ""): v for k, v in checkpoint.items() if vocoder_key_prefix in k}
33
+
34
+ hf_model.apply_weight_norm()
35
+
36
+ hf_model.conv_pre.weight_g.data = checkpoint["input_conv.weight_g"]
37
+ hf_model.conv_pre.weight_v.data = checkpoint["input_conv.weight_v"]
38
+ hf_model.conv_pre.bias.data = checkpoint["input_conv.bias"]
39
+
40
+ for i in range(len(config.upsample_rates)):
41
+ hf_model.upsampler[i].weight_g.data = checkpoint[f"upsamples.{i}.1.weight_g"]
42
+ hf_model.upsampler[i].weight_v.data = checkpoint[f"upsamples.{i}.1.weight_v"]
43
+ hf_model.upsampler[i].bias.data = checkpoint[f"upsamples.{i}.1.bias"]
44
+
45
+ for i in range(len(config.upsample_rates) * len(config.resblock_kernel_sizes)):
46
+ for j in range(len(config.resblock_dilation_sizes)):
47
+ hf_model.resblocks[i].convs1[j].weight_g.data = checkpoint[f"blocks.{i}.convs1.{j}.1.weight_g"]
48
+ hf_model.resblocks[i].convs1[j].weight_v.data = checkpoint[f"blocks.{i}.convs1.{j}.1.weight_v"]
49
+ hf_model.resblocks[i].convs1[j].bias.data = checkpoint[f"blocks.{i}.convs1.{j}.1.bias"]
50
+
51
+ hf_model.resblocks[i].convs2[j].weight_g.data = checkpoint[f"blocks.{i}.convs2.{j}.1.weight_g"]
52
+ hf_model.resblocks[i].convs2[j].weight_v.data = checkpoint[f"blocks.{i}.convs2.{j}.1.weight_v"]
53
+ hf_model.resblocks[i].convs2[j].bias.data = checkpoint[f"blocks.{i}.convs2.{j}.1.bias"]
54
+
55
+ hf_model.conv_post.weight_g.data = checkpoint["output_conv.1.weight_g"]
56
+ hf_model.conv_post.weight_v.data = checkpoint["output_conv.1.weight_v"]
57
+ hf_model.conv_post.bias.data = checkpoint["output_conv.1.bias"]
58
+
59
+ hf_model.remove_weight_norm()
60
+
61
+
62
+ def remap_hifigan_yaml_config(yaml_config_path):
63
+ with Path(yaml_config_path).open("r", encoding="utf-8") as f:
64
+ args = yaml.safe_load(f)
65
+ args = argparse.Namespace(**args)
66
+
67
+ vocoder_type = args.tts_conf["vocoder_type"]
68
+ if vocoder_type != "hifigan_generator":
69
+ raise TypeError(f"Vocoder config must be for `hifigan_generator`, but got {vocoder_type}")
70
+
71
+ remapped_dict = {}
72
+ vocoder_params = args.tts_conf["vocoder_params"]
73
+
74
+ # espnet_config_key -> hf_config_key
75
+ key_mappings = {
76
+ "channels": "upsample_initial_channel",
77
+ "in_channels": "model_in_dim",
78
+ "resblock_dilations": "resblock_dilation_sizes",
79
+ "resblock_kernel_sizes": "resblock_kernel_sizes",
80
+ "upsample_kernel_sizes": "upsample_kernel_sizes",
81
+ "upsample_scales": "upsample_rates",
82
+ }
83
+ for espnet_config_key, hf_config_key in key_mappings.items():
84
+ remapped_dict[hf_config_key] = vocoder_params[espnet_config_key]
85
+ remapped_dict["sampling_rate"] = args.tts_conf["sampling_rate"]
86
+ remapped_dict["normalize_before"] = False
87
+ remapped_dict["leaky_relu_slope"] = vocoder_params["nonlinear_activation_params"]["negative_slope"]
88
+
89
+ return remapped_dict
90
+
91
+
92
+ @torch.no_grad()
93
+ def convert_hifigan_checkpoint(
94
+ checkpoint_path,
95
+ pytorch_dump_folder_path,
96
+ yaml_config_path=None,
97
+ repo_id=None,
98
+ ):
99
+ if yaml_config_path is not None:
100
+ config_kwargs = remap_hifigan_yaml_config(yaml_config_path)
101
+ config = FastSpeech2ConformerHifiGanConfig(**config_kwargs)
102
+ else:
103
+ config = FastSpeech2ConformerHifiGanConfig()
104
+
105
+ model = FastSpeech2ConformerHifiGan(config)
106
+
107
+ orig_checkpoint = torch.load(checkpoint_path)
108
+ load_weights(orig_checkpoint, model, config)
109
+
110
+ model.save_pretrained(pytorch_dump_folder_path)
111
+
112
+ if repo_id:
113
+ print("Pushing to the hub...")
114
+ model.push_to_hub(repo_id)
115
+
116
+
117
+ if __name__ == "__main__":
118
+ parser = argparse.ArgumentParser()
119
+ parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint")
120
+ parser.add_argument("--yaml_config_path", default=None, type=str, help="Path to config.yaml of model to convert")
121
+ parser.add_argument(
122
+ "--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model."
123
+ )
124
+ parser.add_argument(
125
+ "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub."
126
+ )
127
+
128
+ args = parser.parse_args()
129
+ convert_hifigan_checkpoint(
130
+ args.checkpoint_path,
131
+ args.pytorch_dump_folder_path,
132
+ args.yaml_config_path,
133
+ args.push_to_hub,
134
+ )
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fastspeech2_conformer/convert_model_with_hifigan.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Convert FastSpeech2Conformer checkpoint."""
16
+
17
+ import argparse
18
+
19
+ import torch
20
+
21
+ from transformers import (
22
+ FastSpeech2ConformerConfig,
23
+ FastSpeech2ConformerHifiGan,
24
+ FastSpeech2ConformerHifiGanConfig,
25
+ FastSpeech2ConformerModel,
26
+ FastSpeech2ConformerWithHifiGan,
27
+ FastSpeech2ConformerWithHifiGanConfig,
28
+ logging,
29
+ )
30
+
31
+ from .convert_fastspeech2_conformer_original_pytorch_checkpoint_to_pytorch import (
32
+ convert_espnet_state_dict_to_hf,
33
+ remap_model_yaml_config,
34
+ )
35
+ from .convert_hifigan import load_weights, remap_hifigan_yaml_config
36
+
37
+
38
+ logging.set_verbosity_info()
39
+ logger = logging.get_logger("transformers.models.FastSpeech2Conformer")
40
+
41
+
42
+ def convert_FastSpeech2ConformerWithHifiGan_checkpoint(
43
+ checkpoint_path,
44
+ yaml_config_path,
45
+ pytorch_dump_folder_path,
46
+ repo_id=None,
47
+ ):
48
+ # Prepare the model
49
+ model_params, *_ = remap_model_yaml_config(yaml_config_path)
50
+ model_config = FastSpeech2ConformerConfig(**model_params)
51
+
52
+ model = FastSpeech2ConformerModel(model_config)
53
+
54
+ espnet_checkpoint = torch.load(checkpoint_path)
55
+ hf_compatible_state_dict = convert_espnet_state_dict_to_hf(espnet_checkpoint)
56
+ model.load_state_dict(hf_compatible_state_dict)
57
+
58
+ # Prepare the vocoder
59
+ config_kwargs = remap_hifigan_yaml_config(yaml_config_path)
60
+ vocoder_config = FastSpeech2ConformerHifiGanConfig(**config_kwargs)
61
+
62
+ vocoder = FastSpeech2ConformerHifiGan(vocoder_config)
63
+ load_weights(espnet_checkpoint, vocoder, vocoder_config)
64
+
65
+ # Prepare the model + vocoder
66
+ config = FastSpeech2ConformerWithHifiGanConfig.from_sub_model_configs(model_config, vocoder_config)
67
+ with_hifigan_model = FastSpeech2ConformerWithHifiGan(config)
68
+ with_hifigan_model.model = model
69
+ with_hifigan_model.vocoder = vocoder
70
+
71
+ with_hifigan_model.save_pretrained(pytorch_dump_folder_path)
72
+
73
+ if repo_id:
74
+ print("Pushing to the hub...")
75
+ with_hifigan_model.push_to_hub(repo_id)
76
+
77
+
78
+ if __name__ == "__main__":
79
+ parser = argparse.ArgumentParser()
80
+ parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint")
81
+ parser.add_argument(
82
+ "--yaml_config_path", required=True, default=None, type=str, help="Path to config.yaml of model to convert"
83
+ )
84
+ parser.add_argument(
85
+ "--pytorch_dump_folder_path",
86
+ required=True,
87
+ default=None,
88
+ type=str,
89
+ help="Path to the output `FastSpeech2ConformerModel` PyTorch model.",
90
+ )
91
+ parser.add_argument(
92
+ "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub."
93
+ )
94
+
95
+ args = parser.parse_args()
96
+
97
+ convert_FastSpeech2ConformerWithHifiGan_checkpoint(
98
+ args.checkpoint_path,
99
+ args.yaml_config_path,
100
+ args.pytorch_dump_folder_path,
101
+ args.push_to_hub,
102
+ )
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fastspeech2_conformer/modeling_fastspeech2_conformer.py ADDED
@@ -0,0 +1,1697 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Espnet authors, IMS Toucan authors, 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 FastSpeech2Conformer model."""
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from typing import Optional, Tuple, Union
20
+
21
+ import torch
22
+ from torch import nn
23
+
24
+ from ...modeling_outputs import BaseModelOutput
25
+ from ...modeling_utils import PreTrainedModel
26
+ from ...utils import ModelOutput, add_start_docstrings, logging, replace_return_docstrings
27
+ from .configuration_fastspeech2_conformer import (
28
+ FastSpeech2ConformerConfig,
29
+ FastSpeech2ConformerHifiGanConfig,
30
+ FastSpeech2ConformerWithHifiGanConfig,
31
+ )
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ @dataclass
38
+ class FastSpeech2ConformerModelOutput(ModelOutput):
39
+ """
40
+ Output type of [`FastSpeech2ConformerModel`].
41
+
42
+ Args:
43
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
44
+ Spectrogram generation loss.
45
+ spectrogram (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_bins)`):
46
+ The predicted spectrogram.
47
+ encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
48
+ Sequence of hidden-states at the output of the last layer of the encoder of the model.
49
+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
50
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
51
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
52
+
53
+ Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
54
+ encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
55
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
56
+ sequence_length)`.
57
+
58
+ Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
59
+ self-attention heads.
60
+ decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
61
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
62
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
63
+
64
+ Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
65
+ decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
66
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
67
+ sequence_length)`.
68
+
69
+ Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
70
+ self-attention heads.
71
+ duration_outputs (`torch.LongTensor` of shape `(batch_size, max_text_length + 1)`, *optional*):
72
+ Outputs of the duration predictor.
73
+ pitch_outputs (`torch.FloatTensor` of shape `(batch_size, max_text_length + 1, 1)`, *optional*):
74
+ Outputs of the pitch predictor.
75
+ energy_outputs (`torch.FloatTensor` of shape `(batch_size, max_text_length + 1, 1)`, *optional*):
76
+ Outputs of the energy predictor.
77
+
78
+ """
79
+
80
+ loss: Optional[torch.FloatTensor] = None
81
+ spectrogram: torch.FloatTensor = None
82
+ encoder_last_hidden_state: Optional[torch.FloatTensor] = None
83
+ encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
84
+ encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
85
+ decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
86
+ decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
87
+ duration_outputs: torch.LongTensor = None
88
+ pitch_outputs: torch.FloatTensor = None
89
+ energy_outputs: torch.FloatTensor = None
90
+
91
+
92
+ @dataclass
93
+ class FastSpeech2ConformerWithHifiGanOutput(FastSpeech2ConformerModelOutput):
94
+ """
95
+ Output type of [`FastSpeech2ConformerWithHifiGan`].
96
+
97
+ Args:
98
+ waveform (`torch.FloatTensor` of shape `(batch_size, audio_length)`):
99
+ Speech output as a result of passing the predicted mel spectrogram through the vocoder.
100
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
101
+ Spectrogram generation loss.
102
+ spectrogram (`torch.FloatTensor` of shape `(batch_size, sequence_length, num_bins)`):
103
+ The predicted spectrogram.
104
+ encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
105
+ Sequence of hidden-states at the output of the last layer of the encoder of the model.
106
+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
107
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
108
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
109
+
110
+ Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
111
+ encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
112
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
113
+ sequence_length)`.
114
+
115
+ Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
116
+ self-attention heads.
117
+ decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
118
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
119
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
120
+
121
+ Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
122
+ decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
123
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
124
+ sequence_length)`.
125
+
126
+ Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
127
+ self-attention heads.
128
+ duration_outputs (`torch.LongTensor` of shape `(batch_size, max_text_length + 1)`, *optional*):
129
+ Outputs of the duration predictor.
130
+ pitch_outputs (`torch.FloatTensor` of shape `(batch_size, max_text_length + 1, 1)`, *optional*):
131
+ Outputs of the pitch predictor.
132
+ energy_outputs (`torch.FloatTensor` of shape `(batch_size, max_text_length + 1, 1)`, *optional*):
133
+ Outputs of the energy predictor.
134
+ """
135
+
136
+ waveform: torch.FloatTensor = None
137
+
138
+
139
+ _CONFIG_FOR_DOC = "FastSpeech2ConformerConfig"
140
+
141
+ FASTSPEECH2_CONFORMER_START_DOCSTRING = r"""
142
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
143
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
144
+ etc.)
145
+
146
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
147
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
148
+ and behavior.
149
+
150
+ Parameters:
151
+ config ([`FastSpeech2ConformerConfig`]):
152
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
153
+ load the weights associated with the model, only the configuration. Check out the
154
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
155
+ """
156
+
157
+
158
+ HIFIGAN_START_DOCSTRING = r"""
159
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
160
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
161
+ etc.)
162
+
163
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
164
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
165
+ and behavior.
166
+
167
+ Parameters:
168
+ config ([`FastSpeech2ConformerConfig`]):
169
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
170
+ load the weights associated with the model, only the configuration. Check out the
171
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
172
+ """
173
+
174
+ FASTSPEECH2_CONFORMER_WITH_HIFIGAN_START_DOCSTRING = r"""
175
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
176
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
177
+ etc.)
178
+
179
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
180
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
181
+ and behavior.
182
+
183
+ Parameters:
184
+ config ([`FastSpeech2ConformerWithHifiGanConfig`]):
185
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
186
+ load the weights associated with the model, only the configuration. Check out the
187
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
188
+ """
189
+
190
+
191
+ def length_regulator(encoded_embeddings, duration_labels, speaking_speed=1.0):
192
+ """
193
+ Length regulator for feed-forward Transformer.
194
+
195
+ This is the length regulator module described in `FastSpeech: Fast, Robust and Controllable Text to Speech`
196
+ https://arxiv.org/pdf/1905.09263.pdf. The length regulator expands char or phoneme-level embedding features to
197
+ frame-level by repeating each feature based on the corresponding predicted durations.
198
+
199
+ Args:
200
+ encoded_embeddings (`torch.Tensor` of shape `(batch_size, max_text_length, embedding_dim)`):
201
+ Batch of sequences of char or phoneme embeddings.
202
+ duration_labels (`torch.LongTensor` of shape `(batch_size, time)`):
203
+ Batch of durations of each frame.
204
+ speaking_speed (`float`, *optional*, defaults to 1.0):
205
+ Value to control speed of speech.
206
+
207
+ Returns:
208
+ `torch.Tensor`:
209
+ Replicated input tensor based on durations (batch_size, time*, embedding_dim).
210
+ """
211
+
212
+ if speaking_speed <= 0:
213
+ raise ValueError("`speaking_speed` must be greater than 0.")
214
+ elif speaking_speed != 1.0:
215
+ duration_labels = torch.round(duration_labels.float() * speaking_speed).long()
216
+
217
+ if duration_labels.sum() == 0:
218
+ duration_labels[duration_labels.sum(dim=1).eq(0)] = 1
219
+
220
+ # Calculate the maximum length needed
221
+ max_len = torch.sum(duration_labels, dim=1).max()
222
+
223
+ # Create a padded tensor to hold the results
224
+ hidden_states = torch.zeros(
225
+ (encoded_embeddings.size(0), max_len, encoded_embeddings.size(2)),
226
+ dtype=torch.float,
227
+ device=encoded_embeddings.device,
228
+ )
229
+
230
+ # Loop through the batch and fill in the data
231
+ for i, (encoded_embedding, target_duration) in enumerate(zip(encoded_embeddings, duration_labels)):
232
+ repeated = torch.repeat_interleave(encoded_embedding, target_duration, dim=0)
233
+ hidden_states[i, : repeated.size(0)] = repeated
234
+
235
+ return hidden_states
236
+
237
+
238
+ class FastSpeech2ConformerDurationPredictor(nn.Module):
239
+ """
240
+ Duration predictor module.
241
+
242
+ This is a module of duration predictor described in the paper 'FastSpeech: Fast, Robust and Controllable Text to
243
+ Speech' https://arxiv.org/pdf/1905.09263.pdf The duration predictor predicts a duration of each frame in log domain
244
+ from the hidden embeddings of encoder.
245
+
246
+ Note:
247
+ The calculation domain of outputs is different between in `forward` and in `inference`. In `forward`, the
248
+ outputs are calculated in log domain but in `inference`, those are calculated in linear domain.
249
+
250
+ """
251
+
252
+ def __init__(self, config: FastSpeech2ConformerConfig):
253
+ super().__init__()
254
+
255
+ self.conv_layers = nn.ModuleList()
256
+ self.log_domain_offset = 1.0
257
+
258
+ for layer_idx in range(config.duration_predictor_layers):
259
+ num_chans = config.duration_predictor_channels
260
+ input_channels = config.hidden_size if layer_idx == 0 else num_chans
261
+ layer = FastSpeech2ConformerPredictorLayer(
262
+ input_channels,
263
+ num_chans,
264
+ config.duration_predictor_kernel_size,
265
+ config.duration_predictor_dropout_rate,
266
+ )
267
+ self.conv_layers.append(layer)
268
+ self.linear = nn.Linear(config.duration_predictor_channels, 1)
269
+
270
+ def forward(self, encoder_hidden_states):
271
+ """
272
+ Args:
273
+ hidden_states (`torch.Tensor` of shape `(batch_size, max_text_length, input_dim)`):
274
+ Batch of input sequences.
275
+ padding_masks (`torch.ByteTensor` of shape `(batch_size, max_text_length)`, *optional*):
276
+ Batch of masks indicating padded part.
277
+
278
+ Returns:
279
+ `torch.Tensor`: Batch of predicted durations in log domain `(batch_size, max_text_length)`.
280
+
281
+ """
282
+ # (batch_size, input_dim, max_text_length)
283
+ hidden_states = encoder_hidden_states.transpose(1, -1)
284
+ for layer in self.conv_layers:
285
+ hidden_states = layer(hidden_states)
286
+
287
+ # NOTE: calculate in log domain, (batch_size, max_text_length)
288
+ hidden_states = self.linear(hidden_states.transpose(1, -1)).squeeze(-1)
289
+
290
+ if not self.training:
291
+ # NOTE: calculate in linear domain
292
+ hidden_states = torch.clamp(torch.round(hidden_states.exp() - self.log_domain_offset), min=0).long()
293
+
294
+ return hidden_states
295
+
296
+
297
+ # Copied from transformers.models.speecht5.modeling_speecht5.SpeechT5BatchNormConvLayer
298
+ class FastSpeech2ConformerBatchNormConvLayer(nn.Module):
299
+ def __init__(self, config, layer_id=0):
300
+ super().__init__()
301
+
302
+ if layer_id == 0:
303
+ in_conv_dim = config.num_mel_bins
304
+ else:
305
+ in_conv_dim = config.speech_decoder_postnet_units
306
+
307
+ if layer_id == config.speech_decoder_postnet_layers - 1:
308
+ out_conv_dim = config.num_mel_bins
309
+ else:
310
+ out_conv_dim = config.speech_decoder_postnet_units
311
+
312
+ self.conv = nn.Conv1d(
313
+ in_conv_dim,
314
+ out_conv_dim,
315
+ kernel_size=config.speech_decoder_postnet_kernel,
316
+ stride=1,
317
+ padding=(config.speech_decoder_postnet_kernel - 1) // 2,
318
+ bias=False,
319
+ )
320
+ self.batch_norm = nn.BatchNorm1d(out_conv_dim)
321
+
322
+ if layer_id < config.speech_decoder_postnet_layers - 1:
323
+ self.activation = nn.Tanh()
324
+ else:
325
+ self.activation = None
326
+
327
+ self.dropout = nn.Dropout(config.speech_decoder_postnet_dropout)
328
+
329
+ def forward(self, hidden_states):
330
+ hidden_states = self.conv(hidden_states)
331
+ hidden_states = self.batch_norm(hidden_states)
332
+ if self.activation is not None:
333
+ hidden_states = self.activation(hidden_states)
334
+ hidden_states = self.dropout(hidden_states)
335
+ return hidden_states
336
+
337
+
338
+ class FastSpeech2ConformerSpeechDecoderPostnet(nn.Module):
339
+ def __init__(self, config):
340
+ super().__init__()
341
+ self.config = config
342
+ self.feat_out = nn.Linear(config.hidden_size, config.num_mel_bins * config.reduction_factor)
343
+ self.layers = nn.ModuleList(
344
+ [FastSpeech2ConformerBatchNormConvLayer(config, i) for i in range(config.speech_decoder_postnet_layers)]
345
+ )
346
+
347
+ def forward(self, hidden_states: torch.Tensor):
348
+ outputs_before_postnet = self.feat_out(hidden_states).view(hidden_states.size(0), -1, self.config.num_mel_bins)
349
+ layer_output = outputs_before_postnet.transpose(1, 2)
350
+ for layer in self.layers:
351
+ layer_output = layer(layer_output)
352
+ outputs_after_postnet = outputs_before_postnet + layer_output.transpose(1, 2)
353
+ return outputs_before_postnet, outputs_after_postnet
354
+
355
+
356
+ class FastSpeech2ConformerPredictorLayer(nn.Module):
357
+ def __init__(self, input_channels, num_chans, kernel_size, dropout_rate):
358
+ super().__init__()
359
+ self.conv = nn.Conv1d(
360
+ input_channels,
361
+ num_chans,
362
+ kernel_size,
363
+ stride=1,
364
+ padding=(kernel_size - 1) // 2,
365
+ )
366
+ self.activation = nn.ReLU()
367
+ self.layer_norm = nn.LayerNorm(num_chans)
368
+ self.dropout = nn.Dropout(dropout_rate)
369
+
370
+ def forward(self, hidden_states):
371
+ hidden_states = self.conv(hidden_states)
372
+ hidden_states = self.activation(hidden_states)
373
+
374
+ # Perform layer norm on dimension 1
375
+ hidden_states = hidden_states.transpose(1, -1)
376
+ hidden_states = self.layer_norm(hidden_states)
377
+ hidden_states = hidden_states.transpose(1, -1)
378
+
379
+ hidden_states = self.dropout(hidden_states)
380
+
381
+ return hidden_states
382
+
383
+
384
+ class FastSpeech2ConformerVariancePredictor(nn.Module):
385
+ def __init__(
386
+ self,
387
+ config: FastSpeech2ConformerConfig,
388
+ num_layers=2,
389
+ num_chans=384,
390
+ kernel_size=3,
391
+ dropout_rate=0.5,
392
+ ):
393
+ """
394
+ Initilize variance predictor module.
395
+
396
+ Args:
397
+ input_dim (`int`): Input dimension.
398
+ num_layers (`int`, *optional*, defaults to 2): Number of convolutional layers.
399
+ num_chans (`int`, *optional*, defaults to 384): Number of channels of convolutional layers.
400
+ kernel_size (`int`, *optional*, defaults to 3): Kernel size of convolutional layers.
401
+ dropout_rate (`float`, *optional*, defaults to 0.5): Dropout rate.
402
+ """
403
+ super().__init__()
404
+ self.conv_layers = nn.ModuleList()
405
+ for idx in range(num_layers):
406
+ input_channels = config.hidden_size if idx == 0 else num_chans
407
+ layer = FastSpeech2ConformerPredictorLayer(input_channels, num_chans, kernel_size, dropout_rate)
408
+ self.conv_layers.append(layer)
409
+ self.linear = nn.Linear(num_chans, 1)
410
+
411
+ def forward(self, encoder_hidden_states, padding_masks=None):
412
+ """
413
+ Calculate forward propagation.
414
+
415
+ Args:
416
+ encoder_hidden_states (`torch.Tensor` of shape `(batch_size, max_text_length, input_dim)`):
417
+ Batch of input sequences.
418
+ padding_masks (`torch.ByteTensor` of shape `(batch_size, max_text_length)`, *optional*):
419
+ Batch of masks indicating padded part.
420
+
421
+ Returns:
422
+ Tensor: Batch of predicted sequences `(batch_size, max_text_length, 1)`.
423
+ """
424
+ # (batch_size, input_dim, max_text_length)
425
+ hidden_states = encoder_hidden_states.transpose(1, -1)
426
+ for layer in self.conv_layers:
427
+ hidden_states = layer(hidden_states)
428
+
429
+ hidden_states = self.linear(hidden_states.transpose(1, 2))
430
+
431
+ if padding_masks is not None:
432
+ hidden_states = hidden_states.masked_fill(padding_masks, 0.0)
433
+
434
+ return hidden_states
435
+
436
+
437
+ class FastSpeech2ConformerVarianceEmbedding(nn.Module):
438
+ def __init__(
439
+ self,
440
+ in_channels=1,
441
+ out_channels=384,
442
+ kernel_size=1,
443
+ padding=0,
444
+ dropout_rate=0.0,
445
+ ):
446
+ super().__init__()
447
+ self.conv = nn.Conv1d(
448
+ in_channels=in_channels,
449
+ out_channels=out_channels,
450
+ kernel_size=kernel_size,
451
+ padding=padding,
452
+ )
453
+ self.dropout = nn.Dropout(dropout_rate)
454
+
455
+ def forward(self, hidden_states):
456
+ hidden_states = hidden_states.transpose(1, 2)
457
+ hidden_states = self.conv(hidden_states)
458
+ hidden_states = self.dropout(hidden_states)
459
+ hidden_states = hidden_states.transpose(1, 2)
460
+ return hidden_states
461
+
462
+
463
+ class FastSpeech2ConformerAttention(nn.Module):
464
+ """
465
+ Multi-Head attention layer with relative position encoding. Details can be found in
466
+ https://github.com/espnet/espnet/pull/2816. Paper: https://arxiv.org/abs/1901.02860.
467
+ """
468
+
469
+ def __init__(self, config: FastSpeech2ConformerConfig, module_config):
470
+ """Construct an FastSpeech2ConformerAttention object."""
471
+ super().__init__()
472
+ # We assume d_v always equals dim_key
473
+ self.num_heads = module_config["num_attention_heads"]
474
+ self.hidden_size = config.hidden_size
475
+ self.dim_key = self.hidden_size // self.num_heads
476
+ self.head_dim = self.hidden_size // self.num_heads
477
+ self.linear_q = nn.Linear(self.hidden_size, self.hidden_size)
478
+ self.linear_k = nn.Linear(self.hidden_size, self.hidden_size)
479
+ self.linear_v = nn.Linear(self.hidden_size, self.hidden_size)
480
+ self.linear_out = nn.Linear(self.hidden_size, self.hidden_size)
481
+ self.dropout = nn.Dropout(p=module_config["attention_dropout_rate"])
482
+
483
+ # linear transformation for positional encoding
484
+ self.linear_pos = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
485
+ # these two learnable bias are used in matrix c and matrix d
486
+ # as described in https://arxiv.org/abs/1901.02860 Section 3.3
487
+ self.pos_bias_u = nn.Parameter(torch.Tensor(self.num_heads, self.head_dim))
488
+ self.pos_bias_v = nn.Parameter(torch.Tensor(self.num_heads, self.head_dim))
489
+
490
+ def shift_relative_position_tensor(self, pos_tensor):
491
+ """
492
+ Args:
493
+ pos_tensor (torch.Tensor of shape (batch_size, head, time1, 2*time1-1)): Input tensor.
494
+ """
495
+ zero_pad = torch.zeros((*pos_tensor.size()[:3], 1), device=pos_tensor.device, dtype=pos_tensor.dtype)
496
+ pos_tensor_padded = torch.cat([zero_pad, pos_tensor], dim=-1)
497
+
498
+ pos_tensor_padded = pos_tensor_padded.view(*pos_tensor.size()[:2], pos_tensor.size(3) + 1, pos_tensor.size(2))
499
+ # only keep the positions from 0 to time2
500
+ pos_tensor = pos_tensor_padded[:, :, 1:].view_as(pos_tensor)[:, :, :, : pos_tensor.size(-1) // 2 + 1]
501
+
502
+ return pos_tensor
503
+
504
+ def forward(
505
+ self,
506
+ hidden_states: torch.Tensor,
507
+ attention_mask: Optional[torch.Tensor] = None,
508
+ pos_emb: Optional[torch.Tensor] = None,
509
+ output_attentions: Optional[torch.Tensor] = False,
510
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
511
+ """
512
+ Compute 'Scaled Dot Product Attention' with rel. positional encoding.
513
+
514
+ Args:
515
+ hidden_states (`torch.Tensor` of shape `(batch, time2, size)`): Values of the hidden states
516
+ attention_mask (`torch.Tensor` of shape `(batch, time1, time2)`): Mask tensor.
517
+ pos_emb (`torch.Tensor` of shape `(batch, 2*time1-1, size)`): Positional embedding tensor.
518
+ output_attentions (`bool`, *optional*):
519
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
520
+ returned tensors for more detail.
521
+ Returns:
522
+ `torch.Tensor`: Output tensor of shape `(batch, time1, d_model)`.
523
+ """
524
+ bsz, q_len, _ = hidden_states.size()
525
+ query_states = self.linear_q(hidden_states).view(bsz, -1, self.num_heads, self.head_dim)
526
+ key_states = self.linear_k(hidden_states).view(bsz, -1, self.num_heads, self.head_dim)
527
+ value_states = self.linear_v(hidden_states).view(bsz, -1, self.num_heads, self.head_dim)
528
+
529
+ bsz_pos = pos_emb.size(0)
530
+ pos_encoding = self.linear_pos(pos_emb).view(bsz_pos, -1, self.num_heads, self.head_dim)
531
+
532
+ # (batch_size, head, time1, dim_key)
533
+ query_with_bias_u = (query_states + self.pos_bias_u).transpose(1, 2)
534
+ # (batch_size, head, time1, dim_key)
535
+ query_with_bias_v = (query_states + self.pos_bias_v).transpose(1, 2)
536
+
537
+ # compute attention score
538
+ # first compute matrix a and matrix c
539
+ # as described in https://arxiv.org/abs/1901.02860 Section 3.3
540
+ # (batch_size, head, time1, time2)
541
+ matrix_ac = torch.matmul(query_with_bias_u, key_states.permute(0, 2, 3, 1))
542
+
543
+ # compute matrix b and matrix d
544
+ # (batch_size, head, time1, 2*time1-1)
545
+ matrix_bd = torch.matmul(query_with_bias_v, pos_encoding.permute(0, 2, 3, 1))
546
+ matrix_bd = self.shift_relative_position_tensor(matrix_bd)
547
+
548
+ # (batch_size, head, time1, time2)
549
+ scores = (matrix_ac + matrix_bd) / math.sqrt(self.dim_key)
550
+
551
+ # Forward attention
552
+ if attention_mask is not None:
553
+ expected_size = (bsz, 1, q_len)
554
+ if attention_mask.size() != expected_size:
555
+ raise ValueError(f"Attention mask should be of size {expected_size}, but is {attention_mask.size()}")
556
+ attention_mask = attention_mask.unsqueeze(1).eq(0)
557
+ min_value = float(torch.finfo(scores.dtype).min)
558
+ scores = scores.masked_fill(attention_mask, min_value)
559
+ attn_weights = torch.softmax(scores, dim=-1).masked_fill(attention_mask, 0.0)
560
+ else:
561
+ attn_weights = torch.softmax(scores, dim=-1)
562
+
563
+ attn_weights = self.dropout(attn_weights)
564
+ attn_output = torch.matmul(attn_weights, value_states.transpose(1, 2))
565
+ attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, q_len, -1)
566
+
567
+ attn_output = self.linear_out(attn_output)
568
+
569
+ if not output_attentions:
570
+ attn_weights = None
571
+
572
+ return attn_output, attn_weights
573
+
574
+
575
+ class FastSpeech2ConformerConvolutionModule(nn.Module):
576
+ def __init__(self, config: FastSpeech2ConformerConfig, module_config):
577
+ super().__init__()
578
+ # kernel_size should be an odd number for 'SAME' padding
579
+ channels = config.hidden_size
580
+ kernel_size = module_config["kernel_size"]
581
+ self.pointwise_conv1 = nn.Conv1d(channels, 2 * channels, kernel_size=1, stride=1, padding=0, bias=True)
582
+ self.depthwise_conv = nn.Conv1d(
583
+ channels, channels, kernel_size, stride=1, padding=(kernel_size - 1) // 2, groups=channels, bias=True
584
+ )
585
+ self.norm = nn.BatchNorm1d(channels)
586
+ self.pointwise_conv2 = nn.Conv1d(channels, channels, kernel_size=1, stride=1, padding=0, bias=True)
587
+
588
+ def forward(self, hidden_states):
589
+ """
590
+ Compute convolution module.
591
+
592
+ Args:
593
+ hidden_states (`torch.Tensor` of shape `(batch, time, channels)`): Input tensor.
594
+
595
+ Returns:
596
+ `torch.Tensor`: Output tensor of shape `(batch, time, channels)`.
597
+
598
+ """
599
+ # exchange the temporal dimension and the feature dimension
600
+ hidden_states = hidden_states.transpose(1, 2)
601
+
602
+ # GLU mechanism, (batch_size, 2*channel, dim)
603
+ hidden_states = self.pointwise_conv1(hidden_states)
604
+ # (batch_size, channel, dim)
605
+ hidden_states = nn.functional.glu(hidden_states, dim=1)
606
+
607
+ # 1D Depthwise Conv
608
+ hidden_states = self.depthwise_conv(hidden_states)
609
+ hidden_states = self.norm(hidden_states)
610
+
611
+ hidden_states = hidden_states * torch.sigmoid(hidden_states)
612
+
613
+ hidden_states = self.pointwise_conv2(hidden_states)
614
+
615
+ return hidden_states.transpose(1, 2)
616
+
617
+
618
+ class FastSpeech2ConformerEncoderLayer(nn.Module):
619
+ def __init__(self, config: FastSpeech2ConformerConfig, module_config):
620
+ super().__init__()
621
+
622
+ # self-attention module definition
623
+ self.self_attn = FastSpeech2ConformerAttention(config, module_config)
624
+
625
+ # feed-forward module definition
626
+ self.feed_forward = FastSpeech2ConformerMultiLayeredConv1d(config, module_config)
627
+
628
+ self.macaron_style = config.use_macaron_style_in_conformer
629
+ if self.macaron_style:
630
+ self.feed_forward_macaron = FastSpeech2ConformerMultiLayeredConv1d(config, module_config)
631
+ self.ff_macaron_layer_norm = nn.LayerNorm(config.hidden_size)
632
+ self.ff_scale = 0.5
633
+ else:
634
+ self.ff_scale = 1.0
635
+
636
+ # convolution module definition
637
+ self.use_cnn_module = config.use_cnn_in_conformer
638
+ if self.use_cnn_module:
639
+ self.conv_module = FastSpeech2ConformerConvolutionModule(config, module_config)
640
+ self.conv_layer_norm = nn.LayerNorm(config.hidden_size)
641
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size)
642
+
643
+ self.ff_layer_norm = nn.LayerNorm(config.hidden_size)
644
+
645
+ self.self_attn_layer_norm = nn.LayerNorm(config.hidden_size)
646
+
647
+ self.dropout = nn.Dropout(module_config["dropout_rate"])
648
+ self.size = config.hidden_size
649
+ self.normalize_before = module_config["normalize_before"]
650
+ self.concat_after = module_config["concat_after"]
651
+ if self.concat_after:
652
+ self.concat_linear = nn.Linear(config.hidden_size + config.hidden_size, config.hidden_size)
653
+
654
+ def forward(
655
+ self,
656
+ hidden_states: torch.Tensor,
657
+ pos_emb: Optional[torch.Tensor] = None,
658
+ attention_mask: Optional[torch.Tensor] = None,
659
+ output_attentions: Optional[torch.Tensor] = False,
660
+ ):
661
+ """
662
+ Compute encoded features.
663
+
664
+ Args:
665
+ hidden_states (`torch.Tensor` of shape `(batch, time, size)`): Input tensor.
666
+ pos_emb (`torch.Tensor` of shape `(1, time, size)`): Positional embeddings tensor.
667
+ attention_mask (`torch.Tensor` of shape `(batch, time)`): Attention mask tensor for the input.
668
+ output_attentions (`bool`, *optional*):
669
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
670
+ returned tensors for more detail.
671
+ Returns:
672
+ `torch.Tensor`: Output tensor of shape `(batch, time, size)`.
673
+
674
+ """
675
+ # whether to use macaron style
676
+ if self.macaron_style:
677
+ residual = hidden_states
678
+ if self.normalize_before:
679
+ hidden_states = self.ff_macaron_layer_norm(hidden_states)
680
+ hidden_states = residual + self.ff_scale * self.dropout(self.feed_forward_macaron(hidden_states))
681
+ if not self.normalize_before:
682
+ hidden_states = self.ff_macaron_layer_norm(hidden_states)
683
+
684
+ # multi-headed self-attention module
685
+ residual = hidden_states
686
+ if self.normalize_before:
687
+ hidden_states = self.self_attn_layer_norm(hidden_states)
688
+
689
+ attention_output, attention_scores = self.self_attn(
690
+ hidden_states, attention_mask=attention_mask, pos_emb=pos_emb, output_attentions=output_attentions
691
+ )
692
+
693
+ if self.concat_after:
694
+ x_concat = torch.cat((hidden_states, attention_output), dim=-1)
695
+ hidden_states = self.concat_linear(x_concat)
696
+ hidden_states = residual + hidden_states
697
+ else:
698
+ hidden_states = self.dropout(attention_output)
699
+ hidden_states = residual + hidden_states
700
+ if not self.normalize_before:
701
+ hidden_states = self.self_attn_layer_norm(hidden_states)
702
+
703
+ # convolution module
704
+ if self.use_cnn_module:
705
+ residual = hidden_states
706
+ if self.normalize_before:
707
+ hidden_states = self.conv_layer_norm(hidden_states)
708
+ hidden_states = self.conv_module(hidden_states)
709
+ hidden_states = self.dropout(hidden_states)
710
+ hidden_states = residual + hidden_states
711
+ if not self.normalize_before:
712
+ hidden_states = self.conv_layer_norm(hidden_states)
713
+
714
+ # feed forward module
715
+ residual = hidden_states
716
+ if self.normalize_before:
717
+ hidden_states = self.ff_layer_norm(hidden_states)
718
+ hidden_states = self.feed_forward(hidden_states)
719
+ hidden_states = self.dropout(hidden_states)
720
+ hidden_states = residual + self.ff_scale * hidden_states
721
+ if not self.normalize_before:
722
+ hidden_states = self.ff_layer_norm(hidden_states)
723
+
724
+ if self.conv_module is not None:
725
+ hidden_states = self.final_layer_norm(hidden_states)
726
+
727
+ outputs = (hidden_states,)
728
+
729
+ if output_attentions:
730
+ outputs += (attention_scores,)
731
+
732
+ return outputs
733
+
734
+
735
+ class FastSpeech2ConformerMultiLayeredConv1d(nn.Module):
736
+ """
737
+ Multi-layered conv1d for Transformer block.
738
+
739
+ This is a module of multi-layered conv1d designed to replace positionwise feed-forward network in Transformer
740
+ block, which is introduced in 'FastSpeech: Fast, Robust and Controllable Text to Speech'
741
+ https://arxiv.org/pdf/1905.09263.pdf
742
+ """
743
+
744
+ def __init__(self, config: FastSpeech2ConformerConfig, module_config):
745
+ """
746
+ Initialize FastSpeech2ConformerMultiLayeredConv1d module.
747
+
748
+ Args:
749
+ input_channels (`int`): Number of input channels.
750
+ hidden_channels (`int`): Number of hidden channels.
751
+ kernel_size (`int`): Kernel size of conv1d.
752
+ dropout_rate (`float`): Dropout rate.
753
+ """
754
+ super().__init__()
755
+ input_channels = config.hidden_size
756
+ hidden_channels = module_config["linear_units"]
757
+ kernel_size = config.positionwise_conv_kernel_size
758
+ self.conv1 = nn.Conv1d(input_channels, hidden_channels, kernel_size, stride=1, padding=(kernel_size - 1) // 2)
759
+ self.conv2 = nn.Conv1d(hidden_channels, input_channels, kernel_size, stride=1, padding=(kernel_size - 1) // 2)
760
+ self.dropout = nn.Dropout(module_config["dropout_rate"])
761
+
762
+ def forward(self, hidden_states):
763
+ """
764
+ Calculate forward propagation.
765
+
766
+ Args:
767
+ hidden_states (torch.Tensor): Batch of input tensors (batch_size, time, input_channels).
768
+
769
+ Returns:
770
+ torch.Tensor: Batch of output tensors (batch_size, time, hidden_channels).
771
+ """
772
+ hidden_states = hidden_states.transpose(-1, 1)
773
+ hidden_states = self.conv1(hidden_states)
774
+ hidden_states = torch.relu(hidden_states)
775
+ hidden_states = self.dropout(hidden_states)
776
+ hidden_states = self.conv2(hidden_states)
777
+ hidden_states = hidden_states.transpose(-1, 1)
778
+ return hidden_states
779
+
780
+
781
+ class FastSpeech2ConformerRelPositionalEncoding(nn.Module):
782
+ """
783
+ Args:
784
+ Relative positional encoding module (new implementation). Details can be found in
785
+ https://github.com/espnet/espnet/pull/2816. See : Appendix Batch in https://arxiv.org/abs/1901.02860
786
+ config (`FastSpeech2ConformerConfig`):
787
+ FastSpeech2ConformerConfig instance.
788
+ module_config (`dict`):
789
+ Dictionary containing the encoder or decoder module configuration from the `FastSpeech2ConformerConfig`.
790
+ """
791
+
792
+ def __init__(self, config: FastSpeech2ConformerConfig, module_config):
793
+ """
794
+ Construct an PositionalEncoding object.
795
+ """
796
+ super().__init__()
797
+ self.embed_dim = config.hidden_size
798
+ self.input_scale = math.sqrt(self.embed_dim)
799
+ self.dropout = nn.Dropout(p=module_config["positional_dropout_rate"])
800
+ self.pos_enc = None
801
+ self.max_len = 5000
802
+ self.extend_pos_enc(torch.tensor(0.0).expand(1, self.max_len))
803
+
804
+ def extend_pos_enc(self, x):
805
+ """Reset the positional encodings."""
806
+ if self.pos_enc is not None:
807
+ # self.pos_enc contains both positive and negative parts
808
+ # the length of self.pos_enc is 2 * input_len - 1
809
+ if self.pos_enc.size(1) >= x.size(1) * 2 - 1:
810
+ if self.pos_enc.dtype != x.dtype or self.pos_enc.device != x.device:
811
+ self.pos_enc = self.pos_enc.to(dtype=x.dtype, device=x.device)
812
+ return
813
+ # Suppose `i` means to the position of query vector and `j` means the
814
+ # position of key vector. We use position relative positions when keys
815
+ # are to the left (i>j) and negative relative positions otherwise (i<j).
816
+ pos_enc_positive = torch.zeros(x.size(1), self.embed_dim)
817
+ pos_enc_negative = torch.zeros(x.size(1), self.embed_dim)
818
+ position = torch.arange(0, x.size(1), dtype=torch.int64).float().unsqueeze(1)
819
+ div_term = torch.exp(
820
+ torch.arange(0, self.embed_dim, 2, dtype=torch.int64).float() * -(math.log(10000.0) / self.embed_dim)
821
+ )
822
+ pos_enc_positive[:, 0::2] = torch.sin(position * div_term)
823
+ pos_enc_positive[:, 1::2] = torch.cos(position * div_term)
824
+ pos_enc_negative[:, 0::2] = torch.sin(-1 * position * div_term)
825
+ pos_enc_negative[:, 1::2] = torch.cos(-1 * position * div_term)
826
+
827
+ # Reserve the order of positive indices and concat both positive and
828
+ # negative indices. This is used to support the shifting trick
829
+ # as in https://arxiv.org/abs/1901.02860
830
+ pos_enc_positive = torch.flip(pos_enc_positive, [0]).unsqueeze(0)
831
+ pos_enc_negative = pos_enc_negative[1:].unsqueeze(0)
832
+ pos_enc = torch.cat([pos_enc_positive, pos_enc_negative], dim=1)
833
+ self.pos_enc = pos_enc.to(device=x.device, dtype=x.dtype)
834
+
835
+ def forward(self, feature_representation):
836
+ """
837
+ Args:
838
+ feature_representation (`torch.Tensor` of shape (batch_size, time, `*`)):
839
+ Input tensor.
840
+
841
+ Returns:
842
+ `torch.Tensor`: Encoded tensor (batch_size, time, `*`).
843
+ """
844
+ self.extend_pos_enc(feature_representation)
845
+ hidden_states = feature_representation * self.input_scale
846
+ center_idx = self.pos_enc.size(1) // 2
847
+ pos_emb = self.pos_enc[:, center_idx - hidden_states.size(1) + 1 : center_idx + hidden_states.size(1)]
848
+ return self.dropout(hidden_states), self.dropout(pos_emb)
849
+
850
+
851
+ class FastSpeech2ConformerEncoder(nn.Module):
852
+ """
853
+ FastSpeech2ConformerEncoder encoder module.
854
+
855
+ Args:
856
+ config (`FastSpeech2ConformerConfig`):
857
+ FastSpeech2ConformerConfig instance.
858
+ module_config (`dict`):
859
+ Dictionary containing the encoder or decoder module configuration from the `FastSpeech2ConformerConfig`.
860
+ use_encoder_input_layer (`bool`, *optional*, defaults to `False`):
861
+ Input layer type.
862
+ """
863
+
864
+ def __init__(
865
+ self,
866
+ config: FastSpeech2ConformerConfig,
867
+ module_config,
868
+ use_encoder_input_layer=False,
869
+ ):
870
+ super().__init__()
871
+
872
+ self.embed = None
873
+ if use_encoder_input_layer:
874
+ self.embed = nn.Embedding(
875
+ num_embeddings=config.vocab_size, embedding_dim=config.hidden_size, padding_idx=0
876
+ )
877
+
878
+ self.pos_enc = FastSpeech2ConformerRelPositionalEncoding(config, module_config)
879
+
880
+ self.conformer_layers = nn.ModuleList(
881
+ [FastSpeech2ConformerEncoderLayer(config, module_config) for _ in range(module_config["layers"])]
882
+ )
883
+
884
+ def forward(
885
+ self,
886
+ input_tensor: torch.LongTensor,
887
+ attention_mask: Optional[bool] = None,
888
+ output_hidden_states: Optional[bool] = None,
889
+ output_attentions: Optional[bool] = False,
890
+ return_dict: Optional[bool] = None,
891
+ ):
892
+ """
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
+ output_hidden_states (`bool`, *optional*):
910
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
911
+ for more detail.
912
+ output_attentions (`bool`, *optional*):
913
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
914
+ returned tensors for more detail.
915
+ return_dict (`bool`, *optional*):
916
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
917
+ Returns:
918
+ `torch.Tensor`:
919
+ Output tensor of shape `(batch, time, attention_dim)`.
920
+ """
921
+ feature_representation = input_tensor
922
+ if self.embed is not None:
923
+ feature_representation = self.embed(feature_representation)
924
+
925
+ hidden_states, pos_emb = self.pos_enc(feature_representation)
926
+
927
+ all_hidden_states = () if output_hidden_states else None
928
+ all_self_attentions = () if output_attentions else None
929
+
930
+ for conformer_layer in self.conformer_layers:
931
+ if output_hidden_states:
932
+ all_hidden_states = all_hidden_states + (hidden_states,)
933
+
934
+ layer_outputs = conformer_layer(hidden_states, pos_emb, attention_mask, output_attentions)
935
+ hidden_states = layer_outputs[0]
936
+
937
+ if output_attentions:
938
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
939
+
940
+ # Add last layer
941
+ if output_hidden_states:
942
+ all_hidden_states = all_hidden_states + (hidden_states,)
943
+
944
+ if not return_dict:
945
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
946
+ return BaseModelOutput(
947
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_self_attentions
948
+ )
949
+
950
+
951
+ class FastSpeech2ConformerLoss(nn.Module):
952
+ def __init__(self, config: FastSpeech2ConformerConfig):
953
+ super().__init__()
954
+
955
+ use_masking = config.use_masking
956
+ use_weighted_masking = config.use_weighted_masking
957
+
958
+ if use_masking and use_weighted_masking:
959
+ raise ValueError("Either use_masking or use_weighted_masking can be True, but not both.")
960
+
961
+ self.use_masking = use_masking
962
+ self.use_weighted_masking = use_weighted_masking
963
+
964
+ # define criterions
965
+ reduction = "none" if self.use_weighted_masking else "mean"
966
+ self.l1_criterion = nn.L1Loss(reduction=reduction)
967
+ self.mse_criterion = nn.MSELoss(reduction=reduction)
968
+ self.duration_criterion = nn.MSELoss(reduction=reduction)
969
+ self.log_domain_offset = 1.0
970
+
971
+ def forward(
972
+ self,
973
+ outputs_after_postnet,
974
+ outputs_before_postnet,
975
+ duration_outputs,
976
+ pitch_outputs,
977
+ energy_outputs,
978
+ spectrogram_labels,
979
+ duration_labels,
980
+ pitch_labels,
981
+ energy_labels,
982
+ duration_mask,
983
+ spectrogram_mask,
984
+ ):
985
+ """
986
+ Args:
987
+ outputs_after_postnet (`torch.Tensor` of shape `(batch_size, max_spectrogram_length, num_mel_bins)`):
988
+ Batch of outputs after postnet.
989
+ outputs_before_postnet (`torch.Tensor` of shape `(batch_size, max_spectrogram_length, num_mel_bins)`):
990
+ Batch of outputs before postnet.
991
+ duration_outputs (`torch.LongTensor` of shape `(batch_size, max_text_length)`):
992
+ Batch of outputs of duration predictor.
993
+ pitch_outputs (`torch.Tensor` of shape `(batch_size, max_text_length, 1)`):
994
+ Batch of outputs of pitch predictor.
995
+ energy_outputs (`torch.Tensor` of shape `(batch_size, max_text_length, 1)`):
996
+ Batch of outputs of energy predictor.
997
+ spectrogram_labels (`torch.Tensor` of shape `(batch_size, max_spectrogram_length, num_mel_bins)`):
998
+ Batch of target features.
999
+ duration_labels (`torch.LongTensor` of shape `(batch_size, max_text_length)`): Batch of durations.
1000
+ pitch_labels (`torch.Tensor` of shape `(batch_size, max_text_length, 1)`):
1001
+ Batch of target token-averaged pitch.
1002
+ energy_labels (`torch.Tensor` of shape `(batch_size, max_text_length, 1)`):
1003
+ Batch of target token-averaged energy.
1004
+ duration_mask (`torch.LongTensor`):
1005
+ Mask used to discern which values the duration loss should be calculated for.
1006
+ spectrogram_mask (`torch.LongTensor`):
1007
+ Mask used to discern which values the spectrogam loss should be calculated for.
1008
+
1009
+ Returns:
1010
+ `tuple(torch.FloatTensor)`: Tuple of tensors containing, in order, the L1 loss value, duration predictor
1011
+ loss value, pitch predictor loss value, and energy predictor loss value.
1012
+
1013
+ """
1014
+ pitch_and_energy_masks = duration_mask.unsqueeze(-1)
1015
+
1016
+ # apply mask to remove padded part
1017
+ if self.use_masking:
1018
+ outputs_before_postnet = outputs_before_postnet.masked_select(spectrogram_mask)
1019
+ if outputs_after_postnet is not None:
1020
+ outputs_after_postnet = outputs_after_postnet.masked_select(spectrogram_mask)
1021
+ spectrogram_labels = spectrogram_labels.masked_select(spectrogram_mask)
1022
+ duration_outputs = duration_outputs.masked_select(duration_mask)
1023
+ duration_labels = duration_labels.masked_select(duration_mask)
1024
+ pitch_outputs = pitch_outputs.masked_select(pitch_and_energy_masks)
1025
+ energy_outputs = energy_outputs.masked_select(pitch_and_energy_masks)
1026
+ pitch_labels = pitch_labels.masked_select(pitch_and_energy_masks)
1027
+ energy_labels = energy_labels.masked_select(pitch_and_energy_masks)
1028
+
1029
+ # calculate loss
1030
+ l1_loss = self.l1_criterion(outputs_before_postnet, spectrogram_labels)
1031
+ if outputs_after_postnet is not None:
1032
+ l1_loss = l1_loss + self.l1_criterion(outputs_after_postnet, spectrogram_labels)
1033
+ duration_labels = torch.log(duration_labels.float() + self.log_domain_offset)
1034
+ duration_loss = self.duration_criterion(duration_outputs, duration_labels)
1035
+ pitch_loss = self.mse_criterion(pitch_outputs, pitch_labels)
1036
+ energy_loss = self.mse_criterion(energy_outputs, energy_labels)
1037
+
1038
+ # make weighted mask and apply it
1039
+ if self.use_weighted_masking:
1040
+ spectrogram_mask = nn.functional.pad(
1041
+ spectrogram_mask.transpose(1, 2),
1042
+ [0, spectrogram_labels.size(1) - spectrogram_mask.size(1), 0, 0, 0, 0],
1043
+ value=False,
1044
+ ).transpose(1, 2)
1045
+
1046
+ out_weights = spectrogram_mask.float() / spectrogram_mask.sum(dim=1, keepdim=True).float()
1047
+ out_weights /= spectrogram_labels.size(0) * spectrogram_labels.size(2)
1048
+ duration_weights = duration_mask.float() / duration_mask.sum(dim=1, keepdim=True).float()
1049
+ duration_weights /= duration_labels.size(0)
1050
+
1051
+ # apply weight
1052
+ l1_loss = l1_loss.mul(out_weights).masked_select(spectrogram_mask).sum()
1053
+ duration_loss = duration_loss.mul(duration_weights).masked_select(duration_mask).sum()
1054
+ pitch_weights = duration_weights.unsqueeze(-1)
1055
+ pitch_loss = pitch_loss.mul(pitch_weights).masked_select(pitch_and_energy_masks).sum()
1056
+ energy_loss = energy_loss.mul(pitch_weights).masked_select(pitch_and_energy_masks).sum()
1057
+
1058
+ return l1_loss + duration_loss + pitch_loss + energy_loss
1059
+
1060
+
1061
+ class FastSpeech2ConformerPreTrainedModel(PreTrainedModel):
1062
+ """
1063
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1064
+ models.
1065
+ """
1066
+
1067
+ config_class = FastSpeech2ConformerConfig
1068
+ base_model_prefix = "fastspeech2_conformer"
1069
+
1070
+ main_input_name = "input_ids"
1071
+
1072
+ def _init_weights(self, module):
1073
+ """Initialize the weights"""
1074
+ if isinstance(module, (nn.LayerNorm)):
1075
+ module.bias.data.zero_()
1076
+ module.weight.data.fill_(1.0)
1077
+ elif isinstance(module, nn.Conv1d):
1078
+ nn.init.kaiming_normal_(module.weight)
1079
+ if module.bias is not None:
1080
+ key = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
1081
+ nn.init.uniform_(module.bias, a=-key, b=key)
1082
+ elif isinstance(module, nn.Embedding):
1083
+ module.weight.data.normal_()
1084
+ if module.padding_idx is not None:
1085
+ module.weight.data[module.padding_idx].zero_()
1086
+ elif isinstance(module, FastSpeech2ConformerAttention):
1087
+ nn.init.xavier_uniform_(module.pos_bias_u)
1088
+ nn.init.xavier_uniform_(module.pos_bias_v)
1089
+
1090
+ def _set_gradient_checkpointing(self, module, value=False):
1091
+ if isinstance(module, FastSpeech2ConformerEncoder):
1092
+ module.gradient_checkpointing = value
1093
+
1094
+
1095
+ @add_start_docstrings(
1096
+ """FastSpeech2Conformer Model.""",
1097
+ FASTSPEECH2_CONFORMER_START_DOCSTRING,
1098
+ )
1099
+ class FastSpeech2ConformerModel(FastSpeech2ConformerPreTrainedModel):
1100
+ """
1101
+ FastSpeech 2 module.
1102
+
1103
+ This is a module of FastSpeech 2 described in 'FastSpeech 2: Fast and High-Quality End-to-End Text to Speech'
1104
+ https://arxiv.org/abs/2006.04558. Instead of quantized pitch and energy, we use token-averaged value introduced in
1105
+ FastPitch: Parallel Text-to-speech with Pitch Prediction. The encoder and decoder are Conformers instead of regular
1106
+ Transformers.
1107
+ """
1108
+
1109
+ def __init__(self, config: FastSpeech2ConformerConfig):
1110
+ super().__init__(config)
1111
+ self.config = config
1112
+
1113
+ # store hyperparameters
1114
+ self.vocab_size = config.vocab_size
1115
+ self.num_mel_bins = config.num_mel_bins
1116
+ self.hidden_size = config.hidden_size
1117
+ self.reduction_factor = config.reduction_factor
1118
+ self.stop_gradient_from_pitch_predictor = config.stop_gradient_from_pitch_predictor
1119
+ self.stop_gradient_from_energy_predictor = config.stop_gradient_from_energy_predictor
1120
+
1121
+ self.multilingual_model = config.num_languages is not None and config.num_languages > 1
1122
+ if self.multilingual_model:
1123
+ self.language_id_embedding = torch.nn.Embedding(config.num_languages, self.hidden_size)
1124
+
1125
+ self.multispeaker_model = config.num_speakers is not None and config.num_speakers > 1
1126
+ if self.multispeaker_model:
1127
+ self.speaker_id_embedding = torch.nn.Embedding(config.num_speakers, config.hidden_size)
1128
+
1129
+ self.speaker_embed_dim = config.speaker_embed_dim
1130
+ if self.speaker_embed_dim:
1131
+ self.projection = nn.Linear(config.hidden_size + self.speaker_embed_dim, config.hidden_size)
1132
+
1133
+ self.encoder = FastSpeech2ConformerEncoder(config, config.encoder_config, use_encoder_input_layer=True)
1134
+
1135
+ self.duration_predictor = FastSpeech2ConformerDurationPredictor(config)
1136
+
1137
+ self.pitch_predictor = FastSpeech2ConformerVariancePredictor(
1138
+ config,
1139
+ num_layers=config.pitch_predictor_layers,
1140
+ num_chans=config.pitch_predictor_channels,
1141
+ kernel_size=config.pitch_predictor_kernel_size,
1142
+ dropout_rate=config.pitch_predictor_dropout,
1143
+ )
1144
+ # continuous pitch + FastPitch style avg
1145
+ self.pitch_embed = FastSpeech2ConformerVarianceEmbedding(
1146
+ out_channels=self.hidden_size,
1147
+ kernel_size=config.pitch_embed_kernel_size,
1148
+ padding=(config.pitch_embed_kernel_size - 1) // 2,
1149
+ dropout_rate=config.pitch_embed_dropout,
1150
+ )
1151
+
1152
+ self.energy_predictor = FastSpeech2ConformerVariancePredictor(
1153
+ config,
1154
+ num_layers=config.energy_predictor_layers,
1155
+ num_chans=config.energy_predictor_channels,
1156
+ kernel_size=config.energy_predictor_kernel_size,
1157
+ dropout_rate=config.energy_predictor_dropout,
1158
+ )
1159
+ # continuous energy + FastPitch style avg
1160
+ self.energy_embed = FastSpeech2ConformerVarianceEmbedding(
1161
+ out_channels=self.hidden_size,
1162
+ kernel_size=config.energy_embed_kernel_size,
1163
+ padding=(config.energy_embed_kernel_size - 1) // 2,
1164
+ dropout_rate=config.energy_embed_dropout,
1165
+ )
1166
+
1167
+ # The decoder is an encoder
1168
+ self.decoder = FastSpeech2ConformerEncoder(config, config.decoder_config, use_encoder_input_layer=False)
1169
+
1170
+ self.speech_decoder_postnet = FastSpeech2ConformerSpeechDecoderPostnet(config)
1171
+
1172
+ self.criterion = FastSpeech2ConformerLoss(config)
1173
+
1174
+ self.post_init()
1175
+
1176
+ @replace_return_docstrings(output_type=FastSpeech2ConformerModelOutput, config_class=_CONFIG_FOR_DOC)
1177
+ def forward(
1178
+ self,
1179
+ input_ids: torch.LongTensor,
1180
+ attention_mask: Optional[torch.LongTensor] = None,
1181
+ spectrogram_labels: Optional[torch.FloatTensor] = None,
1182
+ duration_labels: Optional[torch.LongTensor] = None,
1183
+ pitch_labels: Optional[torch.FloatTensor] = None,
1184
+ energy_labels: Optional[torch.FloatTensor] = None,
1185
+ speaker_ids: Optional[torch.LongTensor] = None,
1186
+ lang_ids: Optional[torch.LongTensor] = None,
1187
+ speaker_embedding: Optional[torch.FloatTensor] = None,
1188
+ return_dict: Optional[bool] = None,
1189
+ output_attentions: Optional[bool] = None,
1190
+ output_hidden_states: Optional[bool] = None,
1191
+ ) -> Union[Tuple, FastSpeech2ConformerModelOutput]:
1192
+ """
1193
+ Args:
1194
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1195
+ Input sequence of text vectors.
1196
+ attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*, defaults to `None`):
1197
+ Mask to avoid performing convolution and attention on padding token indices. Mask values selected in
1198
+ `[0, 1]`: 0 for tokens that are **masked**, 1 for tokens that are **not masked**.
1199
+ spectrogram_labels (`torch.FloatTensor` of shape `(batch_size, max_spectrogram_length, num_mel_bins)`, *optional*, defaults to `None`):
1200
+ Batch of padded target features.
1201
+ duration_labels (`torch.LongTensor` of shape `(batch_size, sequence_length + 1)`, *optional*, defaults to `None`):
1202
+ Batch of padded durations.
1203
+ pitch_labels (`torch.FloatTensor` of shape `(batch_size, sequence_length + 1, 1)`, *optional*, defaults to `None`):
1204
+ Batch of padded token-averaged pitch.
1205
+ energy_labels (`torch.FloatTensor` of shape `(batch_size, sequence_length + 1, 1)`, *optional*, defaults to `None`):
1206
+ Batch of padded token-averaged energy.
1207
+ speaker_ids (`torch.LongTensor` of shape `(batch_size, 1)`, *optional*, defaults to `None`):
1208
+ Speaker ids used to condition features of speech output by the model.
1209
+ lang_ids (`torch.LongTensor` of shape `(batch_size, 1)`, *optional*, defaults to `None`):
1210
+ Language ids used to condition features of speech output by the model.
1211
+ speaker_embedding (`torch.FloatTensor` of shape `(batch_size, embedding_dim)`, *optional*, defaults to `None`):
1212
+ Embedding containing conditioning signals for the features of the speech.
1213
+ return_dict (`bool`, *optional*, defaults to `None`):
1214
+ Whether or not to return a [`FastSpeech2ConformerModelOutput`] instead of a plain tuple.
1215
+ output_attentions (`bool`, *optional*, defaults to `None`):
1216
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1217
+ returned tensors for more detail.
1218
+ output_hidden_states (`bool`, *optional*, defaults to `None`):
1219
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1220
+ for more detail.
1221
+
1222
+ Returns:
1223
+
1224
+ Example:
1225
+
1226
+ ```python
1227
+ >>> from transformers import (
1228
+ ... FastSpeech2ConformerTokenizer,
1229
+ ... FastSpeech2ConformerModel,
1230
+ ... FastSpeech2ConformerHifiGan,
1231
+ ... )
1232
+
1233
+ >>> tokenizer = FastSpeech2ConformerTokenizer.from_pretrained("espnet/fastspeech2_conformer")
1234
+ >>> inputs = tokenizer("some text to convert to speech", return_tensors="pt")
1235
+ >>> input_ids = inputs["input_ids"]
1236
+
1237
+ >>> model = FastSpeech2ConformerModel.from_pretrained("espnet/fastspeech2_conformer")
1238
+ >>> output_dict = model(input_ids, return_dict=True)
1239
+ >>> spectrogram = output_dict["spectrogram"]
1240
+
1241
+ >>> vocoder = FastSpeech2ConformerHifiGan.from_pretrained("espnet/fastspeech2_conformer_hifigan")
1242
+ >>> waveform = vocoder(spectrogram)
1243
+ >>> print(waveform.shape)
1244
+ torch.Size([1, 49664])
1245
+ ```
1246
+ """
1247
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1248
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1249
+ output_hidden_states = (
1250
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1251
+ )
1252
+
1253
+ if attention_mask is None:
1254
+ attention_mask = torch.ones(input_ids.shape, device=input_ids.device)
1255
+
1256
+ has_missing_labels = (
1257
+ spectrogram_labels is None or duration_labels is None or pitch_labels is None or energy_labels is None
1258
+ )
1259
+ if self.training and has_missing_labels:
1260
+ raise ValueError("All labels must be provided to run in training mode.")
1261
+
1262
+ # forward encoder
1263
+ text_masks = attention_mask.unsqueeze(-2)
1264
+
1265
+ encoder_outputs = self.encoder(
1266
+ input_ids,
1267
+ text_masks,
1268
+ output_hidden_states=output_hidden_states,
1269
+ output_attentions=output_attentions,
1270
+ return_dict=return_dict,
1271
+ )
1272
+ hidden_states = encoder_outputs[0]
1273
+
1274
+ # Integrate with language id, speaker id, and speaker embedding
1275
+ if self.multispeaker_model and speaker_ids is not None:
1276
+ speaker_id_embeddings = self.speaker_id_embedding(speaker_ids.view(-1))
1277
+ hidden_states = hidden_states + speaker_id_embeddings.unsqueeze(1)
1278
+
1279
+ if self.multilingual_model and lang_ids is not None:
1280
+ language_id_embbedings = self.language_id_embedding(lang_ids.view(-1))
1281
+ hidden_states = hidden_states + language_id_embbedings.unsqueeze(1)
1282
+
1283
+ if self.speaker_embed_dim is not None and speaker_embedding is not None:
1284
+ embeddings_expanded = (
1285
+ nn.functional.normalize(speaker_embedding).unsqueeze(1).expand(-1, hidden_states.size(1), -1)
1286
+ )
1287
+ hidden_states = self.projection(torch.cat([hidden_states, embeddings_expanded], dim=-1))
1288
+
1289
+ # forward duration predictor and variance predictors
1290
+ duration_mask = ~attention_mask.bool()
1291
+
1292
+ if self.stop_gradient_from_pitch_predictor:
1293
+ pitch_predictions = self.pitch_predictor(hidden_states.detach(), duration_mask.unsqueeze(-1))
1294
+ else:
1295
+ pitch_predictions = self.pitch_predictor(hidden_states, duration_mask.unsqueeze(-1))
1296
+
1297
+ if self.stop_gradient_from_energy_predictor:
1298
+ energy_predictions = self.energy_predictor(hidden_states.detach(), duration_mask.unsqueeze(-1))
1299
+ else:
1300
+ energy_predictions = self.energy_predictor(hidden_states, duration_mask.unsqueeze(-1))
1301
+
1302
+ duration_predictions = self.duration_predictor(hidden_states)
1303
+ duration_predictions = duration_predictions.masked_fill(duration_mask, 0.0)
1304
+
1305
+ if not self.training:
1306
+ # use prediction in inference
1307
+ embedded_pitch_curve = self.pitch_embed(pitch_predictions)
1308
+ embedded_energy_curve = self.energy_embed(energy_predictions)
1309
+ hidden_states = hidden_states + embedded_energy_curve + embedded_pitch_curve
1310
+ hidden_states = length_regulator(hidden_states, duration_predictions, self.config.speaking_speed)
1311
+ else:
1312
+ # use groundtruth in training
1313
+ embedded_pitch_curve = self.pitch_embed(pitch_labels)
1314
+ embedded_energy_curve = self.energy_embed(energy_labels)
1315
+ hidden_states = hidden_states + embedded_energy_curve + embedded_pitch_curve
1316
+ hidden_states = length_regulator(hidden_states, duration_labels)
1317
+
1318
+ # forward decoder
1319
+ if not self.training:
1320
+ hidden_mask = None
1321
+ else:
1322
+ spectrogram_mask = (spectrogram_labels != -100).any(dim=-1)
1323
+ spectrogram_mask = spectrogram_mask.int()
1324
+ if self.reduction_factor > 1:
1325
+ length_dim = spectrogram_mask.shape[1] - spectrogram_mask.shape[1] % self.reduction_factor
1326
+ spectrogram_mask = spectrogram_mask[:, :, :length_dim]
1327
+ hidden_mask = spectrogram_mask.unsqueeze(-2)
1328
+
1329
+ decoder_outputs = self.decoder(
1330
+ hidden_states,
1331
+ hidden_mask,
1332
+ output_hidden_states=output_hidden_states,
1333
+ output_attentions=output_attentions,
1334
+ return_dict=return_dict,
1335
+ )
1336
+
1337
+ outputs_before_postnet, outputs_after_postnet = self.speech_decoder_postnet(decoder_outputs[0])
1338
+
1339
+ loss = None
1340
+ if self.training:
1341
+ # calculate loss
1342
+ loss_duration_mask = ~duration_mask
1343
+ loss_spectrogram_mask = spectrogram_mask.unsqueeze(-1).bool()
1344
+ loss = self.criterion(
1345
+ outputs_after_postnet=outputs_after_postnet,
1346
+ outputs_before_postnet=outputs_before_postnet,
1347
+ duration_outputs=duration_predictions,
1348
+ pitch_outputs=pitch_predictions,
1349
+ energy_outputs=energy_predictions,
1350
+ spectrogram_labels=spectrogram_labels,
1351
+ duration_labels=duration_labels,
1352
+ pitch_labels=pitch_labels,
1353
+ energy_labels=energy_labels,
1354
+ duration_mask=loss_duration_mask,
1355
+ spectrogram_mask=loss_spectrogram_mask,
1356
+ )
1357
+
1358
+ if not return_dict:
1359
+ postnet_outputs = (outputs_after_postnet,)
1360
+ audio_feature_predictions = (
1361
+ duration_predictions,
1362
+ pitch_predictions,
1363
+ energy_predictions,
1364
+ )
1365
+ outputs = postnet_outputs + encoder_outputs + decoder_outputs[1:] + audio_feature_predictions
1366
+ return ((loss,) + outputs) if loss is not None else outputs
1367
+
1368
+ return FastSpeech2ConformerModelOutput(
1369
+ loss=loss,
1370
+ spectrogram=outputs_after_postnet,
1371
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1372
+ encoder_hidden_states=encoder_outputs.hidden_states,
1373
+ encoder_attentions=encoder_outputs.attentions,
1374
+ decoder_hidden_states=decoder_outputs.hidden_states,
1375
+ decoder_attentions=decoder_outputs.attentions,
1376
+ duration_outputs=duration_predictions,
1377
+ pitch_outputs=pitch_predictions,
1378
+ energy_outputs=energy_predictions,
1379
+ )
1380
+
1381
+
1382
+ # Copied from transformers.models.speecht5.modeling_speecht5.HifiGanResidualBlock
1383
+ class HifiGanResidualBlock(nn.Module):
1384
+ def __init__(self, channels, kernel_size=3, dilation=(1, 3, 5), leaky_relu_slope=0.1):
1385
+ super().__init__()
1386
+ self.leaky_relu_slope = leaky_relu_slope
1387
+
1388
+ self.convs1 = nn.ModuleList(
1389
+ [
1390
+ nn.Conv1d(
1391
+ channels,
1392
+ channels,
1393
+ kernel_size,
1394
+ stride=1,
1395
+ dilation=dilation[i],
1396
+ padding=self.get_padding(kernel_size, dilation[i]),
1397
+ )
1398
+ for i in range(len(dilation))
1399
+ ]
1400
+ )
1401
+ self.convs2 = nn.ModuleList(
1402
+ [
1403
+ nn.Conv1d(
1404
+ channels,
1405
+ channels,
1406
+ kernel_size,
1407
+ stride=1,
1408
+ dilation=1,
1409
+ padding=self.get_padding(kernel_size, 1),
1410
+ )
1411
+ for _ in range(len(dilation))
1412
+ ]
1413
+ )
1414
+
1415
+ def get_padding(self, kernel_size, dilation=1):
1416
+ return (kernel_size * dilation - dilation) // 2
1417
+
1418
+ def apply_weight_norm(self):
1419
+ weight_norm = nn.utils.weight_norm
1420
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
1421
+ weight_norm = nn.utils.parametrizations.weight_norm
1422
+
1423
+ for layer in self.convs1:
1424
+ weight_norm(layer)
1425
+ for layer in self.convs2:
1426
+ weight_norm(layer)
1427
+
1428
+ def remove_weight_norm(self):
1429
+ for layer in self.convs1:
1430
+ nn.utils.remove_weight_norm(layer)
1431
+ for layer in self.convs2:
1432
+ nn.utils.remove_weight_norm(layer)
1433
+
1434
+ def forward(self, hidden_states):
1435
+ for conv1, conv2 in zip(self.convs1, self.convs2):
1436
+ residual = hidden_states
1437
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
1438
+ hidden_states = conv1(hidden_states)
1439
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
1440
+ hidden_states = conv2(hidden_states)
1441
+ hidden_states = hidden_states + residual
1442
+ return hidden_states
1443
+
1444
+
1445
+ @add_start_docstrings(
1446
+ """HiFi-GAN vocoder.""",
1447
+ HIFIGAN_START_DOCSTRING,
1448
+ )
1449
+ # Copied from transformers.models.speecht5.modeling_speecht5.SpeechT5HifiGan with SpeechT5->FastSpeech2Conformer
1450
+ class FastSpeech2ConformerHifiGan(PreTrainedModel):
1451
+ config_class = FastSpeech2ConformerHifiGanConfig
1452
+ main_input_name = "spectrogram"
1453
+
1454
+ def __init__(self, config: FastSpeech2ConformerHifiGanConfig):
1455
+ super().__init__(config)
1456
+ self.num_kernels = len(config.resblock_kernel_sizes)
1457
+ self.num_upsamples = len(config.upsample_rates)
1458
+ self.conv_pre = nn.Conv1d(
1459
+ config.model_in_dim,
1460
+ config.upsample_initial_channel,
1461
+ kernel_size=7,
1462
+ stride=1,
1463
+ padding=3,
1464
+ )
1465
+
1466
+ self.upsampler = nn.ModuleList()
1467
+ for i, (upsample_rate, kernel_size) in enumerate(zip(config.upsample_rates, config.upsample_kernel_sizes)):
1468
+ self.upsampler.append(
1469
+ nn.ConvTranspose1d(
1470
+ config.upsample_initial_channel // (2**i),
1471
+ config.upsample_initial_channel // (2 ** (i + 1)),
1472
+ kernel_size=kernel_size,
1473
+ stride=upsample_rate,
1474
+ padding=(kernel_size - upsample_rate) // 2,
1475
+ )
1476
+ )
1477
+
1478
+ self.resblocks = nn.ModuleList()
1479
+ for i in range(len(self.upsampler)):
1480
+ channels = config.upsample_initial_channel // (2 ** (i + 1))
1481
+ for kernel_size, dilation in zip(config.resblock_kernel_sizes, config.resblock_dilation_sizes):
1482
+ self.resblocks.append(HifiGanResidualBlock(channels, kernel_size, dilation, config.leaky_relu_slope))
1483
+
1484
+ self.conv_post = nn.Conv1d(channels, 1, kernel_size=7, stride=1, padding=3)
1485
+
1486
+ self.register_buffer("mean", torch.zeros(config.model_in_dim))
1487
+ self.register_buffer("scale", torch.ones(config.model_in_dim))
1488
+
1489
+ # Initialize weights and apply final processing
1490
+ self.post_init()
1491
+
1492
+ def _init_weights(self, module):
1493
+ """Initialize the weights."""
1494
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
1495
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
1496
+ if module.bias is not None:
1497
+ module.bias.data.zero_()
1498
+
1499
+ def apply_weight_norm(self):
1500
+ weight_norm = nn.utils.weight_norm
1501
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
1502
+ weight_norm = nn.utils.parametrizations.weight_norm
1503
+
1504
+ weight_norm(self.conv_pre)
1505
+ for layer in self.upsampler:
1506
+ weight_norm(layer)
1507
+ for layer in self.resblocks:
1508
+ layer.apply_weight_norm()
1509
+ weight_norm(self.conv_post)
1510
+
1511
+ def remove_weight_norm(self):
1512
+ nn.utils.remove_weight_norm(self.conv_pre)
1513
+ for layer in self.upsampler:
1514
+ nn.utils.remove_weight_norm(layer)
1515
+ for layer in self.resblocks:
1516
+ layer.remove_weight_norm()
1517
+ nn.utils.remove_weight_norm(self.conv_post)
1518
+
1519
+ def forward(self, spectrogram: torch.FloatTensor) -> torch.FloatTensor:
1520
+ r"""
1521
+ Converts a log-mel spectrogram into a speech waveform. Passing a batch of log-mel spectrograms returns a batch
1522
+ of speech waveforms. Passing a single, un-batched log-mel spectrogram returns a single, un-batched speech
1523
+ waveform.
1524
+
1525
+ Args:
1526
+ spectrogram (`torch.FloatTensor`):
1527
+ Tensor containing the log-mel spectrograms. Can be batched and of shape `(batch_size, sequence_length,
1528
+ config.model_in_dim)`, or un-batched and of shape `(sequence_length, config.model_in_dim)`.
1529
+
1530
+ Returns:
1531
+ `torch.FloatTensor`: Tensor containing the speech waveform. If the input spectrogram is batched, will be of
1532
+ shape `(batch_size, num_frames,)`. If un-batched, will be of shape `(num_frames,)`.
1533
+ """
1534
+ if self.config.normalize_before:
1535
+ spectrogram = (spectrogram - self.mean) / self.scale
1536
+
1537
+ is_batched = spectrogram.dim() == 3
1538
+ if not is_batched:
1539
+ spectrogram = spectrogram.unsqueeze(0)
1540
+
1541
+ hidden_states = spectrogram.transpose(2, 1)
1542
+
1543
+ hidden_states = self.conv_pre(hidden_states)
1544
+ for i in range(self.num_upsamples):
1545
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.config.leaky_relu_slope)
1546
+ hidden_states = self.upsampler[i](hidden_states)
1547
+
1548
+ res_state = self.resblocks[i * self.num_kernels](hidden_states)
1549
+ for j in range(1, self.num_kernels):
1550
+ res_state += self.resblocks[i * self.num_kernels + j](hidden_states)
1551
+ hidden_states = res_state / self.num_kernels
1552
+
1553
+ hidden_states = nn.functional.leaky_relu(hidden_states)
1554
+ hidden_states = self.conv_post(hidden_states)
1555
+ hidden_states = torch.tanh(hidden_states)
1556
+
1557
+ if not is_batched:
1558
+ # remove batch dim and collapse tensor to 1-d audio waveform
1559
+ waveform = hidden_states.squeeze(0).transpose(1, 0).view(-1)
1560
+ else:
1561
+ # remove seq-len dim since this collapses to 1
1562
+ waveform = hidden_states.squeeze(1)
1563
+
1564
+ return waveform
1565
+
1566
+
1567
+ @add_start_docstrings(
1568
+ "The FastSpeech2ConformerModel with a FastSpeech2ConformerHifiGan vocoder head that performs text-to-speech (waveform).",
1569
+ FASTSPEECH2_CONFORMER_WITH_HIFIGAN_START_DOCSTRING,
1570
+ )
1571
+ class FastSpeech2ConformerWithHifiGan(PreTrainedModel):
1572
+ config_class = FastSpeech2ConformerWithHifiGanConfig
1573
+
1574
+ def __init__(self, config: FastSpeech2ConformerWithHifiGanConfig):
1575
+ super().__init__(config)
1576
+
1577
+ self.model = FastSpeech2ConformerModel(config.model_config)
1578
+ self.vocoder = FastSpeech2ConformerHifiGan(config.vocoder_config)
1579
+
1580
+ self.config = config
1581
+
1582
+ @replace_return_docstrings(
1583
+ output_type=FastSpeech2ConformerWithHifiGanOutput, config_class=FastSpeech2ConformerWithHifiGanConfig
1584
+ )
1585
+ def forward(
1586
+ self,
1587
+ input_ids: torch.LongTensor,
1588
+ attention_mask: Optional[torch.LongTensor] = None,
1589
+ spectrogram_labels: Optional[torch.FloatTensor] = None,
1590
+ duration_labels: Optional[torch.LongTensor] = None,
1591
+ pitch_labels: Optional[torch.FloatTensor] = None,
1592
+ energy_labels: Optional[torch.FloatTensor] = None,
1593
+ speaker_ids: Optional[torch.LongTensor] = None,
1594
+ lang_ids: Optional[torch.LongTensor] = None,
1595
+ speaker_embedding: Optional[torch.FloatTensor] = None,
1596
+ return_dict: Optional[bool] = None,
1597
+ output_attentions: Optional[bool] = None,
1598
+ output_hidden_states: Optional[bool] = None,
1599
+ ) -> Union[Tuple, FastSpeech2ConformerModelOutput]:
1600
+ """
1601
+ Args:
1602
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1603
+ Input sequence of text vectors.
1604
+ attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*, defaults to `None`):
1605
+ Mask to avoid performing convolution and attention on padding token indices. Mask values selected in
1606
+ `[0, 1]`: 0 for tokens that are **masked**, 1 for tokens that are **not masked**.
1607
+ spectrogram_labels (`torch.FloatTensor` of shape `(batch_size, max_spectrogram_length, num_mel_bins)`, *optional*, defaults to `None`):
1608
+ Batch of padded target features.
1609
+ duration_labels (`torch.LongTensor` of shape `(batch_size, sequence_length + 1)`, *optional*, defaults to `None`):
1610
+ Batch of padded durations.
1611
+ pitch_labels (`torch.FloatTensor` of shape `(batch_size, sequence_length + 1, 1)`, *optional*, defaults to `None`):
1612
+ Batch of padded token-averaged pitch.
1613
+ energy_labels (`torch.FloatTensor` of shape `(batch_size, sequence_length + 1, 1)`, *optional*, defaults to `None`):
1614
+ Batch of padded token-averaged energy.
1615
+ speaker_ids (`torch.LongTensor` of shape `(batch_size, 1)`, *optional*, defaults to `None`):
1616
+ Speaker ids used to condition features of speech output by the model.
1617
+ lang_ids (`torch.LongTensor` of shape `(batch_size, 1)`, *optional*, defaults to `None`):
1618
+ Language ids used to condition features of speech output by the model.
1619
+ speaker_embedding (`torch.FloatTensor` of shape `(batch_size, embedding_dim)`, *optional*, defaults to `None`):
1620
+ Embedding containing conditioning signals for the features of the speech.
1621
+ return_dict (`bool`, *optional*, defaults to `None`):
1622
+ Whether or not to return a [`FastSpeech2ConformerModelOutput`] instead of a plain tuple.
1623
+ output_attentions (`bool`, *optional*, defaults to `None`):
1624
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1625
+ returned tensors for more detail.
1626
+ output_hidden_states (`bool`, *optional*, defaults to `None`):
1627
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1628
+ for more detail.
1629
+
1630
+ Returns:
1631
+
1632
+ Example:
1633
+
1634
+ ```python
1635
+ >>> from transformers import (
1636
+ ... FastSpeech2ConformerTokenizer,
1637
+ ... FastSpeech2ConformerWithHifiGan,
1638
+ ... )
1639
+
1640
+ >>> tokenizer = FastSpeech2ConformerTokenizer.from_pretrained("espnet/fastspeech2_conformer")
1641
+ >>> inputs = tokenizer("some text to convert to speech", return_tensors="pt")
1642
+ >>> input_ids = inputs["input_ids"]
1643
+
1644
+ >>> model = FastSpeech2ConformerWithHifiGan.from_pretrained("espnet/fastspeech2_conformer_with_hifigan")
1645
+ >>> output_dict = model(input_ids, return_dict=True)
1646
+ >>> waveform = output_dict["waveform"]
1647
+ >>> print(waveform.shape)
1648
+ torch.Size([1, 49664])
1649
+ ```
1650
+ """
1651
+ return_dict = return_dict if return_dict is not None else self.config.model_config.use_return_dict
1652
+ output_attentions = (
1653
+ output_attentions if output_attentions is not None else self.config.model_config.output_attentions
1654
+ )
1655
+ output_hidden_states = (
1656
+ output_hidden_states if output_hidden_states is not None else self.config.model_config.output_hidden_states
1657
+ )
1658
+
1659
+ model_outputs = self.model(
1660
+ input_ids,
1661
+ attention_mask,
1662
+ spectrogram_labels=spectrogram_labels,
1663
+ duration_labels=duration_labels,
1664
+ pitch_labels=pitch_labels,
1665
+ energy_labels=energy_labels,
1666
+ speaker_ids=speaker_ids,
1667
+ lang_ids=lang_ids,
1668
+ speaker_embedding=speaker_embedding,
1669
+ return_dict=return_dict,
1670
+ output_attentions=output_attentions,
1671
+ output_hidden_states=output_hidden_states,
1672
+ )
1673
+
1674
+ if not return_dict:
1675
+ has_missing_labels = (
1676
+ spectrogram_labels is None or duration_labels is None or pitch_labels is None or energy_labels is None
1677
+ )
1678
+ if has_missing_labels:
1679
+ spectrogram = model_outputs[0]
1680
+ else:
1681
+ spectrogram = model_outputs[1]
1682
+ else:
1683
+ spectrogram = model_outputs["spectrogram"]
1684
+ waveform = self.vocoder(spectrogram)
1685
+
1686
+ if not return_dict:
1687
+ return model_outputs + (waveform,)
1688
+
1689
+ return FastSpeech2ConformerWithHifiGanOutput(waveform=waveform, **model_outputs)
1690
+
1691
+
1692
+ __all__ = [
1693
+ "FastSpeech2ConformerWithHifiGan",
1694
+ "FastSpeech2ConformerHifiGan",
1695
+ "FastSpeech2ConformerModel",
1696
+ "FastSpeech2ConformerPreTrainedModel",
1697
+ ]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fastspeech2_conformer/tokenization_fastspeech2_conformer.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Team 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 classes for FastSpeech2Conformer."""
16
+
17
+ import json
18
+ import os
19
+ from typing import Optional, Tuple
20
+
21
+ import regex
22
+
23
+ from ...tokenization_utils import PreTrainedTokenizer
24
+ from ...utils import logging, requires_backends
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json"}
30
+
31
+
32
+ class FastSpeech2ConformerTokenizer(PreTrainedTokenizer):
33
+ """
34
+ Construct a FastSpeech2Conformer tokenizer.
35
+
36
+ Args:
37
+ vocab_file (`str`):
38
+ Path to the vocabulary file.
39
+ bos_token (`str`, *optional*, defaults to `"<sos/eos>"`):
40
+ The begin of sequence token. Note that for FastSpeech2, it is the same as the `eos_token`.
41
+ eos_token (`str`, *optional*, defaults to `"<sos/eos>"`):
42
+ The end of sequence token. Note that for FastSpeech2, it is the same as the `bos_token`.
43
+ pad_token (`str`, *optional*, defaults to `"<blank>"`):
44
+ The token used for padding, for example when batching sequences of different lengths.
45
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
46
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
47
+ token instead.
48
+ should_strip_spaces (`bool`, *optional*, defaults to `False`):
49
+ Whether or not to strip the spaces from the list of tokens.
50
+ """
51
+
52
+ vocab_files_names = VOCAB_FILES_NAMES
53
+ model_input_names = ["input_ids", "attention_mask"]
54
+
55
+ def __init__(
56
+ self,
57
+ vocab_file,
58
+ bos_token="<sos/eos>",
59
+ eos_token="<sos/eos>",
60
+ pad_token="<blank>",
61
+ unk_token="<unk>",
62
+ should_strip_spaces=False,
63
+ **kwargs,
64
+ ):
65
+ requires_backends(self, "g2p_en")
66
+
67
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
68
+ self.encoder = json.load(vocab_handle)
69
+
70
+ import g2p_en
71
+
72
+ self.g2p = g2p_en.G2p()
73
+
74
+ self.decoder = {v: k for k, v in self.encoder.items()}
75
+
76
+ super().__init__(
77
+ bos_token=bos_token,
78
+ eos_token=eos_token,
79
+ unk_token=unk_token,
80
+ pad_token=pad_token,
81
+ should_strip_spaces=should_strip_spaces,
82
+ **kwargs,
83
+ )
84
+
85
+ self.should_strip_spaces = should_strip_spaces
86
+
87
+ @property
88
+ def vocab_size(self):
89
+ return len(self.decoder)
90
+
91
+ def get_vocab(self):
92
+ "Returns vocab as a dict"
93
+ return dict(self.encoder, **self.added_tokens_encoder)
94
+
95
+ def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
96
+ # expand symbols
97
+ text = regex.sub(";", ",", text)
98
+ text = regex.sub(":", ",", text)
99
+ text = regex.sub("-", " ", text)
100
+ text = regex.sub("&", "and", text)
101
+
102
+ # strip unnecessary symbols
103
+ text = regex.sub(r"[\(\)\[\]\<\>\"]+", "", text)
104
+
105
+ # strip whitespaces
106
+ text = regex.sub(r"\s+", " ", text)
107
+
108
+ text = text.upper()
109
+
110
+ return text, kwargs
111
+
112
+ def _tokenize(self, text):
113
+ """Returns a tokenized string."""
114
+ # phonemize
115
+ tokens = self.g2p(text)
116
+
117
+ if self.should_strip_spaces:
118
+ tokens = list(filter(lambda s: s != " ", tokens))
119
+
120
+ tokens.append(self.eos_token)
121
+
122
+ return tokens
123
+
124
+ def _convert_token_to_id(self, token):
125
+ """Converts a token (str) in an id using the vocab."""
126
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
127
+
128
+ def _convert_id_to_token(self, index):
129
+ """Converts an index (integer) in a token (str) using the vocab."""
130
+ return self.decoder.get(index, self.unk_token)
131
+
132
+ # Override since phonemes cannot be converted back to strings
133
+ def decode(self, token_ids, **kwargs):
134
+ logger.warning(
135
+ "Phonemes cannot be reliably converted to a string due to the one-many mapping, converting to tokens instead."
136
+ )
137
+ return self.convert_ids_to_tokens(token_ids)
138
+
139
+ # Override since phonemes cannot be converted back to strings
140
+ def convert_tokens_to_string(self, tokens, **kwargs):
141
+ logger.warning(
142
+ "Phonemes cannot be reliably converted to a string due to the one-many mapping, returning the tokens."
143
+ )
144
+ return tokens
145
+
146
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
147
+ """
148
+ Save the vocabulary and special tokens file to a directory.
149
+
150
+ Args:
151
+ save_directory (`str`):
152
+ The directory in which to save the vocabulary.
153
+
154
+ Returns:
155
+ `Tuple(str)`: Paths to the files saved.
156
+ """
157
+ if not os.path.isdir(save_directory):
158
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
159
+ return
160
+ vocab_file = os.path.join(
161
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
162
+ )
163
+
164
+ with open(vocab_file, "w", encoding="utf-8") as f:
165
+ f.write(json.dumps(self.get_vocab(), ensure_ascii=False))
166
+
167
+ return (vocab_file,)
168
+
169
+ def __getstate__(self):
170
+ state = self.__dict__.copy()
171
+ state["g2p"] = None
172
+ return state
173
+
174
+ def __setstate__(self, d):
175
+ self.__dict__ = d
176
+
177
+ try:
178
+ import g2p_en
179
+
180
+ self.g2p = g2p_en.G2p()
181
+ except ImportError:
182
+ raise ImportError(
183
+ "You need to install g2p-en to use FastSpeech2ConformerTokenizer. "
184
+ "See https://pypi.org/project/g2p-en/ for installation."
185
+ )
186
+
187
+
188
+ __all__ = ["FastSpeech2ConformerTokenizer"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flaubert/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_flaubert import *
22
+ from .modeling_flaubert import *
23
+ from .modeling_tf_flaubert import *
24
+ from .tokenization_flaubert import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flaubert/configuration_flaubert.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-present CNRS, Facebook Inc. 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
+ """Flaubert configuration"""
16
+
17
+ from collections import OrderedDict
18
+ from typing import Mapping
19
+
20
+ from ...configuration_utils import PretrainedConfig
21
+ from ...onnx import OnnxConfig
22
+ from ...utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class FlaubertConfig(PretrainedConfig):
29
+ """
30
+ This is the configuration class to store the configuration of a [`FlaubertModel`] or a [`TFFlaubertModel`]. It is
31
+ used to instantiate a FlauBERT model according to the specified arguments, defining the model architecture.
32
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the FlauBERT
33
+ [flaubert/flaubert_base_uncased](https://huggingface.co/flaubert/flaubert_base_uncased) architecture.
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+ Args:
39
+ pre_norm (`bool`, *optional*, defaults to `False`):
40
+ Whether to apply the layer normalization before or after the feed forward layer following the attention in
41
+ each layer (Vaswani et al., Tensor2Tensor for Neural Machine Translation. 2018)
42
+ layerdrop (`float`, *optional*, defaults to 0.0):
43
+ Probability to drop layers during training (Fan et al., Reducing Transformer Depth on Demand with
44
+ Structured Dropout. ICLR 2020)
45
+ vocab_size (`int`, *optional*, defaults to 30145):
46
+ Vocabulary size of the FlauBERT model. Defines the number of different tokens that can be represented by
47
+ the `inputs_ids` passed when calling [`FlaubertModel`] or [`TFFlaubertModel`].
48
+ emb_dim (`int`, *optional*, defaults to 2048):
49
+ Dimensionality of the encoder layers and the pooler layer.
50
+ n_layer (`int`, *optional*, defaults to 12):
51
+ Number of hidden layers in the Transformer encoder.
52
+ n_head (`int`, *optional*, defaults to 16):
53
+ Number of attention heads for each attention layer in the Transformer encoder.
54
+ dropout (`float`, *optional*, defaults to 0.1):
55
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
56
+ attention_dropout (`float`, *optional*, defaults to 0.1):
57
+ The dropout probability for the attention mechanism
58
+ gelu_activation (`bool`, *optional*, defaults to `True`):
59
+ Whether or not to use a *gelu* activation instead of *relu*.
60
+ sinusoidal_embeddings (`bool`, *optional*, defaults to `False`):
61
+ Whether or not to use sinusoidal positional embeddings instead of absolute positional embeddings.
62
+ causal (`bool`, *optional*, defaults to `False`):
63
+ Whether or not the model should behave in a causal manner. Causal models use a triangular attention mask in
64
+ order to only attend to the left-side context instead if a bidirectional context.
65
+ asm (`bool`, *optional*, defaults to `False`):
66
+ Whether or not to use an adaptive log softmax projection layer instead of a linear layer for the prediction
67
+ layer.
68
+ n_langs (`int`, *optional*, defaults to 1):
69
+ The number of languages the model handles. Set to 1 for monolingual models.
70
+ use_lang_emb (`bool`, *optional*, defaults to `True`)
71
+ Whether to use language embeddings. Some models use additional language embeddings, see [the multilingual
72
+ models page](http://huggingface.co/transformers/multilingual.html#xlm-language-embeddings) for information
73
+ on how to use them.
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
+ embed_init_std (`float`, *optional*, defaults to 2048^-0.5):
78
+ The standard deviation of the truncated_normal_initializer for initializing the embedding matrices.
79
+ init_std (`int`, *optional*, defaults to 50257):
80
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices except the
81
+ embedding matrices.
82
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
83
+ The epsilon used by the layer normalization layers.
84
+ bos_index (`int`, *optional*, defaults to 0):
85
+ The index of the beginning of sentence token in the vocabulary.
86
+ eos_index (`int`, *optional*, defaults to 1):
87
+ The index of the end of sentence token in the vocabulary.
88
+ pad_index (`int`, *optional*, defaults to 2):
89
+ The index of the padding token in the vocabulary.
90
+ unk_index (`int`, *optional*, defaults to 3):
91
+ The index of the unknown token in the vocabulary.
92
+ mask_index (`int`, *optional*, defaults to 5):
93
+ The index of the masking token in the vocabulary.
94
+ is_encoder(`bool`, *optional*, defaults to `True`):
95
+ Whether or not the initialized model should be a transformer encoder or decoder as seen in Vaswani et al.
96
+ summary_type (`string`, *optional*, defaults to "first"):
97
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
98
+
99
+ Has to be one of the following options:
100
+
101
+ - `"last"`: Take the last token hidden state (like XLNet).
102
+ - `"first"`: Take the first token hidden state (like BERT).
103
+ - `"mean"`: Take the mean of all tokens hidden states.
104
+ - `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
105
+ - `"attn"`: Not implemented now, use multi-head attention.
106
+ summary_use_proj (`bool`, *optional*, defaults to `True`):
107
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
108
+
109
+ Whether or not to add a projection after the vector extraction.
110
+ summary_activation (`str`, *optional*):
111
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
112
+
113
+ Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
114
+ summary_proj_to_labels (`bool`, *optional*, defaults to `True`):
115
+ Used in the sequence classification and multiple choice models.
116
+
117
+ Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.
118
+ summary_first_dropout (`float`, *optional*, defaults to 0.1):
119
+ Used in the sequence classification and multiple choice models.
120
+
121
+ The dropout ratio to be used after the projection and activation.
122
+ start_n_top (`int`, *optional*, defaults to 5):
123
+ Used in the SQuAD evaluation script.
124
+ end_n_top (`int`, *optional*, defaults to 5):
125
+ Used in the SQuAD evaluation script.
126
+ mask_token_id (`int`, *optional*, defaults to 0):
127
+ Model agnostic parameter to identify masked tokens when generating text in an MLM context.
128
+ lang_id (`int`, *optional*, defaults to 1):
129
+ The ID of the language used by the model. This parameter is used when generating text in a given language.
130
+ """
131
+
132
+ model_type = "flaubert"
133
+ attribute_map = {
134
+ "hidden_size": "emb_dim",
135
+ "num_attention_heads": "n_heads",
136
+ "num_hidden_layers": "n_layers",
137
+ "n_words": "vocab_size", # For backward compatibility
138
+ }
139
+
140
+ def __init__(
141
+ self,
142
+ pre_norm=False,
143
+ layerdrop=0.0,
144
+ vocab_size=30145,
145
+ emb_dim=2048,
146
+ n_layers=12,
147
+ n_heads=16,
148
+ dropout=0.1,
149
+ attention_dropout=0.1,
150
+ gelu_activation=True,
151
+ sinusoidal_embeddings=False,
152
+ causal=False,
153
+ asm=False,
154
+ n_langs=1,
155
+ use_lang_emb=True,
156
+ max_position_embeddings=512,
157
+ embed_init_std=2048**-0.5,
158
+ layer_norm_eps=1e-12,
159
+ init_std=0.02,
160
+ bos_index=0,
161
+ eos_index=1,
162
+ pad_index=2,
163
+ unk_index=3,
164
+ mask_index=5,
165
+ is_encoder=True,
166
+ summary_type="first",
167
+ summary_use_proj=True,
168
+ summary_activation=None,
169
+ summary_proj_to_labels=True,
170
+ summary_first_dropout=0.1,
171
+ start_n_top=5,
172
+ end_n_top=5,
173
+ mask_token_id=0,
174
+ lang_id=0,
175
+ pad_token_id=2,
176
+ bos_token_id=0,
177
+ **kwargs,
178
+ ):
179
+ """Constructs FlaubertConfig."""
180
+ self.pre_norm = pre_norm
181
+ self.layerdrop = layerdrop
182
+ self.vocab_size = vocab_size
183
+ self.emb_dim = emb_dim
184
+ self.n_layers = n_layers
185
+ self.n_heads = n_heads
186
+ self.dropout = dropout
187
+ self.attention_dropout = attention_dropout
188
+ self.gelu_activation = gelu_activation
189
+ self.sinusoidal_embeddings = sinusoidal_embeddings
190
+ self.causal = causal
191
+ self.asm = asm
192
+ self.n_langs = n_langs
193
+ self.use_lang_emb = use_lang_emb
194
+ self.layer_norm_eps = layer_norm_eps
195
+ self.bos_index = bos_index
196
+ self.eos_index = eos_index
197
+ self.pad_index = pad_index
198
+ self.unk_index = unk_index
199
+ self.mask_index = mask_index
200
+ self.is_encoder = is_encoder
201
+ self.max_position_embeddings = max_position_embeddings
202
+ self.embed_init_std = embed_init_std
203
+ self.init_std = init_std
204
+ self.summary_type = summary_type
205
+ self.summary_use_proj = summary_use_proj
206
+ self.summary_activation = summary_activation
207
+ self.summary_proj_to_labels = summary_proj_to_labels
208
+ self.summary_first_dropout = summary_first_dropout
209
+ self.start_n_top = start_n_top
210
+ self.end_n_top = end_n_top
211
+ self.mask_token_id = mask_token_id
212
+ self.lang_id = lang_id
213
+
214
+ if "n_words" in kwargs:
215
+ self.n_words = kwargs["n_words"]
216
+
217
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, **kwargs)
218
+
219
+
220
+ class FlaubertOnnxConfig(OnnxConfig):
221
+ @property
222
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
223
+ if self.task == "multiple-choice":
224
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
225
+ else:
226
+ dynamic_axis = {0: "batch", 1: "sequence"}
227
+ return OrderedDict(
228
+ [
229
+ ("input_ids", dynamic_axis),
230
+ ("attention_mask", dynamic_axis),
231
+ ]
232
+ )
233
+
234
+
235
+ __all__ = ["FlaubertConfig", "FlaubertOnnxConfig"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flaubert/modeling_flaubert.py ADDED
@@ -0,0 +1,1314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-present CNRS, Facebook Inc. 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 Flaubert model, based on XLM."""
16
+
17
+ import itertools
18
+ import math
19
+ from dataclasses import dataclass
20
+ from typing import Dict, Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+ import torch
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+
27
+ from ...activations import gelu
28
+ from ...generation import GenerationMixin
29
+ from ...modeling_outputs import (
30
+ BaseModelOutput,
31
+ MaskedLMOutput,
32
+ MultipleChoiceModelOutput,
33
+ QuestionAnsweringModelOutput,
34
+ SequenceClassifierOutput,
35
+ TokenClassifierOutput,
36
+ )
37
+ from ...modeling_utils import PreTrainedModel, SequenceSummary, SQuADHead
38
+ from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
39
+ from ...utils import (
40
+ ModelOutput,
41
+ add_code_sample_docstrings,
42
+ add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+ from .configuration_flaubert import FlaubertConfig
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+ _CHECKPOINT_FOR_DOC = "flaubert/flaubert_base_cased"
53
+ _CONFIG_FOR_DOC = "FlaubertConfig"
54
+
55
+
56
+ # Copied from transformers.models.xlm.modeling_xlm.create_sinusoidal_embeddings
57
+ def create_sinusoidal_embeddings(n_pos, dim, out):
58
+ position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)])
59
+ out.requires_grad = False
60
+ out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
61
+ out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
62
+ out.detach_()
63
+
64
+
65
+ # Copied from transformers.models.xlm.modeling_xlm.get_masks
66
+ def get_masks(slen, lengths, causal, padding_mask=None):
67
+ """
68
+ Generate hidden states mask, and optionally an attention mask.
69
+ """
70
+ alen = torch.arange(slen, dtype=torch.long, device=lengths.device)
71
+ if padding_mask is not None:
72
+ mask = padding_mask
73
+ else:
74
+ assert lengths.max().item() <= slen
75
+ mask = alen < lengths[:, None]
76
+
77
+ # attention mask is the same as mask, or triangular inferior attention (causal)
78
+ bs = lengths.size(0)
79
+ if causal:
80
+ attn_mask = alen[None, None, :].repeat(bs, slen, 1) <= alen[None, :, None]
81
+ else:
82
+ attn_mask = mask
83
+
84
+ # sanity check
85
+ assert mask.size() == (bs, slen)
86
+ assert causal is False or attn_mask.size() == (bs, slen, slen)
87
+
88
+ return mask, attn_mask
89
+
90
+
91
+ # Copied from transformers.models.xlm.modeling_xlm.MultiHeadAttention
92
+ class MultiHeadAttention(nn.Module):
93
+ NEW_ID = itertools.count()
94
+
95
+ def __init__(self, n_heads, dim, config):
96
+ super().__init__()
97
+ self.layer_id = next(MultiHeadAttention.NEW_ID)
98
+ self.dim = dim
99
+ self.n_heads = n_heads
100
+ self.dropout = config.attention_dropout
101
+ assert self.dim % self.n_heads == 0
102
+
103
+ self.q_lin = nn.Linear(dim, dim)
104
+ self.k_lin = nn.Linear(dim, dim)
105
+ self.v_lin = nn.Linear(dim, dim)
106
+ self.out_lin = nn.Linear(dim, dim)
107
+ self.pruned_heads = set()
108
+
109
+ def prune_heads(self, heads):
110
+ attention_head_size = self.dim // self.n_heads
111
+ if len(heads) == 0:
112
+ return
113
+ heads, index = find_pruneable_heads_and_indices(heads, self.n_heads, attention_head_size, self.pruned_heads)
114
+ # Prune linear layers
115
+ self.q_lin = prune_linear_layer(self.q_lin, index)
116
+ self.k_lin = prune_linear_layer(self.k_lin, index)
117
+ self.v_lin = prune_linear_layer(self.v_lin, index)
118
+ self.out_lin = prune_linear_layer(self.out_lin, index, dim=1)
119
+ # Update hyper params
120
+ self.n_heads = self.n_heads - len(heads)
121
+ self.dim = attention_head_size * self.n_heads
122
+ self.pruned_heads = self.pruned_heads.union(heads)
123
+
124
+ def forward(self, input, mask, kv=None, cache=None, head_mask=None, output_attentions=False):
125
+ """
126
+ Self-attention (if kv is None) or attention over source sentence (provided by kv).
127
+ """
128
+ # Input is (bs, qlen, dim)
129
+ # Mask is (bs, klen) (non-causal) or (bs, klen, klen)
130
+ bs, qlen, dim = input.size()
131
+ if kv is None:
132
+ klen = qlen if cache is None else cache["slen"] + qlen
133
+ else:
134
+ klen = kv.size(1)
135
+ # assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured'
136
+ n_heads = self.n_heads
137
+ dim_per_head = self.dim // n_heads
138
+ mask_reshape = (bs, 1, qlen, klen) if mask.dim() == 3 else (bs, 1, 1, klen)
139
+
140
+ def shape(x):
141
+ """projection"""
142
+ return x.view(bs, -1, self.n_heads, dim_per_head).transpose(1, 2)
143
+
144
+ def unshape(x):
145
+ """compute context"""
146
+ return x.transpose(1, 2).contiguous().view(bs, -1, self.n_heads * dim_per_head)
147
+
148
+ q = shape(self.q_lin(input)) # (bs, n_heads, qlen, dim_per_head)
149
+ if kv is None:
150
+ k = shape(self.k_lin(input)) # (bs, n_heads, qlen, dim_per_head)
151
+ v = shape(self.v_lin(input)) # (bs, n_heads, qlen, dim_per_head)
152
+ elif cache is None or self.layer_id not in cache:
153
+ k = v = kv
154
+ k = shape(self.k_lin(k)) # (bs, n_heads, qlen, dim_per_head)
155
+ v = shape(self.v_lin(v)) # (bs, n_heads, qlen, dim_per_head)
156
+
157
+ if cache is not None:
158
+ if self.layer_id in cache:
159
+ if kv is None:
160
+ k_, v_ = cache[self.layer_id]
161
+ k = torch.cat([k_, k], dim=2) # (bs, n_heads, klen, dim_per_head)
162
+ v = torch.cat([v_, v], dim=2) # (bs, n_heads, klen, dim_per_head)
163
+ else:
164
+ k, v = cache[self.layer_id]
165
+ cache[self.layer_id] = (k, v)
166
+
167
+ q = q / math.sqrt(dim_per_head) # (bs, n_heads, qlen, dim_per_head)
168
+ scores = torch.matmul(q, k.transpose(2, 3)) # (bs, n_heads, qlen, klen)
169
+ mask = (mask == 0).view(mask_reshape).expand_as(scores) # (bs, n_heads, qlen, klen)
170
+ scores.masked_fill_(mask, torch.finfo(scores.dtype).min) # (bs, n_heads, qlen, klen)
171
+
172
+ weights = nn.functional.softmax(scores.float(), dim=-1).type_as(scores) # (bs, n_heads, qlen, klen)
173
+ weights = nn.functional.dropout(weights, p=self.dropout, training=self.training) # (bs, n_heads, qlen, klen)
174
+
175
+ # Mask heads if we want to
176
+ if head_mask is not None:
177
+ weights = weights * head_mask
178
+
179
+ context = torch.matmul(weights, v) # (bs, n_heads, qlen, dim_per_head)
180
+ context = unshape(context) # (bs, qlen, dim)
181
+
182
+ outputs = (self.out_lin(context),)
183
+ if output_attentions:
184
+ outputs = outputs + (weights,)
185
+ return outputs
186
+
187
+
188
+ # Copied from transformers.models.xlm.modeling_xlm.TransformerFFN
189
+ class TransformerFFN(nn.Module):
190
+ def __init__(self, in_dim, dim_hidden, out_dim, config):
191
+ super().__init__()
192
+ self.dropout = config.dropout
193
+ self.lin1 = nn.Linear(in_dim, dim_hidden)
194
+ self.lin2 = nn.Linear(dim_hidden, out_dim)
195
+ self.act = gelu if config.gelu_activation else nn.functional.relu
196
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
197
+ self.seq_len_dim = 1
198
+
199
+ def forward(self, input):
200
+ return apply_chunking_to_forward(self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, input)
201
+
202
+ def ff_chunk(self, input):
203
+ x = self.lin1(input)
204
+ x = self.act(x)
205
+ x = self.lin2(x)
206
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
207
+ return x
208
+
209
+
210
+ FLAUBERT_START_DOCSTRING = r"""
211
+
212
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
213
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
214
+ etc.)
215
+
216
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
217
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
218
+ and behavior.
219
+
220
+ Parameters:
221
+ config ([`FlaubertConfig`]): Model configuration class with all the parameters of the model.
222
+ Initializing with a config file does not load the weights associated with the model, only the
223
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
224
+ """
225
+
226
+ FLAUBERT_INPUTS_DOCSTRING = r"""
227
+ Args:
228
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
229
+ Indices of input sequence tokens in the vocabulary.
230
+
231
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
232
+ [`PreTrainedTokenizer.__call__`] for details.
233
+
234
+ [What are input IDs?](../glossary#input-ids)
235
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
236
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
237
+
238
+ - 1 for tokens that are **not masked**,
239
+ - 0 for tokens that are **masked**.
240
+
241
+ [What are attention masks?](../glossary#attention-mask)
242
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
243
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
244
+ 1]`:
245
+
246
+ - 0 corresponds to a *sentence A* token,
247
+ - 1 corresponds to a *sentence B* token.
248
+
249
+ [What are token type IDs?](../glossary#token-type-ids)
250
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
251
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
252
+ config.max_position_embeddings - 1]`.
253
+
254
+ [What are position IDs?](../glossary#position-ids)
255
+ lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
256
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
257
+ also use `attention_mask` for the same result (see above), kept here for compatibility. Indices selected in
258
+ `[0, ..., input_ids.size(-1)]`:
259
+ cache (`Dict[str, torch.FloatTensor]`, *optional*):
260
+ Dictionary strings to `torch.FloatTensor` that contains precomputed hidden-states (key and values in the
261
+ attention blocks) as computed by the model (see `cache` output below). Can be used to speed up sequential
262
+ decoding. The dictionary object will be modified in-place during the forward pass to add newly computed
263
+ hidden-states.
264
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
265
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
266
+
267
+ - 1 indicates the head is **not masked**,
268
+ - 0 indicates the head is **masked**.
269
+
270
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
271
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
272
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
273
+ model's internal embedding lookup matrix.
274
+ output_attentions (`bool`, *optional*):
275
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
276
+ tensors for more detail.
277
+ output_hidden_states (`bool`, *optional*):
278
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
279
+ more detail.
280
+ return_dict (`bool`, *optional*):
281
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
282
+ """
283
+
284
+
285
+ @add_start_docstrings(
286
+ "The bare Flaubert Model transformer outputting raw hidden-states without any specific head on top.",
287
+ FLAUBERT_START_DOCSTRING,
288
+ )
289
+ # Copied from transformers.models.xlm.modeling_xlm.XLMPredLayer with XLM->Flaubert
290
+ class FlaubertPredLayer(nn.Module):
291
+ """
292
+ Prediction layer (cross_entropy or adaptive_softmax).
293
+ """
294
+
295
+ def __init__(self, config):
296
+ super().__init__()
297
+ self.asm = config.asm
298
+ self.n_words = config.n_words
299
+ self.pad_index = config.pad_index
300
+ dim = config.emb_dim
301
+
302
+ if config.asm is False:
303
+ self.proj = nn.Linear(dim, config.n_words, bias=True)
304
+ else:
305
+ self.proj = nn.AdaptiveLogSoftmaxWithLoss(
306
+ in_features=dim,
307
+ n_classes=config.n_words,
308
+ cutoffs=config.asm_cutoffs,
309
+ div_value=config.asm_div_value,
310
+ head_bias=True, # default is False
311
+ )
312
+
313
+ def forward(self, x, y=None):
314
+ """Compute the loss, and optionally the scores."""
315
+ outputs = ()
316
+ if self.asm is False:
317
+ scores = self.proj(x)
318
+ outputs = (scores,) + outputs
319
+ if y is not None:
320
+ loss = nn.functional.cross_entropy(scores.view(-1, self.n_words), y.view(-1), reduction="mean")
321
+ outputs = (loss,) + outputs
322
+ else:
323
+ scores = self.proj.log_prob(x)
324
+ outputs = (scores,) + outputs
325
+ if y is not None:
326
+ _, loss = self.proj(x, y)
327
+ outputs = (loss,) + outputs
328
+
329
+ return outputs
330
+
331
+
332
+ # Copied from transformers.models.xlm.modeling_xlm.XLMPreTrainedModel with XLM->Flaubert
333
+ class FlaubertPreTrainedModel(PreTrainedModel):
334
+ """
335
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
336
+ models.
337
+ """
338
+
339
+ config_class = FlaubertConfig
340
+ load_tf_weights = None
341
+ base_model_prefix = "transformer"
342
+
343
+ def __init__(self, *inputs, **kwargs):
344
+ super().__init__(*inputs, **kwargs)
345
+
346
+ @property
347
+ def dummy_inputs(self):
348
+ inputs_list = torch.tensor([[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]])
349
+ attns_list = torch.tensor([[1, 1, 0, 0, 1], [1, 1, 1, 0, 0], [1, 0, 0, 1, 1]])
350
+ if self.config.use_lang_emb and self.config.n_langs > 1:
351
+ langs_list = torch.tensor([[1, 1, 0, 0, 1], [1, 1, 1, 0, 0], [1, 0, 0, 1, 1]])
352
+ else:
353
+ langs_list = None
354
+ return {"input_ids": inputs_list, "attention_mask": attns_list, "langs": langs_list}
355
+
356
+ def _init_weights(self, module):
357
+ """Initialize the weights."""
358
+ if isinstance(module, nn.Embedding):
359
+ if self.config is not None and self.config.embed_init_std is not None:
360
+ nn.init.normal_(module.weight, mean=0, std=self.config.embed_init_std)
361
+ if module.padding_idx is not None:
362
+ module.weight.data[module.padding_idx].zero_()
363
+ if isinstance(module, nn.Linear):
364
+ if self.config is not None and self.config.init_std is not None:
365
+ nn.init.normal_(module.weight, mean=0, std=self.config.init_std)
366
+ if module.bias is not None:
367
+ nn.init.constant_(module.bias, 0.0)
368
+ if isinstance(module, nn.LayerNorm):
369
+ module.bias.data.zero_()
370
+ module.weight.data.fill_(1.0)
371
+ if isinstance(module, FlaubertModel) and self.config.sinusoidal_embeddings:
372
+ create_sinusoidal_embeddings(
373
+ self.config.max_position_embeddings, self.config.emb_dim, out=module.position_embeddings.weight
374
+ )
375
+
376
+
377
+ class FlaubertModel(FlaubertPreTrainedModel):
378
+ def __init__(self, config): # , dico, is_encoder, with_output):
379
+ super().__init__(config)
380
+
381
+ # encoder / decoder, output layer
382
+ self.is_encoder = config.is_encoder
383
+ self.is_decoder = not config.is_encoder
384
+ if self.is_decoder:
385
+ raise NotImplementedError("Currently Flaubert can only be used as an encoder")
386
+ # self.with_output = with_output
387
+ self.causal = config.causal
388
+
389
+ # dictionary / languages
390
+ self.n_langs = config.n_langs
391
+ self.use_lang_emb = config.use_lang_emb
392
+ self.n_words = config.n_words
393
+ self.eos_index = config.eos_index
394
+ self.pad_index = config.pad_index
395
+ # self.dico = dico
396
+ # self.id2lang = config.id2lang
397
+ # self.lang2id = config.lang2id
398
+ # assert len(self.dico) == self.n_words
399
+ # assert len(self.id2lang) == len(self.lang2id) == self.n_langs
400
+
401
+ # model parameters
402
+ self.dim = config.emb_dim # 512 by default
403
+ self.hidden_dim = self.dim * 4 # 2048 by default
404
+ self.n_heads = config.n_heads # 8 by default
405
+ self.n_layers = config.n_layers
406
+ self.dropout = config.dropout
407
+ self.attention_dropout = config.attention_dropout
408
+ assert self.dim % self.n_heads == 0, "transformer dim must be a multiple of n_heads"
409
+
410
+ # embeddings
411
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, self.dim)
412
+ if config.n_langs > 1 and config.use_lang_emb:
413
+ self.lang_embeddings = nn.Embedding(self.n_langs, self.dim)
414
+ self.embeddings = nn.Embedding(self.n_words, self.dim, padding_idx=self.pad_index)
415
+ self.layer_norm_emb = nn.LayerNorm(self.dim, eps=config.layer_norm_eps)
416
+
417
+ # transformer layers
418
+ self.attentions = nn.ModuleList()
419
+ self.layer_norm1 = nn.ModuleList()
420
+ self.ffns = nn.ModuleList()
421
+ self.layer_norm2 = nn.ModuleList()
422
+ # if self.is_decoder:
423
+ # self.layer_norm15 = nn.ModuleList()
424
+ # self.encoder_attn = nn.ModuleList()
425
+
426
+ for _ in range(self.n_layers):
427
+ self.attentions.append(MultiHeadAttention(self.n_heads, self.dim, config=config))
428
+ self.layer_norm1.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
429
+ # if self.is_decoder:
430
+ # self.layer_norm15.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
431
+ # self.encoder_attn.append(MultiHeadAttention(self.n_heads, self.dim, dropout=self.attention_dropout))
432
+ self.ffns.append(TransformerFFN(self.dim, self.hidden_dim, self.dim, config=config))
433
+ self.layer_norm2.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
434
+
435
+ if hasattr(config, "pruned_heads"):
436
+ pruned_heads = config.pruned_heads.copy().items()
437
+ config.pruned_heads = {}
438
+ for layer, heads in pruned_heads:
439
+ if self.attentions[int(layer)].n_heads == config.n_heads:
440
+ self.prune_heads({int(layer): list(map(int, heads))})
441
+
442
+ # Initialize weights and apply final processing
443
+ self.post_init()
444
+
445
+ self.layerdrop = getattr(config, "layerdrop", 0.0)
446
+ self.pre_norm = getattr(config, "pre_norm", False)
447
+ self.register_buffer(
448
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
449
+ )
450
+
451
+ # Copied from transformers.models.xlm.modeling_xlm.XLMModel.get_input_embeddings
452
+ def get_input_embeddings(self):
453
+ return self.embeddings
454
+
455
+ # Copied from transformers.models.xlm.modeling_xlm.XLMModel.set_input_embeddings
456
+ def set_input_embeddings(self, new_embeddings):
457
+ self.embeddings = new_embeddings
458
+
459
+ # Copied from transformers.models.xlm.modeling_xlm.XLMModel._prune_heads
460
+ def _prune_heads(self, heads_to_prune):
461
+ """
462
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
463
+ class PreTrainedModel
464
+ """
465
+ for layer, heads in heads_to_prune.items():
466
+ self.attentions[layer].prune_heads(heads)
467
+
468
+ @add_start_docstrings_to_model_forward(FLAUBERT_INPUTS_DOCSTRING)
469
+ @add_code_sample_docstrings(
470
+ checkpoint=_CHECKPOINT_FOR_DOC,
471
+ output_type=BaseModelOutput,
472
+ config_class=_CONFIG_FOR_DOC,
473
+ )
474
+ def forward(
475
+ self,
476
+ input_ids: Optional[torch.LongTensor] = None,
477
+ attention_mask: Optional[torch.FloatTensor] = None,
478
+ langs: Optional[torch.Tensor] = None,
479
+ token_type_ids: Optional[torch.LongTensor] = None,
480
+ position_ids: Optional[torch.LongTensor] = None,
481
+ lengths: Optional[torch.LongTensor] = None,
482
+ cache: Optional[Dict[str, torch.FloatTensor]] = None,
483
+ head_mask: Optional[torch.FloatTensor] = None,
484
+ inputs_embeds: Optional[torch.FloatTensor] = None,
485
+ output_attentions: Optional[bool] = None,
486
+ output_hidden_states: Optional[bool] = None,
487
+ return_dict: Optional[bool] = None,
488
+ ) -> Union[Tuple, BaseModelOutput]:
489
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
490
+ output_hidden_states = (
491
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
492
+ )
493
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
494
+
495
+ # removed: src_enc=None, src_len=None
496
+ if input_ids is not None:
497
+ bs, slen = input_ids.size()
498
+ else:
499
+ bs, slen = inputs_embeds.size()[:-1]
500
+
501
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
502
+
503
+ if lengths is None:
504
+ if input_ids is not None:
505
+ lengths = (input_ids != self.pad_index).sum(dim=1).long()
506
+ else:
507
+ lengths = torch.tensor([slen] * bs, device=device)
508
+ # mask = input_ids != self.pad_index
509
+
510
+ # check inputs
511
+ assert lengths.size(0) == bs
512
+ assert lengths.max().item() <= slen
513
+ # input_ids = input_ids.transpose(0, 1) # batch size as dimension 0
514
+ # assert (src_enc is None) == (src_len is None)
515
+ # if src_enc is not None:
516
+ # assert self.is_decoder
517
+ # assert src_enc.size(0) == bs
518
+
519
+ # generate masks
520
+ mask, attn_mask = get_masks(slen, lengths, self.causal, padding_mask=attention_mask)
521
+ # if self.is_decoder and src_enc is not None:
522
+ # src_mask = torch.arange(src_len.max(), dtype=torch.long, device=lengths.device) < src_len[:, None]
523
+
524
+ # Setting the position-ids to the registered buffer in constructor, it helps
525
+ # when tracing the model without passing position-ids, solves
526
+ # isues similar to issue #5664
527
+ if position_ids is None:
528
+ if hasattr(self, "position_ids"):
529
+ position_ids = self.position_ids[:, :slen]
530
+ position_ids = position_ids.expand((bs, slen))
531
+ else:
532
+ position_ids = torch.arange(slen, dtype=torch.long, device=device)
533
+ position_ids = position_ids.unsqueeze(0).expand((bs, slen))
534
+ else:
535
+ assert position_ids.size() == (bs, slen) # (slen, bs)
536
+ # position_ids = position_ids.transpose(0, 1)
537
+
538
+ # langs
539
+ if langs is not None:
540
+ assert langs.size() == (bs, slen) # (slen, bs)
541
+ # langs = langs.transpose(0, 1)
542
+
543
+ # Prepare head mask if needed
544
+ head_mask = self.get_head_mask(head_mask, self.config.n_layers)
545
+
546
+ # do not recompute cached elements
547
+ if cache is not None and input_ids is not None:
548
+ _slen = slen - cache["slen"]
549
+ input_ids = input_ids[:, -_slen:]
550
+ position_ids = position_ids[:, -_slen:]
551
+ if langs is not None:
552
+ langs = langs[:, -_slen:]
553
+ mask = mask[:, -_slen:]
554
+ attn_mask = attn_mask[:, -_slen:]
555
+
556
+ # embeddings
557
+ if inputs_embeds is None:
558
+ inputs_embeds = self.embeddings(input_ids)
559
+
560
+ tensor = inputs_embeds + self.position_embeddings(position_ids).expand_as(inputs_embeds)
561
+ if langs is not None and self.use_lang_emb and self.config.n_langs > 1:
562
+ tensor = tensor + self.lang_embeddings(langs)
563
+ if token_type_ids is not None:
564
+ tensor = tensor + self.embeddings(token_type_ids)
565
+ tensor = self.layer_norm_emb(tensor)
566
+ tensor = nn.functional.dropout(tensor, p=self.dropout, training=self.training)
567
+ tensor *= mask.unsqueeze(-1).to(tensor.dtype)
568
+
569
+ # transformer layers
570
+ hidden_states = () if output_hidden_states else None
571
+ attentions = () if output_attentions else None
572
+ for i in range(self.n_layers):
573
+ # LayerDrop
574
+ if self.training:
575
+ dropout_probability = torch.rand([])
576
+ if dropout_probability < self.layerdrop:
577
+ continue
578
+
579
+ if output_hidden_states:
580
+ hidden_states = hidden_states + (tensor,)
581
+
582
+ # self attention
583
+ if not self.pre_norm:
584
+ attn_outputs = self.attentions[i](
585
+ tensor,
586
+ attn_mask,
587
+ cache=cache,
588
+ head_mask=head_mask[i],
589
+ output_attentions=output_attentions,
590
+ )
591
+ attn = attn_outputs[0]
592
+ if output_attentions:
593
+ attentions = attentions + (attn_outputs[1],)
594
+ attn = nn.functional.dropout(attn, p=self.dropout, training=self.training)
595
+ tensor = tensor + attn
596
+ tensor = self.layer_norm1[i](tensor)
597
+ else:
598
+ tensor_normalized = self.layer_norm1[i](tensor)
599
+ attn_outputs = self.attentions[i](tensor_normalized, attn_mask, cache=cache, head_mask=head_mask[i])
600
+ attn = attn_outputs[0]
601
+ if output_attentions:
602
+ attentions = attentions + (attn_outputs[1],)
603
+ attn = nn.functional.dropout(attn, p=self.dropout, training=self.training)
604
+ tensor = tensor + attn
605
+
606
+ # encoder attention (for decoder only)
607
+ # if self.is_decoder and src_enc is not None:
608
+ # attn = self.encoder_attn[i](tensor, src_mask, kv=src_enc, cache=cache)
609
+ # attn = nn.functional.dropout(attn, p=self.dropout, training=self.training)
610
+ # tensor = tensor + attn
611
+ # tensor = self.layer_norm15[i](tensor)
612
+
613
+ # FFN
614
+ if not self.pre_norm:
615
+ tensor = tensor + self.ffns[i](tensor)
616
+ tensor = self.layer_norm2[i](tensor)
617
+ else:
618
+ tensor_normalized = self.layer_norm2[i](tensor)
619
+ tensor = tensor + self.ffns[i](tensor_normalized)
620
+
621
+ tensor *= mask.unsqueeze(-1).to(tensor.dtype)
622
+
623
+ # Add last hidden state
624
+ if output_hidden_states:
625
+ hidden_states = hidden_states + (tensor,)
626
+
627
+ # update cache length
628
+ if cache is not None:
629
+ cache["slen"] += tensor.size(1)
630
+
631
+ # move back sequence length to dimension 0
632
+ # tensor = tensor.transpose(0, 1)
633
+
634
+ if not return_dict:
635
+ return tuple(v for v in [tensor, hidden_states, attentions] if v is not None)
636
+
637
+ return BaseModelOutput(last_hidden_state=tensor, hidden_states=hidden_states, attentions=attentions)
638
+
639
+
640
+ @add_start_docstrings(
641
+ """
642
+ The Flaubert Model transformer with a language modeling head on top (linear layer with weights tied to the input
643
+ embeddings).
644
+ """,
645
+ FLAUBERT_START_DOCSTRING,
646
+ )
647
+ # Copied transformers.models.xlm.modeling_xlm.XLMWithLMHeadModel with XLM_INPUTS->FLAUBERT_INPUTS,XLM->Flaubert
648
+ class FlaubertWithLMHeadModel(FlaubertPreTrainedModel, GenerationMixin):
649
+ _tied_weights_keys = ["pred_layer.proj.weight"]
650
+
651
+ def __init__(self, config):
652
+ super().__init__(config)
653
+ self.transformer = FlaubertModel(config)
654
+ self.pred_layer = FlaubertPredLayer(config)
655
+
656
+ # Initialize weights and apply final processing
657
+ self.post_init()
658
+
659
+ def get_output_embeddings(self):
660
+ return self.pred_layer.proj
661
+
662
+ def set_output_embeddings(self, new_embeddings):
663
+ self.pred_layer.proj = new_embeddings
664
+
665
+ def prepare_inputs_for_generation(self, input_ids, **kwargs):
666
+ # Overwritten -- uses a language id
667
+
668
+ mask_token_id = self.config.mask_token_id
669
+ lang_id = self.config.lang_id
670
+
671
+ effective_batch_size = input_ids.shape[0]
672
+ mask_token = torch.full((effective_batch_size, 1), mask_token_id, dtype=torch.long, device=input_ids.device)
673
+ input_ids = torch.cat([input_ids, mask_token], dim=1)
674
+ if lang_id is not None:
675
+ langs = torch.full_like(input_ids, lang_id)
676
+ else:
677
+ langs = None
678
+ return {"input_ids": input_ids, "langs": langs}
679
+
680
+ @add_start_docstrings_to_model_forward(FLAUBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
681
+ @add_code_sample_docstrings(
682
+ checkpoint=_CHECKPOINT_FOR_DOC,
683
+ output_type=MaskedLMOutput,
684
+ config_class=_CONFIG_FOR_DOC,
685
+ mask="<special1>",
686
+ )
687
+ def forward(
688
+ self,
689
+ input_ids: Optional[torch.Tensor] = None,
690
+ attention_mask: Optional[torch.Tensor] = None,
691
+ langs: Optional[torch.Tensor] = None,
692
+ token_type_ids: Optional[torch.Tensor] = None,
693
+ position_ids: Optional[torch.Tensor] = None,
694
+ lengths: Optional[torch.Tensor] = None,
695
+ cache: Optional[Dict[str, torch.Tensor]] = None,
696
+ head_mask: Optional[torch.Tensor] = None,
697
+ inputs_embeds: Optional[torch.Tensor] = None,
698
+ labels: Optional[torch.Tensor] = None,
699
+ output_attentions: Optional[bool] = None,
700
+ output_hidden_states: Optional[bool] = None,
701
+ return_dict: Optional[bool] = None,
702
+ ) -> Union[Tuple, MaskedLMOutput]:
703
+ r"""
704
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
705
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
706
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
707
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
708
+ """
709
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
710
+
711
+ transformer_outputs = self.transformer(
712
+ input_ids,
713
+ attention_mask=attention_mask,
714
+ langs=langs,
715
+ token_type_ids=token_type_ids,
716
+ position_ids=position_ids,
717
+ lengths=lengths,
718
+ cache=cache,
719
+ head_mask=head_mask,
720
+ inputs_embeds=inputs_embeds,
721
+ output_attentions=output_attentions,
722
+ output_hidden_states=output_hidden_states,
723
+ return_dict=return_dict,
724
+ )
725
+
726
+ output = transformer_outputs[0]
727
+ outputs = self.pred_layer(output, labels) # (loss, logits) or (logits,) depending on if labels are provided.
728
+
729
+ if not return_dict:
730
+ return outputs + transformer_outputs[1:]
731
+
732
+ return MaskedLMOutput(
733
+ loss=outputs[0] if labels is not None else None,
734
+ logits=outputs[0] if labels is None else outputs[1],
735
+ hidden_states=transformer_outputs.hidden_states,
736
+ attentions=transformer_outputs.attentions,
737
+ )
738
+
739
+
740
+ @add_start_docstrings(
741
+ """
742
+ Flaubert Model with a sequence classification/regression head on top (a linear layer on top of the pooled output)
743
+ e.g. for GLUE tasks.
744
+ """,
745
+ FLAUBERT_START_DOCSTRING,
746
+ )
747
+ # Copied transformers.models.xlm.modeling_xlm.XLMForSequenceClassification with XLM_INPUTS->FLAUBERT_INPUTS,XLM->Flaubert
748
+ class FlaubertForSequenceClassification(FlaubertPreTrainedModel):
749
+ def __init__(self, config):
750
+ super().__init__(config)
751
+ self.num_labels = config.num_labels
752
+ self.config = config
753
+
754
+ self.transformer = FlaubertModel(config)
755
+ self.sequence_summary = SequenceSummary(config)
756
+
757
+ # Initialize weights and apply final processing
758
+ self.post_init()
759
+
760
+ @add_start_docstrings_to_model_forward(FLAUBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
761
+ @add_code_sample_docstrings(
762
+ checkpoint=_CHECKPOINT_FOR_DOC,
763
+ output_type=SequenceClassifierOutput,
764
+ config_class=_CONFIG_FOR_DOC,
765
+ )
766
+ def forward(
767
+ self,
768
+ input_ids: Optional[torch.Tensor] = None,
769
+ attention_mask: Optional[torch.Tensor] = None,
770
+ langs: Optional[torch.Tensor] = None,
771
+ token_type_ids: Optional[torch.Tensor] = None,
772
+ position_ids: Optional[torch.Tensor] = None,
773
+ lengths: Optional[torch.Tensor] = None,
774
+ cache: Optional[Dict[str, torch.Tensor]] = None,
775
+ head_mask: Optional[torch.Tensor] = None,
776
+ inputs_embeds: Optional[torch.Tensor] = None,
777
+ labels: Optional[torch.Tensor] = None,
778
+ output_attentions: Optional[bool] = None,
779
+ output_hidden_states: Optional[bool] = None,
780
+ return_dict: Optional[bool] = None,
781
+ ) -> Union[Tuple, SequenceClassifierOutput]:
782
+ r"""
783
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
784
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
785
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
786
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
787
+ """
788
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
789
+
790
+ transformer_outputs = self.transformer(
791
+ input_ids,
792
+ attention_mask=attention_mask,
793
+ langs=langs,
794
+ token_type_ids=token_type_ids,
795
+ position_ids=position_ids,
796
+ lengths=lengths,
797
+ cache=cache,
798
+ head_mask=head_mask,
799
+ inputs_embeds=inputs_embeds,
800
+ output_attentions=output_attentions,
801
+ output_hidden_states=output_hidden_states,
802
+ return_dict=return_dict,
803
+ )
804
+
805
+ output = transformer_outputs[0]
806
+ logits = self.sequence_summary(output)
807
+
808
+ loss = None
809
+ if labels is not None:
810
+ if self.config.problem_type is None:
811
+ if self.num_labels == 1:
812
+ self.config.problem_type = "regression"
813
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
814
+ self.config.problem_type = "single_label_classification"
815
+ else:
816
+ self.config.problem_type = "multi_label_classification"
817
+
818
+ if self.config.problem_type == "regression":
819
+ loss_fct = MSELoss()
820
+ if self.num_labels == 1:
821
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
822
+ else:
823
+ loss = loss_fct(logits, labels)
824
+ elif self.config.problem_type == "single_label_classification":
825
+ loss_fct = CrossEntropyLoss()
826
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
827
+ elif self.config.problem_type == "multi_label_classification":
828
+ loss_fct = BCEWithLogitsLoss()
829
+ loss = loss_fct(logits, labels)
830
+
831
+ if not return_dict:
832
+ output = (logits,) + transformer_outputs[1:]
833
+ return ((loss,) + output) if loss is not None else output
834
+
835
+ return SequenceClassifierOutput(
836
+ loss=loss,
837
+ logits=logits,
838
+ hidden_states=transformer_outputs.hidden_states,
839
+ attentions=transformer_outputs.attentions,
840
+ )
841
+
842
+
843
+ @add_start_docstrings(
844
+ """
845
+ Flaubert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
846
+ Named-Entity-Recognition (NER) tasks.
847
+ """,
848
+ FLAUBERT_START_DOCSTRING,
849
+ )
850
+ # Copied from transformers.models.xlm.modeling_xlm.XLMForTokenClassification with XLM_INPUTS->FLAUBERT_INPUTS,XLM->Flaubert
851
+ class FlaubertForTokenClassification(FlaubertPreTrainedModel):
852
+ def __init__(self, config):
853
+ super().__init__(config)
854
+ self.num_labels = config.num_labels
855
+
856
+ self.transformer = FlaubertModel(config)
857
+ self.dropout = nn.Dropout(config.dropout)
858
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
859
+
860
+ # Initialize weights and apply final processing
861
+ self.post_init()
862
+
863
+ @add_start_docstrings_to_model_forward(FLAUBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
864
+ @add_code_sample_docstrings(
865
+ checkpoint=_CHECKPOINT_FOR_DOC,
866
+ output_type=TokenClassifierOutput,
867
+ config_class=_CONFIG_FOR_DOC,
868
+ )
869
+ def forward(
870
+ self,
871
+ input_ids: Optional[torch.Tensor] = None,
872
+ attention_mask: Optional[torch.Tensor] = None,
873
+ langs: Optional[torch.Tensor] = None,
874
+ token_type_ids: Optional[torch.Tensor] = None,
875
+ position_ids: Optional[torch.Tensor] = None,
876
+ lengths: Optional[torch.Tensor] = None,
877
+ cache: Optional[Dict[str, torch.Tensor]] = None,
878
+ head_mask: Optional[torch.Tensor] = None,
879
+ inputs_embeds: Optional[torch.Tensor] = None,
880
+ labels: Optional[torch.Tensor] = None,
881
+ output_attentions: Optional[bool] = None,
882
+ output_hidden_states: Optional[bool] = None,
883
+ return_dict: Optional[bool] = None,
884
+ ) -> Union[Tuple, TokenClassifierOutput]:
885
+ r"""
886
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
887
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
888
+ """
889
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
890
+
891
+ outputs = self.transformer(
892
+ input_ids,
893
+ attention_mask=attention_mask,
894
+ langs=langs,
895
+ token_type_ids=token_type_ids,
896
+ position_ids=position_ids,
897
+ lengths=lengths,
898
+ cache=cache,
899
+ head_mask=head_mask,
900
+ inputs_embeds=inputs_embeds,
901
+ output_attentions=output_attentions,
902
+ output_hidden_states=output_hidden_states,
903
+ return_dict=return_dict,
904
+ )
905
+
906
+ sequence_output = outputs[0]
907
+
908
+ sequence_output = self.dropout(sequence_output)
909
+ logits = self.classifier(sequence_output)
910
+
911
+ loss = None
912
+ if labels is not None:
913
+ loss_fct = CrossEntropyLoss()
914
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
915
+
916
+ if not return_dict:
917
+ output = (logits,) + outputs[1:]
918
+ return ((loss,) + output) if loss is not None else output
919
+
920
+ return TokenClassifierOutput(
921
+ loss=loss,
922
+ logits=logits,
923
+ hidden_states=outputs.hidden_states,
924
+ attentions=outputs.attentions,
925
+ )
926
+
927
+
928
+ @add_start_docstrings(
929
+ """
930
+ Flaubert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
931
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
932
+ """,
933
+ FLAUBERT_START_DOCSTRING,
934
+ )
935
+ # Copied from transformers.models.xlm.modeling_xlm.XLMForQuestionAnsweringSimple with XLM_INPUTS->FLAUBERT_INPUTS,XLM->Flaubert
936
+ class FlaubertForQuestionAnsweringSimple(FlaubertPreTrainedModel):
937
+ def __init__(self, config):
938
+ super().__init__(config)
939
+
940
+ self.transformer = FlaubertModel(config)
941
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
942
+
943
+ # Initialize weights and apply final processing
944
+ self.post_init()
945
+
946
+ @add_start_docstrings_to_model_forward(FLAUBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
947
+ @add_code_sample_docstrings(
948
+ checkpoint=_CHECKPOINT_FOR_DOC,
949
+ output_type=QuestionAnsweringModelOutput,
950
+ config_class=_CONFIG_FOR_DOC,
951
+ )
952
+ def forward(
953
+ self,
954
+ input_ids: Optional[torch.Tensor] = None,
955
+ attention_mask: Optional[torch.Tensor] = None,
956
+ langs: Optional[torch.Tensor] = None,
957
+ token_type_ids: Optional[torch.Tensor] = None,
958
+ position_ids: Optional[torch.Tensor] = None,
959
+ lengths: Optional[torch.Tensor] = None,
960
+ cache: Optional[Dict[str, torch.Tensor]] = None,
961
+ head_mask: Optional[torch.Tensor] = None,
962
+ inputs_embeds: Optional[torch.Tensor] = None,
963
+ start_positions: Optional[torch.Tensor] = None,
964
+ end_positions: Optional[torch.Tensor] = None,
965
+ output_attentions: Optional[bool] = None,
966
+ output_hidden_states: Optional[bool] = None,
967
+ return_dict: Optional[bool] = None,
968
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
969
+ r"""
970
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
971
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
972
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
973
+ are not taken into account for computing the loss.
974
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
975
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
976
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
977
+ are not taken into account for computing the loss.
978
+ """
979
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
980
+
981
+ transformer_outputs = self.transformer(
982
+ input_ids,
983
+ attention_mask=attention_mask,
984
+ langs=langs,
985
+ token_type_ids=token_type_ids,
986
+ position_ids=position_ids,
987
+ lengths=lengths,
988
+ cache=cache,
989
+ head_mask=head_mask,
990
+ inputs_embeds=inputs_embeds,
991
+ output_attentions=output_attentions,
992
+ output_hidden_states=output_hidden_states,
993
+ return_dict=return_dict,
994
+ )
995
+
996
+ sequence_output = transformer_outputs[0]
997
+
998
+ logits = self.qa_outputs(sequence_output)
999
+ start_logits, end_logits = logits.split(1, dim=-1)
1000
+ start_logits = start_logits.squeeze(-1).contiguous()
1001
+ end_logits = end_logits.squeeze(-1).contiguous()
1002
+
1003
+ total_loss = None
1004
+ if start_positions is not None and end_positions is not None:
1005
+ # If we are on multi-GPU, split add a dimension
1006
+ if len(start_positions.size()) > 1:
1007
+ start_positions = start_positions.squeeze(-1)
1008
+ if len(end_positions.size()) > 1:
1009
+ end_positions = end_positions.squeeze(-1)
1010
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1011
+ ignored_index = start_logits.size(1)
1012
+ start_positions = start_positions.clamp(0, ignored_index)
1013
+ end_positions = end_positions.clamp(0, ignored_index)
1014
+
1015
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1016
+ start_loss = loss_fct(start_logits, start_positions)
1017
+ end_loss = loss_fct(end_logits, end_positions)
1018
+ total_loss = (start_loss + end_loss) / 2
1019
+
1020
+ if not return_dict:
1021
+ output = (start_logits, end_logits) + transformer_outputs[1:]
1022
+ return ((total_loss,) + output) if total_loss is not None else output
1023
+
1024
+ return QuestionAnsweringModelOutput(
1025
+ loss=total_loss,
1026
+ start_logits=start_logits,
1027
+ end_logits=end_logits,
1028
+ hidden_states=transformer_outputs.hidden_states,
1029
+ attentions=transformer_outputs.attentions,
1030
+ )
1031
+
1032
+
1033
+ @add_start_docstrings(
1034
+ """
1035
+ Flaubert Model with a beam-search span classification head on top for extractive question-answering tasks like
1036
+ SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1037
+ """,
1038
+ FLAUBERT_START_DOCSTRING,
1039
+ )
1040
+ @dataclass
1041
+ # Copied from transformer.models.xlm.modeling_xlm.XLMForQuestionAnsweringOutput with XLM->Flaubert
1042
+ class FlaubertForQuestionAnsweringOutput(ModelOutput):
1043
+ """
1044
+ Base class for outputs of question answering models using a `SquadHead`.
1045
+
1046
+ Args:
1047
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned if both `start_positions` and `end_positions` are provided):
1048
+ Classification loss as the sum of start token, end token (and is_impossible if provided) classification
1049
+ losses.
1050
+ start_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
1051
+ Log probabilities for the top config.start_n_top start token possibilities (beam-search).
1052
+ start_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
1053
+ Indices for the top config.start_n_top start token possibilities (beam-search).
1054
+ end_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
1055
+ Log probabilities for the top `config.start_n_top * config.end_n_top` end token possibilities
1056
+ (beam-search).
1057
+ end_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
1058
+ Indices for the top `config.start_n_top * config.end_n_top` end token possibilities (beam-search).
1059
+ cls_logits (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
1060
+ Log probabilities for the `is_impossible` label of the answers.
1061
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1062
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
1063
+ shape `(batch_size, sequence_length, hidden_size)`.
1064
+
1065
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
1066
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
1067
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
1068
+ sequence_length)`.
1069
+
1070
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
1071
+ heads.
1072
+ """
1073
+
1074
+ loss: Optional[torch.FloatTensor] = None
1075
+ start_top_log_probs: Optional[torch.FloatTensor] = None
1076
+ start_top_index: Optional[torch.LongTensor] = None
1077
+ end_top_log_probs: Optional[torch.FloatTensor] = None
1078
+ end_top_index: Optional[torch.LongTensor] = None
1079
+ cls_logits: Optional[torch.FloatTensor] = None
1080
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
1081
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
1082
+
1083
+
1084
+ # Copied from transformer.models.xlm.modeling_xlm.XLMForQuestionAnswering with XLM_INPUTS->FLAUBERT_INPUTS,XLM->Flaubert
1085
+ class FlaubertForQuestionAnswering(FlaubertPreTrainedModel):
1086
+ def __init__(self, config):
1087
+ super().__init__(config)
1088
+
1089
+ self.transformer = FlaubertModel(config)
1090
+ self.qa_outputs = SQuADHead(config)
1091
+
1092
+ # Initialize weights and apply final processing
1093
+ self.post_init()
1094
+
1095
+ @add_start_docstrings_to_model_forward(FLAUBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1096
+ @replace_return_docstrings(output_type=FlaubertForQuestionAnsweringOutput, config_class=_CONFIG_FOR_DOC)
1097
+ def forward(
1098
+ self,
1099
+ input_ids: Optional[torch.Tensor] = None,
1100
+ attention_mask: Optional[torch.Tensor] = None,
1101
+ langs: Optional[torch.Tensor] = None,
1102
+ token_type_ids: Optional[torch.Tensor] = None,
1103
+ position_ids: Optional[torch.Tensor] = None,
1104
+ lengths: Optional[torch.Tensor] = None,
1105
+ cache: Optional[Dict[str, torch.Tensor]] = None,
1106
+ head_mask: Optional[torch.Tensor] = None,
1107
+ inputs_embeds: Optional[torch.Tensor] = None,
1108
+ start_positions: Optional[torch.Tensor] = None,
1109
+ end_positions: Optional[torch.Tensor] = None,
1110
+ is_impossible: Optional[torch.Tensor] = None,
1111
+ cls_index: Optional[torch.Tensor] = None,
1112
+ p_mask: Optional[torch.Tensor] = None,
1113
+ output_attentions: Optional[bool] = None,
1114
+ output_hidden_states: Optional[bool] = None,
1115
+ return_dict: Optional[bool] = None,
1116
+ ) -> Union[Tuple, FlaubertForQuestionAnsweringOutput]:
1117
+ r"""
1118
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1119
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1120
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1121
+ are not taken into account for computing the loss.
1122
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1123
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1124
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1125
+ are not taken into account for computing the loss.
1126
+ is_impossible (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1127
+ Labels whether a question has an answer or no answer (SQuAD 2.0)
1128
+ cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1129
+ Labels for position (index) of the classification token to use as input for computing plausibility of the
1130
+ answer.
1131
+ p_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1132
+ Optional mask of tokens which can't be in answers (e.g. [CLS], [PAD], ...). 1.0 means token should be
1133
+ masked. 0.0 mean token is not masked.
1134
+
1135
+ Returns:
1136
+
1137
+ Example:
1138
+
1139
+ ```python
1140
+ >>> from transformers import XLMTokenizer, XLMForQuestionAnswering
1141
+ >>> import torch
1142
+
1143
+ >>> tokenizer = XLMTokenizer.from_pretrained("FacebookAI/xlm-mlm-en-2048")
1144
+ >>> model = XLMForQuestionAnswering.from_pretrained("FacebookAI/xlm-mlm-en-2048")
1145
+
1146
+ >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(
1147
+ ... 0
1148
+ ... ) # Batch size 1
1149
+ >>> start_positions = torch.tensor([1])
1150
+ >>> end_positions = torch.tensor([3])
1151
+
1152
+ >>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)
1153
+ >>> loss = outputs.loss
1154
+ ```"""
1155
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1156
+
1157
+ transformer_outputs = self.transformer(
1158
+ input_ids,
1159
+ attention_mask=attention_mask,
1160
+ langs=langs,
1161
+ token_type_ids=token_type_ids,
1162
+ position_ids=position_ids,
1163
+ lengths=lengths,
1164
+ cache=cache,
1165
+ head_mask=head_mask,
1166
+ inputs_embeds=inputs_embeds,
1167
+ output_attentions=output_attentions,
1168
+ output_hidden_states=output_hidden_states,
1169
+ return_dict=return_dict,
1170
+ )
1171
+
1172
+ output = transformer_outputs[0]
1173
+
1174
+ outputs = self.qa_outputs(
1175
+ output,
1176
+ start_positions=start_positions,
1177
+ end_positions=end_positions,
1178
+ cls_index=cls_index,
1179
+ is_impossible=is_impossible,
1180
+ p_mask=p_mask,
1181
+ return_dict=return_dict,
1182
+ )
1183
+
1184
+ if not return_dict:
1185
+ return outputs + transformer_outputs[1:]
1186
+
1187
+ return FlaubertForQuestionAnsweringOutput(
1188
+ loss=outputs.loss,
1189
+ start_top_log_probs=outputs.start_top_log_probs,
1190
+ start_top_index=outputs.start_top_index,
1191
+ end_top_log_probs=outputs.end_top_log_probs,
1192
+ end_top_index=outputs.end_top_index,
1193
+ cls_logits=outputs.cls_logits,
1194
+ hidden_states=transformer_outputs.hidden_states,
1195
+ attentions=transformer_outputs.attentions,
1196
+ )
1197
+
1198
+
1199
+ @add_start_docstrings(
1200
+ """
1201
+ Flaubert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1202
+ softmax) e.g. for RocStories/SWAG tasks.
1203
+ """,
1204
+ FLAUBERT_START_DOCSTRING,
1205
+ )
1206
+ # Copied from transformer.models.xlm.modeling_xlm.XLMForMultipleChoice with XLM_INPUTS->FLAUBERT_INPUTS,XLM->Flaubert
1207
+ class FlaubertForMultipleChoice(FlaubertPreTrainedModel):
1208
+ def __init__(self, config, *inputs, **kwargs):
1209
+ super().__init__(config, *inputs, **kwargs)
1210
+
1211
+ self.transformer = FlaubertModel(config)
1212
+ self.sequence_summary = SequenceSummary(config)
1213
+ self.logits_proj = nn.Linear(config.num_labels, 1)
1214
+
1215
+ # Initialize weights and apply final processing
1216
+ self.post_init()
1217
+
1218
+ @add_start_docstrings_to_model_forward(
1219
+ FLAUBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
1220
+ )
1221
+ @add_code_sample_docstrings(
1222
+ checkpoint=_CHECKPOINT_FOR_DOC,
1223
+ output_type=MultipleChoiceModelOutput,
1224
+ config_class=_CONFIG_FOR_DOC,
1225
+ )
1226
+ def forward(
1227
+ self,
1228
+ input_ids: Optional[torch.Tensor] = None,
1229
+ attention_mask: Optional[torch.Tensor] = None,
1230
+ langs: Optional[torch.Tensor] = None,
1231
+ token_type_ids: Optional[torch.Tensor] = None,
1232
+ position_ids: Optional[torch.Tensor] = None,
1233
+ lengths: Optional[torch.Tensor] = None,
1234
+ cache: Optional[Dict[str, torch.Tensor]] = None,
1235
+ head_mask: Optional[torch.Tensor] = None,
1236
+ inputs_embeds: Optional[torch.Tensor] = None,
1237
+ labels: Optional[torch.Tensor] = None,
1238
+ output_attentions: Optional[bool] = None,
1239
+ output_hidden_states: Optional[bool] = None,
1240
+ return_dict: Optional[bool] = None,
1241
+ ) -> Union[Tuple, MultipleChoiceModelOutput]:
1242
+ r"""
1243
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1244
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1245
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1246
+ `input_ids` above)
1247
+ """
1248
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1249
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1250
+
1251
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1252
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1253
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1254
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
1255
+ langs = langs.view(-1, langs.size(-1)) if langs is not None else None
1256
+ inputs_embeds = (
1257
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1258
+ if inputs_embeds is not None
1259
+ else None
1260
+ )
1261
+
1262
+ if lengths is not None:
1263
+ logger.warning(
1264
+ "The `lengths` parameter cannot be used with the Flaubert multiple choice models. Please use the "
1265
+ "attention mask instead."
1266
+ )
1267
+ lengths = None
1268
+
1269
+ transformer_outputs = self.transformer(
1270
+ input_ids=input_ids,
1271
+ attention_mask=attention_mask,
1272
+ langs=langs,
1273
+ token_type_ids=token_type_ids,
1274
+ position_ids=position_ids,
1275
+ lengths=lengths,
1276
+ cache=cache,
1277
+ head_mask=head_mask,
1278
+ inputs_embeds=inputs_embeds,
1279
+ output_attentions=output_attentions,
1280
+ output_hidden_states=output_hidden_states,
1281
+ return_dict=return_dict,
1282
+ )
1283
+ output = transformer_outputs[0]
1284
+ logits = self.sequence_summary(output)
1285
+ logits = self.logits_proj(logits)
1286
+ reshaped_logits = logits.view(-1, num_choices)
1287
+
1288
+ loss = None
1289
+ if labels is not None:
1290
+ loss_fct = CrossEntropyLoss()
1291
+ loss = loss_fct(reshaped_logits, labels)
1292
+
1293
+ if not return_dict:
1294
+ output = (reshaped_logits,) + transformer_outputs[1:]
1295
+ return ((loss,) + output) if loss is not None else output
1296
+
1297
+ return MultipleChoiceModelOutput(
1298
+ loss=loss,
1299
+ logits=reshaped_logits,
1300
+ hidden_states=transformer_outputs.hidden_states,
1301
+ attentions=transformer_outputs.attentions,
1302
+ )
1303
+
1304
+
1305
+ __all__ = [
1306
+ "FlaubertForMultipleChoice",
1307
+ "FlaubertForQuestionAnswering",
1308
+ "FlaubertForQuestionAnsweringSimple",
1309
+ "FlaubertForSequenceClassification",
1310
+ "FlaubertForTokenClassification",
1311
+ "FlaubertModel",
1312
+ "FlaubertWithLMHeadModel",
1313
+ "FlaubertPreTrainedModel",
1314
+ ]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flaubert/modeling_tf_flaubert.py ADDED
@@ -0,0 +1,1344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-present, Facebook, Inc 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
+ """
16
+ TF 2.0 Flaubert model.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import itertools
22
+ import random
23
+ import warnings
24
+ from dataclasses import dataclass
25
+ from typing import Dict, Optional, Tuple, Union
26
+
27
+ import numpy as np
28
+ import tensorflow as tf
29
+
30
+ from ...activations_tf import get_tf_activation
31
+ from ...modeling_tf_outputs import (
32
+ TFBaseModelOutput,
33
+ TFMultipleChoiceModelOutput,
34
+ TFQuestionAnsweringModelOutput,
35
+ TFSequenceClassifierOutput,
36
+ TFTokenClassifierOutput,
37
+ )
38
+ from ...modeling_tf_utils import (
39
+ TFModelInputType,
40
+ TFMultipleChoiceLoss,
41
+ TFPreTrainedModel,
42
+ TFQuestionAnsweringLoss,
43
+ TFSequenceClassificationLoss,
44
+ TFSequenceSummary,
45
+ TFSharedEmbeddings,
46
+ TFTokenClassificationLoss,
47
+ get_initializer,
48
+ keras,
49
+ keras_serializable,
50
+ unpack_inputs,
51
+ )
52
+ from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
53
+ from ...utils import (
54
+ MULTIPLE_CHOICE_DUMMY_INPUTS,
55
+ ModelOutput,
56
+ add_code_sample_docstrings,
57
+ add_start_docstrings,
58
+ add_start_docstrings_to_model_forward,
59
+ logging,
60
+ )
61
+ from .configuration_flaubert import FlaubertConfig
62
+
63
+
64
+ logger = logging.get_logger(__name__)
65
+
66
+ _CHECKPOINT_FOR_DOC = "flaubert/flaubert_base_cased"
67
+ _CONFIG_FOR_DOC = "FlaubertConfig"
68
+
69
+
70
+ FLAUBERT_START_DOCSTRING = r"""
71
+
72
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
73
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
74
+ etc.)
75
+
76
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
77
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
78
+ behavior.
79
+
80
+ <Tip>
81
+
82
+ TensorFlow models and layers in `transformers` accept two formats as input:
83
+
84
+ - having all inputs as keyword arguments (like PyTorch models), or
85
+ - having all inputs as a list, tuple or dict in the first positional argument.
86
+
87
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
88
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
89
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
90
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
91
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
92
+ positional argument:
93
+
94
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
95
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
96
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
97
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
98
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
99
+
100
+ Note that when creating models and layers with
101
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
102
+ about any of this, as you can just pass inputs like you would to any other Python function!
103
+
104
+ </Tip>
105
+
106
+ Parameters:
107
+ config ([`FlaubertConfig`]): Model configuration class with all the parameters of the model.
108
+ Initializing with a config file does not load the weights associated with the model, only the
109
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
110
+ """
111
+
112
+ FLAUBERT_INPUTS_DOCSTRING = r"""
113
+ Args:
114
+ input_ids (`Numpy array` or `tf.Tensor` of shape `(batch_size, sequence_length)`):
115
+ Indices of input sequence tokens in the vocabulary.
116
+
117
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
118
+ [`PreTrainedTokenizer.encode`] for details.
119
+
120
+ [What are input IDs?](../glossary#input-ids)
121
+ attention_mask (`Numpy array` or `tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
122
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
123
+
124
+ - `1` for tokens that are **not masked**,
125
+ - `0` for tokens that are **masked**.
126
+
127
+ [What are attention masks?](../glossary#attention-mask)
128
+ langs (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*):
129
+ A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
130
+ languages ids which can be obtained from the language names by using two conversion mappings provided in
131
+ the configuration of the model (only provided for multilingual models). More precisely, the *language name
132
+ to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
133
+ *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
134
+
135
+ See usage examples detailed in the [multilingual documentation](../multilingual).
136
+ token_type_ids (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*):
137
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
138
+ 1]`:
139
+
140
+ - `0` corresponds to a *sentence A* token,
141
+ - `1` corresponds to a *sentence B* token.
142
+
143
+ [What are token type IDs?](../glossary#token-type-ids)
144
+ position_ids (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*):
145
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
146
+ config.max_position_embeddings - 1]`.
147
+
148
+ [What are position IDs?](../glossary#position-ids)
149
+ lengths (`tf.Tensor` or `Numpy array` of shape `(batch_size,)`, *optional*):
150
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
151
+ also use *attention_mask* for the same result (see above), kept here for compatibility Indices selected in
152
+ `[0, ..., input_ids.size(-1)]`:
153
+ cache (`Dict[str, tf.Tensor]`, *optional*):
154
+ Dictionary string to `tf.FloatTensor` that contains precomputed hidden states (key and values in the
155
+ attention blocks) as computed by the model (see `cache` output below). Can be used to speed up sequential
156
+ decoding.
157
+
158
+ The dictionary object will be modified in-place during the forward pass to add newly computed
159
+ hidden-states.
160
+ head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
161
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
162
+
163
+ - `1` indicates the head is **not masked**,
164
+ - `0` indicates the head is **masked**.
165
+
166
+ inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
167
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
168
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
169
+ model's internal embedding lookup matrix.
170
+ output_attentions (`bool`, *optional*):
171
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
172
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
173
+ config will be used instead.
174
+ output_hidden_states (`bool`, *optional*):
175
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
176
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
177
+ used instead.
178
+ return_dict (`bool`, *optional*):
179
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
180
+ eager mode, in graph mode the value will always be set to True.
181
+ training (`bool`, *optional*, defaults to `False`):
182
+ Whether or not to use the model in training mode (some modules like dropout modules have different
183
+ behaviors between training and evaluation).
184
+ """
185
+
186
+
187
+ def get_masks(slen, lengths, causal, padding_mask=None):
188
+ """
189
+ Generate hidden states mask, and optionally an attention mask.
190
+ """
191
+ bs = shape_list(lengths)[0]
192
+ if padding_mask is not None:
193
+ mask = padding_mask
194
+ else:
195
+ # assert lengths.max().item() <= slen
196
+ alen = tf.range(slen, dtype=lengths.dtype)
197
+ mask = alen < tf.expand_dims(lengths, axis=1)
198
+
199
+ # attention mask is the same as mask, or triangular inferior attention (causal)
200
+ if causal:
201
+ attn_mask = tf.less_equal(
202
+ tf.tile(tf.reshape(alen, (1, 1, slen)), (bs, slen, 1)), tf.reshape(alen, (1, slen, 1))
203
+ )
204
+ else:
205
+ attn_mask = mask
206
+
207
+ # sanity check
208
+ # assert shape_list(mask) == [bs, slen]
209
+ tf.debugging.assert_equal(shape_list(mask), [bs, slen])
210
+ if causal:
211
+ tf.debugging.assert_equal(shape_list(attn_mask), [bs, slen, slen])
212
+
213
+ return mask, attn_mask
214
+
215
+
216
+ class TFFlaubertPreTrainedModel(TFPreTrainedModel):
217
+ """
218
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
219
+ models.
220
+ """
221
+
222
+ config_class = FlaubertConfig
223
+ base_model_prefix = "transformer"
224
+
225
+ @property
226
+ def dummy_inputs(self):
227
+ # Sometimes Flaubert has language embeddings so don't forget to build them as well if needed
228
+ inputs_list = tf.constant([[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]], dtype=tf.int32)
229
+ attns_list = tf.constant([[1, 1, 0, 0, 1], [1, 1, 1, 0, 0], [1, 0, 0, 1, 1]], dtype=tf.int32)
230
+ if self.config.use_lang_emb and self.config.n_langs > 1:
231
+ return {
232
+ "input_ids": inputs_list,
233
+ "attention_mask": attns_list,
234
+ "langs": tf.constant([[1, 1, 0, 0, 1], [1, 1, 1, 0, 0], [1, 0, 0, 1, 1]], dtype=tf.int32),
235
+ }
236
+ else:
237
+ return {"input_ids": inputs_list, "attention_mask": attns_list}
238
+
239
+
240
+ @add_start_docstrings(
241
+ "The bare Flaubert Model transformer outputting raw hidden-states without any specific head on top.",
242
+ FLAUBERT_START_DOCSTRING,
243
+ )
244
+ class TFFlaubertModel(TFFlaubertPreTrainedModel):
245
+ def __init__(self, config, *inputs, **kwargs):
246
+ super().__init__(config, *inputs, **kwargs)
247
+ self.transformer = TFFlaubertMainLayer(config, name="transformer")
248
+
249
+ @unpack_inputs
250
+ @add_start_docstrings_to_model_forward(FLAUBERT_INPUTS_DOCSTRING)
251
+ @add_code_sample_docstrings(
252
+ checkpoint=_CHECKPOINT_FOR_DOC,
253
+ output_type=TFBaseModelOutput,
254
+ config_class=_CONFIG_FOR_DOC,
255
+ )
256
+ def call(
257
+ self,
258
+ input_ids: np.ndarray | tf.Tensor | None = None,
259
+ attention_mask: np.ndarray | tf.Tensor | None = None,
260
+ langs: np.ndarray | tf.Tensor | None = None,
261
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
262
+ position_ids: np.ndarray | tf.Tensor | None = None,
263
+ lengths: np.ndarray | tf.Tensor | None = None,
264
+ cache: Optional[Dict[str, tf.Tensor]] = None,
265
+ head_mask: np.ndarray | tf.Tensor | None = None,
266
+ inputs_embeds: tf.Tensor | None = None,
267
+ output_attentions: Optional[bool] = None,
268
+ output_hidden_states: Optional[bool] = None,
269
+ return_dict: Optional[bool] = None,
270
+ training: Optional[bool] = False,
271
+ ) -> Union[Tuple, TFBaseModelOutput]:
272
+ outputs = self.transformer(
273
+ input_ids=input_ids,
274
+ attention_mask=attention_mask,
275
+ langs=langs,
276
+ token_type_ids=token_type_ids,
277
+ position_ids=position_ids,
278
+ lengths=lengths,
279
+ cache=cache,
280
+ head_mask=head_mask,
281
+ inputs_embeds=inputs_embeds,
282
+ output_attentions=output_attentions,
283
+ output_hidden_states=output_hidden_states,
284
+ return_dict=return_dict,
285
+ training=training,
286
+ )
287
+
288
+ return outputs
289
+
290
+ def build(self, input_shape=None):
291
+ if self.built:
292
+ return
293
+ self.built = True
294
+ if getattr(self, "transformer", None) is not None:
295
+ with tf.name_scope(self.transformer.name):
296
+ self.transformer.build(None)
297
+
298
+
299
+ # Copied from transformers.models.xlm.modeling_tf_xlm.TFXLMMultiHeadAttention with XLM->Flaubert
300
+ class TFFlaubertMultiHeadAttention(keras.layers.Layer):
301
+ NEW_ID = itertools.count()
302
+
303
+ def __init__(self, n_heads, dim, config, **kwargs):
304
+ super().__init__(**kwargs)
305
+ self.layer_id = next(TFFlaubertMultiHeadAttention.NEW_ID)
306
+ self.dim = dim
307
+ self.n_heads = n_heads
308
+ self.output_attentions = config.output_attentions
309
+ assert self.dim % self.n_heads == 0
310
+
311
+ self.q_lin = keras.layers.Dense(dim, kernel_initializer=get_initializer(config.init_std), name="q_lin")
312
+ self.k_lin = keras.layers.Dense(dim, kernel_initializer=get_initializer(config.init_std), name="k_lin")
313
+ self.v_lin = keras.layers.Dense(dim, kernel_initializer=get_initializer(config.init_std), name="v_lin")
314
+ self.out_lin = keras.layers.Dense(dim, kernel_initializer=get_initializer(config.init_std), name="out_lin")
315
+ self.dropout = keras.layers.Dropout(config.attention_dropout)
316
+ self.pruned_heads = set()
317
+ self.dim = dim
318
+
319
+ def prune_heads(self, heads):
320
+ raise NotImplementedError
321
+
322
+ def call(self, input, mask, kv, cache, head_mask, output_attentions, training=False):
323
+ """
324
+ Self-attention (if kv is None) or attention over source sentence (provided by kv).
325
+ """
326
+ # Input is (bs, qlen, dim)
327
+ # Mask is (bs, klen) (non-causal) or (bs, klen, klen)
328
+ bs, qlen, dim = shape_list(input)
329
+
330
+ if kv is None:
331
+ klen = qlen if cache is None else cache["slen"] + qlen
332
+ else:
333
+ klen = shape_list(kv)[1]
334
+
335
+ # assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured'
336
+ dim_per_head = self.dim // self.n_heads
337
+ mask_reshape = (bs, 1, qlen, klen) if len(shape_list(mask)) == 3 else (bs, 1, 1, klen)
338
+
339
+ def shape(x):
340
+ """projection"""
341
+ return tf.transpose(tf.reshape(x, (bs, -1, self.n_heads, dim_per_head)), perm=(0, 2, 1, 3))
342
+
343
+ def unshape(x):
344
+ """compute context"""
345
+ return tf.reshape(tf.transpose(x, perm=(0, 2, 1, 3)), (bs, -1, self.n_heads * dim_per_head))
346
+
347
+ q = shape(self.q_lin(input)) # (bs, n_heads, qlen, dim_per_head)
348
+
349
+ if kv is None:
350
+ k = shape(self.k_lin(input)) # (bs, n_heads, qlen, dim_per_head)
351
+ v = shape(self.v_lin(input)) # (bs, n_heads, qlen, dim_per_head)
352
+ elif cache is None or self.layer_id not in cache:
353
+ k = v = kv
354
+ k = shape(self.k_lin(k)) # (bs, n_heads, qlen, dim_per_head)
355
+ v = shape(self.v_lin(v)) # (bs, n_heads, qlen, dim_per_head)
356
+
357
+ if cache is not None:
358
+ if self.layer_id in cache:
359
+ if kv is None:
360
+ k_, v_ = cache[self.layer_id]
361
+ k = tf.concat([k_, k], axis=2) # (bs, n_heads, klen, dim_per_head)
362
+ v = tf.concat([v_, v], axis=2) # (bs, n_heads, klen, dim_per_head)
363
+ else:
364
+ k, v = cache[self.layer_id]
365
+
366
+ cache[self.layer_id] = (k, v)
367
+
368
+ f_dim_per_head = tf.cast(dim_per_head, dtype=q.dtype)
369
+ q = tf.multiply(q, tf.math.rsqrt(f_dim_per_head)) # (bs, n_heads, qlen, dim_per_head)
370
+ k = tf.cast(k, dtype=q.dtype)
371
+ scores = tf.matmul(q, k, transpose_b=True) # (bs, n_heads, qlen, klen)
372
+ mask = tf.reshape(mask, mask_reshape) # (bs, n_heads, qlen, klen)
373
+ # scores.masked_fill_(mask, -float('inf')) # (bs, n_heads, qlen, klen)
374
+ mask = tf.cast(mask, dtype=scores.dtype)
375
+ scores = scores - 1e30 * (1.0 - mask)
376
+ weights = stable_softmax(scores, axis=-1) # (bs, n_heads, qlen, klen)
377
+ weights = self.dropout(weights, training=training) # (bs, n_heads, qlen, klen)
378
+
379
+ # Mask heads if we want to
380
+ if head_mask is not None:
381
+ weights = weights * head_mask
382
+
383
+ context = tf.matmul(weights, v) # (bs, n_heads, qlen, dim_per_head)
384
+ context = unshape(context) # (bs, qlen, dim)
385
+ outputs = (self.out_lin(context),)
386
+
387
+ if output_attentions:
388
+ outputs = outputs + (weights,)
389
+
390
+ return outputs
391
+
392
+ def build(self, input_shape=None):
393
+ if self.built:
394
+ return
395
+ self.built = True
396
+ if getattr(self, "q_lin", None) is not None:
397
+ with tf.name_scope(self.q_lin.name):
398
+ self.q_lin.build([None, None, self.dim])
399
+ if getattr(self, "k_lin", None) is not None:
400
+ with tf.name_scope(self.k_lin.name):
401
+ self.k_lin.build([None, None, self.dim])
402
+ if getattr(self, "v_lin", None) is not None:
403
+ with tf.name_scope(self.v_lin.name):
404
+ self.v_lin.build([None, None, self.dim])
405
+ if getattr(self, "out_lin", None) is not None:
406
+ with tf.name_scope(self.out_lin.name):
407
+ self.out_lin.build([None, None, self.dim])
408
+
409
+
410
+ # Copied from transformers.models.xlm.modeling_tf_xlm.TFXLMTransformerFFN
411
+ class TFFlaubertTransformerFFN(keras.layers.Layer):
412
+ def __init__(self, in_dim, dim_hidden, out_dim, config, **kwargs):
413
+ super().__init__(**kwargs)
414
+
415
+ self.lin1 = keras.layers.Dense(dim_hidden, kernel_initializer=get_initializer(config.init_std), name="lin1")
416
+ self.lin2 = keras.layers.Dense(out_dim, kernel_initializer=get_initializer(config.init_std), name="lin2")
417
+ self.act = get_tf_activation("gelu") if config.gelu_activation else get_tf_activation("relu")
418
+ self.dropout = keras.layers.Dropout(config.dropout)
419
+ self.in_dim = in_dim
420
+ self.dim_hidden = dim_hidden
421
+
422
+ def call(self, input, training=False):
423
+ x = self.lin1(input)
424
+ x = self.act(x)
425
+ x = self.lin2(x)
426
+ x = self.dropout(x, training=training)
427
+
428
+ return x
429
+
430
+ def build(self, input_shape=None):
431
+ if self.built:
432
+ return
433
+ self.built = True
434
+ if getattr(self, "lin1", None) is not None:
435
+ with tf.name_scope(self.lin1.name):
436
+ self.lin1.build([None, None, self.in_dim])
437
+ if getattr(self, "lin2", None) is not None:
438
+ with tf.name_scope(self.lin2.name):
439
+ self.lin2.build([None, None, self.dim_hidden])
440
+
441
+
442
+ @keras_serializable
443
+ class TFFlaubertMainLayer(keras.layers.Layer):
444
+ config_class = FlaubertConfig
445
+
446
+ def __init__(self, config, **kwargs):
447
+ super().__init__(**kwargs)
448
+
449
+ self.config = config
450
+ self.n_heads = config.n_heads
451
+ self.n_langs = config.n_langs
452
+ self.dim = config.emb_dim
453
+ self.hidden_dim = self.dim * 4
454
+ self.n_words = config.n_words
455
+ self.pad_index = config.pad_index
456
+ self.causal = config.causal
457
+ self.n_layers = config.n_layers
458
+ self.use_lang_emb = config.use_lang_emb
459
+ self.layerdrop = getattr(config, "layerdrop", 0.0)
460
+ self.pre_norm = getattr(config, "pre_norm", False)
461
+ self.output_attentions = config.output_attentions
462
+ self.output_hidden_states = config.output_hidden_states
463
+ self.return_dict = config.use_return_dict
464
+ self.max_position_embeddings = config.max_position_embeddings
465
+ self.embed_init_std = config.embed_init_std
466
+ self.dropout = keras.layers.Dropout(config.dropout)
467
+ self.embeddings = TFSharedEmbeddings(
468
+ self.n_words, self.dim, initializer_range=config.embed_init_std, name="embeddings"
469
+ )
470
+ self.layer_norm_emb = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm_emb")
471
+ self.attentions = []
472
+ self.layer_norm1 = []
473
+ self.ffns = []
474
+ self.layer_norm2 = []
475
+
476
+ for i in range(self.n_layers):
477
+ self.attentions.append(
478
+ TFFlaubertMultiHeadAttention(self.n_heads, self.dim, config=config, name=f"attentions_._{i}")
479
+ )
480
+ self.layer_norm1.append(
481
+ keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name=f"layer_norm1_._{i}")
482
+ )
483
+ # if self.is_decoder:
484
+ # self.layer_norm15.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
485
+ # self.encoder_attn.append(MultiHeadAttention(self.n_heads, self.dim, dropout=self.attention_dropout))
486
+ self.ffns.append(
487
+ TFFlaubertTransformerFFN(self.dim, self.hidden_dim, self.dim, config=config, name=f"ffns_._{i}")
488
+ )
489
+ self.layer_norm2.append(
490
+ keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name=f"layer_norm2_._{i}")
491
+ )
492
+
493
+ def build(self, input_shape=None):
494
+ with tf.name_scope("position_embeddings"):
495
+ self.position_embeddings = self.add_weight(
496
+ name="embeddings",
497
+ shape=[self.max_position_embeddings, self.dim],
498
+ initializer=get_initializer(self.embed_init_std),
499
+ )
500
+
501
+ if self.n_langs > 1 and self.use_lang_emb:
502
+ with tf.name_scope("lang_embeddings"):
503
+ self.lang_embeddings = self.add_weight(
504
+ name="embeddings",
505
+ shape=[self.n_langs, self.dim],
506
+ initializer=get_initializer(self.embed_init_std),
507
+ )
508
+
509
+ if self.built:
510
+ return
511
+ self.built = True
512
+ if getattr(self, "embeddings", None) is not None:
513
+ with tf.name_scope(self.embeddings.name):
514
+ self.embeddings.build(None)
515
+ if getattr(self, "layer_norm_emb", None) is not None:
516
+ with tf.name_scope(self.layer_norm_emb.name):
517
+ self.layer_norm_emb.build([None, None, self.dim])
518
+ for layer in self.attentions:
519
+ with tf.name_scope(layer.name):
520
+ layer.build(None)
521
+ for layer in self.layer_norm1:
522
+ with tf.name_scope(layer.name):
523
+ layer.build([None, None, self.dim])
524
+ for layer in self.ffns:
525
+ with tf.name_scope(layer.name):
526
+ layer.build(None)
527
+ for layer in self.layer_norm2:
528
+ with tf.name_scope(layer.name):
529
+ layer.build([None, None, self.dim])
530
+
531
+ def get_input_embeddings(self):
532
+ return self.embeddings
533
+
534
+ def set_input_embeddings(self, value):
535
+ self.embeddings.weight = value
536
+ self.embeddings.vocab_size = shape_list(value)[0]
537
+
538
+ @unpack_inputs
539
+ def call(
540
+ self,
541
+ input_ids: np.ndarray | tf.Tensor | None = None,
542
+ attention_mask: np.ndarray | tf.Tensor | None = None,
543
+ langs: np.ndarray | tf.Tensor | None = None,
544
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
545
+ position_ids: np.ndarray | tf.Tensor | None = None,
546
+ lengths: np.ndarray | tf.Tensor | None = None,
547
+ cache: Optional[Dict[str, tf.Tensor]] = None,
548
+ head_mask: np.ndarray | tf.Tensor | None = None,
549
+ inputs_embeds: tf.Tensor | None = None,
550
+ output_attentions: Optional[bool] = None,
551
+ output_hidden_states: Optional[bool] = None,
552
+ return_dict: Optional[bool] = None,
553
+ training: Optional[bool] = False,
554
+ ) -> Union[Tuple, TFBaseModelOutput]:
555
+ # removed: src_enc=None, src_len=None
556
+
557
+ if input_ids is not None and inputs_embeds is not None:
558
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
559
+ elif input_ids is not None:
560
+ bs, slen = shape_list(input_ids)
561
+ elif inputs_embeds is not None:
562
+ bs, slen = shape_list(inputs_embeds)[:2]
563
+ else:
564
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
565
+
566
+ if lengths is None:
567
+ if input_ids is not None:
568
+ lengths = tf.reduce_sum(
569
+ tf.cast(tf.not_equal(input_ids, self.pad_index), dtype=input_ids.dtype), axis=1
570
+ )
571
+ else:
572
+ lengths = tf.convert_to_tensor([slen] * bs)
573
+ # mask = input_ids != self.pad_index
574
+
575
+ # check inputs
576
+ # assert shape_list(lengths)[0] == bs
577
+ (
578
+ tf.debugging.assert_equal(shape_list(lengths)[0], bs),
579
+ f"Expected batch size {shape_list(lengths)[0]} and received batch size {bs} mismatched",
580
+ )
581
+ # assert lengths.max().item() <= slen
582
+ # input_ids = input_ids.transpose(0, 1) # batch size as dimension 0
583
+ # assert (src_enc is None) == (src_len is None)
584
+ # if src_enc is not None:
585
+ # assert self.is_decoder
586
+ # assert src_enc.size(0) == bs
587
+
588
+ # generate masks
589
+ mask, attn_mask = get_masks(slen, lengths, self.causal, padding_mask=attention_mask)
590
+ # if self.is_decoder and src_enc is not None:
591
+ # src_mask = torch.arange(src_len.max(), dtype=torch.long, device=lengths.device) < src_len[:, None]
592
+
593
+ # position_ids
594
+ if position_ids is None:
595
+ position_ids = tf.expand_dims(tf.range(slen), axis=0)
596
+ position_ids = tf.tile(position_ids, (bs, 1))
597
+
598
+ # assert shape_list(position_ids) == [bs, slen] # (slen, bs)
599
+ (
600
+ tf.debugging.assert_equal(shape_list(position_ids), [bs, slen]),
601
+ f"Position id shape {shape_list(position_ids)} and input shape {[bs, slen]} mismatched",
602
+ )
603
+ # position_ids = position_ids.transpose(0, 1)
604
+
605
+ # langs
606
+ if langs is not None:
607
+ # assert shape_list(langs) == [bs, slen] # (slen, bs)
608
+ (
609
+ tf.debugging.assert_equal(shape_list(langs), [bs, slen]),
610
+ f"Lang shape {shape_list(langs)} and input shape {[bs, slen]} mismatched",
611
+ )
612
+ # langs = langs.transpose(0, 1)
613
+
614
+ # Prepare head mask if needed
615
+ # 1.0 in head_mask indicate we keep the head
616
+ # attention_probs has shape bsz x n_heads x N x N
617
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
618
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x qlen x klen]
619
+ if head_mask is not None:
620
+ raise NotImplementedError
621
+ else:
622
+ head_mask = [None] * self.n_layers
623
+
624
+ # do not recompute cached elements
625
+ if cache is not None and input_ids is not None:
626
+ _slen = slen - cache["slen"]
627
+ input_ids = input_ids[:, -_slen:]
628
+ position_ids = position_ids[:, -_slen:]
629
+ if langs is not None:
630
+ langs = langs[:, -_slen:]
631
+ mask = mask[:, -_slen:]
632
+ attn_mask = attn_mask[:, -_slen:]
633
+
634
+ # embeddings
635
+ if inputs_embeds is None:
636
+ check_embeddings_within_bounds(input_ids, self.embeddings.vocab_size)
637
+ inputs_embeds = self.embeddings(input_ids)
638
+
639
+ tensor = inputs_embeds + tf.gather(self.position_embeddings, position_ids)
640
+
641
+ if langs is not None and self.use_lang_emb:
642
+ tensor = tensor + tf.gather(self.lang_embeddings, langs)
643
+ if token_type_ids is not None:
644
+ tensor = tensor + self.embeddings(token_type_ids)
645
+
646
+ tensor = self.layer_norm_emb(tensor)
647
+ tensor = self.dropout(tensor, training=training)
648
+ mask = tf.cast(mask, dtype=tensor.dtype)
649
+ tensor = tensor * tf.expand_dims(mask, axis=-1)
650
+
651
+ # hidden_states and attentions cannot be None in graph mode.
652
+ hidden_states = () if output_hidden_states else None
653
+ attentions = () if output_attentions else None
654
+
655
+ # transformer layers
656
+ for i in range(self.n_layers):
657
+ # LayerDrop
658
+ dropout_probability = random.uniform(0, 1)
659
+
660
+ if training and (dropout_probability < self.layerdrop):
661
+ continue
662
+
663
+ if output_hidden_states:
664
+ hidden_states = hidden_states + (tensor,)
665
+
666
+ # self attention
667
+ if not self.pre_norm:
668
+ attn_outputs = self.attentions[i](
669
+ tensor,
670
+ attn_mask,
671
+ None,
672
+ cache,
673
+ head_mask[i],
674
+ output_attentions,
675
+ training=training,
676
+ )
677
+ attn = attn_outputs[0]
678
+
679
+ if output_attentions:
680
+ attentions = attentions + (attn_outputs[1],)
681
+
682
+ attn = self.dropout(attn, training=training)
683
+ tensor = tensor + attn
684
+ tensor = self.layer_norm1[i](tensor)
685
+ else:
686
+ tensor_normalized = self.layer_norm1[i](tensor)
687
+ attn_outputs = self.attentions[i](
688
+ tensor_normalized,
689
+ attn_mask,
690
+ None,
691
+ cache,
692
+ head_mask[i],
693
+ output_attentions,
694
+ training=training,
695
+ )
696
+ attn = attn_outputs[0]
697
+
698
+ if output_attentions:
699
+ attentions = attentions + (attn_outputs[1],)
700
+
701
+ attn = self.dropout(attn, training=training)
702
+ tensor = tensor + attn
703
+
704
+ # encoder attention (for decoder only)
705
+ # if self.is_decoder and src_enc is not None:
706
+ # attn = self.encoder_attn[i](tensor, src_mask, kv=src_enc, cache=cache)
707
+ # attn = nn.functional.dropout(attn, p=self.dropout, training=self.training)
708
+ # tensor = tensor + attn
709
+ # tensor = self.layer_norm15[i](tensor)
710
+
711
+ # FFN
712
+ if not self.pre_norm:
713
+ tensor = tensor + self.ffns[i](tensor)
714
+ tensor = self.layer_norm2[i](tensor)
715
+ else:
716
+ tensor_normalized = self.layer_norm2[i](tensor)
717
+ tensor = tensor + self.ffns[i](tensor_normalized)
718
+
719
+ tensor = tensor * tf.expand_dims(mask, axis=-1)
720
+
721
+ # Add last hidden state
722
+ if output_hidden_states:
723
+ hidden_states = hidden_states + (tensor,)
724
+
725
+ # update cache length
726
+ if cache is not None:
727
+ cache["slen"] += tensor.size(1)
728
+
729
+ # move back sequence length to dimension 0
730
+ # tensor = tensor.transpose(0, 1)
731
+
732
+ if not return_dict:
733
+ return tuple(v for v in [tensor, hidden_states, attentions] if v is not None)
734
+
735
+ return TFBaseModelOutput(last_hidden_state=tensor, hidden_states=hidden_states, attentions=attentions)
736
+
737
+
738
+ # Copied from transformers.models.xlm.modeling_tf_xlm.TFXLMPredLayer
739
+ class TFFlaubertPredLayer(keras.layers.Layer):
740
+ """
741
+ Prediction layer (cross_entropy or adaptive_softmax).
742
+ """
743
+
744
+ def __init__(self, config, input_embeddings, **kwargs):
745
+ super().__init__(**kwargs)
746
+
747
+ self.asm = config.asm
748
+ self.n_words = config.n_words
749
+ self.pad_index = config.pad_index
750
+
751
+ if config.asm is False:
752
+ self.input_embeddings = input_embeddings
753
+ else:
754
+ raise NotImplementedError
755
+ # self.proj = nn.AdaptiveLogSoftmaxWithLoss(
756
+ # in_features=dim,
757
+ # n_classes=config.n_words,
758
+ # cutoffs=config.asm_cutoffs,
759
+ # div_value=config.asm_div_value,
760
+ # head_bias=True, # default is False
761
+ # )
762
+
763
+ def build(self, input_shape):
764
+ # The output weights are the same as the input embeddings, but there is an output-only bias for each token.
765
+ self.bias = self.add_weight(shape=(self.n_words,), initializer="zeros", trainable=True, name="bias")
766
+
767
+ super().build(input_shape)
768
+
769
+ def get_output_embeddings(self):
770
+ return self.input_embeddings
771
+
772
+ def set_output_embeddings(self, value):
773
+ self.input_embeddings.weight = value
774
+ self.input_embeddings.vocab_size = shape_list(value)[0]
775
+
776
+ def get_bias(self):
777
+ return {"bias": self.bias}
778
+
779
+ def set_bias(self, value):
780
+ self.bias = value["bias"]
781
+ self.vocab_size = shape_list(value["bias"])[0]
782
+
783
+ def call(self, hidden_states):
784
+ hidden_states = self.input_embeddings(hidden_states, mode="linear")
785
+ hidden_states = hidden_states + self.bias
786
+
787
+ return hidden_states
788
+
789
+
790
+ @dataclass
791
+ class TFFlaubertWithLMHeadModelOutput(ModelOutput):
792
+ """
793
+ Base class for [`TFFlaubertWithLMHeadModel`] outputs.
794
+
795
+ Args:
796
+ logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
797
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
798
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
799
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
800
+ `(batch_size, sequence_length, hidden_size)`.
801
+
802
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
803
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
804
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
805
+ sequence_length)`.
806
+
807
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
808
+ heads.
809
+ """
810
+
811
+ logits: tf.Tensor = None
812
+ hidden_states: Tuple[tf.Tensor] | None = None
813
+ attentions: Tuple[tf.Tensor] | None = None
814
+
815
+
816
+ @add_start_docstrings(
817
+ """
818
+ The Flaubert Model transformer with a language modeling head on top (linear layer with weights tied to the input
819
+ embeddings).
820
+ """,
821
+ FLAUBERT_START_DOCSTRING,
822
+ )
823
+ class TFFlaubertWithLMHeadModel(TFFlaubertPreTrainedModel):
824
+ def __init__(self, config, *inputs, **kwargs):
825
+ super().__init__(config, *inputs, **kwargs)
826
+ self.transformer = TFFlaubertMainLayer(config, name="transformer")
827
+ self.pred_layer = TFFlaubertPredLayer(config, self.transformer.embeddings, name="pred_layer_._proj")
828
+ # Flaubert does not have past caching features
829
+ self.supports_xla_generation = False
830
+
831
+ def get_lm_head(self):
832
+ return self.pred_layer
833
+
834
+ def get_prefix_bias_name(self):
835
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
836
+ return self.name + "/" + self.pred_layer.name
837
+
838
+ def prepare_inputs_for_generation(self, inputs, **kwargs):
839
+ mask_token_id = self.config.mask_token_id
840
+ lang_id = self.config.lang_id
841
+
842
+ effective_batch_size = inputs.shape[0]
843
+ mask_token = tf.fill((effective_batch_size, 1), 1) * mask_token_id
844
+ inputs = tf.concat([inputs, mask_token], axis=1)
845
+
846
+ if lang_id is not None:
847
+ langs = tf.ones_like(inputs) * lang_id
848
+ else:
849
+ langs = None
850
+ return {"input_ids": inputs, "langs": langs}
851
+
852
+ @unpack_inputs
853
+ @add_start_docstrings_to_model_forward(FLAUBERT_INPUTS_DOCSTRING)
854
+ @add_code_sample_docstrings(
855
+ checkpoint=_CHECKPOINT_FOR_DOC,
856
+ output_type=TFFlaubertWithLMHeadModelOutput,
857
+ config_class=_CONFIG_FOR_DOC,
858
+ )
859
+ def call(
860
+ self,
861
+ input_ids: np.ndarray | tf.Tensor | None = None,
862
+ attention_mask: np.ndarray | tf.Tensor | None = None,
863
+ langs: np.ndarray | tf.Tensor | None = None,
864
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
865
+ position_ids: np.ndarray | tf.Tensor | None = None,
866
+ lengths: np.ndarray | tf.Tensor | None = None,
867
+ cache: Optional[Dict[str, tf.Tensor]] = None,
868
+ head_mask: np.ndarray | tf.Tensor | None = None,
869
+ inputs_embeds: tf.Tensor | None = None,
870
+ output_attentions: Optional[bool] = None,
871
+ output_hidden_states: Optional[bool] = None,
872
+ return_dict: Optional[bool] = None,
873
+ training: Optional[bool] = False,
874
+ ) -> Union[Tuple, TFFlaubertWithLMHeadModelOutput]:
875
+ transformer_outputs = self.transformer(
876
+ input_ids=input_ids,
877
+ attention_mask=attention_mask,
878
+ langs=langs,
879
+ token_type_ids=token_type_ids,
880
+ position_ids=position_ids,
881
+ lengths=lengths,
882
+ cache=cache,
883
+ head_mask=head_mask,
884
+ inputs_embeds=inputs_embeds,
885
+ output_attentions=output_attentions,
886
+ output_hidden_states=output_hidden_states,
887
+ return_dict=return_dict,
888
+ training=training,
889
+ )
890
+ output = transformer_outputs[0]
891
+ outputs = self.pred_layer(output)
892
+
893
+ if not return_dict:
894
+ return (outputs,) + transformer_outputs[1:]
895
+
896
+ return TFFlaubertWithLMHeadModelOutput(
897
+ logits=outputs, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions
898
+ )
899
+
900
+ def build(self, input_shape=None):
901
+ if self.built:
902
+ return
903
+ self.built = True
904
+ if getattr(self, "transformer", None) is not None:
905
+ with tf.name_scope(self.transformer.name):
906
+ self.transformer.build(None)
907
+ if getattr(self, "pred_layer", None) is not None:
908
+ with tf.name_scope(self.pred_layer.name):
909
+ self.pred_layer.build(None)
910
+
911
+
912
+ @add_start_docstrings(
913
+ """
914
+ Flaubert Model with a sequence classification/regression head on top (a linear layer on top of the pooled output)
915
+ e.g. for GLUE tasks.
916
+ """,
917
+ FLAUBERT_START_DOCSTRING,
918
+ )
919
+ # Copied from transformers.models.xlm.modeling_tf_xlm.TFXLMForSequenceClassification with XLM_INPUTS->FLAUBERT_INPUTS,XLM->Flaubert
920
+ class TFFlaubertForSequenceClassification(TFFlaubertPreTrainedModel, TFSequenceClassificationLoss):
921
+ def __init__(self, config, *inputs, **kwargs):
922
+ super().__init__(config, *inputs, **kwargs)
923
+ self.num_labels = config.num_labels
924
+
925
+ self.transformer = TFFlaubertMainLayer(config, name="transformer")
926
+ self.sequence_summary = TFSequenceSummary(config, initializer_range=config.init_std, name="sequence_summary")
927
+
928
+ @unpack_inputs
929
+ @add_start_docstrings_to_model_forward(FLAUBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
930
+ @add_code_sample_docstrings(
931
+ checkpoint=_CHECKPOINT_FOR_DOC,
932
+ output_type=TFSequenceClassifierOutput,
933
+ config_class=_CONFIG_FOR_DOC,
934
+ )
935
+ def call(
936
+ self,
937
+ input_ids: TFModelInputType | None = None,
938
+ attention_mask: np.ndarray | tf.Tensor | None = None,
939
+ langs: np.ndarray | tf.Tensor | None = None,
940
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
941
+ position_ids: np.ndarray | tf.Tensor | None = None,
942
+ lengths: np.ndarray | tf.Tensor | None = None,
943
+ cache: Optional[Dict[str, tf.Tensor]] = None,
944
+ head_mask: np.ndarray | tf.Tensor | None = None,
945
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
946
+ output_attentions: Optional[bool] = None,
947
+ output_hidden_states: Optional[bool] = None,
948
+ return_dict: Optional[bool] = None,
949
+ labels: np.ndarray | tf.Tensor | None = None,
950
+ training: bool = False,
951
+ ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
952
+ r"""
953
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
954
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
955
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
956
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
957
+ """
958
+ transformer_outputs = self.transformer(
959
+ input_ids=input_ids,
960
+ attention_mask=attention_mask,
961
+ langs=langs,
962
+ token_type_ids=token_type_ids,
963
+ position_ids=position_ids,
964
+ lengths=lengths,
965
+ cache=cache,
966
+ head_mask=head_mask,
967
+ inputs_embeds=inputs_embeds,
968
+ output_attentions=output_attentions,
969
+ output_hidden_states=output_hidden_states,
970
+ return_dict=return_dict,
971
+ training=training,
972
+ )
973
+ output = transformer_outputs[0]
974
+
975
+ logits = self.sequence_summary(output)
976
+
977
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
978
+
979
+ if not return_dict:
980
+ output = (logits,) + transformer_outputs[1:]
981
+ return ((loss,) + output) if loss is not None else output
982
+
983
+ return TFSequenceClassifierOutput(
984
+ loss=loss,
985
+ logits=logits,
986
+ hidden_states=transformer_outputs.hidden_states,
987
+ attentions=transformer_outputs.attentions,
988
+ )
989
+
990
+ def build(self, input_shape=None):
991
+ if self.built:
992
+ return
993
+ self.built = True
994
+ if getattr(self, "transformer", None) is not None:
995
+ with tf.name_scope(self.transformer.name):
996
+ self.transformer.build(None)
997
+ if getattr(self, "sequence_summary", None) is not None:
998
+ with tf.name_scope(self.sequence_summary.name):
999
+ self.sequence_summary.build(None)
1000
+
1001
+
1002
+ @add_start_docstrings(
1003
+ """
1004
+ Flaubert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1005
+ layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1006
+ """,
1007
+ FLAUBERT_START_DOCSTRING,
1008
+ )
1009
+ # Copied from transformers.models.xlm.modeling_tf_xlm.TFXLMForQuestionAnsweringSimple with XLM_INPUTS->FLAUBERT_INPUTS,XLM->Flaubert
1010
+ class TFFlaubertForQuestionAnsweringSimple(TFFlaubertPreTrainedModel, TFQuestionAnsweringLoss):
1011
+ def __init__(self, config, *inputs, **kwargs):
1012
+ super().__init__(config, *inputs, **kwargs)
1013
+ self.transformer = TFFlaubertMainLayer(config, name="transformer")
1014
+ self.qa_outputs = keras.layers.Dense(
1015
+ config.num_labels, kernel_initializer=get_initializer(config.init_std), name="qa_outputs"
1016
+ )
1017
+ self.config = config
1018
+
1019
+ @unpack_inputs
1020
+ @add_start_docstrings_to_model_forward(FLAUBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1021
+ @add_code_sample_docstrings(
1022
+ checkpoint=_CHECKPOINT_FOR_DOC,
1023
+ output_type=TFQuestionAnsweringModelOutput,
1024
+ config_class=_CONFIG_FOR_DOC,
1025
+ )
1026
+ def call(
1027
+ self,
1028
+ input_ids: TFModelInputType | None = None,
1029
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1030
+ langs: np.ndarray | tf.Tensor | None = None,
1031
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1032
+ position_ids: np.ndarray | tf.Tensor | None = None,
1033
+ lengths: np.ndarray | tf.Tensor | None = None,
1034
+ cache: Optional[Dict[str, tf.Tensor]] = None,
1035
+ head_mask: np.ndarray | tf.Tensor | None = None,
1036
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1037
+ output_attentions: Optional[bool] = None,
1038
+ output_hidden_states: Optional[bool] = None,
1039
+ return_dict: Optional[bool] = None,
1040
+ start_positions: np.ndarray | tf.Tensor | None = None,
1041
+ end_positions: np.ndarray | tf.Tensor | None = None,
1042
+ training: bool = False,
1043
+ ) -> Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]:
1044
+ r"""
1045
+ start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1046
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1047
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1048
+ are not taken into account for computing the loss.
1049
+ end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1050
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1051
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1052
+ are not taken into account for computing the loss.
1053
+ """
1054
+ transformer_outputs = self.transformer(
1055
+ input_ids=input_ids,
1056
+ attention_mask=attention_mask,
1057
+ langs=langs,
1058
+ token_type_ids=token_type_ids,
1059
+ position_ids=position_ids,
1060
+ lengths=lengths,
1061
+ cache=cache,
1062
+ head_mask=head_mask,
1063
+ inputs_embeds=inputs_embeds,
1064
+ output_attentions=output_attentions,
1065
+ output_hidden_states=output_hidden_states,
1066
+ return_dict=return_dict,
1067
+ training=training,
1068
+ )
1069
+ sequence_output = transformer_outputs[0]
1070
+
1071
+ logits = self.qa_outputs(sequence_output)
1072
+ start_logits, end_logits = tf.split(logits, 2, axis=-1)
1073
+ start_logits = tf.squeeze(start_logits, axis=-1)
1074
+ end_logits = tf.squeeze(end_logits, axis=-1)
1075
+
1076
+ loss = None
1077
+ if start_positions is not None and end_positions is not None:
1078
+ labels = {"start_position": start_positions}
1079
+ labels["end_position"] = end_positions
1080
+ loss = self.hf_compute_loss(labels, (start_logits, end_logits))
1081
+
1082
+ if not return_dict:
1083
+ output = (start_logits, end_logits) + transformer_outputs[1:]
1084
+ return ((loss,) + output) if loss is not None else output
1085
+
1086
+ return TFQuestionAnsweringModelOutput(
1087
+ loss=loss,
1088
+ start_logits=start_logits,
1089
+ end_logits=end_logits,
1090
+ hidden_states=transformer_outputs.hidden_states,
1091
+ attentions=transformer_outputs.attentions,
1092
+ )
1093
+
1094
+ def build(self, input_shape=None):
1095
+ if self.built:
1096
+ return
1097
+ self.built = True
1098
+ if getattr(self, "transformer", None) is not None:
1099
+ with tf.name_scope(self.transformer.name):
1100
+ self.transformer.build(None)
1101
+ if getattr(self, "qa_outputs", None) is not None:
1102
+ with tf.name_scope(self.qa_outputs.name):
1103
+ self.qa_outputs.build([None, None, self.config.hidden_size])
1104
+
1105
+
1106
+ @add_start_docstrings(
1107
+ """
1108
+ Flaubert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1109
+ Named-Entity-Recognition (NER) tasks.
1110
+ """,
1111
+ FLAUBERT_START_DOCSTRING,
1112
+ )
1113
+ # Copied from transformers.models.xlm.modeling_tf_xlm.TFXLMForTokenClassification with XLM_INPUTS->FLAUBERT_INPUTS,XLM->Flaubert
1114
+ class TFFlaubertForTokenClassification(TFFlaubertPreTrainedModel, TFTokenClassificationLoss):
1115
+ def __init__(self, config, *inputs, **kwargs):
1116
+ super().__init__(config, *inputs, **kwargs)
1117
+ self.num_labels = config.num_labels
1118
+
1119
+ self.transformer = TFFlaubertMainLayer(config, name="transformer")
1120
+ self.dropout = keras.layers.Dropout(config.dropout)
1121
+ self.classifier = keras.layers.Dense(
1122
+ config.num_labels, kernel_initializer=get_initializer(config.init_std), name="classifier"
1123
+ )
1124
+ self.config = config
1125
+
1126
+ @unpack_inputs
1127
+ @add_start_docstrings_to_model_forward(FLAUBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1128
+ @add_code_sample_docstrings(
1129
+ checkpoint=_CHECKPOINT_FOR_DOC,
1130
+ output_type=TFTokenClassifierOutput,
1131
+ config_class=_CONFIG_FOR_DOC,
1132
+ )
1133
+ def call(
1134
+ self,
1135
+ input_ids: TFModelInputType | None = None,
1136
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1137
+ langs: np.ndarray | tf.Tensor | None = None,
1138
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1139
+ position_ids: np.ndarray | tf.Tensor | None = None,
1140
+ lengths: np.ndarray | tf.Tensor | None = None,
1141
+ cache: Optional[Dict[str, tf.Tensor]] = None,
1142
+ head_mask: np.ndarray | tf.Tensor | None = None,
1143
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1144
+ output_attentions: Optional[bool] = None,
1145
+ output_hidden_states: Optional[bool] = None,
1146
+ return_dict: Optional[bool] = None,
1147
+ labels: np.ndarray | tf.Tensor | None = None,
1148
+ training: bool = False,
1149
+ ) -> Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]:
1150
+ r"""
1151
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1152
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1153
+ """
1154
+ transformer_outputs = self.transformer(
1155
+ input_ids=input_ids,
1156
+ attention_mask=attention_mask,
1157
+ langs=langs,
1158
+ token_type_ids=token_type_ids,
1159
+ position_ids=position_ids,
1160
+ lengths=lengths,
1161
+ cache=cache,
1162
+ head_mask=head_mask,
1163
+ inputs_embeds=inputs_embeds,
1164
+ output_attentions=output_attentions,
1165
+ output_hidden_states=output_hidden_states,
1166
+ return_dict=return_dict,
1167
+ training=training,
1168
+ )
1169
+ sequence_output = transformer_outputs[0]
1170
+
1171
+ sequence_output = self.dropout(sequence_output, training=training)
1172
+ logits = self.classifier(sequence_output)
1173
+
1174
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1175
+
1176
+ if not return_dict:
1177
+ output = (logits,) + transformer_outputs[1:]
1178
+ return ((loss,) + output) if loss is not None else output
1179
+
1180
+ return TFTokenClassifierOutput(
1181
+ loss=loss,
1182
+ logits=logits,
1183
+ hidden_states=transformer_outputs.hidden_states,
1184
+ attentions=transformer_outputs.attentions,
1185
+ )
1186
+
1187
+ def build(self, input_shape=None):
1188
+ if self.built:
1189
+ return
1190
+ self.built = True
1191
+ if getattr(self, "transformer", None) is not None:
1192
+ with tf.name_scope(self.transformer.name):
1193
+ self.transformer.build(None)
1194
+ if getattr(self, "classifier", None) is not None:
1195
+ with tf.name_scope(self.classifier.name):
1196
+ self.classifier.build([None, None, self.config.hidden_size])
1197
+
1198
+
1199
+ @add_start_docstrings(
1200
+ """
1201
+ Flaubert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1202
+ softmax) e.g. for RocStories/SWAG tasks.
1203
+ """,
1204
+ FLAUBERT_START_DOCSTRING,
1205
+ )
1206
+ # Copied from transformers.models.xlm.modeling_tf_xlm.TFXLMForMultipleChoice with XLM_INPUTS->FLAUBERT_INPUTS,XLM->Flaubert
1207
+ class TFFlaubertForMultipleChoice(TFFlaubertPreTrainedModel, TFMultipleChoiceLoss):
1208
+ def __init__(self, config, *inputs, **kwargs):
1209
+ super().__init__(config, *inputs, **kwargs)
1210
+
1211
+ self.transformer = TFFlaubertMainLayer(config, name="transformer")
1212
+ self.sequence_summary = TFSequenceSummary(config, initializer_range=config.init_std, name="sequence_summary")
1213
+ self.logits_proj = keras.layers.Dense(
1214
+ 1, kernel_initializer=get_initializer(config.initializer_range), name="logits_proj"
1215
+ )
1216
+ self.config = config
1217
+
1218
+ @property
1219
+ def dummy_inputs(self):
1220
+ """
1221
+ Dummy inputs to build the network.
1222
+
1223
+ Returns:
1224
+ tf.Tensor with dummy inputs
1225
+ """
1226
+ # Sometimes Flaubert has language embeddings so don't forget to build them as well if needed
1227
+ if self.config.use_lang_emb and self.config.n_langs > 1:
1228
+ return {
1229
+ "input_ids": tf.constant(MULTIPLE_CHOICE_DUMMY_INPUTS, dtype=tf.int32),
1230
+ "langs": tf.constant(MULTIPLE_CHOICE_DUMMY_INPUTS, dtype=tf.int32),
1231
+ }
1232
+ else:
1233
+ return {
1234
+ "input_ids": tf.constant(MULTIPLE_CHOICE_DUMMY_INPUTS, dtype=tf.int32),
1235
+ }
1236
+
1237
+ @unpack_inputs
1238
+ @add_start_docstrings_to_model_forward(
1239
+ FLAUBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
1240
+ )
1241
+ @add_code_sample_docstrings(
1242
+ checkpoint=_CHECKPOINT_FOR_DOC,
1243
+ output_type=TFMultipleChoiceModelOutput,
1244
+ config_class=_CONFIG_FOR_DOC,
1245
+ )
1246
+ def call(
1247
+ self,
1248
+ input_ids: TFModelInputType | None = None,
1249
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1250
+ langs: np.ndarray | tf.Tensor | None = None,
1251
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1252
+ position_ids: np.ndarray | tf.Tensor | None = None,
1253
+ lengths: np.ndarray | tf.Tensor | None = None,
1254
+ cache: Optional[Dict[str, tf.Tensor]] = None,
1255
+ head_mask: np.ndarray | tf.Tensor | None = None,
1256
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1257
+ output_attentions: Optional[bool] = None,
1258
+ output_hidden_states: Optional[bool] = None,
1259
+ return_dict: Optional[bool] = None,
1260
+ labels: np.ndarray | tf.Tensor | None = None,
1261
+ training: bool = False,
1262
+ ) -> Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]:
1263
+ if input_ids is not None:
1264
+ num_choices = shape_list(input_ids)[1]
1265
+ seq_length = shape_list(input_ids)[2]
1266
+ else:
1267
+ num_choices = shape_list(inputs_embeds)[1]
1268
+ seq_length = shape_list(inputs_embeds)[2]
1269
+
1270
+ flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
1271
+ flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None
1272
+ flat_token_type_ids = tf.reshape(token_type_ids, (-1, seq_length)) if token_type_ids is not None else None
1273
+ flat_position_ids = tf.reshape(position_ids, (-1, seq_length)) if position_ids is not None else None
1274
+ flat_langs = tf.reshape(langs, (-1, seq_length)) if langs is not None else None
1275
+ flat_inputs_embeds = (
1276
+ tf.reshape(inputs_embeds, (-1, seq_length, shape_list(inputs_embeds)[3]))
1277
+ if inputs_embeds is not None
1278
+ else None
1279
+ )
1280
+
1281
+ if lengths is not None:
1282
+ logger.warning(
1283
+ "The `lengths` parameter cannot be used with the Flaubert multiple choice models. Please use the "
1284
+ "attention mask instead.",
1285
+ )
1286
+ lengths = None
1287
+
1288
+ transformer_outputs = self.transformer(
1289
+ flat_input_ids,
1290
+ flat_attention_mask,
1291
+ flat_langs,
1292
+ flat_token_type_ids,
1293
+ flat_position_ids,
1294
+ lengths,
1295
+ cache,
1296
+ head_mask,
1297
+ flat_inputs_embeds,
1298
+ output_attentions,
1299
+ output_hidden_states,
1300
+ return_dict=return_dict,
1301
+ training=training,
1302
+ )
1303
+ output = transformer_outputs[0]
1304
+ logits = self.sequence_summary(output)
1305
+ logits = self.logits_proj(logits)
1306
+ reshaped_logits = tf.reshape(logits, (-1, num_choices))
1307
+
1308
+ loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)
1309
+
1310
+ if not return_dict:
1311
+ output = (reshaped_logits,) + transformer_outputs[1:]
1312
+ return ((loss,) + output) if loss is not None else output
1313
+
1314
+ return TFMultipleChoiceModelOutput(
1315
+ loss=loss,
1316
+ logits=reshaped_logits,
1317
+ hidden_states=transformer_outputs.hidden_states,
1318
+ attentions=transformer_outputs.attentions,
1319
+ )
1320
+
1321
+ def build(self, input_shape=None):
1322
+ if self.built:
1323
+ return
1324
+ self.built = True
1325
+ if getattr(self, "transformer", None) is not None:
1326
+ with tf.name_scope(self.transformer.name):
1327
+ self.transformer.build(None)
1328
+ if getattr(self, "sequence_summary", None) is not None:
1329
+ with tf.name_scope(self.sequence_summary.name):
1330
+ self.sequence_summary.build(None)
1331
+ if getattr(self, "logits_proj", None) is not None:
1332
+ with tf.name_scope(self.logits_proj.name):
1333
+ self.logits_proj.build([None, None, self.config.num_labels])
1334
+
1335
+
1336
+ __all__ = [
1337
+ "TFFlaubertForMultipleChoice",
1338
+ "TFFlaubertForQuestionAnsweringSimple",
1339
+ "TFFlaubertForSequenceClassification",
1340
+ "TFFlaubertForTokenClassification",
1341
+ "TFFlaubertModel",
1342
+ "TFFlaubertPreTrainedModel",
1343
+ "TFFlaubertWithLMHeadModel",
1344
+ ]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flaubert/tokenization_flaubert.py ADDED
@@ -0,0 +1,568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-present CNRS, Facebook Inc. 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
+ """Tokenization classes for Flaubert."""
16
+
17
+ import json
18
+ import os
19
+ import re
20
+ import unicodedata
21
+ from typing import List, Optional, Tuple
22
+
23
+ from ...tokenization_utils import PreTrainedTokenizer
24
+ from ...utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {
30
+ "vocab_file": "vocab.json",
31
+ "merges_file": "merges.txt",
32
+ }
33
+
34
+
35
+ def convert_to_unicode(text):
36
+ """
37
+ Converts `text` to Unicode (if it's not already), assuming UTF-8 input.
38
+ """
39
+
40
+ def ensure_text(s, encoding="utf-8", errors="strict"):
41
+ if isinstance(s, bytes):
42
+ return s.decode(encoding, errors)
43
+ elif isinstance(s, str):
44
+ return s
45
+ else:
46
+ raise TypeError(f"not expecting type '{type(s)}'")
47
+
48
+ return ensure_text(text, encoding="utf-8", errors="ignore")
49
+
50
+
51
+ # Copied from transformers.models.xlm.tokenization_xlm.get_pairs
52
+ def get_pairs(word):
53
+ """
54
+ Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length
55
+ strings)
56
+ """
57
+ pairs = set()
58
+ prev_char = word[0]
59
+ for char in word[1:]:
60
+ pairs.add((prev_char, char))
61
+ prev_char = char
62
+ return pairs
63
+
64
+
65
+ # Copied from transformers.models.xlm.tokenization_xlm.replace_unicode_punct
66
+ def replace_unicode_punct(text):
67
+ """
68
+ Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/replace-unicode-punctuation.perl
69
+ """
70
+ text = text.replace(",", ",")
71
+ text = re.sub(r"。\s*", ". ", text)
72
+ text = text.replace("、", ",")
73
+ text = text.replace("”", '"')
74
+ text = text.replace("“", '"')
75
+ text = text.replace("∶", ":")
76
+ text = text.replace(":", ":")
77
+ text = text.replace("?", "?")
78
+ text = text.replace("《", '"')
79
+ text = text.replace("》", '"')
80
+ text = text.replace(")", ")")
81
+ text = text.replace("!", "!")
82
+ text = text.replace("(", "(")
83
+ text = text.replace(";", ";")
84
+ text = text.replace("1", "1")
85
+ text = text.replace("」", '"')
86
+ text = text.replace("「", '"')
87
+ text = text.replace("0", "0")
88
+ text = text.replace("3", "3")
89
+ text = text.replace("2", "2")
90
+ text = text.replace("5", "5")
91
+ text = text.replace("6", "6")
92
+ text = text.replace("9", "9")
93
+ text = text.replace("7", "7")
94
+ text = text.replace("8", "8")
95
+ text = text.replace("4", "4")
96
+ text = re.sub(r".\s*", ". ", text)
97
+ text = text.replace("~", "~")
98
+ text = text.replace("’", "'")
99
+ text = text.replace("…", "...")
100
+ text = text.replace("━", "-")
101
+ text = text.replace("〈", "<")
102
+ text = text.replace("〉", ">")
103
+ text = text.replace("【", "[")
104
+ text = text.replace("】", "]")
105
+ text = text.replace("%", "%")
106
+ return text
107
+
108
+
109
+ # Copied from transformers.models.xlm.tokenization_xlm.remove_non_printing_char
110
+ def remove_non_printing_char(text):
111
+ """
112
+ Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/remove-non-printing-char.perl
113
+ """
114
+ output = []
115
+ for char in text:
116
+ cat = unicodedata.category(char)
117
+ if cat.startswith("C"):
118
+ continue
119
+ output.append(char)
120
+ return "".join(output)
121
+
122
+
123
+ class FlaubertTokenizer(PreTrainedTokenizer):
124
+ """
125
+ Construct a Flaubert tokenizer. Based on Byte-Pair Encoding. The tokenization process is the following:
126
+
127
+ - Moses preprocessing and tokenization.
128
+ - Normalizing all inputs text.
129
+ - The arguments `special_tokens` and the function `set_special_tokens`, can be used to add additional symbols (like
130
+ "__classify__") to a vocabulary.
131
+ - The argument `do_lowercase` controls lower casing (automatically set for pretrained vocabularies).
132
+
133
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
134
+ this superclass for more information regarding those methods.
135
+
136
+ Args:
137
+ vocab_file (`str`):
138
+ Vocabulary file.
139
+ merges_file (`str`):
140
+ Merges file.
141
+ do_lowercase (`bool`, *optional*, defaults to `False`):
142
+ Controls lower casing.
143
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
144
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
145
+ token instead.
146
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
147
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
148
+
149
+ <Tip>
150
+
151
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
152
+ sequence. The token used is the `cls_token`.
153
+
154
+ </Tip>
155
+
156
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
157
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
158
+ sequence classification or for a text and a question for question answering. It is also used as the last
159
+ token of a sequence built with special tokens.
160
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
161
+ The token used for padding, for example when batching sequences of different lengths.
162
+ cls_token (`str`, *optional*, defaults to `"</s>"`):
163
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
164
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
165
+ mask_token (`str`, *optional*, defaults to `"<special1>"`):
166
+ The token used for masking values. This is the token used when training this model with masked language
167
+ modeling. This is the token which the model will try to predict.
168
+ additional_special_tokens (`List[str]`, *optional*, defaults to `['<special0>', '<special1>', '<special2>', '<special3>', '<special4>', '<special5>', '<special6>', '<special7>', '<special8>', '<special9>']`):
169
+ List of additional special tokens.
170
+ lang2id (`Dict[str, int]`, *optional*):
171
+ Dictionary mapping languages string identifiers to their IDs.
172
+ id2lang (`Dict[int, str]`, *optional*):
173
+ Dictionary mapping language IDs to their string identifiers.
174
+ """
175
+
176
+ vocab_files_names = VOCAB_FILES_NAMES
177
+
178
+ def __init__(
179
+ self,
180
+ vocab_file,
181
+ merges_file,
182
+ do_lowercase=False,
183
+ unk_token="<unk>",
184
+ bos_token="<s>",
185
+ sep_token="</s>",
186
+ pad_token="<pad>",
187
+ cls_token="</s>",
188
+ mask_token="<special1>",
189
+ additional_special_tokens=[
190
+ "<special0>",
191
+ "<special1>",
192
+ "<special2>",
193
+ "<special3>",
194
+ "<special4>",
195
+ "<special5>",
196
+ "<special6>",
197
+ "<special7>",
198
+ "<special8>",
199
+ "<special9>",
200
+ ],
201
+ lang2id=None,
202
+ id2lang=None,
203
+ **kwargs,
204
+ ):
205
+ do_lowercase_and_remove_accent = kwargs.pop("do_lowercase_and_remove_accent", None)
206
+ if do_lowercase_and_remove_accent is not None:
207
+ logger.warning(
208
+ "`do_lowercase_and_remove_accent` is passed as a keyword argument, but this won't do anything."
209
+ " `FlaubertTokenizer` will always set it to `False`."
210
+ )
211
+ # always `False`
212
+ self.do_lowercase_and_remove_accent = False
213
+
214
+ self.do_lowercase = do_lowercase
215
+
216
+ try:
217
+ import sacremoses
218
+ except ImportError:
219
+ raise ImportError(
220
+ "You need to install sacremoses to use FlaubertTokenizer. "
221
+ "See https://pypi.org/project/sacremoses/ for installation."
222
+ )
223
+
224
+ self.sm = sacremoses
225
+
226
+ # cache of sm.MosesPunctNormalizer instance
227
+ self.cache_moses_punct_normalizer = {}
228
+ # cache of sm.MosesTokenizer instance
229
+ self.cache_moses_tokenizer = {}
230
+ self.lang_with_custom_tokenizer = {"zh", "th", "ja"}
231
+ self.lang2id = lang2id
232
+ self.id2lang = id2lang
233
+ if lang2id is not None and id2lang is not None:
234
+ assert len(lang2id) == len(id2lang)
235
+
236
+ self.ja_word_tokenizer = None
237
+ self.zh_word_tokenizer = None
238
+
239
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
240
+ self.encoder = json.load(vocab_handle)
241
+ self.decoder = {v: k for k, v in self.encoder.items()}
242
+ with open(merges_file, encoding="utf-8") as merges_handle:
243
+ merges = merges_handle.read().split("\n")[:-1]
244
+ merges = [tuple(merge.split()[:2]) for merge in merges]
245
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
246
+ self.cache = {}
247
+
248
+ super().__init__(
249
+ do_lowercase=do_lowercase,
250
+ unk_token=unk_token,
251
+ bos_token=bos_token,
252
+ sep_token=sep_token,
253
+ pad_token=pad_token,
254
+ cls_token=cls_token,
255
+ mask_token=mask_token,
256
+ additional_special_tokens=additional_special_tokens,
257
+ lang2id=lang2id,
258
+ id2lang=id2lang,
259
+ **kwargs,
260
+ )
261
+
262
+ @property
263
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.do_lower_case
264
+ def do_lower_case(self):
265
+ return self.do_lowercase_and_remove_accent
266
+
267
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.moses_punct_norm
268
+ def moses_punct_norm(self, text, lang):
269
+ if lang not in self.cache_moses_punct_normalizer:
270
+ punct_normalizer = self.sm.MosesPunctNormalizer(lang=lang)
271
+ self.cache_moses_punct_normalizer[lang] = punct_normalizer
272
+ else:
273
+ punct_normalizer = self.cache_moses_punct_normalizer[lang]
274
+ return punct_normalizer.normalize(text)
275
+
276
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.moses_tokenize
277
+ def moses_tokenize(self, text, lang):
278
+ if lang not in self.cache_moses_tokenizer:
279
+ moses_tokenizer = self.sm.MosesTokenizer(lang=lang)
280
+ self.cache_moses_tokenizer[lang] = moses_tokenizer
281
+ else:
282
+ moses_tokenizer = self.cache_moses_tokenizer[lang]
283
+ return moses_tokenizer.tokenize(text, return_str=False, escape=False)
284
+
285
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.moses_pipeline
286
+ def moses_pipeline(self, text, lang):
287
+ text = replace_unicode_punct(text)
288
+ text = self.moses_punct_norm(text, lang)
289
+ text = remove_non_printing_char(text)
290
+ return text
291
+
292
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.ja_tokenize
293
+ def ja_tokenize(self, text):
294
+ if self.ja_word_tokenizer is None:
295
+ try:
296
+ import Mykytea
297
+
298
+ self.ja_word_tokenizer = Mykytea.Mykytea(
299
+ f"-model {os.path.expanduser('~')}/local/share/kytea/model.bin"
300
+ )
301
+ except (AttributeError, ImportError):
302
+ logger.error(
303
+ "Make sure you install KyTea (https://github.com/neubig/kytea) and it's python wrapper"
304
+ " (https://github.com/chezou/Mykytea-python) with the following steps"
305
+ )
306
+ logger.error("1. git clone git@github.com:neubig/kytea.git && cd kytea")
307
+ logger.error("2. autoreconf -i")
308
+ logger.error("3. ./configure --prefix=$HOME/local")
309
+ logger.error("4. make && make install")
310
+ logger.error("5. pip install kytea")
311
+ raise
312
+ return list(self.ja_word_tokenizer.getWS(text))
313
+
314
+ @property
315
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.vocab_size
316
+ def vocab_size(self):
317
+ return len(self.encoder)
318
+
319
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.get_vocab
320
+ def get_vocab(self):
321
+ return dict(self.encoder, **self.added_tokens_encoder)
322
+
323
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.bpe
324
+ def bpe(self, token):
325
+ word = tuple(token[:-1]) + (token[-1] + "</w>",)
326
+ if token in self.cache:
327
+ return self.cache[token]
328
+ pairs = get_pairs(word)
329
+
330
+ if not pairs:
331
+ return token + "</w>"
332
+
333
+ while True:
334
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
335
+ if bigram not in self.bpe_ranks:
336
+ break
337
+ first, second = bigram
338
+ new_word = []
339
+ i = 0
340
+ while i < len(word):
341
+ try:
342
+ j = word.index(first, i)
343
+ except ValueError:
344
+ new_word.extend(word[i:])
345
+ break
346
+ else:
347
+ new_word.extend(word[i:j])
348
+ i = j
349
+
350
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
351
+ new_word.append(first + second)
352
+ i += 2
353
+ else:
354
+ new_word.append(word[i])
355
+ i += 1
356
+ new_word = tuple(new_word)
357
+ word = new_word
358
+ if len(word) == 1:
359
+ break
360
+ else:
361
+ pairs = get_pairs(word)
362
+ word = " ".join(word)
363
+ if word == "\n </w>":
364
+ word = "\n</w>"
365
+ self.cache[token] = word
366
+ return word
367
+
368
+ def preprocess_text(self, text):
369
+ text = text.replace("``", '"').replace("''", '"')
370
+ text = convert_to_unicode(text)
371
+ text = unicodedata.normalize("NFC", text)
372
+
373
+ if self.do_lowercase:
374
+ text = text.lower()
375
+
376
+ return text
377
+
378
+ def _tokenize(self, text, bypass_tokenizer=False):
379
+ """
380
+ Tokenize a string given language code using Moses.
381
+
382
+ Details of tokenization:
383
+
384
+ - [sacremoses](https://github.com/alvations/sacremoses): port of Moses
385
+ - Install with `pip install sacremoses`
386
+
387
+ Args:
388
+ - bypass_tokenizer: Allow users to preprocess and tokenize the sentences externally (default = False)
389
+ (bool). If True, we only apply BPE.
390
+
391
+ Returns:
392
+ List of tokens.
393
+ """
394
+ lang = "fr"
395
+ if lang and self.lang2id and lang not in self.lang2id:
396
+ logger.error(
397
+ "Supplied language code not found in lang2id mapping. Please check that your language is supported by"
398
+ " the loaded pretrained model."
399
+ )
400
+
401
+ if bypass_tokenizer:
402
+ text = text.split()
403
+ else:
404
+ text = self.preprocess_text(text)
405
+ text = self.moses_pipeline(text, lang=lang)
406
+ text = self.moses_tokenize(text, lang=lang)
407
+
408
+ split_tokens = []
409
+ for token in text:
410
+ if token:
411
+ split_tokens.extend(list(self.bpe(token).split(" ")))
412
+
413
+ return split_tokens
414
+
415
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer._convert_token_to_id
416
+ def _convert_token_to_id(self, token):
417
+ """Converts a token (str) in an id using the vocab."""
418
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
419
+
420
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer._convert_id_to_token
421
+ def _convert_id_to_token(self, index):
422
+ """Converts an index (integer) in a token (str) using the vocab."""
423
+ return self.decoder.get(index, self.unk_token)
424
+
425
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.convert_tokens_to_string
426
+ def convert_tokens_to_string(self, tokens):
427
+ """Converts a sequence of tokens (string) in a single string."""
428
+ out_string = "".join(tokens).replace("</w>", " ").strip()
429
+ return out_string
430
+
431
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.build_inputs_with_special_tokens
432
+ def build_inputs_with_special_tokens(
433
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
434
+ ) -> List[int]:
435
+ """
436
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
437
+ adding special tokens. An XLM sequence has the following format:
438
+
439
+ - single sequence: `<s> X </s>`
440
+ - pair of sequences: `<s> A </s> B </s>`
441
+
442
+ Args:
443
+ token_ids_0 (`List[int]`):
444
+ List of IDs to which the special tokens will be added.
445
+ token_ids_1 (`List[int]`, *optional*):
446
+ Optional second list of IDs for sequence pairs.
447
+
448
+ Returns:
449
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
450
+
451
+ """
452
+ bos = [self.bos_token_id]
453
+ sep = [self.sep_token_id]
454
+
455
+ if token_ids_1 is None:
456
+ return bos + token_ids_0 + sep
457
+ return bos + token_ids_0 + sep + token_ids_1 + sep
458
+
459
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.get_special_tokens_mask
460
+ def get_special_tokens_mask(
461
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
462
+ ) -> List[int]:
463
+ """
464
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
465
+ special tokens using the tokenizer `prepare_for_model` method.
466
+
467
+ Args:
468
+ token_ids_0 (`List[int]`):
469
+ List of IDs.
470
+ token_ids_1 (`List[int]`, *optional*):
471
+ Optional second list of IDs for sequence pairs.
472
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
473
+ Whether or not the token list is already formatted with special tokens for the model.
474
+
475
+ Returns:
476
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
477
+ """
478
+
479
+ if already_has_special_tokens:
480
+ return super().get_special_tokens_mask(
481
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
482
+ )
483
+
484
+ if token_ids_1 is not None:
485
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
486
+ return [1] + ([0] * len(token_ids_0)) + [1]
487
+
488
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.create_token_type_ids_from_sequences
489
+ def create_token_type_ids_from_sequences(
490
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
491
+ ) -> List[int]:
492
+ """
493
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLM sequence
494
+ pair mask has the following format:
495
+
496
+ ```
497
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
498
+ | first sequence | second sequence |
499
+ ```
500
+
501
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
502
+
503
+ Args:
504
+ token_ids_0 (`List[int]`):
505
+ List of IDs.
506
+ token_ids_1 (`List[int]`, *optional*):
507
+ Optional second list of IDs for sequence pairs.
508
+
509
+ Returns:
510
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
511
+ """
512
+ sep = [self.sep_token_id]
513
+ cls = [self.cls_token_id]
514
+ if token_ids_1 is None:
515
+ return len(cls + token_ids_0 + sep) * [0]
516
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
517
+
518
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.save_vocabulary
519
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
520
+ if not os.path.isdir(save_directory):
521
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
522
+ return
523
+ vocab_file = os.path.join(
524
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
525
+ )
526
+ merge_file = os.path.join(
527
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
528
+ )
529
+
530
+ with open(vocab_file, "w", encoding="utf-8") as f:
531
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
532
+
533
+ index = 0
534
+ with open(merge_file, "w", encoding="utf-8") as writer:
535
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
536
+ if index != token_index:
537
+ logger.warning(
538
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
539
+ " Please check that the tokenizer is not corrupted!"
540
+ )
541
+ index = token_index
542
+ writer.write(" ".join(bpe_tokens) + "\n")
543
+ index += 1
544
+
545
+ return vocab_file, merge_file
546
+
547
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.__getstate__
548
+ def __getstate__(self):
549
+ state = self.__dict__.copy()
550
+ state["sm"] = None
551
+ return state
552
+
553
+ # Copied from transformers.models.xlm.tokenization_xlm.XLMTokenizer.__setstate__
554
+ def __setstate__(self, d):
555
+ self.__dict__ = d
556
+
557
+ try:
558
+ import sacremoses
559
+ except ImportError:
560
+ raise ImportError(
561
+ "You need to install sacremoses to use XLMTokenizer. "
562
+ "See https://pypi.org/project/sacremoses/ for installation."
563
+ )
564
+
565
+ self.sm = sacremoses
566
+
567
+
568
+ __all__ = ["FlaubertTokenizer"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flava/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_flava import *
22
+ from .feature_extraction_flava import *
23
+ from .image_processing_flava import *
24
+ from .modeling_flava import *
25
+ from .processing_flava import *
26
+ else:
27
+ import sys
28
+
29
+ _file = globals()["__file__"]
30
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flava/configuration_flava.py ADDED
@@ -0,0 +1,701 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta Platforms authors and The HuggingFace 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
+ """FLAVA model configurations"""
16
+
17
+ from typing import Any, Dict
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class FlavaImageConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`FlavaImageModel`]. It is used to instantiate an
29
+ FLAVA model according to the specified arguments, defining the model architecture.
30
+
31
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the FLAVA
32
+ [facebook/flava-full](https://huggingface.co/facebook/flava-full) architecture.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ hidden_size (`int`, *optional*, defaults to 768):
40
+ Dimensionality of the encoder layers and the pooler layer.
41
+ num_hidden_layers (`int`, *optional*, defaults to 12):
42
+ Number of hidden layers in the Transformer encoder.
43
+ num_attention_heads (`int`, *optional*, defaults to 12):
44
+ Number of attention heads for each attention layer in the Transformer encoder.
45
+ intermediate_size (`int`, *optional*, defaults to 3072):
46
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
47
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
48
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
49
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
50
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
51
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
52
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
53
+ The dropout ratio for the attention probabilities.
54
+ initializer_range (`float`, *optional*, defaults to 0.02):
55
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
56
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
57
+ The epsilon used by the layer normalization layers.
58
+ image_size (`int`, *optional*, defaults to 224):
59
+ The size (resolution) of each image.
60
+ patch_size (`int`, *optional*, defaults to 16):
61
+ The size (resolution) of each patch.
62
+ num_channels (`int`, *optional*, defaults to 3):
63
+ The number of input channels.
64
+ qkv_bias (`bool`, *optional*, defaults to `True`):
65
+ Whether to add a bias to the queries, keys and values.
66
+ mask_token (`bool`, *optional*, defaults to `True`):
67
+ Whether to use a mask token or not. Used in MIM (Masked Image Modeling) loss for FLAVA.
68
+ vocab_size (`int`, *optional*, defaults to 8192):
69
+ Vocabulary size of the [`FlavaImageCodebook`] used in conjunction with [`FlavaImageModel`] for MIM (Masked
70
+ Image Modeling) loss for FLAVA.
71
+
72
+ Example:
73
+
74
+ ```python
75
+ >>> from transformers import FlavaImageConfig, FlavaImageModel
76
+
77
+ >>> # Initializing a FlavaImageModel with style configuration
78
+ >>> configuration = FlavaImageConfig()
79
+
80
+ >>> # Initializing a FlavaImageModel model (with random weights) from the style configuration
81
+ >>> model = FlavaImageModel(configuration)
82
+
83
+ >>> # Accessing the model configuration
84
+ >>> configuration = model.config
85
+ ```"""
86
+
87
+ model_type = "flava_image_model"
88
+ base_config_key = "image_config"
89
+
90
+ def __init__(
91
+ self,
92
+ hidden_size: int = 768,
93
+ num_hidden_layers: int = 12,
94
+ num_attention_heads: int = 12,
95
+ intermediate_size: int = 3072,
96
+ hidden_act: int = "gelu",
97
+ hidden_dropout_prob: float = 0.0,
98
+ attention_probs_dropout_prob: float = 0.0,
99
+ initializer_range: float = 0.02,
100
+ layer_norm_eps: float = 1e-12,
101
+ image_size: int = 224,
102
+ patch_size: int = 16,
103
+ num_channels: int = 3,
104
+ qkv_bias: bool = True,
105
+ mask_token: bool = True,
106
+ vocab_size: int = 8192,
107
+ **kwargs,
108
+ ):
109
+ super().__init__(**kwargs)
110
+
111
+ self.hidden_size = hidden_size
112
+ self.num_hidden_layers = num_hidden_layers
113
+ self.num_attention_heads = num_attention_heads
114
+ self.intermediate_size = intermediate_size
115
+ self.hidden_act = hidden_act
116
+ self.hidden_dropout_prob = hidden_dropout_prob
117
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
118
+ self.initializer_range = initializer_range
119
+ self.layer_norm_eps = layer_norm_eps
120
+ self.image_size = image_size
121
+ self.patch_size = patch_size
122
+ self.num_channels = num_channels
123
+ self.qkv_bias = qkv_bias
124
+ self.mask_token = mask_token
125
+ self.vocab_size = vocab_size
126
+
127
+
128
+ class FlavaTextConfig(PretrainedConfig):
129
+ r"""
130
+ This is the configuration class to store the configuration of a [`FlavaTextModel`]. It is used to instantiate an
131
+ FLAVA model according to the specified arguments, defining the model architecture.
132
+
133
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the FLAVA
134
+ [facebook/flava-full](https://huggingface.co/facebook/flava-full) architecture.
135
+
136
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
137
+ documentation from [`PretrainedConfig`] for more information.
138
+
139
+
140
+ Args:
141
+ vocab_size (`int`, *optional*, defaults to 30522):
142
+ Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
143
+ `inputs_ids` passed when calling [`FlavaTextModel`].
144
+ type_vocab_size (`int`, *optional*, defaults to 2):
145
+ The vocabulary size of the `token_type_ids` passed when calling [`FlavaTextModel`]. Note that even though
146
+ text encoder allows `token_type_ids`'s value as 2, for text-only pretraining and fine-tuning, only 1 is
147
+ used similar to RoBERTa.
148
+ max_position_embeddings (`int`, *optional*, defaults to 512):
149
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
150
+ just in case (e.g., 512 or 1024 or 2048). For VL, max_length passed to model is 77.
151
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
152
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
153
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
154
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
155
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
156
+ with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
157
+ hidden_size (`int`, *optional*, defaults to 768):
158
+ Dimensionality of the encoder layers and the pooler layer.
159
+ num_hidden_layers (`int`, *optional*, defaults to 12):
160
+ Number of hidden layers in the Transformer encoder.
161
+ num_attention_heads (`int`, *optional*, defaults to 12):
162
+ Number of attention heads for each attention layer in the Transformer encoder.
163
+ intermediate_size (`int`, *optional*, defaults to 3072):
164
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
165
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
166
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
167
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
168
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
169
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
170
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
171
+ The dropout ratio for the attention probabilities.
172
+ initializer_range (`float`, *optional*, defaults to 0.02):
173
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
174
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
175
+ The epsilon used by the layer normalization layers.
176
+ image_size (`int`, *optional*, defaults to 224):
177
+ The size (resolution) of each image.
178
+ patch_size (`int`, *optional*, defaults to 16):
179
+ The size (resolution) of each patch.
180
+ num_channels (`int`, *optional*, defaults to 3):
181
+ The number of input channels.
182
+ qkv_bias (`bool`, *optional*, defaults to `True`):
183
+ Whether to add a bias to the queries, keys and values.
184
+
185
+ Example:
186
+
187
+ ```python
188
+ >>> from transformers import FlavaTextConfig, FlavaTextModel
189
+
190
+ >>> # Initializing a FlavaTextModel with style configuration
191
+ >>> configuration = FlavaTextConfig()
192
+
193
+ >>> # Initializing a FlavaTextModel model (with random weights) from the style configuration
194
+ >>> model = FlavaTextModel(configuration)
195
+
196
+ >>> # Accessing the model configuration
197
+ >>> configuration = model.config
198
+ ```"""
199
+
200
+ model_type = "flava_text_model"
201
+ base_config_key = "text_config"
202
+
203
+ def __init__(
204
+ self,
205
+ vocab_size: int = 30522,
206
+ type_vocab_size: int = 2,
207
+ max_position_embeddings: int = 512,
208
+ position_embedding_type: str = "absolute",
209
+ hidden_size: int = 768,
210
+ num_hidden_layers: int = 12,
211
+ num_attention_heads: int = 12,
212
+ intermediate_size: int = 3072,
213
+ hidden_act: str = "gelu",
214
+ hidden_dropout_prob: float = 0.0,
215
+ attention_probs_dropout_prob: float = 0.0,
216
+ initializer_range: float = 0.02,
217
+ layer_norm_eps: float = 1e-12,
218
+ pad_token_id: int = 0,
219
+ qkv_bias: bool = True,
220
+ **kwargs,
221
+ ):
222
+ super().__init__(**kwargs)
223
+
224
+ self.vocab_size = vocab_size
225
+ self.type_vocab_size = type_vocab_size
226
+ self.max_position_embeddings = max_position_embeddings
227
+ self.position_embedding_type = position_embedding_type
228
+ self.hidden_size = hidden_size
229
+ self.num_hidden_layers = num_hidden_layers
230
+ self.num_attention_heads = num_attention_heads
231
+ self.intermediate_size = intermediate_size
232
+ self.hidden_act = hidden_act
233
+ self.hidden_dropout_prob = hidden_dropout_prob
234
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
235
+ self.initializer_range = initializer_range
236
+ self.layer_norm_eps = layer_norm_eps
237
+ self.qkv_bias = qkv_bias
238
+ self.pad_token_id = pad_token_id
239
+
240
+
241
+ class FlavaMultimodalConfig(PretrainedConfig):
242
+ r"""
243
+ This is the configuration class to store the configuration of a [`FlavaMultimodalModel`]. It is used to instantiate
244
+ an FLAVA model according to the specified arguments, defining the model architecture.
245
+
246
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the FLAVA
247
+ [facebook/flava-full](https://huggingface.co/facebook/flava-full) architecture.
248
+
249
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
250
+ documentation from [`PretrainedConfig`] for more information.
251
+
252
+
253
+ Args:
254
+ hidden_size (`int`, *optional*, defaults to 768):
255
+ Dimensionality of the encoder layers and the pooler layer.
256
+ num_hidden_layers (`int`, *optional*, defaults to 6):
257
+ Number of hidden layers in the Transformer encoder.
258
+ num_attention_heads (`int`, *optional*, defaults to 12):
259
+ Number of attention heads for each attention layer in the Transformer encoder.
260
+ intermediate_size (`int`, *optional*, defaults to 3072):
261
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
262
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
263
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
264
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
265
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
266
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
267
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
268
+ The dropout ratio for the attention probabilities.
269
+ initializer_range (`float`, *optional*, defaults to 0.02):
270
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
271
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
272
+ The epsilon used by the layer normalization layers.
273
+ qkv_bias (`bool`, *optional*, defaults to `True`):
274
+ Whether to add a bias to the queries, keys and values.
275
+ use_cls_token (`bool`, *optional*, defaults to `True`):
276
+ Whether to use an extra CLS token for multimodal settings. Usually needed by the FLAVA model.
277
+
278
+
279
+ Example:
280
+
281
+ ```python
282
+ >>> from transformers import FlavaMultimodalConfig, FlavaMultimodalModel
283
+
284
+ >>> # Initializing a FlavaMultimodalModel with style configuration
285
+ >>> configuration = FlavaMultimodalConfig()
286
+
287
+ >>> # Initializing a FlavaMultimodalModel model (with random weights) from the style configuration
288
+ >>> model = FlavaMultimodalModel(configuration)
289
+
290
+ >>> # Accessing the model configuration
291
+ >>> configuration = model.config
292
+ ```"""
293
+
294
+ model_type = "flava_multimodal_model"
295
+ base_config_key = "multimodal_config"
296
+
297
+ def __init__(
298
+ self,
299
+ hidden_size: int = 768,
300
+ num_hidden_layers: int = 6,
301
+ num_attention_heads: int = 12,
302
+ intermediate_size: int = 3072,
303
+ hidden_act: int = "gelu",
304
+ hidden_dropout_prob: int = 0.0,
305
+ attention_probs_dropout_prob: int = 0.0,
306
+ initializer_range: float = 0.02,
307
+ layer_norm_eps: float = 1e-12,
308
+ qkv_bias: bool = True,
309
+ use_cls_token: bool = True,
310
+ **kwargs,
311
+ ):
312
+ super().__init__(**kwargs)
313
+
314
+ self.hidden_size = hidden_size
315
+ self.num_hidden_layers = num_hidden_layers
316
+ self.num_attention_heads = num_attention_heads
317
+ self.intermediate_size = intermediate_size
318
+ self.hidden_act = hidden_act
319
+ self.hidden_dropout_prob = hidden_dropout_prob
320
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
321
+ self.initializer_range = initializer_range
322
+ self.layer_norm_eps = layer_norm_eps
323
+ self.qkv_bias = qkv_bias
324
+ self.use_cls_token = use_cls_token
325
+
326
+
327
+ class FlavaImageCodebookConfig(PretrainedConfig):
328
+ model_type = "flava_image_codebook"
329
+ base_config_key = "image_codebook_config"
330
+
331
+ r"""
332
+ [`FlavaImageCodebookConfig`] is the configuration class to store the configuration of a [`FlavaImageCodebook`]. It
333
+ is used to instantiate an FLAVA model according to the specified arguments, defining the model architecture.
334
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the FLAVA
335
+ [facebook/flava-image-codebook](https://huggingface.co/facebook/flava-image-codebook) architecture.
336
+
337
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
338
+ documentation from [`PretrainedConfig`] for more information.
339
+
340
+ Args:
341
+ num_groups (`int`, *optional*, defaults to 4):
342
+ Number of groups to be created. This parameter as of now doesn't affect the model and is used for some
343
+ internal calculation and estimations.
344
+ input_channels (`int`, *optional*, defaults to 3):
345
+ Number of channels in the image to be passed.
346
+ num_blocks_per_group (`int`, *optional*, defaults to 2):
347
+ Number of conv-based blocks per group.
348
+ hidden_size (`int`, *optional*, defaults to 256):
349
+ Size of hidden dim for the blocks.
350
+ vocab_size (`int`, *optional*, defaults to 8192):
351
+ Size of the output vocabulary for the codebook.
352
+ freeze (`bool`, defaults to `True`):
353
+ Whether to freeze the weights of the model.
354
+ initializer_range (`float`, *optional*, defaults to 0.02):
355
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
356
+ kwargs (*optional*):
357
+ Dictionary of keyword arguments.
358
+
359
+ Example:
360
+
361
+ ```python
362
+ >>> from transformers import FlavaImageCodebookConfig, FlavaImageCodebook
363
+
364
+ >>> # Initializing a FlavaImageCodebook with style configuration
365
+ >>> configuration = FlavaImageCodebookConfig()
366
+
367
+ >>> # Initializing a FlavaImageCodebook model (with random weights) from the style configuration
368
+ >>> model = FlavaImageCodebook(configuration)
369
+ >>> # Accessing the model configuration
370
+ >>> configuration = model.config
371
+ ```
372
+ """
373
+
374
+ def __init__(
375
+ self,
376
+ num_groups: int = 4,
377
+ input_channels: int = 3,
378
+ num_blocks_per_group: int = 2,
379
+ hidden_size: int = 256,
380
+ vocab_size: int = 8192,
381
+ freeze: int = True,
382
+ initializer_range: float = 0.02,
383
+ **kwargs,
384
+ ):
385
+ super().__init__(**kwargs)
386
+ self.num_groups = num_groups
387
+ self.input_channels = input_channels
388
+ self.num_blocks_per_group = num_blocks_per_group
389
+ self.hidden_size = hidden_size
390
+ self.vocab_size = vocab_size
391
+ self.freeze = freeze
392
+ self.initializer_range = initializer_range
393
+
394
+
395
+ class FlavaConfig(PretrainedConfig):
396
+ r"""
397
+ [`FlavaConfig`] is the configuration class to store the configuration of a [`FlavaModel`]. It is used to
398
+ instantiate FLAVA model according to the specified arguments, defining the text model, image model, image codebook
399
+ and multimodal model configs. Instantiating a configuration with the defaults will yield a similar configuration to
400
+ that of the FLAVA [facebook/flava-full](https://huggingface.co/facebook/flava-full) architecture.
401
+
402
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
403
+ documentation from [`PretrainedConfig`] for more information.
404
+
405
+ Args:
406
+ text_config (`dict`, *optional*):
407
+ Dictionary of configuration options used to initialize [`FlavaTextConfig`].
408
+ image_config (`dict`, *optional*):
409
+ Dictionary of configuration options used to initialize [`FlavaImageConfig`].
410
+ multimodal_config (`dict`, *optional*):
411
+ Dictionary of configuration options used to initialize [`FlavaMultimodalConfig`].
412
+ hidden_size (`int`, *optional*, defaults to 768):
413
+ Dimensionality of the encoder layers and the pooler layer.
414
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
415
+ The epsilon used by the layer normalization layers.
416
+ projection_dim (`int`, *optional*, defaults to 512):
417
+ Dimensionality of text and image projection layers.
418
+ logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
419
+ The initial value of the *logit_scale* parameter. Default is used as per the original FLAVA/CLIP
420
+ implementation.
421
+ initializer_range (`float`, *optional*, defaults to 0.02):
422
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
423
+ ce_ignore_index (`int`, *optional*, defaults to -100):
424
+ Cross entropy index to ignore.
425
+ mim_weight (`float`, *optional*, defaults to 1.0):
426
+ Weight to be assigned to MIM (Masked Image Modeling) unimodal loss
427
+ mlm_weight (`float`, *optional*, defaults to 1.0):
428
+ Weight to be assigned to MLM (Masked Language Modeling) unimodal loss
429
+ global_contrastive_weight (`float`, *optional*, defaults to 1.0):
430
+ Weight to be assigned to global contrastive cross-alignment loss.
431
+ itm_weight (`float`, *optional*, defaults to 1.0):
432
+ Weight to be assigned to image-text matching multimodal loss.
433
+ mmm_image_weight (`float`, *optional*, defaults to 1.0):
434
+ Weight to be assigned to MMM loss's image part.
435
+ mmm_text_weight (`float`, *optional*, defaults to 1.0):
436
+ Weight to be assigned to MMM loss's text part.
437
+ global_backprop_contrastive (`bool`, *optional*, defaults to `True`):
438
+ Whether to use global backpropgation through all workers in contrastive loss.
439
+ skip_unmasked_multimodal_encoder (`bool`, *optional*, defaults to `True`):
440
+ Whether to skip running unmasked multimodal encoder whose outputs are not used by FLAVA losses.
441
+ return_loss (`bool`, *optional*, defaults to `True`):
442
+ Whether to return loss or not
443
+
444
+ kwargs (*optional*):
445
+ Dictionary of keyword arguments.
446
+
447
+ Example:
448
+
449
+ ```python
450
+ >>> from transformers import FlavaConfig, FlavaModel, FlavaForPreTraining
451
+
452
+ >>> # Initializing a FlavaConfig with style configuration
453
+ >>> configuration = FlavaConfig()
454
+
455
+ >>> # Initializing a FlavaModel and FlavaForPreTraining model (with random weights) from the style configuration
456
+ >>> model = FlavaModel(configuration)
457
+ >>> model_pre = FlavaForPreTraining(configuration)
458
+
459
+ >>> # Accessing the model configuration
460
+ >>> configuration = model.config
461
+ >>> configuration_pre = model_pre.config
462
+ ```
463
+ """
464
+
465
+ model_type = "flava"
466
+ sub_configs = {
467
+ "text_config": FlavaTextConfig,
468
+ "image_config": FlavaImageConfig,
469
+ "multimodal_config": FlavaMultimodalConfig,
470
+ "image_codebook_config": FlavaImageCodebookConfig,
471
+ }
472
+
473
+ def __init__(
474
+ self,
475
+ image_config: Dict[str, Any] = None,
476
+ text_config: Dict[str, Any] = None,
477
+ multimodal_config: Dict[str, Any] = None,
478
+ image_codebook_config: Dict[str, Any] = None,
479
+ hidden_size: int = 768,
480
+ layer_norm_eps: float = 1e-12,
481
+ projection_dim: int = 768,
482
+ init_codebook: bool = True,
483
+ logit_scale_init_value: float = 2.6592,
484
+ initializer_range: float = 0.02,
485
+ ce_ignore_index: int = -100,
486
+ mim_weight: float = 1.0,
487
+ mlm_weight: float = 1.0,
488
+ global_contrastive_weight: float = 1.0,
489
+ itm_weight: float = 1.0,
490
+ mmm_image_weight: float = 1.0,
491
+ mmm_text_weight: float = 1.0,
492
+ global_backprop_contrastive: bool = True,
493
+ skip_unmasked_multimodal_encoder: bool = True,
494
+ return_loss: bool = True,
495
+ **kwargs,
496
+ ):
497
+ # If `_config_dict` exist, we use them for the backward compatibility.
498
+ # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
499
+ # of confusion!).
500
+ text_config_dict = kwargs.pop("text_config_dict", None)
501
+ image_config_dict = kwargs.pop("image_config_dict", None)
502
+ multimodal_config_dict = kwargs.pop("multimodal_config_dict", None)
503
+ image_codebook_config_dict = kwargs.pop("image_codebook_config_dict", None)
504
+
505
+ super().__init__(**kwargs)
506
+
507
+ # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
508
+ # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
509
+ # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
510
+ if text_config_dict is not None:
511
+ if text_config is None:
512
+ text_config = {}
513
+
514
+ # This is the complete result when using `text_config_dict`.
515
+ _text_config_dict = FlavaTextConfig(**text_config_dict).to_dict()
516
+
517
+ # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
518
+ for key, value in _text_config_dict.items():
519
+ if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
520
+ # If specified in `text_config_dict`
521
+ if key in text_config_dict:
522
+ message = (
523
+ f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
524
+ f'The value `text_config_dict["{key}"]` will be used instead.'
525
+ )
526
+ # If inferred from default argument values (just to be super careful)
527
+ else:
528
+ message = (
529
+ f"`text_config_dict` is provided which will be used to initialize `FlavaTextConfig`. The "
530
+ f'value `text_config["{key}"]` will be overridden.'
531
+ )
532
+ logger.info(message)
533
+
534
+ # Update all values in `text_config` with the ones in `_text_config_dict`.
535
+ text_config.update(_text_config_dict)
536
+
537
+ if image_config_dict is not None:
538
+ if image_config is None:
539
+ image_config = {}
540
+
541
+ # This is the complete result when using `image_config_dict`.
542
+ _image_config_dict = FlavaImageConfig(**image_config_dict).to_dict()
543
+ # convert keys to string instead of integer
544
+ if "id2label" in _image_config_dict:
545
+ _image_config_dict["id2label"] = {
546
+ str(key): value for key, value in _image_config_dict["id2label"].items()
547
+ }
548
+
549
+ # Give a warning if the values exist in both `_image_config_dict` and `image_config` but being different.
550
+ for key, value in _image_config_dict.items():
551
+ if key in image_config and value != image_config[key] and key not in ["transformers_version"]:
552
+ # If specified in `image_config_dict`
553
+ if key in image_config_dict:
554
+ message = (
555
+ f"`{key}` is found in both `image_config_dict` and `image_config` but with different "
556
+ f'values. The value `image_config_dict["{key}"]` will be used instead.'
557
+ )
558
+ # If inferred from default argument values (just to be super careful)
559
+ else:
560
+ message = (
561
+ f"`image_config_dict` is provided which will be used to initialize `FlavaImageConfig`. "
562
+ f'The value `image_config["{key}"]` will be overridden.'
563
+ )
564
+ logger.info(message)
565
+
566
+ # Update all values in `image_config` with the ones in `_image_config_dict`.
567
+ image_config.update(_image_config_dict)
568
+
569
+ if multimodal_config_dict is not None:
570
+ if multimodal_config is None:
571
+ multimodal_config = {}
572
+
573
+ # This is the complete result when using `multimodal_config_dict`.
574
+ _multimodal_config_dict = FlavaMultimodalConfig(**multimodal_config_dict).to_dict()
575
+
576
+ # Give a warning if the values exist in both `_multimodal_config_dict` and `multimodal_config` but being
577
+ # different.
578
+ for key, value in _multimodal_config_dict.items():
579
+ if (
580
+ key in multimodal_config
581
+ and value != multimodal_config[key]
582
+ and key not in ["transformers_version"]
583
+ ):
584
+ # If specified in `multimodal_config_dict`
585
+ if key in multimodal_config_dict:
586
+ message = (
587
+ f"`{key}` is found in both `multimodal_config_dict` and `multimodal_config` but with "
588
+ f'different values. The value `multimodal_config_dict["{key}"]` will be used instead.'
589
+ )
590
+ # If inferred from default argument values (just to be super careful)
591
+ else:
592
+ message = (
593
+ f"`multimodal_config_dict` is provided which will be used to initialize "
594
+ f'`FlavaMultimodalConfig`. The value `multimodal_config["{key}"]` will be overridden.'
595
+ )
596
+ logger.info(message)
597
+
598
+ # Update all values in `multimodal_config` with the ones in `_multimodal_config_dict`.
599
+ multimodal_config.update(_multimodal_config_dict)
600
+
601
+ if image_codebook_config_dict is not None:
602
+ if image_codebook_config is None:
603
+ image_codebook_config = {}
604
+
605
+ # This is the complete result when using `image_codebook_config_dict`.
606
+ _image_codebook_config_dict = FlavaImageCodebookConfig(**image_codebook_config_dict).to_dict()
607
+
608
+ # Give a warning if the values exist in both `_image_codebook_config_dict` and `image_codebook_config` but
609
+ # being different.
610
+ for key, value in _image_codebook_config_dict.items():
611
+ if (
612
+ key in image_codebook_config
613
+ and value != image_codebook_config[key]
614
+ and key not in ["transformers_version"]
615
+ ):
616
+ # If specified in `image_codebook_config_dict`
617
+ if key in image_codebook_config_dict:
618
+ message = (
619
+ f"`{key}` is found in both `image_codebook_config_dict` and `image_codebook_config` but "
620
+ f'with different values. The value `image_codebook_config_dict["{key}"]` will be used '
621
+ "instead."
622
+ )
623
+ # If inferred from default argument values (just to be super careful)
624
+ else:
625
+ message = (
626
+ f"`image_codebook_config_dict` is provided which will be used to initialize "
627
+ f'`FlavaImageCodebookConfig`. The value `image_codebook_config["{key}"]` will be overridden.'
628
+ )
629
+ logger.info(message)
630
+
631
+ # Update all values in `image_codebook_config` with the ones in `_image_codebook_config_dict`.
632
+ image_codebook_config.update(_image_codebook_config_dict)
633
+
634
+ if image_config is None:
635
+ image_config = {}
636
+ logger.info("`image_config` is `None`. initializing the `FlavaImageConfig` with default values.")
637
+
638
+ if text_config is None:
639
+ text_config = {}
640
+ logger.info("`text_config` is `None`. Initializing the `FlavaTextConfig` with default values.")
641
+
642
+ if multimodal_config is None:
643
+ multimodal_config = {}
644
+ logger.info("`multimodal_config` is `None`. initializing the `FlavaMultimodalConfig` with default values.")
645
+
646
+ if image_codebook_config is None:
647
+ image_codebook_config = {}
648
+ logger.info(
649
+ "`image_codebook_config` is `None`. initializing the `FlavaImageCodebookConfig` with default values."
650
+ )
651
+
652
+ self.image_config = FlavaImageConfig(**image_config)
653
+ self.text_config = FlavaTextConfig(**text_config)
654
+ self.multimodal_config = FlavaMultimodalConfig(**multimodal_config)
655
+ self.image_codebook_config = FlavaImageCodebookConfig(**image_codebook_config)
656
+ self.projection_dim = projection_dim
657
+ self.init_codebook = init_codebook
658
+
659
+ self.hidden_size = hidden_size
660
+ self.layer_norm_eps = layer_norm_eps
661
+ self.initializer_range = initializer_range
662
+ self.logit_scale_init_value = logit_scale_init_value
663
+ self.initializer_factor = 1.0
664
+ self.ce_ignore_index = ce_ignore_index
665
+ self.mim_weight = mim_weight
666
+ self.mlm_weight = mlm_weight
667
+ self.global_contrastive_weight = global_contrastive_weight
668
+ self.itm_weight = itm_weight
669
+ self.mmm_image_weight = mmm_image_weight
670
+ self.mmm_text_weight = mmm_text_weight
671
+ self.global_backprop_contrastive = global_backprop_contrastive
672
+ self.skip_unmasked_multimodal_encoder = skip_unmasked_multimodal_encoder
673
+ self.return_loss = return_loss
674
+
675
+ @classmethod
676
+ def from_configs(
677
+ cls,
678
+ image_config: FlavaImageConfig,
679
+ text_config: FlavaTextConfig,
680
+ multimodal_config: FlavaMultimodalConfig,
681
+ image_codebook_config: FlavaImageCodebookConfig,
682
+ **kwargs,
683
+ ):
684
+ r"""
685
+ Instantiate a [`FlavaConfig`] (or a derived class) from flava text model configuration, flava image model
686
+ configuration, flava multimodal model and flava codebook model configuration.
687
+
688
+ Returns:
689
+ [`FlavaConfig`]: An instance of a configuration object
690
+ """
691
+
692
+ return cls(
693
+ image_config=image_config.to_dict(),
694
+ text_config=text_config.to_dict(),
695
+ multimodal_config=multimodal_config.to_dict(),
696
+ image_codebook_config=image_codebook_config.to_dict(),
697
+ **kwargs,
698
+ )
699
+
700
+
701
+ __all__ = ["FlavaConfig", "FlavaImageCodebookConfig", "FlavaImageConfig", "FlavaMultimodalConfig", "FlavaTextConfig"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flava/convert_dalle_to_flava_codebook.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta Platforms authors and The HuggingFace 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
+ import argparse
17
+ import os
18
+
19
+ import torch
20
+
21
+ from transformers import FlavaImageCodebook, FlavaImageCodebookConfig
22
+
23
+
24
+ def rreplace(s, old, new, occurrence):
25
+ li = s.rsplit(old, occurrence)
26
+ return new.join(li)
27
+
28
+
29
+ def count_parameters(state_dict):
30
+ # encoder.embeddings are double copied in original FLAVA
31
+ return sum(param.float().sum() if "encoder.embeddings" not in key else 0 for key, param in state_dict.items())
32
+
33
+
34
+ def upgrade_state_dict(state_dict):
35
+ upgrade = {}
36
+
37
+ group_keys = ["group_1", "group_2", "group_3", "group_4"]
38
+ for key, value in state_dict.items():
39
+ for group_key in group_keys:
40
+ if group_key in key:
41
+ key = key.replace(f"{group_key}.", f"{group_key}.group.")
42
+
43
+ if "res_path" in key:
44
+ key = key.replace("res_path.", "res_path.path.")
45
+
46
+ if key.endswith(".w"):
47
+ key = rreplace(key, ".w", ".weight", 1)
48
+ if key.endswith(".b"):
49
+ key = rreplace(key, ".b", ".bias", 1)
50
+
51
+ upgrade[key] = value.float()
52
+
53
+ return upgrade
54
+
55
+
56
+ @torch.no_grad()
57
+ def convert_dalle_checkpoint(checkpoint_path, pytorch_dump_folder_path, config_path=None, save_checkpoint=True):
58
+ """
59
+ Copy/paste/tweak model's weights to transformers design.
60
+ """
61
+ from dall_e import Encoder
62
+
63
+ encoder = Encoder()
64
+ if os.path.exists(checkpoint_path):
65
+ ckpt = torch.load(checkpoint_path)
66
+ else:
67
+ ckpt = torch.hub.load_state_dict_from_url(checkpoint_path)
68
+
69
+ if isinstance(ckpt, Encoder):
70
+ ckpt = ckpt.state_dict()
71
+ encoder.load_state_dict(ckpt)
72
+
73
+ if config_path is not None:
74
+ config = FlavaImageCodebookConfig.from_pretrained(config_path)
75
+ else:
76
+ config = FlavaImageCodebookConfig()
77
+
78
+ hf_model = FlavaImageCodebook(config).eval()
79
+ state_dict = encoder.state_dict()
80
+
81
+ hf_state_dict = upgrade_state_dict(state_dict)
82
+ hf_model.load_state_dict(hf_state_dict)
83
+ hf_state_dict = hf_model.state_dict()
84
+ hf_count = count_parameters(hf_state_dict)
85
+ state_dict_count = count_parameters(state_dict)
86
+
87
+ assert torch.allclose(hf_count, state_dict_count, atol=1e-3)
88
+
89
+ if save_checkpoint:
90
+ hf_model.save_pretrained(pytorch_dump_folder_path)
91
+ else:
92
+ return hf_state_dict
93
+
94
+
95
+ if __name__ == "__main__":
96
+ parser = argparse.ArgumentParser()
97
+ parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
98
+ parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to flava checkpoint")
99
+ parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
100
+ args = parser.parse_args()
101
+
102
+ convert_dalle_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flava/convert_flava_original_pytorch_to_hf.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta Platforms authors and The HuggingFace 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
+ import argparse
17
+ import os
18
+
19
+ import torch
20
+
21
+ from transformers import FlavaConfig, FlavaForPreTraining
22
+ from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint
23
+
24
+
25
+ def count_parameters(state_dict):
26
+ # encoder.embeddings are double copied in original FLAVA
27
+ return sum(param.float().sum() if "encoder.embeddings" not in key else 0 for key, param in state_dict.items())
28
+
29
+
30
+ def upgrade_state_dict(state_dict, codebook_state_dict):
31
+ upgrade = {}
32
+
33
+ for key, value in state_dict.items():
34
+ if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key:
35
+ continue
36
+
37
+ key = key.replace("heads.cmd.mim_head.cls.predictions", "mmm_image_head")
38
+ key = key.replace("heads.cmd.mlm_head.cls.predictions", "mmm_text_head")
39
+ key = key.replace("heads.cmd.itm_head.cls", "itm_head")
40
+ key = key.replace("heads.cmd.itm_head.pooler", "itm_head.pooler")
41
+ key = key.replace("heads.cmd.clip_head.logit_scale", "flava.logit_scale")
42
+ key = key.replace("heads.fairseq_mlm.cls.predictions", "mlm_head")
43
+ key = key.replace("heads.imagenet.mim_head.cls.predictions", "mim_head")
44
+ key = key.replace("mm_text_projection", "flava.text_to_mm_projection")
45
+ key = key.replace("mm_image_projection", "flava.image_to_mm_projection")
46
+ key = key.replace("image_encoder.module", "flava.image_model")
47
+ key = key.replace("text_encoder.module", "flava.text_model")
48
+ key = key.replace("mm_encoder.module.encoder.cls_token", "flava.multimodal_model.cls_token")
49
+ key = key.replace("mm_encoder.module", "flava.multimodal_model")
50
+ key = key.replace("text_projection", "flava.text_projection")
51
+ key = key.replace("image_projection", "flava.image_projection")
52
+
53
+ upgrade[key] = value.float()
54
+
55
+ for key, value in codebook_state_dict.items():
56
+ upgrade[f"image_codebook.{key}"] = value
57
+
58
+ return upgrade
59
+
60
+
61
+ @torch.no_grad()
62
+ def convert_flava_checkpoint(checkpoint_path, codebook_path, pytorch_dump_folder_path, config_path=None):
63
+ """
64
+ Copy/paste/tweak model's weights to transformers design.
65
+ """
66
+ if config_path is not None:
67
+ config = FlavaConfig.from_pretrained(config_path)
68
+ else:
69
+ config = FlavaConfig()
70
+
71
+ hf_model = FlavaForPreTraining(config).eval()
72
+
73
+ codebook_state_dict = convert_dalle_checkpoint(codebook_path, None, save_checkpoint=False)
74
+
75
+ if os.path.exists(checkpoint_path):
76
+ state_dict = torch.load(checkpoint_path, map_location="cpu")
77
+ else:
78
+ state_dict = torch.hub.load_state_dict_from_url(checkpoint_path, map_location="cpu")
79
+
80
+ hf_state_dict = upgrade_state_dict(state_dict, codebook_state_dict)
81
+ hf_model.load_state_dict(hf_state_dict)
82
+ hf_state_dict = hf_model.state_dict()
83
+ hf_count = count_parameters(hf_state_dict)
84
+ state_dict_count = count_parameters(state_dict) + count_parameters(codebook_state_dict)
85
+
86
+ assert torch.allclose(hf_count, state_dict_count, atol=1e-3)
87
+
88
+ hf_model.save_pretrained(pytorch_dump_folder_path)
89
+
90
+
91
+ if __name__ == "__main__":
92
+ parser = argparse.ArgumentParser()
93
+ parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
94
+ parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to flava checkpoint")
95
+ parser.add_argument("--codebook_path", default=None, type=str, help="Path to flava codebook checkpoint")
96
+ parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
97
+ args = parser.parse_args()
98
+
99
+ convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flava/feature_extraction_flava.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta Platforms authors and The HuggingFace 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
+ """Feature extractor class for FLAVA."""
16
+
17
+ import warnings
18
+
19
+ from ...utils import logging
20
+ from .image_processing_flava import FlavaImageProcessor
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class FlavaFeatureExtractor(FlavaImageProcessor):
27
+ def __init__(self, *args, **kwargs) -> None:
28
+ warnings.warn(
29
+ "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
30
+ " use FlavaImageProcessor instead.",
31
+ FutureWarning,
32
+ )
33
+ super().__init__(*args, **kwargs)
34
+
35
+
36
+ __all__ = ["FlavaFeatureExtractor"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flava/image_processing_flava.py ADDED
@@ -0,0 +1,703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 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
+ """Image processor class for Flava."""
16
+
17
+ import math
18
+ import random
19
+ from functools import lru_cache
20
+ from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+
24
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
25
+ from ...image_transforms import resize, to_channel_dimension_format
26
+ from ...image_utils import (
27
+ OPENAI_CLIP_MEAN,
28
+ OPENAI_CLIP_STD,
29
+ ChannelDimension,
30
+ ImageInput,
31
+ PILImageResampling,
32
+ infer_channel_dimension_format,
33
+ is_scaled_image,
34
+ make_list_of_images,
35
+ to_numpy_array,
36
+ valid_images,
37
+ validate_preprocess_arguments,
38
+ )
39
+ from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
40
+
41
+
42
+ if is_vision_available():
43
+ import PIL
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ # These values are taken from CLIP
50
+ FLAVA_IMAGE_MEAN = OPENAI_CLIP_MEAN
51
+ FLAVA_IMAGE_STD = OPENAI_CLIP_STD
52
+ FLAVA_CODEBOOK_MEAN = [0.0, 0.0, 0.0]
53
+ FLAVA_CODEBOOK_STD = [1.0, 1.0, 1.0]
54
+ LOGIT_LAPLACE_EPS: float = 0.1
55
+
56
+
57
+ # Inspired from https://github.com/microsoft/unilm/blob/master/beit/masking_generator.py
58
+ class FlavaMaskingGenerator:
59
+ def __init__(
60
+ self,
61
+ input_size: Union[int, Tuple[int, int]] = 14,
62
+ total_mask_patches: int = 75,
63
+ mask_group_max_patches: Optional[int] = None,
64
+ mask_group_min_patches: int = 16,
65
+ mask_group_min_aspect_ratio: Optional[float] = 0.3,
66
+ mask_group_max_aspect_ratio: float = None,
67
+ ):
68
+ if not isinstance(input_size, tuple):
69
+ input_size = (input_size,) * 2
70
+ self.height, self.width = input_size
71
+
72
+ self.num_patches = self.height * self.width
73
+ self.total_mask_patches = total_mask_patches
74
+
75
+ self.mask_group_min_patches = mask_group_min_patches
76
+ self.mask_group_max_patches = total_mask_patches if mask_group_max_patches is None else mask_group_max_patches
77
+
78
+ mask_group_max_aspect_ratio = mask_group_max_aspect_ratio or 1 / mask_group_min_aspect_ratio
79
+ self.log_aspect_ratio = (math.log(mask_group_min_aspect_ratio), math.log(mask_group_max_aspect_ratio))
80
+
81
+ def __repr__(self):
82
+ repr_str = "MaskingGenerator(%d, %d -> [%d ~ %d], max = %d, %.3f ~ %.3f)" % (
83
+ self.height,
84
+ self.width,
85
+ self.mask_group_min_patches,
86
+ self.mask_group_max_patches,
87
+ self.total_mask_patches,
88
+ self.log_aspect_ratio[0],
89
+ self.log_aspect_ratio[1],
90
+ )
91
+ return repr_str
92
+
93
+ def get_shape(self):
94
+ return self.height, self.width
95
+
96
+ def _mask(self, mask, max_mask_patches):
97
+ delta = 0
98
+ for _attempt in range(10):
99
+ target_area = random.uniform(self.mask_group_min_patches, max_mask_patches)
100
+ aspect_ratio = math.exp(random.uniform(*self.log_aspect_ratio))
101
+ height = int(round(math.sqrt(target_area * aspect_ratio)))
102
+ width = int(round(math.sqrt(target_area / aspect_ratio)))
103
+ if width < self.width and height < self.height:
104
+ top = random.randint(0, self.height - height)
105
+ left = random.randint(0, self.width - width)
106
+
107
+ num_masked = mask[top : top + height, left : left + width].sum()
108
+ # Overlap
109
+ if 0 < height * width - num_masked <= max_mask_patches:
110
+ for i in range(top, top + height):
111
+ for j in range(left, left + width):
112
+ if mask[i, j] == 0:
113
+ mask[i, j] = 1
114
+ delta += 1
115
+
116
+ if delta > 0:
117
+ break
118
+ return delta
119
+
120
+ def __call__(self):
121
+ mask = np.zeros(shape=self.get_shape(), dtype=int)
122
+ mask_count = 0
123
+ while mask_count < self.total_mask_patches:
124
+ max_mask_patches = self.total_mask_patches - mask_count
125
+ max_mask_patches = min(max_mask_patches, self.mask_group_max_patches)
126
+
127
+ delta = self._mask(mask, max_mask_patches)
128
+ if delta == 0:
129
+ break
130
+ else:
131
+ mask_count += delta
132
+
133
+ return mask
134
+
135
+
136
+ class FlavaImageProcessor(BaseImageProcessor):
137
+ r"""
138
+ Constructs a Flava image processor.
139
+
140
+ Args:
141
+ do_resize (`bool`, *optional*, defaults to `True`):
142
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
143
+ `do_resize` parameter in `preprocess`.
144
+ size (`Dict[str, int]` *optional*, defaults to `{"height": 224, "width": 224}`):
145
+ Size of the image after resizing. Can be overridden by the `size` parameter in `preprocess`.
146
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
147
+ Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in
148
+ `preprocess`.
149
+ do_center_crop (`bool`, *optional*, defaults to `True`):
150
+ Whether to center crop the images. Can be overridden by the `do_center_crop` parameter in `preprocess`.
151
+ crop_size (`Dict[str, int]` *optional*, defaults to `{"height": 224, "width": 224}`):
152
+ Size of image after the center crop `(crop_size["height"], crop_size["width"])`. Can be overridden by the
153
+ `crop_size` parameter in `preprocess`.
154
+ do_rescale (`bool`, *optional*, defaults to `True`):
155
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
156
+ parameter in `preprocess`.
157
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
158
+ Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in
159
+ `preprocess`.
160
+ do_normalize (`bool`, *optional*, defaults to `True`):
161
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in `preprocess`.
162
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
163
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
164
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
165
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
166
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
167
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
168
+ return_image_mask (`bool`, *optional*, defaults to `False`):
169
+ Whether to return the image mask. Can be overridden by the `return_image_mask` parameter in `preprocess`.
170
+ input_size_patches (`int`, *optional*, defaults to 14):
171
+ Number of patches in the image in height and width direction. 14x14 = 196 total patches. Can be overridden
172
+ by the `input_size_patches` parameter in `preprocess`.
173
+ total_mask_patches (`int`, *optional*, defaults to 75):
174
+ Total number of patches that should be masked. Can be overridden by the `total_mask_patches` parameter in
175
+ `preprocess`.
176
+ mask_group_min_patches (`int`, *optional*, defaults to 16):
177
+ Minimum number of patches that should be masked. Can be overridden by the `mask_group_min_patches`
178
+ parameter in `preprocess`.
179
+ mask_group_max_patches (`int`, *optional*):
180
+ Maximum number of patches that should be masked. Can be overridden by the `mask_group_max_patches`
181
+ parameter in `preprocess`.
182
+ mask_group_min_aspect_ratio (`float`, *optional*, defaults to 0.3):
183
+ Minimum aspect ratio of the mask window. Can be overridden by the `mask_group_min_aspect_ratio` parameter
184
+ in `preprocess`.
185
+ mask_group_max_aspect_ratio (`float`, *optional*):
186
+ Maximum aspect ratio of the mask window. Can be overridden by the `mask_group_max_aspect_ratio` parameter
187
+ in `preprocess`.
188
+ codebook_do_resize (`bool`, *optional*, defaults to `True`):
189
+ Whether to resize the input for codebook to a certain. Can be overridden by the `codebook_do_resize`
190
+ parameter in `preprocess`. `codebook_size`.
191
+ codebook_size (`Dict[str, int]`, *optional*, defaults to `{"height": 224, "width": 224}`):
192
+ Resize the input for codebook to the given size. Can be overridden by the `codebook_size` parameter in
193
+ `preprocess`.
194
+ codebook_resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.LANCZOS`):
195
+ Resampling filter to use if resizing the codebook image. Can be overridden by the `codebook_resample`
196
+ parameter in `preprocess`.
197
+ codebook_do_center_crop (`bool`, *optional*, defaults to `True`):
198
+ Whether to crop the input for codebook at the center. If the input size is smaller than
199
+ `codebook_crop_size` along any edge, the image is padded with 0's and then center cropped. Can be
200
+ overridden by the `codebook_do_center_crop` parameter in `preprocess`.
201
+ codebook_crop_size (`Dict[str, int]`, *optional*, defaults to `{"height": 224, "width": 224}`):
202
+ Desired output size for codebook input when applying center-cropping. Can be overridden by the
203
+ `codebook_crop_size` parameter in `preprocess`.
204
+ codebook_do_rescale (`bool`, *optional*, defaults to `True`):
205
+ Whether to rescale the input for codebook by the specified scale `codebook_rescale_factor`. Can be
206
+ overridden by the `codebook_do_rescale` parameter in `preprocess`.
207
+ codebook_rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
208
+ Defines the scale factor to use if rescaling the codebook image. Can be overridden by the
209
+ `codebook_rescale_factor` parameter in `preprocess`.
210
+ codebook_do_map_pixels (`bool`, *optional*, defaults to `True`):
211
+ Whether to map the pixel values of the codebook input to (1 - 2e)x + e. Can be overridden by the
212
+ `codebook_do_map_pixels` parameter in `preprocess`.
213
+ codebook_do_normalize (`bool`, *optional*, defaults to `True`):
214
+ Whether or not to normalize the input for codebook with `codebook_image_mean` and `codebook_image_std`. Can
215
+ be overridden by the `codebook_do_normalize` parameter in `preprocess`.
216
+ codebook_image_mean (`Optional[Union[float, Iterable[float]]]`, *optional*, defaults to `[0, 0, 0]`):
217
+ The sequence of means for each channel, to be used when normalizing images for codebook. Can be overridden
218
+ by the `codebook_image_mean` parameter in `preprocess`.
219
+ codebook_image_std (`Optional[Union[float, Iterable[float]]]`, *optional*, defaults to `[0.5, 0.5, 0.5]`):
220
+ The sequence of standard deviations for each channel, to be used when normalizing images for codebook. Can
221
+ be overridden by the `codebook_image_std` parameter in `preprocess`.
222
+ """
223
+
224
+ model_input_names = ["pixel_values"]
225
+
226
+ def __init__(
227
+ self,
228
+ do_resize: bool = True,
229
+ size: Dict[str, int] = None,
230
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
231
+ do_center_crop: bool = True,
232
+ crop_size: Dict[str, int] = None,
233
+ do_rescale: bool = True,
234
+ rescale_factor: Union[int, float] = 1 / 255,
235
+ do_normalize: bool = True,
236
+ image_mean: Optional[Union[float, Iterable[float]]] = None,
237
+ image_std: Optional[Union[float, Iterable[float]]] = None,
238
+ # Mask related params
239
+ return_image_mask: bool = False,
240
+ input_size_patches: int = 14,
241
+ total_mask_patches: int = 75,
242
+ mask_group_min_patches: int = 16,
243
+ mask_group_max_patches: Optional[int] = None,
244
+ mask_group_min_aspect_ratio: float = 0.3,
245
+ mask_group_max_aspect_ratio: Optional[float] = None,
246
+ # Codebook related params
247
+ return_codebook_pixels: bool = False,
248
+ codebook_do_resize: bool = True,
249
+ codebook_size: bool = None,
250
+ codebook_resample: int = PILImageResampling.LANCZOS,
251
+ codebook_do_center_crop: bool = True,
252
+ codebook_crop_size: int = None,
253
+ codebook_do_rescale: bool = True,
254
+ codebook_rescale_factor: Union[int, float] = 1 / 255,
255
+ codebook_do_map_pixels: bool = True,
256
+ codebook_do_normalize: bool = True,
257
+ codebook_image_mean: Optional[Union[float, Iterable[float]]] = None,
258
+ codebook_image_std: Optional[Union[float, Iterable[float]]] = None,
259
+ **kwargs,
260
+ ) -> None:
261
+ super().__init__(**kwargs)
262
+ size = size if size is not None else {"height": 224, "width": 224}
263
+ size = get_size_dict(size)
264
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
265
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
266
+
267
+ codebook_size = codebook_size if codebook_size is not None else {"height": 112, "width": 112}
268
+ codebook_size = get_size_dict(codebook_size, param_name="codebook_size")
269
+ codebook_crop_size = codebook_crop_size if codebook_crop_size is not None else {"height": 112, "width": 112}
270
+ codebook_crop_size = get_size_dict(codebook_crop_size, param_name="codebook_crop_size")
271
+
272
+ self.do_resize = do_resize
273
+ self.size = size
274
+ self.resample = resample
275
+ self.do_rescale = do_rescale
276
+ self.rescale_factor = rescale_factor
277
+ self.do_center_crop = do_center_crop
278
+ self.crop_size = crop_size
279
+ self.do_normalize = do_normalize
280
+ self.image_mean = image_mean if image_mean is not None else FLAVA_IMAGE_MEAN
281
+ self.image_std = image_std if image_std is not None else FLAVA_IMAGE_STD
282
+
283
+ self.return_image_mask = return_image_mask
284
+ self.input_size_patches = input_size_patches
285
+ self.total_mask_patches = total_mask_patches
286
+ self.mask_group_min_patches = mask_group_min_patches
287
+ self.mask_group_max_patches = mask_group_max_patches
288
+ self.mask_group_min_aspect_ratio = mask_group_min_aspect_ratio
289
+ self.mask_group_max_aspect_ratio = mask_group_max_aspect_ratio
290
+
291
+ self.return_codebook_pixels = return_codebook_pixels
292
+ self.codebook_do_resize = codebook_do_resize
293
+ self.codebook_size = codebook_size
294
+ self.codebook_resample = codebook_resample
295
+ self.codebook_do_center_crop = codebook_do_center_crop
296
+ self.codebook_crop_size = codebook_crop_size
297
+ self.codebook_do_rescale = codebook_do_rescale
298
+ self.codebook_rescale_factor = codebook_rescale_factor
299
+ self.codebook_do_map_pixels = codebook_do_map_pixels
300
+ self.codebook_do_normalize = codebook_do_normalize
301
+ self.codebook_image_mean = codebook_image_mean
302
+ self.codebook_image_mean = codebook_image_mean if codebook_image_mean is not None else FLAVA_CODEBOOK_MEAN
303
+ self.codebook_image_std = codebook_image_std if codebook_image_std is not None else FLAVA_CODEBOOK_STD
304
+
305
+ @classmethod
306
+ def from_dict(cls, image_processor_dict: Dict[str, Any], **kwargs):
307
+ """
308
+ Overrides the `from_dict` method from the base class to make sure parameters are updated if image processor is
309
+ created using from_dict and kwargs e.g. `FlavaImageProcessor.from_pretrained(checkpoint, codebook_size=600)`
310
+ """
311
+ image_processor_dict = image_processor_dict.copy()
312
+ if "codebook_size" in kwargs:
313
+ image_processor_dict["codebook_size"] = kwargs.pop("codebook_size")
314
+ if "codebook_crop_size" in kwargs:
315
+ image_processor_dict["codebook_crop_size"] = kwargs.pop("codebook_crop_size")
316
+ return super().from_dict(image_processor_dict, **kwargs)
317
+
318
+ @lru_cache()
319
+ def masking_generator(
320
+ self,
321
+ input_size_patches,
322
+ total_mask_patches,
323
+ mask_group_min_patches,
324
+ mask_group_max_patches,
325
+ mask_group_min_aspect_ratio,
326
+ mask_group_max_aspect_ratio,
327
+ ) -> FlavaMaskingGenerator:
328
+ return FlavaMaskingGenerator(
329
+ input_size=input_size_patches,
330
+ total_mask_patches=total_mask_patches,
331
+ mask_group_min_patches=mask_group_min_patches,
332
+ mask_group_max_patches=mask_group_max_patches,
333
+ mask_group_min_aspect_ratio=mask_group_min_aspect_ratio,
334
+ mask_group_max_aspect_ratio=mask_group_max_aspect_ratio,
335
+ )
336
+
337
+ # Copied from transformers.models.vit.image_processing_vit.ViTImageProcessor.resize with PILImageResampling.BILINEAR->PILImageResampling.BICUBIC
338
+ def resize(
339
+ self,
340
+ image: np.ndarray,
341
+ size: Dict[str, int],
342
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
343
+ data_format: Optional[Union[str, ChannelDimension]] = None,
344
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
345
+ **kwargs,
346
+ ) -> np.ndarray:
347
+ """
348
+ Resize an image to `(size["height"], size["width"])`.
349
+
350
+ Args:
351
+ image (`np.ndarray`):
352
+ Image to resize.
353
+ size (`Dict[str, int]`):
354
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
355
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
356
+ `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BICUBIC`.
357
+ data_format (`ChannelDimension` or `str`, *optional*):
358
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
359
+ image is used. Can be one of:
360
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
361
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
362
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
363
+ input_data_format (`ChannelDimension` or `str`, *optional*):
364
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
365
+ from the input image. Can be one of:
366
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
367
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
368
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
369
+
370
+ Returns:
371
+ `np.ndarray`: The resized image.
372
+ """
373
+ size = get_size_dict(size)
374
+ if "height" not in size or "width" not in size:
375
+ raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
376
+ output_size = (size["height"], size["width"])
377
+ return resize(
378
+ image,
379
+ size=output_size,
380
+ resample=resample,
381
+ data_format=data_format,
382
+ input_data_format=input_data_format,
383
+ **kwargs,
384
+ )
385
+
386
+ def map_pixels(self, image: np.ndarray) -> np.ndarray:
387
+ return (1 - 2 * LOGIT_LAPLACE_EPS) * image + LOGIT_LAPLACE_EPS
388
+
389
+ def _preprocess_image(
390
+ self,
391
+ image: ImageInput,
392
+ do_resize: bool = None,
393
+ size: Dict[str, int] = None,
394
+ resample: PILImageResampling = None,
395
+ do_center_crop: bool = None,
396
+ crop_size: Dict[str, int] = None,
397
+ do_rescale: bool = None,
398
+ rescale_factor: float = None,
399
+ do_normalize: bool = None,
400
+ image_mean: Optional[Union[float, List[float]]] = None,
401
+ image_std: Optional[Union[float, List[float]]] = None,
402
+ do_map_pixels: bool = None,
403
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
404
+ input_data_format: Optional[ChannelDimension] = None,
405
+ ) -> np.ndarray:
406
+ """Preprocesses a single image."""
407
+
408
+ validate_preprocess_arguments(
409
+ do_rescale=do_rescale,
410
+ rescale_factor=rescale_factor,
411
+ do_normalize=do_normalize,
412
+ image_mean=image_mean,
413
+ image_std=image_std,
414
+ do_center_crop=do_center_crop,
415
+ crop_size=crop_size,
416
+ do_resize=do_resize,
417
+ size=size,
418
+ resample=resample,
419
+ )
420
+
421
+ # All transformations expect numpy arrays.
422
+ image = to_numpy_array(image)
423
+
424
+ if do_rescale and is_scaled_image(image):
425
+ logger.warning_once(
426
+ "It looks like you are trying to rescale already rescaled images. If the input"
427
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
428
+ )
429
+
430
+ if input_data_format is None:
431
+ # We assume that all images have the same channel dimension format.
432
+ input_data_format = infer_channel_dimension_format(image)
433
+
434
+ if do_resize:
435
+ image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
436
+
437
+ if do_center_crop:
438
+ image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)
439
+
440
+ if do_rescale:
441
+ image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
442
+
443
+ if do_normalize:
444
+ image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
445
+
446
+ if do_map_pixels:
447
+ image = self.map_pixels(image)
448
+
449
+ if data_format is not None:
450
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
451
+ return image
452
+
453
+ @filter_out_non_signature_kwargs()
454
+ def preprocess(
455
+ self,
456
+ images: ImageInput,
457
+ do_resize: Optional[bool] = None,
458
+ size: Dict[str, int] = None,
459
+ resample: PILImageResampling = None,
460
+ do_center_crop: Optional[bool] = None,
461
+ crop_size: Optional[Dict[str, int]] = None,
462
+ do_rescale: Optional[bool] = None,
463
+ rescale_factor: Optional[float] = None,
464
+ do_normalize: Optional[bool] = None,
465
+ image_mean: Optional[Union[float, List[float]]] = None,
466
+ image_std: Optional[Union[float, List[float]]] = None,
467
+ # Mask related params
468
+ return_image_mask: Optional[bool] = None,
469
+ input_size_patches: Optional[int] = None,
470
+ total_mask_patches: Optional[int] = None,
471
+ mask_group_min_patches: Optional[int] = None,
472
+ mask_group_max_patches: Optional[int] = None,
473
+ mask_group_min_aspect_ratio: Optional[float] = None,
474
+ mask_group_max_aspect_ratio: Optional[float] = None,
475
+ # Codebook related params
476
+ return_codebook_pixels: Optional[bool] = None,
477
+ codebook_do_resize: Optional[bool] = None,
478
+ codebook_size: Optional[Dict[str, int]] = None,
479
+ codebook_resample: Optional[int] = None,
480
+ codebook_do_center_crop: Optional[bool] = None,
481
+ codebook_crop_size: Optional[Dict[str, int]] = None,
482
+ codebook_do_rescale: Optional[bool] = None,
483
+ codebook_rescale_factor: Optional[float] = None,
484
+ codebook_do_map_pixels: Optional[bool] = None,
485
+ codebook_do_normalize: Optional[bool] = None,
486
+ codebook_image_mean: Optional[Iterable[float]] = None,
487
+ codebook_image_std: Optional[Iterable[float]] = None,
488
+ return_tensors: Optional[Union[str, TensorType]] = None,
489
+ data_format: ChannelDimension = ChannelDimension.FIRST,
490
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
491
+ ) -> PIL.Image.Image:
492
+ """
493
+ Preprocess an image or batch of images.
494
+
495
+ Args:
496
+ images (`ImageInput`):
497
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
498
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
499
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
500
+ Whether to resize the image.
501
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
502
+ Size of the image.
503
+ resample (`int`, *optional*, defaults to `self.resample`):
504
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
505
+ has an effect if `do_resize` is set to `True`.
506
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
507
+ Whether to center crop the image.
508
+ crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
509
+ Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
510
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
511
+ Whether to rescale the image values between [0 - 1].
512
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
513
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
514
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
515
+ Whether to normalize the image.
516
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
517
+ Image mean.
518
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
519
+ Image standard deviation.
520
+ return_image_mask (`bool`, *optional*, defaults to `self.return_image_mask`):
521
+ Whether to return the image mask.
522
+ input_size_patches (`int`, *optional*, defaults to `self.input_size_patches`):
523
+ Size of the patches to extract from the image.
524
+ total_mask_patches (`int`, *optional*, defaults to `self.total_mask_patches`):
525
+ Total number of patches to extract from the image.
526
+ mask_group_min_patches (`int`, *optional*, defaults to `self.mask_group_min_patches`):
527
+ Minimum number of patches to extract from the image.
528
+ mask_group_max_patches (`int`, *optional*, defaults to `self.mask_group_max_patches`):
529
+ Maximum number of patches to extract from the image.
530
+ mask_group_min_aspect_ratio (`float`, *optional*, defaults to `self.mask_group_min_aspect_ratio`):
531
+ Minimum aspect ratio of the patches to extract from the image.
532
+ mask_group_max_aspect_ratio (`float`, *optional*, defaults to `self.mask_group_max_aspect_ratio`):
533
+ Maximum aspect ratio of the patches to extract from the image.
534
+ return_codebook_pixels (`bool`, *optional*, defaults to `self.return_codebook_pixels`):
535
+ Whether to return the codebook pixels.
536
+ codebook_do_resize (`bool`, *optional*, defaults to `self.codebook_do_resize`):
537
+ Whether to resize the codebook pixels.
538
+ codebook_size (`Dict[str, int]`, *optional*, defaults to `self.codebook_size`):
539
+ Size of the codebook pixels.
540
+ codebook_resample (`int`, *optional*, defaults to `self.codebook_resample`):
541
+ Resampling filter to use if resizing the codebook pixels. This can be one of the enum
542
+ `PILImageResampling`, Only has an effect if `codebook_do_resize` is set to `True`.
543
+ codebook_do_center_crop (`bool`, *optional*, defaults to `self.codebook_do_center_crop`):
544
+ Whether to center crop the codebook pixels.
545
+ codebook_crop_size (`Dict[str, int]`, *optional*, defaults to `self.codebook_crop_size`):
546
+ Size of the center crop of the codebook pixels. Only has an effect if `codebook_do_center_crop` is set
547
+ to `True`.
548
+ codebook_do_rescale (`bool`, *optional*, defaults to `self.codebook_do_rescale`):
549
+ Whether to rescale the codebook pixels values between [0 - 1].
550
+ codebook_rescale_factor (`float`, *optional*, defaults to `self.codebook_rescale_factor`):
551
+ Rescale factor to rescale the codebook pixels by if `codebook_do_rescale` is set to `True`.
552
+ codebook_do_map_pixels (`bool`, *optional*, defaults to `self.codebook_do_map_pixels`):
553
+ Whether to map the codebook pixels values.
554
+ codebook_do_normalize (`bool`, *optional*, defaults to `self.codebook_do_normalize`):
555
+ Whether to normalize the codebook pixels.
556
+ codebook_image_mean (`float` or `List[float]`, *optional*, defaults to `self.codebook_image_mean`):
557
+ Codebook pixels mean to normalize the codebook pixels by if `codebook_do_normalize` is set to `True`.
558
+ codebook_image_std (`float` or `List[float]`, *optional*, defaults to `self.codebook_image_std`):
559
+ Codebook pixels standard deviation to normalize the codebook pixels by if `codebook_do_normalize` is
560
+ set to `True`.
561
+ return_tensors (`str` or `TensorType`, *optional*):
562
+ The type of tensors to return. Can be one of:
563
+ - Unset: Return a list of `np.ndarray`.
564
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
565
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
566
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
567
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
568
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
569
+ The channel dimension format for the output image. Can be one of:
570
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
571
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
572
+ input_data_format (`ChannelDimension` or `str`, *optional*):
573
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
574
+ from the input image. Can be one of:
575
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
576
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
577
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
578
+ """
579
+ do_resize = do_resize if do_resize is not None else self.do_resize
580
+ size = size if size is not None else self.size
581
+ size = get_size_dict(size)
582
+ resample = resample if resample is not None else self.resample
583
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
584
+ crop_size = crop_size if crop_size is not None else self.crop_size
585
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
586
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
587
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
588
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
589
+ image_mean = image_mean if image_mean is not None else self.image_mean
590
+ image_std = image_std if image_std is not None else self.image_std
591
+
592
+ return_image_mask = return_image_mask if return_image_mask is not None else self.return_image_mask
593
+ input_size_patches = input_size_patches if input_size_patches is not None else self.input_size_patches
594
+ total_mask_patches = total_mask_patches if total_mask_patches is not None else self.total_mask_patches
595
+ mask_group_min_patches = (
596
+ mask_group_min_patches if mask_group_min_patches is not None else self.mask_group_min_patches
597
+ )
598
+ mask_group_max_patches = (
599
+ mask_group_max_patches if mask_group_max_patches is not None else self.mask_group_max_patches
600
+ )
601
+ mask_group_min_aspect_ratio = (
602
+ mask_group_min_aspect_ratio
603
+ if mask_group_min_aspect_ratio is not None
604
+ else self.mask_group_min_aspect_ratio
605
+ )
606
+ mask_group_max_aspect_ratio = (
607
+ mask_group_max_aspect_ratio
608
+ if mask_group_max_aspect_ratio is not None
609
+ else self.mask_group_max_aspect_ratio
610
+ )
611
+
612
+ return_codebook_pixels = (
613
+ return_codebook_pixels if return_codebook_pixels is not None else self.return_codebook_pixels
614
+ )
615
+ codebook_do_resize = codebook_do_resize if codebook_do_resize is not None else self.codebook_do_resize
616
+ codebook_size = codebook_size if codebook_size is not None else self.codebook_size
617
+ codebook_size = get_size_dict(codebook_size, param_name="codebook_size")
618
+ codebook_resample = codebook_resample if codebook_resample is not None else self.codebook_resample
619
+ codebook_do_rescale = codebook_do_rescale if codebook_do_rescale is not None else self.codebook_do_rescale
620
+ codebook_rescale_factor = (
621
+ codebook_rescale_factor if codebook_rescale_factor is not None else self.codebook_rescale_factor
622
+ )
623
+ codebook_do_center_crop = (
624
+ codebook_do_center_crop if codebook_do_center_crop is not None else self.codebook_do_center_crop
625
+ )
626
+ codebook_crop_size = codebook_crop_size if codebook_crop_size is not None else self.codebook_crop_size
627
+ codebook_crop_size = get_size_dict(codebook_crop_size, param_name="codebook_crop_size")
628
+ codebook_do_map_pixels = (
629
+ codebook_do_map_pixels if codebook_do_map_pixels is not None else self.codebook_do_map_pixels
630
+ )
631
+ codebook_do_normalize = (
632
+ codebook_do_normalize if codebook_do_normalize is not None else self.codebook_do_normalize
633
+ )
634
+ codebook_image_mean = codebook_image_mean if codebook_image_mean is not None else self.codebook_image_mean
635
+ codebook_image_std = codebook_image_std if codebook_image_std is not None else self.codebook_image_std
636
+
637
+ images = make_list_of_images(images)
638
+
639
+ if not valid_images(images):
640
+ raise ValueError(
641
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
642
+ "torch.Tensor, tf.Tensor or jax.ndarray."
643
+ )
644
+
645
+ processed_images = [
646
+ self._preprocess_image(
647
+ image=img,
648
+ do_resize=do_resize,
649
+ size=size,
650
+ resample=resample,
651
+ do_center_crop=do_center_crop,
652
+ crop_size=crop_size,
653
+ do_rescale=do_rescale,
654
+ rescale_factor=rescale_factor,
655
+ do_normalize=do_normalize,
656
+ image_mean=image_mean,
657
+ image_std=image_std,
658
+ do_map_pixels=False,
659
+ data_format=data_format,
660
+ input_data_format=input_data_format,
661
+ )
662
+ for img in images
663
+ ]
664
+ data = {"pixel_values": processed_images}
665
+
666
+ if return_codebook_pixels:
667
+ codebook_images = [
668
+ self._preprocess_image(
669
+ image=img,
670
+ do_resize=codebook_do_resize,
671
+ size=codebook_size,
672
+ resample=codebook_resample,
673
+ do_center_crop=codebook_do_center_crop,
674
+ crop_size=codebook_crop_size,
675
+ do_rescale=codebook_do_rescale,
676
+ rescale_factor=codebook_rescale_factor,
677
+ do_normalize=codebook_do_normalize,
678
+ image_mean=codebook_image_mean,
679
+ image_std=codebook_image_std,
680
+ do_map_pixels=codebook_do_map_pixels,
681
+ data_format=data_format,
682
+ input_data_format=input_data_format,
683
+ )
684
+ for img in images
685
+ ]
686
+ data["codebook_pixel_values"] = codebook_images
687
+
688
+ if return_image_mask:
689
+ mask_generator = self.masking_generator(
690
+ input_size_patches=input_size_patches,
691
+ total_mask_patches=total_mask_patches,
692
+ mask_group_min_patches=mask_group_min_patches,
693
+ mask_group_max_patches=mask_group_max_patches,
694
+ mask_group_min_aspect_ratio=mask_group_min_aspect_ratio,
695
+ mask_group_max_aspect_ratio=mask_group_max_aspect_ratio,
696
+ )
697
+ masks = [mask_generator() for _ in images]
698
+ data["bool_masked_pos"] = masks
699
+
700
+ return BatchFeature(data=data, tensor_type=return_tensors)
701
+
702
+
703
+ __all__ = ["FlavaImageProcessor"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flava/modeling_flava.py ADDED
@@ -0,0 +1,2115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta Platforms authors and The HuggingFace 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 FLAVA model."""
16
+
17
+ import collections
18
+ import math
19
+ from collections import OrderedDict
20
+ from dataclasses import dataclass
21
+ from typing import Any, Dict, List, Optional, Set, Tuple, Union
22
+
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+
27
+ from ...activations import ACT2FN
28
+ from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
29
+ from ...modeling_utils import PreTrainedModel, find_pruneable_heads_and_indices, prune_linear_layer
30
+ from ...utils import (
31
+ ModelOutput,
32
+ add_code_sample_docstrings,
33
+ add_start_docstrings,
34
+ add_start_docstrings_to_model_forward,
35
+ logging,
36
+ replace_return_docstrings,
37
+ torch_int,
38
+ )
39
+ from .configuration_flava import (
40
+ FlavaConfig,
41
+ FlavaImageCodebookConfig,
42
+ FlavaImageConfig,
43
+ FlavaMultimodalConfig,
44
+ FlavaTextConfig,
45
+ )
46
+
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+ _CHECKPOINT_FOR_DOC = "facebook/flava-full"
51
+
52
+ # Codebook docstring
53
+ _CHECKPOINT_FOR_CODEBOOK_DOC = "facebook/flava-image-codebook"
54
+ _CONFIG_CLASS_FOR_IMAGE_MODEL_DOC = "FlavaImageConfig"
55
+ _CONFIG_CLASS_FOR_TEXT_MODEL_DOC = "FlavaTextConfig"
56
+ _CONFIG_CLASS_FOR_MULTIMODAL_MODEL_DOC = "FlavaMultimodalConfig"
57
+ _EXPECTED_IMAGE_OUTPUT_SHAPE = [1, 197, 768]
58
+
59
+
60
+ LOGIT_SCALE_CLAMP_MIN = 0
61
+ LOGIT_SCALE_CLAMP_MAX = 4.6052
62
+
63
+ FlavaPossibleConfigs = Union[FlavaTextConfig, FlavaImageConfig, FlavaMultimodalConfig]
64
+
65
+
66
+ @dataclass
67
+ class FlavaModelOutput(ModelOutput):
68
+ """
69
+ Output from FlavaModel containing embeddings and outputs from individual encoders.
70
+
71
+ Note that `image_embeddings` and `text_embeddigns` returned are similar to pooled output returned from a
72
+ transformer. If you want embeddings for contrastive loss or retrieval use a FLAVA model's `image_projection` and
73
+ `text_projection` layers on `image_embeddings` and `text_embeddings` respectively.
74
+
75
+ Args:
76
+ image_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `pixel_values` are present):
77
+ The image embeddings which are basically the pooled output of [`FlavaImageModel`].
78
+ image_output (`BaseModelOutputWithPooling`, *optional*, returned when `pixel_values` are present):
79
+ The output of the [`FlavaImageModel`].
80
+ text_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `input_ids` are present):
81
+ The text embeddings which are basically the pooled output of [`FlavaTextModel`].
82
+ text_output (`BaseModelOutputWithPooling`, *optional*, returned when `input_ids` are present):
83
+ The output of the [`FlavaTextModel`].
84
+ multimodal_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `input_ids` and `pixel_values` are present and `skip_multimodal_encoder` is `None` or `False`):
85
+ The multimodal embeddings which are basically the pooled output of [`FlavaTextModel`].
86
+ multimodal_output (`BaseModelOutputWithPooling`, returned when `input_ids` and `pixel_values` are present and `skip_multimodal_encoder` is `None` or `False`):
87
+ The output of the [`FlavaMultimodalModel`].
88
+ """
89
+
90
+ image_embeddings: Optional[torch.FloatTensor] = None
91
+ image_output: Optional[BaseModelOutputWithPooling] = None
92
+ text_embeddings: Optional[torch.FloatTensor] = None
93
+ text_output: Optional[BaseModelOutputWithPooling] = None
94
+ multimodal_embeddings: Optional[torch.FloatTensor] = None
95
+ multimodal_output: Optional[BaseModelOutputWithPooling] = None
96
+
97
+ def to_tuple(self) -> Tuple[Any]:
98
+ return tuple(
99
+ self[k] if k not in ["text_output", "image_output", "multimodal_output"] else getattr(self, k).to_tuple()
100
+ for k in self.keys()
101
+ )
102
+
103
+
104
+ @dataclass
105
+ class FlavaLosses(ModelOutput):
106
+ """Class representing pretraining losses from FLAVA model
107
+
108
+ Args:
109
+ mim (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mim_labels` and `pixel_values` are present, `input_ids_masked` is absent and `mim_weight` > 0.:
110
+ Masked Image Modeling loss as used in BeIT calculated only for unimodal image data.
111
+ mlm (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mlm_labels` and `input_ids_masked` are present, `pixel_values` is absent and `mlm_weight` > 0.:
112
+ Masked Language Modeling loss as used in BERT calculated only for unimodal text data.
113
+ itm (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `itm_labels`, `input_ids_masked`, `pixel_values` are present and `itm_weight` > 0.:
114
+ Image Text Matching (ITM) loss calculated for paired image-text data. Note that ITM loss is calculated on
115
+ masked pairs in FLAVA.
116
+ global_contrastive (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `input_ids` and `pixel_values` are present and `global_contrastive_weight` > 0.:
117
+ Contrastive loss for image-text similarity similar to CLIP but calculated globally for paired image-text
118
+ data. This is calculated on unmasked images and texts.
119
+ mmm_image (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mim_labels`, `pixel_values` and `input_ids_masked` are present and `mmm_image_weight` > 0.:
120
+ Masked Multimodal Modeling loss's image component calculated on paired image-text data.
121
+ mmm_text (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `mlm_labels`, `pixel_values` and `input_ids_masked` are present and `mmm_text_weight` > 0.:
122
+ Masked Multimodal Modeling loss's text component calculated on paired image-text data.
123
+ """
124
+
125
+ mim: Optional[torch.FloatTensor] = None
126
+ mlm: Optional[torch.FloatTensor] = None
127
+ itm: Optional[torch.FloatTensor] = None
128
+ global_contrastive: Optional[torch.FloatTensor] = None
129
+ mmm_image: Optional[torch.FloatTensor] = None
130
+ mmm_text: Optional[torch.FloatTensor] = None
131
+
132
+ def all_none(self) -> bool:
133
+ all_none = True
134
+ for v in self.values():
135
+ if v is not None:
136
+ all_none = False
137
+ break
138
+ return all_none
139
+
140
+
141
+ @dataclass
142
+ class FlavaForPreTrainingOutput(ModelOutput):
143
+ """
144
+ Output from FlavaForPreTraining containing embeddings, and outputs from individual encoders.
145
+
146
+ Note that `image_embeddings` and `text_embeddings` returned are similar to pooled output returned from a
147
+ transformer. If you want embeddings for contrastive loss or retrieval use a FLAVA model's `image_projection` and
148
+ `text_projection` layers on `image_embeddings` and `text_embeddings` respectively.
149
+
150
+ Args:
151
+ loss (`torch.FloatTensor`, *optional*, returned when `return_loss` is True):
152
+ Total loss calculated for this model.
153
+ loss_info (`FlavaLosses`):
154
+ Detailed info for FLAVA Pretraining losses. Check `FlavaLosses` class description for the information on
155
+ the keys.
156
+ image_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `pixel_values` are present):
157
+ The image embeddings which are basically the pooled output of [`FlavaImageModel`].
158
+ image_output (`BaseModelOutputWithPooling`, *optional*, returned when `pixel_values` are present):
159
+ The output of the [`FlavaImageModel`].
160
+ text_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `input_ids` are present):
161
+ The text embeddings which are basically the pooled output of [`FlavaTextModel`].
162
+ text_output (`BaseModelOutputWithPooling`, *optional*, returned when `input_ids` are present):
163
+ The output of the [`FlavaTextModel`].
164
+ multimodal_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `input_ids` and `pixel_values` are present and `skip_unmasked_multimodal_encoder` is `None` or `False`):
165
+ The multimodal embeddings which are basically the pooled output of [`FlavaTextModel`].
166
+ multimodal_output (`BaseModelOutputWithPooling`, returned when `input_ids` and `pixel_values` are present and `skip_unmasked_multimodal_encoder` is `None` or `False`):
167
+ The output of the [`FlavaMultimodalModel`].
168
+
169
+ image_masked_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `pixel_values` are present):
170
+ The image embeddings which are basically the pooled output of [`FlavaImageModel`]. Uses `bool_masked_pos`
171
+ to create masked images.
172
+ image_masked_output (`BaseModelOutputWithPooling`, *optional*, returned when `pixel_values` are present):
173
+ The output of the [`FlavaImageModel`]. Uses `bool_masked_pos` to create masked images.
174
+ text_masked_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `input_ids_masked` are present):
175
+ The text embeddings which are basically the pooled output of [`FlavaTextModel`].
176
+ text_masked_output (`BaseModelOutputWithPooling`, *optional*, returned when `input_ids_masked` are present):
177
+ The output of the [`FlavaTextModel`].
178
+ multimodal_masked_embeddings (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*, returned when `input_ids` and `pixel_values` are present):
179
+ The multimodal embeddings which are basically the pooled output of [`FlavaTextModel`].
180
+ multimodal_masked_output (`BaseModelOutputWithPooling`, *optional*, returned when `input_ids_masked` and `pixel_values` are present):
181
+ The output of the [`FlavaMultimodalModel`].
182
+
183
+ mim_logits (`torch.FloatTensor` of shape `(batch_size, num_image_patches, image_vocab_size)` or of shape `(total_masked_patches, image_vocab_size)` , *optional*, returned when `pixel_values` are present and `input_ids_masked` are not):
184
+ The logits for MIM unimodal loss. Uses `book_masked_pos` to get masked patches. The flattened output is
185
+ returned when `bool_masked_pos` has some of the patches masked.
186
+ mlm_logits (`torch.FloatTensor` of shape `(batch_size, text_seq_length, text_vocab_size)` or of shape `(total_masked_seq_length, text_vocab_size)`, *optional*, returned when `input_ids_masked` are present and `pixel_values` are not):
187
+ The logits for MLM unimodal loss. The flattened output is returned when `input_ids_masked` has some of
188
+ the tokens masked.
189
+ itm_logits (`torch.FloatTensor` of shape `(batch_size, 2)`, *optional*, returned when `input_ids_masked` and `pixel_values` are present):
190
+ The logits for ITM loss. Note that ITM loss is calculated on masked pairs in FLAVA.
191
+ mmm_image_logits (`torch.FloatTensor` of shape `(batch_size, num_image_patches, image_vocab_size)` or of shape`(total_masked_patches, image_vocab_size)`, *optional*, returned when `pixel_values` and `input_ids_masked` are present):
192
+ The logits for MMM image multimodal loss. Uses `book_masked_pos` to get masked patches. The flattened
193
+ output is returned when `bool_masked_pos` has some of the patches masked.
194
+ mmm_text_logits (`torch.FloatTensor` of shape `(batch_size, text_seq_length, text_vocab_size)` or of shape `(`(total_masked_seq_length, text_vocab_size)`), *optional*, returned when `pixel_values` and `input_ids_masked` are present):
195
+ The logits for MMM text multimodal loss. The flattened output is returned when `input_ids_masked` has
196
+ some of the tokens masked.
197
+ contrastive_logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
198
+ The scaled dot product scores between `image_embeddings` and `text_embeddings` but passed through FLAVA's
199
+ `image_projection` and `text_projection` layers respectively. This represents the image-text similarity
200
+ scores. This is calculated on unmasked images and texts.
201
+ contrastive_logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
202
+ The scaled dot product scores between `text_embeddings` and `image_embeddings` but passed through FLAVA's
203
+ `text_projection` and `image_projection` layers respectively. This is calculated on unmasked images and
204
+ texts.
205
+ """
206
+
207
+ loss: Optional[torch.FloatTensor] = None
208
+ loss_info: FlavaLosses = None
209
+ image_embeddings: Optional[torch.FloatTensor] = None
210
+ image_output: Optional[BaseModelOutputWithPooling] = None
211
+ text_embeddings: Optional[torch.FloatTensor] = None
212
+ text_output: Optional[BaseModelOutputWithPooling] = None
213
+ multimodal_embeddings: Optional[torch.FloatTensor] = None
214
+ multimodal_output: Optional[BaseModelOutputWithPooling] = None
215
+ image_masked_embeddings: Optional[torch.FloatTensor] = None
216
+ image_masked_output: Optional[BaseModelOutputWithPooling] = None
217
+ text_masked_embeddings: Optional[torch.FloatTensor] = None
218
+ text_masked_output: Optional[BaseModelOutputWithPooling] = None
219
+ multimodal_masked_embeddings: Optional[torch.FloatTensor] = None
220
+ multimodal_masked_output: Optional[BaseModelOutputWithPooling] = None
221
+ mim_logits: Optional[torch.FloatTensor] = None
222
+ mlm_logits: Optional[torch.FloatTensor] = None
223
+ itm_logits: Optional[torch.FloatTensor] = None
224
+ contrastive_logits_per_image: Optional[torch.FloatTensor] = None
225
+ contrastive_logits_per_text: Optional[torch.FloatTensor] = None
226
+ mmm_image_logits: Optional[torch.FloatTensor] = None
227
+ mmm_text_logits: Optional[torch.FloatTensor] = None
228
+
229
+ def to_tuple(self) -> Tuple[Any]:
230
+ transformer_outputs = [
231
+ "text_output",
232
+ "image_output",
233
+ "multimodal_output",
234
+ "text_masked_output",
235
+ "image_masked_output",
236
+ "multimodal_masked_output",
237
+ ]
238
+ return tuple(self[k] if k not in transformer_outputs else getattr(self, k).to_tuple() for k in self.keys())
239
+
240
+
241
+ # Based on timm implementation, which can be found here:
242
+ # https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/image_transformer.py
243
+ class FlavaImageEmbeddings(nn.Module):
244
+ """
245
+ Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
246
+ """
247
+
248
+ def __init__(self, config: FlavaImageConfig, use_mask_token: bool = False) -> None:
249
+ super().__init__()
250
+
251
+ use_mask_token = use_mask_token or config.mask_token
252
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
253
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if use_mask_token else None
254
+ self.patch_embeddings = PatchEmbeddings(
255
+ image_size=config.image_size,
256
+ patch_size=config.patch_size,
257
+ num_channels=config.num_channels,
258
+ embed_dim=config.hidden_size,
259
+ )
260
+ num_patches = self.patch_embeddings.num_patches
261
+ self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
262
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
263
+ self.patch_size = config.patch_size
264
+ self.config = config
265
+
266
+ # Copied from transformers.models.vit.modeling_vit.ViTEmbeddings.interpolate_pos_encoding
267
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
268
+ """
269
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
270
+ images. This method is also adapted to support torch.jit tracing.
271
+
272
+ Adapted from:
273
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
274
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
275
+ """
276
+
277
+ num_patches = embeddings.shape[1] - 1
278
+ num_positions = self.position_embeddings.shape[1] - 1
279
+
280
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
281
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
282
+ return self.position_embeddings
283
+
284
+ class_pos_embed = self.position_embeddings[:, :1]
285
+ patch_pos_embed = self.position_embeddings[:, 1:]
286
+
287
+ dim = embeddings.shape[-1]
288
+
289
+ new_height = height // self.patch_size
290
+ new_width = width // self.patch_size
291
+
292
+ sqrt_num_positions = torch_int(num_positions**0.5)
293
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
294
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
295
+
296
+ patch_pos_embed = nn.functional.interpolate(
297
+ patch_pos_embed,
298
+ size=(new_height, new_width),
299
+ mode="bicubic",
300
+ align_corners=False,
301
+ )
302
+
303
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
304
+
305
+ return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
306
+
307
+ def forward(
308
+ self,
309
+ pixel_values: torch.Tensor,
310
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
311
+ interpolate_pos_encoding: bool = False,
312
+ ) -> torch.Tensor:
313
+ batch_size, num_channels, height, width = pixel_values.shape
314
+ embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
315
+
316
+ batch_size, seq_len, _ = embeddings.size()
317
+ if bool_masked_pos is not None:
318
+ mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
319
+ # B X H X W = B X HW
320
+ if bool_masked_pos.dim() == 3:
321
+ bool_masked_pos = bool_masked_pos.view(bool_masked_pos.size(0), -1)
322
+ # replace the masked visual tokens by mask_tokens
323
+ mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
324
+ embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
325
+
326
+ # add the [CLS] token to the embedded patch tokens
327
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1)
328
+ embeddings = torch.cat((cls_tokens, embeddings), dim=1)
329
+
330
+ # add positional encoding to each token
331
+ if interpolate_pos_encoding:
332
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
333
+ else:
334
+ embeddings = embeddings + self.position_embeddings
335
+
336
+ embeddings = self.dropout(embeddings)
337
+
338
+ return embeddings
339
+
340
+
341
+ # Based on timm implementation, which can be found here:
342
+ # https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/image_transformer.py
343
+ class PatchEmbeddings(nn.Module):
344
+ """
345
+ Image to Patch Embedding.
346
+ """
347
+
348
+ def __init__(
349
+ self,
350
+ image_size: int = 224,
351
+ patch_size: Union[int, Tuple[int, int]] = 16,
352
+ num_channels: int = 3,
353
+ embed_dim: int = 768,
354
+ ):
355
+ super().__init__()
356
+ if not isinstance(image_size, collections.abc.Iterable):
357
+ image_size = (image_size, image_size)
358
+ if not isinstance(patch_size, collections.abc.Iterable):
359
+ patch_size = (patch_size, patch_size)
360
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
361
+ self.image_size = image_size
362
+ self.patch_size = patch_size
363
+ self.num_patches = num_patches
364
+
365
+ self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
366
+
367
+ def forward(self, pixel_values: torch.Tensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
368
+ batch_size, num_channels, height, width = pixel_values.shape
369
+ if not interpolate_pos_encoding:
370
+ if height != self.image_size[0] or width != self.image_size[1]:
371
+ raise ValueError(
372
+ f"Input image size ({height}*{width}) doesn't match model"
373
+ f" ({self.image_size[0]}*{self.image_size[1]})."
374
+ )
375
+ x = self.projection(pixel_values).flatten(2).transpose(1, 2)
376
+ return x
377
+
378
+
379
+ class FlavaTextEmbeddings(nn.Module):
380
+ """Construct the embeddings from word, position and token_type embeddings."""
381
+
382
+ def __init__(self, config):
383
+ super().__init__()
384
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
385
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
386
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
387
+
388
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
389
+ # any TensorFlow checkpoint file
390
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
391
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
392
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
393
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
394
+ self.register_buffer(
395
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
396
+ )
397
+ self.register_buffer(
398
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
399
+ )
400
+
401
+ def forward(
402
+ self,
403
+ input_ids: Optional[torch.Tensor] = None,
404
+ token_type_ids: Optional[torch.Tensor] = None,
405
+ position_ids: Optional[torch.Tensor] = None,
406
+ ):
407
+ input_shape = input_ids.size()
408
+ seq_length = input_shape[1]
409
+
410
+ if position_ids is None:
411
+ position_ids = self.position_ids[:, :seq_length]
412
+
413
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
414
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
415
+ # issue #5664
416
+ if token_type_ids is None:
417
+ if hasattr(self, "token_type_ids"):
418
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
419
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
420
+ token_type_ids = buffered_token_type_ids_expanded
421
+ else:
422
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
423
+
424
+ inputs_embeds = self.word_embeddings(input_ids)
425
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
426
+
427
+ embeddings = inputs_embeds + token_type_embeddings
428
+ if self.position_embedding_type == "absolute":
429
+ position_embeddings = self.position_embeddings(position_ids)
430
+ embeddings += position_embeddings
431
+ embeddings = self.LayerNorm(embeddings)
432
+ embeddings = self.dropout(embeddings)
433
+ return embeddings
434
+
435
+
436
+ class FlavaSelfAttention(nn.Module):
437
+ def __init__(self, config: FlavaPossibleConfigs) -> None:
438
+ super().__init__()
439
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
440
+ raise ValueError(
441
+ f"The hidden size {config.hidden_size,} is not a multiple of the number of attention "
442
+ f"heads {config.num_attention_heads}."
443
+ )
444
+
445
+ self.num_attention_heads = config.num_attention_heads
446
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
447
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
448
+
449
+ self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
450
+ self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
451
+ self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
452
+
453
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
454
+
455
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
456
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
457
+ x = x.view(*new_x_shape)
458
+ return x.permute(0, 2, 1, 3)
459
+
460
+ def forward(
461
+ self,
462
+ hidden_states: torch.Tensor,
463
+ attention_mask: Optional[torch.Tensor] = None,
464
+ head_mask: Optional[torch.Tensor] = None,
465
+ output_attentions: bool = False,
466
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
467
+ mixed_query_layer = self.query(hidden_states)
468
+
469
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
470
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
471
+ query_layer = self.transpose_for_scores(mixed_query_layer)
472
+
473
+ # Take the dot product between "query" and "key" to get the raw attention scores.
474
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
475
+
476
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
477
+ if attention_mask is not None:
478
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
479
+ attention_scores = attention_scores + attention_mask
480
+
481
+ # Normalize the attention scores to probabilities.
482
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
483
+
484
+ # This is actually dropping out entire tokens to attend to, which might
485
+ # seem a bit unusual, but is taken from the original Transformer paper.
486
+ attention_probs = self.dropout(attention_probs)
487
+
488
+ # Mask heads if we want to
489
+ if head_mask is not None:
490
+ attention_probs = attention_probs * head_mask
491
+
492
+ context_layer = torch.matmul(attention_probs, value_layer)
493
+
494
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
495
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
496
+ context_layer = context_layer.view(*new_context_layer_shape)
497
+
498
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
499
+
500
+ return outputs
501
+
502
+
503
+ class FlavaSelfOutput(nn.Module):
504
+ """
505
+ The residual connection is defined in FlavaLayer (same as ViTLayer) instead of here (as is the case with other
506
+ models), due to the layernorm applied before each block.
507
+ """
508
+
509
+ def __init__(self, config: FlavaPossibleConfigs) -> None:
510
+ super().__init__()
511
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
512
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
513
+
514
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
515
+ hidden_states = self.dense(hidden_states)
516
+ hidden_states = self.dropout(hidden_states)
517
+
518
+ return hidden_states
519
+
520
+
521
+ class FlavaAttention(nn.Module):
522
+ def __init__(self, config: FlavaPossibleConfigs) -> None:
523
+ super().__init__()
524
+ self.attention = FlavaSelfAttention(config)
525
+ self.output = FlavaSelfOutput(config)
526
+ self.pruned_heads = set()
527
+
528
+ def prune_heads(self, heads: Set[int]) -> None:
529
+ if len(heads) == 0:
530
+ return
531
+ heads, index = find_pruneable_heads_and_indices(
532
+ heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
533
+ )
534
+
535
+ # Prune linear layers
536
+ self.attention.query = prune_linear_layer(self.attention.query, index)
537
+ self.attention.key = prune_linear_layer(self.attention.key, index)
538
+ self.attention.value = prune_linear_layer(self.attention.value, index)
539
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
540
+
541
+ # Update hyper params and store pruned heads
542
+ self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
543
+ self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
544
+ self.pruned_heads = self.pruned_heads.union(heads)
545
+
546
+ def forward(
547
+ self,
548
+ hidden_states: torch.Tensor,
549
+ attention_mask: Optional[torch.Tensor] = None,
550
+ head_mask: Optional[torch.Tensor] = None,
551
+ output_attentions: bool = False,
552
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
553
+ self_outputs = self.attention(
554
+ hidden_states, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions
555
+ )
556
+
557
+ attention_output = self.output(self_outputs[0], hidden_states)
558
+
559
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
560
+ return outputs
561
+
562
+
563
+ class FlavaIntermediate(nn.Module):
564
+ def __init__(self, config: FlavaPossibleConfigs) -> None:
565
+ super().__init__()
566
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
567
+ if isinstance(config.hidden_act, str):
568
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
569
+ else:
570
+ self.intermediate_act_fn = config.hidden_act
571
+
572
+ # Copied from transformers.models.vit.modeling_vit.ViTIntermediate.forward
573
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
574
+ hidden_states = self.dense(hidden_states)
575
+ hidden_states = self.intermediate_act_fn(hidden_states)
576
+
577
+ return hidden_states
578
+
579
+
580
+ class FlavaOutput(nn.Module):
581
+ def __init__(self, config: FlavaPossibleConfigs) -> None:
582
+ super().__init__()
583
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
584
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
585
+
586
+ # Copied from transformers.models.vit.modeling_vit.ViTOutput.forward
587
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
588
+ hidden_states = self.dense(hidden_states)
589
+ hidden_states = self.dropout(hidden_states)
590
+
591
+ hidden_states = hidden_states + input_tensor
592
+
593
+ return hidden_states
594
+
595
+
596
+ class FlavaLayer(nn.Module):
597
+ """This corresponds to the Block class in the timm implementation."""
598
+
599
+ def __init__(self, config: FlavaPossibleConfigs) -> None:
600
+ super().__init__()
601
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
602
+ self.seq_len_dim = 1
603
+ self.attention = FlavaAttention(config)
604
+ self.intermediate = FlavaIntermediate(config)
605
+ self.output = FlavaOutput(config)
606
+
607
+ # TODO: Check fp32 layer norm possiblity
608
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
609
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
610
+
611
+ def forward(
612
+ self,
613
+ hidden_states: torch.Tensor,
614
+ attention_mask: Optional[torch.Tensor] = None,
615
+ head_mask: Optional[torch.Tensor] = None,
616
+ output_attentions: bool = False,
617
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
618
+ self_attention_outputs = self.attention(
619
+ self.layernorm_before(hidden_states), # in ViT, layernorm is applied before self-attention
620
+ attention_mask=attention_mask,
621
+ head_mask=head_mask,
622
+ output_attentions=output_attentions,
623
+ )
624
+ attention_output = self_attention_outputs[0]
625
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
626
+
627
+ # first residual connection
628
+ hidden_states = attention_output + hidden_states
629
+
630
+ # in ViT, layernorm is also applied after self-attention
631
+ layer_output = self.layernorm_after(hidden_states)
632
+ layer_output = self.intermediate(layer_output)
633
+
634
+ # second residual connection is done here
635
+ layer_output = self.output(layer_output, hidden_states)
636
+
637
+ outputs = (layer_output,) + outputs
638
+
639
+ return outputs
640
+
641
+
642
+ class FlavaEncoder(nn.Module):
643
+ def __init__(self, config: FlavaConfig) -> None:
644
+ super().__init__()
645
+ self.config = config
646
+ self.layer = nn.ModuleList([FlavaLayer(config) for _ in range(config.num_hidden_layers)])
647
+ self.gradient_checkpointing = False
648
+
649
+ def forward(
650
+ self,
651
+ hidden_states: torch.Tensor,
652
+ attention_mask: Optional[torch.Tensor] = None,
653
+ head_mask: Optional[torch.Tensor] = None,
654
+ output_attentions: bool = False,
655
+ output_hidden_states: bool = False,
656
+ return_dict: bool = True,
657
+ ) -> Union[tuple, BaseModelOutput]:
658
+ all_hidden_states = () if output_hidden_states else None
659
+ all_self_attentions = () if output_attentions else None
660
+
661
+ for i, layer_module in enumerate(self.layer):
662
+ if output_hidden_states:
663
+ all_hidden_states = all_hidden_states + (hidden_states,)
664
+
665
+ layer_head_mask = head_mask[i] if head_mask is not None else None
666
+
667
+ if self.gradient_checkpointing and self.training:
668
+ layer_outputs = self._gradient_checkpointing_func(
669
+ layer_module.__call__,
670
+ hidden_states,
671
+ attention_mask,
672
+ layer_head_mask,
673
+ output_attentions,
674
+ )
675
+ else:
676
+ layer_outputs = layer_module(hidden_states, attention_mask, layer_head_mask, output_attentions)
677
+
678
+ hidden_states = layer_outputs[0]
679
+
680
+ if output_attentions:
681
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
682
+
683
+ if output_hidden_states:
684
+ all_hidden_states = all_hidden_states + (hidden_states,)
685
+
686
+ if not return_dict:
687
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
688
+ return BaseModelOutput(
689
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_self_attentions
690
+ )
691
+
692
+
693
+ class FlavaPooler(nn.Module):
694
+ def __init__(self, config: FlavaPossibleConfigs):
695
+ super().__init__()
696
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
697
+ self.activation = nn.Tanh()
698
+
699
+ def forward(self, hidden_states: torch.Tensor):
700
+ # We "pool" the model by simply taking the hidden state corresponding
701
+ # to the first token.
702
+ first_token_tensor = hidden_states[:, 0]
703
+ pooled_output = self.dense(first_token_tensor)
704
+ pooled_output = self.activation(pooled_output)
705
+ return pooled_output
706
+
707
+
708
+ FLAVA_START_DOCSTRING = r"""
709
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
710
+ as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
711
+ behavior.
712
+
713
+ Parameters:
714
+ config ([`{config}`]): Model configuration class with all the parameters of the model.
715
+ Initializing with a config file does not load the weights associated with the model, only the
716
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
717
+ """
718
+
719
+ FLAVA_INPUTS_DOCSTRING_COMMON = r"""
720
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
721
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
722
+ - 1 for tokens that are **not masked**,
723
+ - 0 for tokens that are **masked**.
724
+ [What are attention masks?](../glossary#attention-mask)
725
+
726
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
727
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
728
+
729
+ - 1 indicates the head is **not masked**,
730
+ - 0 indicates the head is **masked**.
731
+
732
+ output_attentions (`bool`, *optional*):
733
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
734
+ tensors for more detail.
735
+ output_hidden_states (`bool`, *optional*):
736
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
737
+ more detail.
738
+
739
+ return_dict (`bool`, *optional*):
740
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
741
+ """
742
+
743
+ FLAVA_IMAGE_INPUTS_DOCSTRING_BASE = r"""
744
+ Args:
745
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
746
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
747
+ [`FlavaImageProcessor.__call__`] for details.
748
+
749
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, image_num_patches)`):
750
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
751
+
752
+ interpolate_pos_encoding (`bool`, *optional*):
753
+ Whether to interpolate the pre-trained position encodings.
754
+ """
755
+
756
+ FLAVA_IMAGE_INPUTS_DOCSTRING = FLAVA_IMAGE_INPUTS_DOCSTRING_BASE + FLAVA_INPUTS_DOCSTRING_COMMON
757
+
758
+ FLAVA_TEXT_INPUTS_DOCSTRING_BASE = r"""
759
+ Args:
760
+ input_ids (`torch.LongTensor` of shape `({0})`):
761
+ Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
762
+ [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
763
+ IDs?](../glossary#input-ids)
764
+
765
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
766
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
767
+ 1]`:
768
+ - 0 corresponds to a *sentence A* token,
769
+ - 1 corresponds to a *sentence B* token.
770
+ [What are token type IDs?](../glossary#token-type-ids)
771
+ """
772
+
773
+ FLAVA_TEXT_INPUTS_DOCSTRING = FLAVA_TEXT_INPUTS_DOCSTRING_BASE + FLAVA_INPUTS_DOCSTRING_COMMON
774
+
775
+ FLAVA_MULTIMODAL_INPUTS_DOCSTRING = (
776
+ r"""
777
+ Args:
778
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, image_num_patches + text_seq_len, hidden_size)`):
779
+ The concatenated hidden states of unimodal encoders.
780
+ """
781
+ + FLAVA_INPUTS_DOCSTRING_COMMON
782
+ )
783
+
784
+ FLAVA_MODEL_INPUTS_DOCSTRING_BASE = r"""
785
+ Args:
786
+ skip_multimodal_encoder (*bool*, *optional*):
787
+ Skip any calculations for multimodal encoder. Useful if multimodal encoding is not going to be used.
788
+ """
789
+
790
+ FLAVA_MODEL_INPUTS_DOCSTRING = (
791
+ FLAVA_IMAGE_INPUTS_DOCSTRING_BASE
792
+ + FLAVA_TEXT_INPUTS_DOCSTRING_BASE
793
+ + FLAVA_INPUTS_DOCSTRING_COMMON
794
+ + FLAVA_MODEL_INPUTS_DOCSTRING_BASE
795
+ )
796
+
797
+
798
+ FLAVA_PRETRAINING_INPUTS_DOCSTRING = (
799
+ r"""
800
+ Args:
801
+ input_ids_masked (`torch.LongTensor` of shape `({0})`):
802
+ Indices of input sequence tokens in the vocabulary. These ones are the masked version of the original task
803
+ to be used with MLM. Indices can be obtained using [`AutoTokenizer`] along with
804
+ [`DataCollatorForMaskedLanguageModeling`]. See [`PreTrainedTokenizer.encode`] and
805
+ [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids)
806
+
807
+ """
808
+ + FLAVA_TEXT_INPUTS_DOCSTRING_BASE
809
+ + FLAVA_IMAGE_INPUTS_DOCSTRING_BASE
810
+ + r"""
811
+ image_attention_mask (`torch.FloatTensor` of shape `({1})`, *optional*):
812
+ Mask to avoid performing attention on padding token indices specifically for images. Mask values selected
813
+ in `[0, 1]`:
814
+ - 1 for tokens that are **not masked**,
815
+ - 0 for tokens that are **masked**.
816
+ [What are attention masks?](../glossary#attention-mask)
817
+
818
+ skip_unmasked_multimodal_encoder (*bool*, *optional*):
819
+ Skip any calculations for multimodal encoder for unmasked inputs. FLAVA pretraining doesn't need unmasked
820
+ multimodal embeddings or outputs as of now.
821
+
822
+ mlm_labels (`torch.LongTensor` of shape `(batch_size, text_seq_len)`, *optional*):
823
+ Labels for computing the left-to-right language and multimodal masked modeling loss (next word prediction).
824
+ Indices should be in `[-100, 0, ..., text_config.vocab_size - 1]` (see `input_ids` docstring). Tokens with
825
+ indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0,
826
+ ..., text_config.vocab_size - 1]`.
827
+
828
+ mim_labels (`torch.LongTensor` of shape `(batch_size, image_num_patches)`, *optional*):
829
+ Labels for computing the image and multimodal masked modeling loss. Indices should be in `[-100, 0, ...,
830
+ image_config.vocab_size - 1]`. Tokens with indices set to `-100` are ignored (masked), the loss is only
831
+ computed for the tokens with labels in `[0, ..., image_config.vocab_size - 1]`. If not passed, they are
832
+ generated automatically using the image codebook assigned to the model. By default, it uses
833
+ [`FlavaImageCodebook`]. See [`FlavaImageCodebook`] to understand how to generate mim_labels.
834
+
835
+ itm_labels (`torch.LongTensor` of shape `(batch_size, 1)`, *optional*):
836
+ Labels for computing the image-text matching loss. 0 means the pairs don't match and 1 means they match.
837
+ The pairs with 0 will be skipped for calculation of MMM and global contrastive losses as well.
838
+
839
+ return_loss (`bool`, *optional*, default to None):
840
+ Whether to return calculated loss or not.
841
+ """
842
+ + FLAVA_INPUTS_DOCSTRING_COMMON
843
+ )
844
+
845
+ FLAVA_PRETRAINING_START_DOCSTRING_EXTRA = r"""
846
+ Parameters:
847
+ image_codebook ([`nn.Module`]): If passed, the image codebook will be set to this. Otherwise. it will
848
+ be initialized using the image_codebook_config defined in the config first as the first parameter.
849
+ """
850
+
851
+
852
+ class FlavaPreTrainedModel(PreTrainedModel):
853
+ """
854
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
855
+ models.
856
+ """
857
+
858
+ config_class = FlavaConfig
859
+ base_model_prefix = "flava"
860
+ supports_gradient_checkpointing = True
861
+
862
+ def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
863
+ """Initialize the weights"""
864
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
865
+ # Slightly different from the TF version which uses truncated_normal for initialization
866
+ # cf https://github.com/pytorch/pytorch/pull/5617
867
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
868
+ if module.bias is not None:
869
+ module.bias.data.zero_()
870
+ elif isinstance(module, nn.Embedding):
871
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
872
+ if module.padding_idx is not None:
873
+ module.weight.data[module.padding_idx].zero_()
874
+ elif isinstance(module, nn.LayerNorm):
875
+ module.bias.data.zero_()
876
+ module.weight.data.fill_(1.0)
877
+
878
+
879
+ @add_start_docstrings(
880
+ "The bare FLAVA Image Model transformer outputting raw hidden-states without any specific head on top.",
881
+ FLAVA_START_DOCSTRING.format(config="FlavaImageConfig"),
882
+ )
883
+ class FlavaImageModel(FlavaPreTrainedModel):
884
+ config_class = FlavaImageConfig
885
+ # This override allows us to load FlavaImageModel from FlavaModel/FlavaForPreTraining checkpoints.
886
+ base_model_prefix = "flava.image_model"
887
+ main_input_name = "pixel_values"
888
+
889
+ def __init__(self, config: FlavaImageConfig, add_pooling_layer: bool = True):
890
+ super().__init__(config)
891
+
892
+ self.config = config
893
+
894
+ self.embeddings = FlavaImageEmbeddings(config)
895
+ self.encoder = FlavaEncoder(config)
896
+
897
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
898
+ self.pooler = FlavaPooler(config) if add_pooling_layer else None
899
+
900
+ self.post_init()
901
+
902
+ def get_input_embeddings(self) -> nn.Module:
903
+ return self.embeddings.patch_embeddings
904
+
905
+ def set_input_embeddings(self, value: nn.Module):
906
+ self.embeddings.patch_embeddings = value
907
+
908
+ def _prune_heads(self, heads_to_prune: Dict[int, List[int]]) -> None:
909
+ """
910
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
911
+ class PreTrainedModel
912
+ """
913
+ for layer, heads in heads_to_prune.items():
914
+ self.encoder.layer[layer].attention.prune_heads(heads)
915
+
916
+ @add_start_docstrings_to_model_forward(FLAVA_IMAGE_INPUTS_DOCSTRING.format("batch_size, image_num_patches"))
917
+ @add_code_sample_docstrings(
918
+ checkpoint=_CHECKPOINT_FOR_DOC,
919
+ output_type=BaseModelOutputWithPooling,
920
+ config_class=_CONFIG_CLASS_FOR_IMAGE_MODEL_DOC,
921
+ modality="vision",
922
+ expected_output=_EXPECTED_IMAGE_OUTPUT_SHAPE,
923
+ )
924
+ def forward(
925
+ self,
926
+ pixel_values: Optional[torch.Tensor] = None,
927
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
928
+ interpolate_pos_encoding: Optional[bool] = None,
929
+ attention_mask: Optional[torch.Tensor] = None,
930
+ head_mask: Optional[torch.Tensor] = None,
931
+ output_attentions: Optional[bool] = None,
932
+ output_hidden_states: Optional[bool] = None,
933
+ return_dict: Optional[bool] = None,
934
+ ) -> Union[tuple, BaseModelOutputWithPooling]:
935
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
936
+ output_hidden_states = (
937
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
938
+ )
939
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
940
+
941
+ if pixel_values is None:
942
+ raise ValueError("You have to specify pixel_values")
943
+
944
+ # Prepare head mask if needed
945
+ # 1.0 in head_mask indicate we keep the head
946
+ # attention_probs has shape bsz x n_heads x N x N
947
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
948
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
949
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
950
+
951
+ embedding_output = self.embeddings(
952
+ pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
953
+ )
954
+
955
+ encoder_outputs = self.encoder(
956
+ embedding_output,
957
+ attention_mask=attention_mask,
958
+ head_mask=head_mask,
959
+ output_attentions=output_attentions,
960
+ output_hidden_states=output_hidden_states,
961
+ return_dict=return_dict,
962
+ )
963
+ sequence_output = encoder_outputs[0]
964
+ sequence_output = self.layernorm(sequence_output)
965
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
966
+
967
+ if not return_dict:
968
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
969
+
970
+ return BaseModelOutputWithPooling(
971
+ last_hidden_state=sequence_output,
972
+ pooler_output=pooled_output,
973
+ hidden_states=encoder_outputs.hidden_states,
974
+ attentions=encoder_outputs.attentions,
975
+ )
976
+
977
+
978
+ @add_start_docstrings(
979
+ "The bare FLAVA Text Model transformer outputting raw hidden-states without any specific head on top.",
980
+ FLAVA_START_DOCSTRING.format(config="FlavaTextConfig"),
981
+ )
982
+ class FlavaTextModel(FlavaPreTrainedModel):
983
+ config_class = FlavaTextConfig
984
+ # This override allows us to load FlavaTextModel from FlavaModel/FlavaForPreTraining checkpoints.
985
+ base_model_prefix = "flava.text_model"
986
+
987
+ def __init__(self, config: FlavaTextConfig, add_pooling_layer: bool = True):
988
+ super().__init__(config)
989
+ self.config = config
990
+
991
+ self.embeddings = FlavaTextEmbeddings(config)
992
+ self.encoder = FlavaEncoder(config)
993
+
994
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
995
+ self.pooler = FlavaPooler(config) if add_pooling_layer else None
996
+
997
+ self.post_init()
998
+
999
+ def get_input_embeddings(self) -> PatchEmbeddings:
1000
+ return self.embeddings.word_embeddings
1001
+
1002
+ def set_input_embeddings(self, value: nn.Module):
1003
+ self.embeddings.word_embeddings = value
1004
+
1005
+ def _prune_heads(self, heads_to_prune: Dict[int, List[int]]) -> None:
1006
+ """
1007
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
1008
+ class PreTrainedModel
1009
+ """
1010
+ for layer, heads in heads_to_prune.items():
1011
+ self.encoder.layer[layer].attention.prune_heads(heads)
1012
+
1013
+ @add_start_docstrings_to_model_forward(FLAVA_TEXT_INPUTS_DOCSTRING.format("batch_size, text_seq_length"))
1014
+ @add_code_sample_docstrings(
1015
+ checkpoint=_CHECKPOINT_FOR_DOC,
1016
+ output_type=BaseModelOutputWithPooling,
1017
+ config_class=_CONFIG_CLASS_FOR_TEXT_MODEL_DOC,
1018
+ )
1019
+ def forward(
1020
+ self,
1021
+ input_ids: Optional[torch.Tensor] = None,
1022
+ attention_mask: Optional[torch.Tensor] = None,
1023
+ token_type_ids: Optional[torch.Tensor] = None,
1024
+ position_ids: Optional[torch.Tensor] = None,
1025
+ head_mask: Optional[torch.Tensor] = None,
1026
+ output_attentions: Optional[bool] = None,
1027
+ output_hidden_states: Optional[bool] = None,
1028
+ return_dict: Optional[bool] = None,
1029
+ ) -> Union[tuple, BaseModelOutputWithPooling]:
1030
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1031
+ output_hidden_states = (
1032
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1033
+ )
1034
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1035
+
1036
+ if input_ids is None:
1037
+ raise ValueError("You have to specify input_ids")
1038
+
1039
+ input_shape = input_ids.size()
1040
+
1041
+ if attention_mask is None:
1042
+ attention_mask = torch.ones(input_shape, device=input_ids.device)
1043
+
1044
+ # Prepare head mask if needed
1045
+ # 1.0 in head_mask indicate we keep the head
1046
+ # attention_probs has shape bsz x n_heads x N x N
1047
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
1048
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
1049
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
1050
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
1051
+ attention_mask, input_shape, input_ids.device
1052
+ )
1053
+
1054
+ embedding_output = self.embeddings(
1055
+ input_ids=input_ids,
1056
+ token_type_ids=token_type_ids,
1057
+ position_ids=position_ids,
1058
+ )
1059
+
1060
+ encoder_outputs = self.encoder(
1061
+ embedding_output,
1062
+ attention_mask=extended_attention_mask,
1063
+ head_mask=head_mask,
1064
+ output_attentions=output_attentions,
1065
+ output_hidden_states=output_hidden_states,
1066
+ return_dict=return_dict,
1067
+ )
1068
+ sequence_output = encoder_outputs[0]
1069
+ sequence_output = self.layernorm(sequence_output)
1070
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
1071
+
1072
+ if not return_dict:
1073
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
1074
+
1075
+ return BaseModelOutputWithPooling(
1076
+ last_hidden_state=sequence_output,
1077
+ pooler_output=pooled_output,
1078
+ hidden_states=encoder_outputs.hidden_states,
1079
+ attentions=encoder_outputs.attentions,
1080
+ )
1081
+
1082
+
1083
+ @add_start_docstrings(
1084
+ "The bare FLAVA Multimodal Model transformer outputting raw hidden-states without any specific head on top.",
1085
+ FLAVA_START_DOCSTRING.format(config="FlavaMultimodalConfig"),
1086
+ )
1087
+ class FlavaMultimodalModel(FlavaPreTrainedModel):
1088
+ config_class = FlavaMultimodalConfig
1089
+ # This override allows us to load FlavaMultimodalModel from FlavaModel/FlavaForPreTraining checkpoints.
1090
+ base_model_prefix = "flava.multimodal_model"
1091
+ main_input_name = "hidden_states"
1092
+
1093
+ def __init__(self, config: FlavaMultimodalConfig, add_pooling_layer=True):
1094
+ super().__init__(config)
1095
+ self.config = config
1096
+ self.use_cls_token = self.config.use_cls_token
1097
+ if self.use_cls_token:
1098
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
1099
+
1100
+ self.encoder = FlavaEncoder(config)
1101
+
1102
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
1103
+ self.pooler = FlavaPooler(config) if add_pooling_layer else None
1104
+
1105
+ self.post_init()
1106
+
1107
+ def _prune_heads(self, heads_to_prune: Dict[int, List[int]]) -> None:
1108
+ """
1109
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
1110
+ class PreTrainedModel
1111
+ """
1112
+ for layer, heads in heads_to_prune.items():
1113
+ self.encoder.layer[layer].attention.prune_heads(heads)
1114
+
1115
+ @add_start_docstrings_to_model_forward(
1116
+ FLAVA_MULTIMODAL_INPUTS_DOCSTRING.format("batch_size, image_num_patches + text_seq_len")
1117
+ )
1118
+ @add_code_sample_docstrings(
1119
+ checkpoint=_CHECKPOINT_FOR_DOC,
1120
+ output_type=BaseModelOutputWithPooling,
1121
+ config_class=_CONFIG_CLASS_FOR_MULTIMODAL_MODEL_DOC,
1122
+ )
1123
+ def forward(
1124
+ self,
1125
+ hidden_states: torch.Tensor,
1126
+ attention_mask: Optional[torch.Tensor] = None,
1127
+ head_mask: Optional[torch.Tensor] = None,
1128
+ output_attentions: Optional[bool] = None,
1129
+ output_hidden_states: Optional[bool] = None,
1130
+ return_dict: Optional[bool] = None,
1131
+ ) -> Union[tuple, BaseModelOutputWithPooling]:
1132
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1133
+ output_hidden_states = (
1134
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1135
+ )
1136
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1137
+
1138
+ batch_size, seq_length, _ = hidden_states.size()
1139
+
1140
+ if self.use_cls_token:
1141
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1)
1142
+ hidden_states = torch.cat((cls_tokens, hidden_states), dim=1)
1143
+ seq_length += 1
1144
+
1145
+ if attention_mask is None:
1146
+ attention_mask = torch.ones((batch_size, seq_length), device=hidden_states.device)
1147
+
1148
+ # Prepare head mask if needed
1149
+ # 1.0 in head_mask indicate we keep the head
1150
+ # attention_probs has shape bsz x n_heads x N x N
1151
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
1152
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
1153
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
1154
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
1155
+ attention_mask, (batch_size, seq_length), hidden_states.device
1156
+ )
1157
+
1158
+ encoder_outputs = self.encoder(
1159
+ hidden_states,
1160
+ attention_mask=extended_attention_mask,
1161
+ head_mask=head_mask,
1162
+ output_attentions=output_attentions,
1163
+ output_hidden_states=output_hidden_states,
1164
+ return_dict=return_dict,
1165
+ )
1166
+ sequence_output = encoder_outputs[0]
1167
+ sequence_output = self.layernorm(sequence_output)
1168
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
1169
+
1170
+ if not return_dict:
1171
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
1172
+
1173
+ return BaseModelOutputWithPooling(
1174
+ last_hidden_state=sequence_output,
1175
+ pooler_output=pooled_output,
1176
+ hidden_states=encoder_outputs.hidden_states,
1177
+ attentions=encoder_outputs.attentions,
1178
+ )
1179
+
1180
+
1181
+ @add_start_docstrings(
1182
+ "The bare FLAVA Model transformer outputting raw hidden-states without any specific head on top.",
1183
+ FLAVA_START_DOCSTRING.format(config="FlavaConfig"),
1184
+ )
1185
+ class FlavaModel(FlavaPreTrainedModel):
1186
+ config_class = FlavaConfig
1187
+
1188
+ def __init__(self, config: FlavaConfig):
1189
+ super().__init__(config)
1190
+
1191
+ if not isinstance(config.text_config, FlavaTextConfig):
1192
+ raise TypeError(
1193
+ "config.text_config is expected to be of type FlavaTextConfig but is of type"
1194
+ f" {type(config.text_config)}."
1195
+ )
1196
+
1197
+ if not isinstance(config.image_config, FlavaImageConfig):
1198
+ raise TypeError(
1199
+ "config.image_config is expected to be of type FlavaImageConfig but is of type"
1200
+ f" {type(config.image_config)}."
1201
+ )
1202
+
1203
+ if not isinstance(config.multimodal_config, FlavaMultimodalConfig):
1204
+ raise TypeError(
1205
+ "config.multimodal_config is expected to be of type FlavaMultimodalConfig but "
1206
+ + f"is of type {type(config.multimodal_config)}."
1207
+ )
1208
+
1209
+ text_config = config.text_config
1210
+ image_config = config.image_config
1211
+ multimodal_config = config.multimodal_config
1212
+
1213
+ self.projection_dim = config.projection_dim
1214
+ self.text_hidden_size = text_config.hidden_size
1215
+ self.image_hidden_size = image_config.hidden_size
1216
+ self.mm_hidden_size = multimodal_config.hidden_size
1217
+
1218
+ self.text_model = FlavaTextModel(text_config)
1219
+ self.image_model = FlavaImageModel(image_config)
1220
+ self.multimodal_model = FlavaMultimodalModel(multimodal_config)
1221
+
1222
+ self.image_projection = nn.Linear(self.image_hidden_size, self.projection_dim)
1223
+ self.text_projection = nn.Linear(self.text_hidden_size, self.projection_dim)
1224
+ self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
1225
+
1226
+ self.image_to_mm_projection = nn.Linear(self.image_hidden_size, self.mm_hidden_size)
1227
+ self.text_to_mm_projection = nn.Linear(self.text_hidden_size, self.mm_hidden_size)
1228
+ # Initialize weights and apply final processing
1229
+ self.post_init()
1230
+
1231
+ @add_start_docstrings_to_model_forward(FLAVA_TEXT_INPUTS_DOCSTRING.format("batch_size, text_seq_length"))
1232
+ def get_text_features(
1233
+ self,
1234
+ input_ids: Optional[torch.Tensor] = None,
1235
+ attention_mask: Optional[torch.Tensor] = None,
1236
+ token_type_ids: Optional[torch.Tensor] = None,
1237
+ position_ids: Optional[torch.Tensor] = None,
1238
+ output_attentions: Optional[bool] = None,
1239
+ output_hidden_states: Optional[bool] = None,
1240
+ return_dict: Optional[bool] = None,
1241
+ ) -> torch.FloatTensor:
1242
+ r"""
1243
+ Returns:
1244
+ text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
1245
+ applying the projection layer to the pooled output of [`FlavaTextModel`].
1246
+
1247
+ Examples:
1248
+
1249
+ ```python
1250
+ >>> from transformers import AutoProcessor, FlavaModel
1251
+
1252
+ >>> model = FlavaModel.from_pretrained("{0}")
1253
+ >>> processor = AutoProcessor.from_pretrained("{0}")
1254
+
1255
+ >>> inputs = processor(
1256
+ ... text=["a photo of a cat", "a photo of a dog"], max_length=77, padding="max_length", return_tensors="pt"
1257
+ ... )
1258
+ >>> text_features = model.get_text_features(**inputs)
1259
+ ```""".format(_CHECKPOINT_FOR_DOC)
1260
+ text_outputs = self.text_model(
1261
+ input_ids=input_ids,
1262
+ attention_mask=attention_mask,
1263
+ token_type_ids=token_type_ids,
1264
+ position_ids=position_ids,
1265
+ output_attentions=output_attentions,
1266
+ output_hidden_states=output_hidden_states,
1267
+ return_dict=return_dict,
1268
+ )
1269
+
1270
+ pooled_output = text_outputs[0] # last_hidden_state
1271
+ text_features = self.text_projection(pooled_output)
1272
+
1273
+ return text_features
1274
+
1275
+ @add_start_docstrings_to_model_forward(FLAVA_IMAGE_INPUTS_DOCSTRING.format("batch_size, image_num_patches"))
1276
+ def get_image_features(
1277
+ self,
1278
+ pixel_values: Optional[torch.Tensor] = None,
1279
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
1280
+ interpolate_pos_encoding: Optional[bool] = None,
1281
+ attention_mask: Optional[torch.Tensor] = None,
1282
+ head_mask: Optional[torch.Tensor] = None,
1283
+ output_attentions: Optional[bool] = None,
1284
+ output_hidden_states: Optional[bool] = None,
1285
+ return_dict: Optional[bool] = None,
1286
+ ) -> torch.FloatTensor:
1287
+ r"""
1288
+ Returns:
1289
+ image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
1290
+ applying the projection layer to the pooled output of [`FlavaImageModel`].
1291
+
1292
+ Examples:
1293
+
1294
+ ```python
1295
+ >>> from PIL import Image
1296
+ >>> import requests
1297
+ >>> from transformers import AutoProcessor, FlavaModel
1298
+
1299
+ >>> model = FlavaModel.from_pretrained("{0}")
1300
+ >>> processor = AutoProcessor.from_pretrained("{0}")
1301
+
1302
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1303
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1304
+
1305
+ >>> inputs = processor(images=image, return_tensors="pt")
1306
+
1307
+ >>> image_features = model.get_image_features(**inputs)
1308
+ ```""".format(_CHECKPOINT_FOR_DOC)
1309
+ image_outputs = self.image_model(
1310
+ pixel_values=pixel_values,
1311
+ bool_masked_pos=bool_masked_pos,
1312
+ attention_mask=attention_mask,
1313
+ head_mask=head_mask,
1314
+ output_attentions=output_attentions,
1315
+ output_hidden_states=output_hidden_states,
1316
+ interpolate_pos_encoding=interpolate_pos_encoding,
1317
+ return_dict=return_dict,
1318
+ )
1319
+
1320
+ pooled_output = image_outputs[0] # last_hidden_state
1321
+ image_features = self.image_projection(pooled_output)
1322
+
1323
+ return image_features
1324
+
1325
+ @add_start_docstrings_to_model_forward(
1326
+ FLAVA_MODEL_INPUTS_DOCSTRING.format("batch_size, image_num_patches + text_seq_len")
1327
+ )
1328
+ @replace_return_docstrings(output_type=FlavaModelOutput, config_class=FlavaConfig)
1329
+ def forward(
1330
+ self,
1331
+ input_ids: Optional[torch.LongTensor] = None,
1332
+ pixel_values: Optional[torch.FloatTensor] = None,
1333
+ attention_mask: Optional[torch.Tensor] = None,
1334
+ token_type_ids: Optional[torch.Tensor] = None,
1335
+ bool_masked_pos: Optional[torch.Tensor] = None,
1336
+ position_ids: Optional[torch.LongTensor] = None,
1337
+ image_attention_mask: Optional[torch.Tensor] = None,
1338
+ skip_multimodal_encoder: Optional[bool] = None,
1339
+ output_attentions: Optional[bool] = None,
1340
+ output_hidden_states: bool = True,
1341
+ return_dict: Optional[bool] = None,
1342
+ ) -> Union[Tuple, FlavaOutput]:
1343
+ r"""
1344
+ Returns:
1345
+
1346
+ Examples:
1347
+
1348
+ ```python
1349
+ >>> from PIL import Image
1350
+ >>> import requests
1351
+ >>> from transformers import AutoProcessor, FlavaModel
1352
+
1353
+ >>> model = FlavaModel.from_pretrained("facebook/flava-full")
1354
+ >>> processor = AutoProcessor.from_pretrained("facebook/flava-full")
1355
+
1356
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1357
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1358
+
1359
+ >>> inputs = processor(text=["a photo of a cat"], images=image, return_tensors="pt", padding=True)
1360
+
1361
+ >>> outputs = model(**inputs)
1362
+
1363
+ >>> image_embeddings = outputs.image_embeddings
1364
+ >>> text_embeddings = outputs.text_embeddings
1365
+ >>> multimodal_embeddings = outputs.multimodal_embeddings
1366
+
1367
+ >>> outputs.image_embeddings.shape
1368
+ torch.Size([1, 197, 768])
1369
+
1370
+ >>> text_embeddings.shape
1371
+ torch.Size([1, 7, 768])
1372
+
1373
+ >>> multimodal_embeddings.shape
1374
+ torch.Size([1, 205, 768])
1375
+ ```
1376
+ """
1377
+
1378
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1379
+ if not output_hidden_states:
1380
+ raise ValueError("FLAVA model requires hidden states to work. Please set `output_hidden_states=True`")
1381
+ image_embeddings = None
1382
+ image_states = None
1383
+ image_mm_projection = None
1384
+ image_output = None
1385
+ if pixel_values is not None:
1386
+ image_output = self.image_model(
1387
+ pixel_values=pixel_values,
1388
+ bool_masked_pos=bool_masked_pos,
1389
+ attention_mask=image_attention_mask,
1390
+ output_attentions=output_attentions,
1391
+ output_hidden_states=output_hidden_states,
1392
+ return_dict=return_dict,
1393
+ )
1394
+ image_embeddings, image_states = image_output[0], image_output[2]
1395
+ # Note that these states don't use final layernorm in the transformer model
1396
+ image_mm_projection = self.image_to_mm_projection(image_states[-1])
1397
+
1398
+ text_embeddings = None
1399
+ text_states = None
1400
+ text_mm_projection = None
1401
+ text_output = None
1402
+ if input_ids is not None:
1403
+ text_output = self.text_model(
1404
+ input_ids=input_ids,
1405
+ attention_mask=attention_mask,
1406
+ position_ids=position_ids,
1407
+ token_type_ids=token_type_ids,
1408
+ output_attentions=output_attentions,
1409
+ output_hidden_states=output_hidden_states,
1410
+ return_dict=return_dict,
1411
+ )
1412
+
1413
+ text_embeddings, text_states = text_output[0], text_output[2]
1414
+ # Note that these states don't use final layernorm in the transformer model
1415
+ text_mm_projection = self.text_to_mm_projection(text_states[-1])
1416
+
1417
+ multimodal_embeddings = None
1418
+ multimodal_output = None
1419
+ if image_mm_projection is not None and text_mm_projection is not None and not skip_multimodal_encoder:
1420
+ if attention_mask is not None:
1421
+ batch_size, seq_len, _ = image_mm_projection.shape
1422
+ if self.multimodal_model.use_cls_token:
1423
+ seq_len += 1
1424
+ attention_mask_image = torch.ones(batch_size, seq_len, device=image_mm_projection.device)
1425
+ attention_multimodal = torch.cat([attention_mask_image, attention_mask], dim=1)
1426
+ else:
1427
+ attention_multimodal = None
1428
+ multimodal_input = torch.cat([image_mm_projection, text_mm_projection], dim=1)
1429
+ multimodal_output = self.multimodal_model(
1430
+ multimodal_input, attention_mask=attention_multimodal, return_dict=return_dict
1431
+ )
1432
+ multimodal_embeddings = multimodal_output[0]
1433
+
1434
+ if not return_dict:
1435
+ return (
1436
+ image_embeddings,
1437
+ image_output,
1438
+ text_embeddings,
1439
+ text_output,
1440
+ multimodal_embeddings,
1441
+ multimodal_output,
1442
+ )
1443
+
1444
+ return FlavaModelOutput(
1445
+ image_embeddings=image_embeddings,
1446
+ image_output=image_output,
1447
+ text_embeddings=text_embeddings,
1448
+ text_output=text_output,
1449
+ multimodal_embeddings=multimodal_embeddings,
1450
+ multimodal_output=multimodal_output,
1451
+ )
1452
+
1453
+
1454
+ class FlavaImageCodebookResPath(nn.Module):
1455
+ def __init__(self, in_size: int, out_size: int, **kwargs):
1456
+ super().__init__()
1457
+ hid_size = out_size // 4
1458
+
1459
+ path = OrderedDict()
1460
+ path["relu_1"] = nn.ReLU()
1461
+ path["conv_1"] = nn.Conv2d(in_size, hid_size, kernel_size=3, padding=1)
1462
+ path["relu_2"] = nn.ReLU()
1463
+ path["conv_2"] = nn.Conv2d(hid_size, hid_size, kernel_size=3, padding=1)
1464
+ path["relu_3"] = nn.ReLU()
1465
+ path["conv_3"] = nn.Conv2d(hid_size, hid_size, kernel_size=3, padding=1)
1466
+ path["relu_4"] = nn.ReLU()
1467
+ path["conv_4"] = nn.Conv2d(hid_size, out_size, kernel_size=1, padding=0)
1468
+
1469
+ self.path = nn.Sequential(path)
1470
+
1471
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
1472
+ return self.path(x)
1473
+
1474
+
1475
+ class FlavaImageCodebookBlock(nn.Module):
1476
+ def __init__(self, in_size: int, out_size: int, num_layers: int, **kwargs):
1477
+ super().__init__()
1478
+
1479
+ self.post_gain = 1 / (num_layers**2)
1480
+
1481
+ if in_size != out_size:
1482
+ self.id_path = nn.Conv2d(in_size, out_size, kernel_size=1, padding=0)
1483
+ else:
1484
+ self.id_path = nn.Identity()
1485
+
1486
+ self.res_path = FlavaImageCodebookResPath(in_size, out_size)
1487
+
1488
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
1489
+ return self.id_path(x) + self.post_gain * self.res_path(x)
1490
+
1491
+
1492
+ class FlavaImageCodebookLayerGroup(nn.Module):
1493
+ def __init__(self, num_blocks: int, num_layers: int, in_size: int, out_size: int, use_pool: bool = True):
1494
+ super().__init__()
1495
+ blocks = OrderedDict()
1496
+ for i in range(num_blocks):
1497
+ if i == 0:
1498
+ blocks[f"block_{i+1}"] = FlavaImageCodebookBlock(in_size, out_size, num_layers)
1499
+ else:
1500
+ blocks[f"block_{i+1}"] = FlavaImageCodebookBlock(out_size, out_size, num_layers)
1501
+
1502
+ if use_pool:
1503
+ blocks["pool"] = nn.MaxPool2d(kernel_size=2)
1504
+
1505
+ self.group = nn.Sequential(blocks)
1506
+
1507
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
1508
+ return self.group(x)
1509
+
1510
+
1511
+ # Inspired by DALLE Encoder in https://github.com/openai/DALL-E/blob/5be4b236bc3ade6943662354117a0e83752cc322/dall_e/encoder.py#L42
1512
+ @add_start_docstrings(
1513
+ """
1514
+ The FLAVA's image codebook model inspired from DALL-E's original encoder. Outputs raw hidden states and can be used
1515
+ to generate image tokens for an image based on DALL-E's vocab. Used to generate labels for MIM. Use
1516
+ `get_codebook_indices` to get image tokens for an image.
1517
+ """,
1518
+ FLAVA_START_DOCSTRING.format(config="FlavaImageCodebookConfig"),
1519
+ )
1520
+ class FlavaImageCodebook(FlavaPreTrainedModel):
1521
+ base_model_prefix = ""
1522
+ config_class = FlavaImageCodebookConfig
1523
+ main_input_name = "pixel_values"
1524
+ supports_gradient_checkpointing = False
1525
+
1526
+ def __init__(
1527
+ self,
1528
+ config: FlavaImageCodebookConfig,
1529
+ **kwargs: Any,
1530
+ ):
1531
+ super().__init__(config)
1532
+
1533
+ self.config = config
1534
+ self.num_groups = config.num_groups
1535
+ self.input_channels = config.input_channels
1536
+ self.num_blocks_per_group = config.num_blocks_per_group
1537
+ self.hidden_size = config.hidden_size
1538
+ self.vocab_size = config.vocab_size
1539
+
1540
+ num_layers = self.num_groups * self.num_blocks_per_group
1541
+
1542
+ output_blocks = OrderedDict()
1543
+ output_blocks["relu"] = nn.ReLU()
1544
+ output_blocks["conv"] = nn.Conv2d(8 * self.hidden_size, self.vocab_size, kernel_size=1, padding=0)
1545
+
1546
+ blocks = OrderedDict()
1547
+ blocks["input"] = nn.Conv2d(self.input_channels, 1 * self.hidden_size, kernel_size=7, padding=3)
1548
+ blocks["group_1"] = FlavaImageCodebookLayerGroup(
1549
+ self.num_blocks_per_group, num_layers, 1 * self.hidden_size, 1 * self.hidden_size
1550
+ )
1551
+ blocks["group_2"] = FlavaImageCodebookLayerGroup(
1552
+ self.num_blocks_per_group, num_layers, 1 * self.hidden_size, 2 * self.hidden_size
1553
+ )
1554
+ blocks["group_3"] = FlavaImageCodebookLayerGroup(
1555
+ self.num_blocks_per_group, num_layers, 2 * self.hidden_size, 4 * self.hidden_size
1556
+ )
1557
+ blocks["group_4"] = FlavaImageCodebookLayerGroup(
1558
+ self.num_blocks_per_group, num_layers, 4 * self.hidden_size, 8 * self.hidden_size, use_pool=False
1559
+ )
1560
+ blocks["output"] = nn.Sequential(output_blocks)
1561
+
1562
+ self.blocks = nn.Sequential(blocks)
1563
+
1564
+ self.post_init()
1565
+
1566
+ if self.config.freeze:
1567
+ for param in self.parameters():
1568
+ param.requires_grad = False
1569
+
1570
+ def get_codebook_indices(self, pixel_values: torch.Tensor) -> torch.Tensor:
1571
+ """
1572
+ Args:
1573
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
1574
+ Pixel values. Codebook pixel values can be obtained using [`AutoImageProcessor`] by passing
1575
+ `return_codebook_pixels=True`. See [`FlavaImageProcessor.__call__`] for details.
1576
+
1577
+ Examples:
1578
+ ```python
1579
+ >>> from PIL import Image
1580
+ >>> import requests
1581
+ >>> from transformers import AutoImageProcessor, FlavaImageCodebook
1582
+
1583
+ >>> model = FlavaImageCodebook.from_pretrained("{0}")
1584
+ >>> image_processor = AutoImageProcessor.from_pretrained("{0}")
1585
+
1586
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1587
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1588
+
1589
+ >>> inputs = image_processor([image], return_codebook_pixels=True, return_tensors="pt")
1590
+ >>> inputs = dict(pixel_values=inputs.codebook_pixel_values)
1591
+
1592
+ >>> outputs = model.get_codebook_indices(**inputs)
1593
+ ```
1594
+ """.format(_CHECKPOINT_FOR_CODEBOOK_DOC)
1595
+ z_logits = self.blocks(pixel_values)
1596
+ return torch.argmax(z_logits, axis=1)
1597
+
1598
+ def get_codebook_probs(self, pixel_values: torch.Tensor) -> torch.Tensor:
1599
+ z_logits = self.blocks(pixel_values)
1600
+ return nn.Softmax(dim=1)(z_logits)
1601
+
1602
+ def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
1603
+ """
1604
+ Args:
1605
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
1606
+ Pixel values. Codebook pixel values can be obtained using [`AutoImageProcessor`] by passing
1607
+ `return_codebook_pixels=True`. See [`FlavaImageProcessor.__call__`] for details.
1608
+
1609
+ Examples:
1610
+
1611
+ ```python
1612
+ >>> from PIL import Image
1613
+ >>> import requests
1614
+ >>> from transformers import AutoImageProcessor, FlavaImageCodebook
1615
+
1616
+ >>> model = FlavaImageCodebook.from_pretrained("{0}")
1617
+ >>> image_processor = AutoImageProcessor.from_pretrained("{0}")
1618
+
1619
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1620
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1621
+
1622
+ >>> inputs = image_processor([image], return_codebook_pixels=True, return_tensors="pt")
1623
+ >>> inputs = dict(pixel_values=inputs.codebook_pixel_values)
1624
+
1625
+ >>> outputs = model(**inputs)
1626
+ >>> print(outputs.shape)
1627
+ (1, 196)
1628
+ ```
1629
+ """.format(_CHECKPOINT_FOR_CODEBOOK_DOC)
1630
+ if len(pixel_values.shape) != 4:
1631
+ raise ValueError(f"input shape {pixel_values.shape} is not 4d")
1632
+ if pixel_values.shape[1] != self.input_channels:
1633
+ raise ValueError(f"input has {pixel_values.shape[1]} channels but model built for {self.input_channels}")
1634
+ return self.blocks(pixel_values)
1635
+
1636
+
1637
+ class FlavaPredictionHeadTransform(nn.Module):
1638
+ def __init__(self, config):
1639
+ super().__init__()
1640
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
1641
+ if isinstance(config.hidden_act, str):
1642
+ self.transform_act_fn = ACT2FN[config.hidden_act]
1643
+ else:
1644
+ self.transform_act_fn = config.hidden_act
1645
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
1646
+
1647
+ def forward(self, hidden_states):
1648
+ hidden_states = self.dense(hidden_states)
1649
+ hidden_states = self.transform_act_fn(hidden_states)
1650
+ hidden_states = self.LayerNorm(hidden_states)
1651
+ return hidden_states
1652
+
1653
+
1654
+ class FlavaMaskedPredictionHead(nn.Module):
1655
+ def __init__(self, config, weight=None):
1656
+ super().__init__()
1657
+ self.config = config
1658
+ self.transform = FlavaPredictionHeadTransform(config)
1659
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1660
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
1661
+ if weight is not None:
1662
+ self.decoder.weight = weight
1663
+
1664
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
1665
+ self.decoder.bias = self.bias
1666
+
1667
+ def _tie_weights(self):
1668
+ self.decoder.bias = self.bias
1669
+
1670
+ def forward(self, x):
1671
+ x = self.transform(x)
1672
+ x = self.decoder(x)
1673
+ return x
1674
+
1675
+
1676
+ class FlavaITMHead(nn.Module):
1677
+ def __init__(self, config):
1678
+ super().__init__()
1679
+ self.config = config
1680
+ self.pooler = FlavaPooler(config)
1681
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
1682
+
1683
+ def forward(self, x):
1684
+ x = self.pooler(x)
1685
+ x = self.seq_relationship(x)
1686
+ return x
1687
+
1688
+
1689
+ class FlavaGlobalContrastiveHead(nn.Module):
1690
+ def __init__(self, config):
1691
+ super().__init__()
1692
+ self.config = config
1693
+ self.global_backprop_contrastive = config.global_backprop_contrastive
1694
+
1695
+ def forward(self, image_embeddings, text_embeddings, logit_scale):
1696
+ temperature = torch.exp(logit_scale)
1697
+ if not torch.distributed.is_available() or not torch.distributed.is_initialized():
1698
+ labels = torch.arange(image_embeddings.size(0), device=image_embeddings.device)
1699
+ image_embeddings_all = [image_embeddings]
1700
+ text_embeddings_all = [text_embeddings]
1701
+ else:
1702
+ local_batch_size = image_embeddings.size(0)
1703
+ world_size = torch.distributed.get_world_size()
1704
+
1705
+ if self.global_backprop_contrastive:
1706
+ # `torch.distributed.nn.functional.all_gather` does backprop on all active workers
1707
+ # whereas `torch.distributed.all_gather` does only backpropagates on the current worker.
1708
+ image_embeddings_all = torch.distributed.nn.functional.all_gather(image_embeddings)
1709
+ text_embeddings_all = torch.distributed.nn.functional.all_gather(text_embeddings)
1710
+ else:
1711
+ image_embeddings_all = [torch.zeros_like(text_embeddings) for _ in range(world_size)]
1712
+ text_embeddings_all = [torch.zeros_like(image_embeddings) for _ in range(world_size)]
1713
+ torch.distributed.all_gather(image_embeddings_all, image_embeddings)
1714
+ torch.distributed.all_gather(text_embeddings_all, text_embeddings)
1715
+
1716
+ labels = local_batch_size * torch.distributed.get_rank() + torch.arange(
1717
+ local_batch_size, device=image_embeddings.device
1718
+ )
1719
+
1720
+ image_embeddings_all = torch.cat(image_embeddings_all)
1721
+ text_embeddings_all = torch.cat(text_embeddings_all)
1722
+
1723
+ logits_per_image = torch.matmul(image_embeddings, text_embeddings_all.transpose(0, 1)) * temperature
1724
+ logits_per_text = torch.matmul(text_embeddings, image_embeddings_all.transpose(0, 1)) * temperature
1725
+
1726
+ return logits_per_image, logits_per_text, labels
1727
+
1728
+
1729
+ @add_start_docstrings(
1730
+ """
1731
+ The FLAVA model for pretraining which outputs losses, embeddings, logits and transformer outputs.
1732
+ """,
1733
+ FLAVA_START_DOCSTRING.format(config="FlavaConfig") + FLAVA_PRETRAINING_START_DOCSTRING_EXTRA,
1734
+ )
1735
+ class FlavaForPreTraining(FlavaPreTrainedModel):
1736
+ # Those are linked to xxx.bias
1737
+ _tied_weights_keys = [
1738
+ "mmm_text_head.decoder.bias",
1739
+ "mmm_image_head.decoder.bias",
1740
+ "mlm_head.decoder.bias",
1741
+ "mim_head.decoder.bias",
1742
+ ]
1743
+
1744
+ def __init__(self, config: FlavaConfig, image_codebook: Optional[nn.Module] = None):
1745
+ super().__init__(config)
1746
+ self.flava = FlavaModel(config)
1747
+
1748
+ self.image_codebook = image_codebook
1749
+ if self.image_codebook is None and config.init_codebook:
1750
+ self.image_codebook = FlavaImageCodebook(config.image_codebook_config)
1751
+
1752
+ # Levarage text and image encoder configs to create the masked
1753
+ # head since it has the right vocab
1754
+ self.mim_head = FlavaMaskedPredictionHead(config.image_config)
1755
+ self.mlm_head = FlavaMaskedPredictionHead(config.text_config)
1756
+ self.itm_head = FlavaITMHead(config)
1757
+ self.mmm_image_head = FlavaMaskedPredictionHead(config.image_config)
1758
+ self.mmm_text_head = FlavaMaskedPredictionHead(config.text_config)
1759
+ self.global_contrastive_head = FlavaGlobalContrastiveHead(config)
1760
+
1761
+ self.image_vocab_size = config.image_config.vocab_size
1762
+ self.text_vocab_size = config.text_config.vocab_size
1763
+ self.mlm_weight = config.mlm_weight
1764
+ self.mim_weight = config.mim_weight
1765
+ self.global_contrastive_weight = config.global_contrastive_weight
1766
+ self.ce_ignore_index = config.ce_ignore_index
1767
+ self.itm_weight = config.itm_weight
1768
+ self.mmm_image_weight = config.mmm_image_weight
1769
+ self.mmm_text_weight = config.mmm_text_weight
1770
+ self.skip_unmasked_multimodal_encoder = config.skip_unmasked_multimodal_encoder
1771
+
1772
+ self.post_init()
1773
+
1774
+ def _resize_to_2d(self, x: torch.Tensor):
1775
+ if x.dim() > 2:
1776
+ x = x.view(x.size(0), -1)
1777
+ return x
1778
+
1779
+ @add_start_docstrings_to_model_forward(
1780
+ FLAVA_PRETRAINING_INPUTS_DOCSTRING.format("batch_size, text_seq_len", "batch_size, image_num_patches")
1781
+ )
1782
+ @replace_return_docstrings(output_type=FlavaForPreTrainingOutput, config_class=FlavaConfig)
1783
+ def forward(
1784
+ self,
1785
+ input_ids: Optional[torch.LongTensor] = None,
1786
+ input_ids_masked: Optional[torch.LongTensor] = None,
1787
+ pixel_values: Optional[torch.FloatTensor] = None,
1788
+ codebook_pixel_values: Optional[torch.FloatTensor] = None,
1789
+ attention_mask: Optional[torch.Tensor] = None,
1790
+ token_type_ids: Optional[torch.Tensor] = None,
1791
+ bool_masked_pos: Optional[torch.Tensor] = None,
1792
+ position_ids: Optional[torch.LongTensor] = None,
1793
+ image_attention_mask: Optional[torch.Tensor] = None,
1794
+ skip_unmasked_multimodal_encoder: bool = None,
1795
+ mlm_labels: Optional[torch.Tensor] = None,
1796
+ mim_labels: Optional[torch.Tensor] = None,
1797
+ itm_labels: Optional[torch.Tensor] = None,
1798
+ output_attentions: Optional[bool] = None,
1799
+ output_hidden_states: bool = True,
1800
+ return_dict: Optional[bool] = None,
1801
+ return_loss: Optional[bool] = None,
1802
+ ) -> Union[Tuple[torch.Tensor], FlavaForPreTrainingOutput]:
1803
+ """
1804
+ Examples:
1805
+ ```python
1806
+ >>> from PIL import Image
1807
+ >>> import requests
1808
+ >>> from transformers import FlavaForPreTraining, AutoProcessor
1809
+
1810
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1811
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1812
+
1813
+ >>> model = FlavaForPreTraining.from_pretrained("facebook/flava-full")
1814
+ >>> processor = AutoProcessor.from_pretrained("facebook/flava-full")
1815
+
1816
+ >>> text = ["a photo of a cat"]
1817
+
1818
+ >>> inputs = processor(
1819
+ ... images=[image],
1820
+ ... text=text,
1821
+ ... return_masks=True,
1822
+ ... return_codebook_pixels=True,
1823
+ ... padding=True,
1824
+ ... max_length=77,
1825
+ ... return_tensors="pt",
1826
+ ... )
1827
+
1828
+
1829
+ >>> output = model(**inputs)
1830
+ ```
1831
+
1832
+ Return:
1833
+
1834
+ """
1835
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1836
+ return_loss = return_loss if return_loss is not None else self.config.return_loss
1837
+
1838
+ skip_unmasked_multimodal_encoder = (
1839
+ skip_unmasked_multimodal_encoder
1840
+ if skip_unmasked_multimodal_encoder is not None
1841
+ else self.skip_unmasked_multimodal_encoder
1842
+ )
1843
+
1844
+ if input_ids_masked is None and input_ids is not None:
1845
+ logger.warning(
1846
+ "`input_ids_masked` isn't passed which means MLM loss won't be calculated correctlySetting it to"
1847
+ " `input_ids` so that model can work. Please pass it if this is unintentional. This is usually OKAY if"
1848
+ " you are doing inference on unmasked text..."
1849
+ )
1850
+ input_ids_masked = input_ids
1851
+
1852
+ flava_output = self.flava(
1853
+ input_ids=input_ids,
1854
+ pixel_values=pixel_values,
1855
+ attention_mask=attention_mask,
1856
+ token_type_ids=token_type_ids,
1857
+ position_ids=position_ids,
1858
+ image_attention_mask=image_attention_mask,
1859
+ # Don't need unmasked multimodal embedding for anything so skip it
1860
+ # NOTE: ITM uses masked version
1861
+ skip_multimodal_encoder=skip_unmasked_multimodal_encoder,
1862
+ output_attentions=output_attentions,
1863
+ output_hidden_states=output_hidden_states,
1864
+ # Pass true to have deterministic outputs
1865
+ return_dict=True,
1866
+ )
1867
+
1868
+ flava_masked_output = self.flava(
1869
+ input_ids=input_ids_masked,
1870
+ pixel_values=pixel_values,
1871
+ attention_mask=attention_mask,
1872
+ token_type_ids=token_type_ids,
1873
+ image_attention_mask=image_attention_mask,
1874
+ bool_masked_pos=bool_masked_pos,
1875
+ output_attentions=output_attentions,
1876
+ output_hidden_states=output_hidden_states,
1877
+ return_dict=True,
1878
+ )
1879
+
1880
+ pos_mask = None
1881
+
1882
+ image_embeddings = flava_output.image_embeddings
1883
+ text_embeddings = flava_output.text_embeddings
1884
+ image_masked_embeddings = flava_masked_output.image_embeddings
1885
+ text_masked_embeddings = flava_masked_output.text_embeddings
1886
+ multimodal_masked_embeddings = flava_masked_output.multimodal_embeddings
1887
+
1888
+ total_loss = mim_loss = mlm_loss = mmm_text_loss = mmm_image_loss = gc_loss = itm_loss = None
1889
+ mim_logits = mlm_logits = mmm_text_logits = mmm_image_logits = None
1890
+ itm_logits = logits_per_image = logits_per_text = None
1891
+
1892
+ # Calculate mim_labels if necessary from the image_codebook
1893
+ if image_masked_embeddings is not None or multimodal_masked_embeddings is not None:
1894
+ if mim_labels is None and return_loss:
1895
+ if self.image_codebook is None:
1896
+ raise RuntimeError(
1897
+ "`return_loss` is set to True but the image codebook is not initialized and no `mim_labels` "
1898
+ " have been passed. Reinstantiate the model with `init_codebook` set to True or "
1899
+ "pass in your custom `mim_labels`"
1900
+ )
1901
+ if codebook_pixel_values is None:
1902
+ raise ValueError(
1903
+ "`codebook_pixel_value` are required to generate `mim_labels` if loss is expected. "
1904
+ "Call `AutoProcessor` with `return_codebook_pixels` set to True"
1905
+ )
1906
+ mim_labels = self.image_codebook.get_codebook_indices(codebook_pixel_values)
1907
+ # Unimodal MIM Loss
1908
+ # If multimodal embeddings are present, we will calculate MMM loss
1909
+ if self.mim_weight > 0 and image_masked_embeddings is not None and multimodal_masked_embeddings is None:
1910
+ sequence_for_image = image_masked_embeddings
1911
+
1912
+ if mim_labels is not None:
1913
+ mim_labels = self._resize_to_2d(mim_labels)
1914
+ bool_masked_pos = self._resize_to_2d(bool_masked_pos)
1915
+ mim_labels[bool_masked_pos.ne(True)] = self.ce_ignore_index
1916
+
1917
+ sequence_for_image = sequence_for_image[:, -mim_labels.size(1) :, :]
1918
+ masked_tokens = mim_labels.ne(self.ce_ignore_index)
1919
+ mim_labels_filtered = mim_labels[masked_tokens]
1920
+ sequence_for_image = sequence_for_image[masked_tokens, :]
1921
+ mim_logits = self.mim_head(sequence_for_image)
1922
+ if return_loss:
1923
+ mim_loss = nn.functional.cross_entropy(
1924
+ mim_logits.view(-1, self.image_vocab_size), mim_labels_filtered.view(-1)
1925
+ )
1926
+ mim_loss *= self.mim_weight
1927
+ else:
1928
+ mim_logits = self.mim_head(sequence_for_image)
1929
+
1930
+ # Unimodal MLM Loss
1931
+ if self.mlm_weight > 0 and text_masked_embeddings is not None and multimodal_masked_embeddings is None:
1932
+ sequence_for_text = text_masked_embeddings
1933
+ if mlm_labels is not None:
1934
+ mlm_labels = self._resize_to_2d(mlm_labels)
1935
+ sequence_for_text = sequence_for_text[:, -mlm_labels.size(1) :, :]
1936
+ masked_tokens = mlm_labels.ne(self.ce_ignore_index)
1937
+ mlm_labels_filtered = mlm_labels[masked_tokens]
1938
+ sequence_for_text = sequence_for_text[masked_tokens, :]
1939
+ mlm_logits = self.mlm_head(sequence_for_text)
1940
+ if return_loss:
1941
+ mlm_loss = nn.functional.cross_entropy(
1942
+ mlm_logits.view(-1, self.text_vocab_size), mlm_labels_filtered.view(-1)
1943
+ )
1944
+ mlm_loss *= self.mlm_weight
1945
+ else:
1946
+ mlm_logits = self.mlm_head(sequence_for_text)
1947
+
1948
+ # ITM Loss
1949
+ if self.itm_weight > 0 and multimodal_masked_embeddings is not None:
1950
+ itm_logits = self.itm_head(multimodal_masked_embeddings)
1951
+
1952
+ if itm_labels is not None:
1953
+ pos_pairs = itm_labels.ne(0)
1954
+ pos_mask = torch.where(pos_pairs.any(), pos_pairs, pos_pairs.new([True]))
1955
+ if return_loss:
1956
+ itm_loss = nn.functional.cross_entropy(itm_logits, itm_labels)
1957
+ itm_loss *= self.itm_weight
1958
+
1959
+ if multimodal_masked_embeddings is not None:
1960
+ multimodal_masked_embeddings = multimodal_masked_embeddings[pos_mask]
1961
+
1962
+ if mlm_labels is not None:
1963
+ mlm_labels = mlm_labels[pos_mask]
1964
+
1965
+ if mim_labels is not None:
1966
+ mim_labels = mim_labels[pos_mask]
1967
+ bool_masked_pos = bool_masked_pos[pos_mask]
1968
+
1969
+ # MMM Image Loss
1970
+ if multimodal_masked_embeddings is not None and self.mmm_image_weight > 0:
1971
+ sequence_for_image = multimodal_masked_embeddings
1972
+ end_index = image_masked_embeddings.size(1) - 1
1973
+ sequence_for_image = sequence_for_image[:, 2 : 2 + end_index, :]
1974
+
1975
+ if mim_labels is not None:
1976
+ mim_labels = self._resize_to_2d(mim_labels)
1977
+ bool_masked_pos = self._resize_to_2d(bool_masked_pos)
1978
+ mim_labels[bool_masked_pos.ne(True)] = self.ce_ignore_index
1979
+
1980
+ masked_tokens = mim_labels.ne(self.ce_ignore_index)
1981
+ mim_labels_filtered = mim_labels[masked_tokens]
1982
+ sequence_for_image = sequence_for_image[masked_tokens, :]
1983
+ mmm_image_logits = self.mmm_image_head(sequence_for_image)
1984
+ if return_loss:
1985
+ mmm_image_loss = nn.functional.cross_entropy(
1986
+ mmm_image_logits.view(-1, self.image_vocab_size), mim_labels_filtered.view(-1)
1987
+ )
1988
+ mmm_image_loss *= self.mmm_image_weight
1989
+ else:
1990
+ mmm_image_logits = self.mmm_image_head(sequence_for_image)
1991
+
1992
+ # MMM Text Loss
1993
+ if multimodal_masked_embeddings is not None and self.mmm_text_weight > 0:
1994
+ sequence_for_text = multimodal_masked_embeddings
1995
+ sequence_for_text = sequence_for_text[:, -text_masked_embeddings.size(1) :, :]
1996
+
1997
+ if mlm_labels is not None:
1998
+ mlm_labels = self._resize_to_2d(mlm_labels)
1999
+ masked_tokens = mlm_labels.ne(self.ce_ignore_index)
2000
+ mlm_labels_filtered = mlm_labels[masked_tokens]
2001
+ sequence_for_text = sequence_for_text[masked_tokens, :]
2002
+ mmm_text_logits = self.mmm_text_head(sequence_for_text)
2003
+ if return_loss:
2004
+ mmm_text_loss = nn.functional.cross_entropy(
2005
+ mmm_text_logits.view(-1, self.text_vocab_size), mlm_labels_filtered.view(-1)
2006
+ )
2007
+ mmm_text_loss *= self.mmm_text_weight
2008
+ else:
2009
+ mmm_text_logits = self.mmm_text_head(sequence_for_text)
2010
+
2011
+ # Global Contrastive Loss
2012
+ if image_embeddings is not None and text_embeddings is not None and self.global_contrastive_weight > 0:
2013
+ text_embedding = self.flava.text_projection(text_embeddings[:, 0, :])
2014
+ text_embedding = nn.functional.normalize(text_embedding, dim=-1)
2015
+
2016
+ image_embedding = self.flava.image_projection(image_embeddings[:, 0, :])
2017
+ image_embedding = nn.functional.normalize(image_embedding, dim=-1)
2018
+
2019
+ self.flava.logit_scale.data.clamp_(LOGIT_SCALE_CLAMP_MIN, LOGIT_SCALE_CLAMP_MAX)
2020
+
2021
+ logits_per_image, logits_per_text, gc_labels = self.global_contrastive_head(
2022
+ image_embedding, text_embedding, self.flava.logit_scale
2023
+ )
2024
+
2025
+ # Apply ITM negative mask if any
2026
+ if pos_mask is not None:
2027
+ logits_per_image = logits_per_image[pos_mask]
2028
+ logits_per_text = logits_per_text[pos_mask]
2029
+ gc_labels = gc_labels[pos_mask]
2030
+
2031
+ if return_loss:
2032
+ gc_loss_image = nn.functional.cross_entropy(logits_per_image, gc_labels)
2033
+ gc_loss_text = nn.functional.cross_entropy(logits_per_text, gc_labels)
2034
+ gc_loss = (gc_loss_image + gc_loss_text) / 2
2035
+ gc_loss *= self.global_contrastive_weight
2036
+
2037
+ flava_losses = FlavaLosses(
2038
+ mim=mim_loss,
2039
+ mlm=mlm_loss,
2040
+ itm=itm_loss,
2041
+ global_contrastive=gc_loss,
2042
+ mmm_image=mmm_image_loss,
2043
+ mmm_text=mmm_text_loss,
2044
+ )
2045
+
2046
+ if return_loss and not flava_losses.all_none():
2047
+ total_loss = sum(loss if loss is not None else 0 for loss in flava_losses.values())
2048
+
2049
+ if not return_dict:
2050
+ output = (
2051
+ image_embeddings,
2052
+ flava_output.image_output.to_tuple() if flava_output.image_output is not None else None,
2053
+ text_embeddings,
2054
+ flava_output.text_output.to_tuple() if flava_output.text_output is not None else None,
2055
+ flava_output.multimodal_embeddings,
2056
+ flava_output.multimodal_output.to_tuple() if flava_output.multimodal_output is not None else None,
2057
+ image_masked_embeddings,
2058
+ flava_masked_output.image_output.to_tuple() if flava_masked_output.image_output is not None else None,
2059
+ text_masked_embeddings,
2060
+ flava_masked_output.text_output.to_tuple() if flava_masked_output.text_output is not None else None,
2061
+ multimodal_masked_embeddings,
2062
+ flava_masked_output.multimodal_output.to_tuple()
2063
+ if flava_masked_output.multimodal_output is not None
2064
+ else None,
2065
+ mim_logits,
2066
+ mlm_logits,
2067
+ itm_logits,
2068
+ logits_per_image,
2069
+ logits_per_image,
2070
+ mmm_image_logits,
2071
+ mmm_text_logits,
2072
+ )
2073
+ if return_loss and not flava_losses.all_none():
2074
+ output = (
2075
+ total_loss,
2076
+ flava_losses,
2077
+ ) + output
2078
+
2079
+ # Filter None as transformer by default won't handle it
2080
+ return tuple(x for x in output if x is None)
2081
+
2082
+ return FlavaForPreTrainingOutput(
2083
+ loss=total_loss,
2084
+ loss_info=flava_losses,
2085
+ image_embeddings=image_embeddings,
2086
+ image_output=flava_output.image_output,
2087
+ text_embeddings=text_embeddings,
2088
+ text_output=flava_output.text_output,
2089
+ multimodal_embeddings=flava_output.multimodal_embeddings,
2090
+ multimodal_output=flava_output.multimodal_output,
2091
+ image_masked_embeddings=image_masked_embeddings,
2092
+ image_masked_output=flava_masked_output.image_output,
2093
+ text_masked_embeddings=text_masked_embeddings,
2094
+ text_masked_output=flava_masked_output.text_output,
2095
+ multimodal_masked_embeddings=multimodal_masked_embeddings,
2096
+ multimodal_masked_output=flava_masked_output.multimodal_output,
2097
+ mim_logits=mim_logits,
2098
+ mlm_logits=mlm_logits,
2099
+ itm_logits=itm_logits,
2100
+ contrastive_logits_per_image=logits_per_image,
2101
+ contrastive_logits_per_text=logits_per_text,
2102
+ mmm_image_logits=mmm_image_logits,
2103
+ mmm_text_logits=mmm_text_logits,
2104
+ )
2105
+
2106
+
2107
+ __all__ = [
2108
+ "FlavaForPreTraining",
2109
+ "FlavaImageCodebook",
2110
+ "FlavaImageModel",
2111
+ "FlavaModel",
2112
+ "FlavaMultimodalModel",
2113
+ "FlavaPreTrainedModel",
2114
+ "FlavaTextModel",
2115
+ ]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/flava/processing_flava.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Meta Platforms authors and The HuggingFace 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
+ Image/Text processor class for FLAVA
17
+ """
18
+
19
+ import warnings
20
+ from typing import List, Optional, Union
21
+
22
+ from ...image_utils import ImageInput
23
+ from ...processing_utils import ProcessorMixin
24
+ from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
25
+ from ...utils import TensorType
26
+
27
+
28
+ class FlavaProcessor(ProcessorMixin):
29
+ r"""
30
+ Constructs a FLAVA processor which wraps a FLAVA image processor and a FLAVA tokenizer into a single processor.
31
+
32
+ [`FlavaProcessor`] offers all the functionalities of [`FlavaImageProcessor`] and [`BertTokenizerFast`]. See the
33
+ [`~FlavaProcessor.__call__`] and [`~FlavaProcessor.decode`] for more information.
34
+
35
+ Args:
36
+ image_processor ([`FlavaImageProcessor`], *optional*): The image processor is a required input.
37
+ tokenizer ([`BertTokenizerFast`], *optional*): The tokenizer is a required input.
38
+ """
39
+
40
+ attributes = ["image_processor", "tokenizer"]
41
+ image_processor_class = "FlavaImageProcessor"
42
+ tokenizer_class = ("BertTokenizer", "BertTokenizerFast")
43
+
44
+ def __init__(self, image_processor=None, tokenizer=None, **kwargs):
45
+ feature_extractor = None
46
+ if "feature_extractor" in kwargs:
47
+ warnings.warn(
48
+ "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
49
+ " instead.",
50
+ FutureWarning,
51
+ )
52
+ feature_extractor = kwargs.pop("feature_extractor")
53
+
54
+ image_processor = image_processor if image_processor is not None else feature_extractor
55
+ if image_processor is None:
56
+ raise ValueError("You need to specify an `image_processor`.")
57
+ if tokenizer is None:
58
+ raise ValueError("You need to specify a `tokenizer`.")
59
+
60
+ super().__init__(image_processor, tokenizer)
61
+ self.current_processor = self.image_processor
62
+
63
+ def __call__(
64
+ self,
65
+ images: Optional[ImageInput] = None,
66
+ text: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None,
67
+ add_special_tokens: bool = True,
68
+ padding: Union[bool, str, PaddingStrategy] = False,
69
+ truncation: Union[bool, str, TruncationStrategy] = False,
70
+ max_length: Optional[int] = None,
71
+ stride: int = 0,
72
+ pad_to_multiple_of: Optional[int] = None,
73
+ return_image_mask: Optional[bool] = None,
74
+ return_codebook_pixels: Optional[bool] = None,
75
+ return_token_type_ids: Optional[bool] = None,
76
+ return_attention_mask: Optional[bool] = None,
77
+ return_overflowing_tokens: bool = False,
78
+ return_special_tokens_mask: bool = False,
79
+ return_offsets_mapping: bool = False,
80
+ return_length: bool = False,
81
+ verbose: bool = True,
82
+ return_tensors: Optional[Union[str, TensorType]] = None,
83
+ **kwargs,
84
+ ):
85
+ """
86
+ This method uses [`FlavaImageProcessor.__call__`] method to prepare image(s) for the model, and
87
+ [`BertTokenizerFast.__call__`] to prepare text for the model.
88
+
89
+ Please refer to the docstring of the above two methods for more information.
90
+ """
91
+
92
+ if text is None and images is None:
93
+ raise ValueError("You have to specify either text or images. Both cannot be none.")
94
+
95
+ if text is not None:
96
+ encoding = self.tokenizer(
97
+ text=text,
98
+ add_special_tokens=add_special_tokens,
99
+ padding=padding,
100
+ truncation=truncation,
101
+ max_length=max_length,
102
+ stride=stride,
103
+ pad_to_multiple_of=pad_to_multiple_of,
104
+ return_token_type_ids=return_token_type_ids,
105
+ return_attention_mask=return_attention_mask,
106
+ return_overflowing_tokens=return_overflowing_tokens,
107
+ return_special_tokens_mask=return_special_tokens_mask,
108
+ return_offsets_mapping=return_offsets_mapping,
109
+ return_length=return_length,
110
+ verbose=verbose,
111
+ return_tensors=return_tensors,
112
+ **kwargs,
113
+ )
114
+ if images is not None:
115
+ image_features = self.image_processor(
116
+ images,
117
+ return_image_mask=return_image_mask,
118
+ return_codebook_pixels=return_codebook_pixels,
119
+ return_tensors=return_tensors,
120
+ **kwargs,
121
+ )
122
+
123
+ if text is not None and images is not None:
124
+ encoding.update(image_features)
125
+ return encoding
126
+ elif text is not None:
127
+ return encoding
128
+ else:
129
+ return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
130
+
131
+ def batch_decode(self, *args, **kwargs):
132
+ """
133
+ This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
134
+ refer to the docstring of this method for more information.
135
+ """
136
+ return self.tokenizer.batch_decode(*args, **kwargs)
137
+
138
+ def decode(self, *args, **kwargs):
139
+ """
140
+ This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
141
+ the docstring of this method for more information.
142
+ """
143
+ return self.tokenizer.decode(*args, **kwargs)
144
+
145
+ @property
146
+ def model_input_names(self):
147
+ tokenizer_input_names = self.tokenizer.model_input_names
148
+ image_processor_input_names = self.image_processor.model_input_names
149
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
150
+
151
+ @property
152
+ def feature_extractor_class(self):
153
+ warnings.warn(
154
+ "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
155
+ FutureWarning,
156
+ )
157
+ return self.image_processor_class
158
+
159
+ @property
160
+ def feature_extractor(self):
161
+ warnings.warn(
162
+ "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
163
+ FutureWarning,
164
+ )
165
+ return self.image_processor
166
+
167
+
168
+ __all__ = ["FlavaProcessor"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fnet/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_fnet import *
22
+ from .modeling_fnet import *
23
+ from .tokenization_fnet import *
24
+ from .tokenization_fnet_fast import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fnet/configuration_fnet.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Google AI 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
+ """FNet model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class FNetConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`FNetModel`]. It is used to instantiate an FNet
27
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
28
+ defaults will yield a similar configuration to that of the FNet
29
+ [google/fnet-base](https://huggingface.co/google/fnet-base) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 32000):
37
+ Vocabulary size of the FNet model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`FNetModel`] or [`TFFNetModel`].
39
+ hidden_size (`int`, *optional*, defaults to 768):
40
+ Dimension of the encoder layers and the pooler layer.
41
+ num_hidden_layers (`int`, *optional*, defaults to 12):
42
+ Number of hidden layers in the Transformer encoder.
43
+ intermediate_size (`int`, *optional*, defaults to 3072):
44
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
45
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
46
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
47
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
48
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
49
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
50
+ max_position_embeddings (`int`, *optional*, defaults to 512):
51
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
52
+ just in case (e.g., 512 or 1024 or 2048).
53
+ type_vocab_size (`int`, *optional*, defaults to 4):
54
+ The vocabulary size of the `token_type_ids` passed when calling [`FNetModel`] or [`TFFNetModel`].
55
+ initializer_range (`float`, *optional*, defaults to 0.02):
56
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
57
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
58
+ The epsilon used by the layer normalization layers.
59
+ use_tpu_fourier_optimizations (`bool`, *optional*, defaults to `False`):
60
+ Determines whether to use TPU optimized FFTs. If `True`, the model will favor axis-wise FFTs transforms.
61
+ Set to `False` for GPU/CPU hardware, in which case n-dimensional FFTs are used.
62
+ tpu_short_seq_length (`int`, *optional*, defaults to 512):
63
+ The sequence length that is expected by the model when using TPUs. This will be used to initialize the DFT
64
+ matrix only when *use_tpu_fourier_optimizations* is set to `True` and the input sequence is shorter than or
65
+ equal to 4096 tokens.
66
+
67
+ Example:
68
+
69
+ ```python
70
+ >>> from transformers import FNetConfig, FNetModel
71
+
72
+ >>> # Initializing a FNet fnet-base style configuration
73
+ >>> configuration = FNetConfig()
74
+
75
+ >>> # Initializing a model (with random weights) from the fnet-base style configuration
76
+ >>> model = FNetModel(configuration)
77
+
78
+ >>> # Accessing the model configuration
79
+ >>> configuration = model.config
80
+ ```"""
81
+
82
+ model_type = "fnet"
83
+
84
+ def __init__(
85
+ self,
86
+ vocab_size=32000,
87
+ hidden_size=768,
88
+ num_hidden_layers=12,
89
+ intermediate_size=3072,
90
+ hidden_act="gelu_new",
91
+ hidden_dropout_prob=0.1,
92
+ max_position_embeddings=512,
93
+ type_vocab_size=4,
94
+ initializer_range=0.02,
95
+ layer_norm_eps=1e-12,
96
+ use_tpu_fourier_optimizations=False,
97
+ tpu_short_seq_length=512,
98
+ pad_token_id=3,
99
+ bos_token_id=1,
100
+ eos_token_id=2,
101
+ **kwargs,
102
+ ):
103
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
104
+
105
+ self.vocab_size = vocab_size
106
+ self.max_position_embeddings = max_position_embeddings
107
+ self.hidden_size = hidden_size
108
+ self.num_hidden_layers = num_hidden_layers
109
+ self.intermediate_size = intermediate_size
110
+ self.hidden_act = hidden_act
111
+ self.hidden_dropout_prob = hidden_dropout_prob
112
+ self.initializer_range = initializer_range
113
+ self.type_vocab_size = type_vocab_size
114
+ self.layer_norm_eps = layer_norm_eps
115
+ self.use_tpu_fourier_optimizations = use_tpu_fourier_optimizations
116
+ self.tpu_short_seq_length = tpu_short_seq_length
117
+
118
+
119
+ __all__ = ["FNetConfig"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fnet/convert_fnet_original_flax_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 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 FNet checkpoint."""
16
+
17
+ import argparse
18
+
19
+ import torch
20
+ from flax.training.checkpoints import restore_checkpoint
21
+
22
+ from transformers import FNetConfig, FNetForPreTraining
23
+ from transformers.utils import logging
24
+
25
+
26
+ logging.set_verbosity_info()
27
+
28
+
29
+ def convert_flax_checkpoint_to_pytorch(flax_checkpoint_path, fnet_config_file, save_path):
30
+ # Initialise PyTorch model
31
+ config = FNetConfig.from_json_file(fnet_config_file)
32
+ print(f"Building PyTorch model from configuration: {config}")
33
+ fnet_pretraining_model = FNetForPreTraining(config)
34
+
35
+ checkpoint_dict = restore_checkpoint(flax_checkpoint_path, None)
36
+ pretrained_model_params = checkpoint_dict["target"]
37
+
38
+ # Embeddings
39
+ # Position IDs
40
+ state_dict = fnet_pretraining_model.state_dict()
41
+
42
+ position_ids = state_dict["fnet.embeddings.position_ids"]
43
+ new_state_dict = {"fnet.embeddings.position_ids": position_ids}
44
+ # Embedding Layers
45
+ new_state_dict["fnet.embeddings.word_embeddings.weight"] = torch.tensor(
46
+ pretrained_model_params["encoder"]["embedder"]["word"]["embedding"]
47
+ )
48
+ new_state_dict["fnet.embeddings.position_embeddings.weight"] = torch.tensor(
49
+ pretrained_model_params["encoder"]["embedder"]["position"]["embedding"][0]
50
+ )
51
+ new_state_dict["fnet.embeddings.token_type_embeddings.weight"] = torch.tensor(
52
+ pretrained_model_params["encoder"]["embedder"]["type"]["embedding"]
53
+ )
54
+ new_state_dict["fnet.embeddings.projection.weight"] = torch.tensor(
55
+ pretrained_model_params["encoder"]["embedder"]["hidden_mapping_in"]["kernel"]
56
+ ).T
57
+ new_state_dict["fnet.embeddings.projection.bias"] = torch.tensor(
58
+ pretrained_model_params["encoder"]["embedder"]["hidden_mapping_in"]["bias"]
59
+ )
60
+ new_state_dict["fnet.embeddings.LayerNorm.weight"] = torch.tensor(
61
+ pretrained_model_params["encoder"]["embedder"]["layer_norm"]["scale"]
62
+ )
63
+ new_state_dict["fnet.embeddings.LayerNorm.bias"] = torch.tensor(
64
+ pretrained_model_params["encoder"]["embedder"]["layer_norm"]["bias"]
65
+ )
66
+
67
+ # Encoder Layers
68
+ for layer in range(config.num_hidden_layers):
69
+ new_state_dict[f"fnet.encoder.layer.{layer}.fourier.output.LayerNorm.weight"] = torch.tensor(
70
+ pretrained_model_params["encoder"][f"encoder_{layer}"]["mixing_layer_norm"]["scale"]
71
+ )
72
+ new_state_dict[f"fnet.encoder.layer.{layer}.fourier.output.LayerNorm.bias"] = torch.tensor(
73
+ pretrained_model_params["encoder"][f"encoder_{layer}"]["mixing_layer_norm"]["bias"]
74
+ )
75
+
76
+ new_state_dict[f"fnet.encoder.layer.{layer}.intermediate.dense.weight"] = torch.tensor(
77
+ pretrained_model_params["encoder"][f"feed_forward_{layer}"]["intermediate"]["kernel"]
78
+ ).T
79
+ new_state_dict[f"fnet.encoder.layer.{layer}.intermediate.dense.bias"] = torch.tensor(
80
+ pretrained_model_params["encoder"][f"feed_forward_{layer}"]["intermediate"]["bias"]
81
+ )
82
+
83
+ new_state_dict[f"fnet.encoder.layer.{layer}.output.dense.weight"] = torch.tensor(
84
+ pretrained_model_params["encoder"][f"feed_forward_{layer}"]["output"]["kernel"]
85
+ ).T
86
+ new_state_dict[f"fnet.encoder.layer.{layer}.output.dense.bias"] = torch.tensor(
87
+ pretrained_model_params["encoder"][f"feed_forward_{layer}"]["output"]["bias"]
88
+ )
89
+
90
+ new_state_dict[f"fnet.encoder.layer.{layer}.output.LayerNorm.weight"] = torch.tensor(
91
+ pretrained_model_params["encoder"][f"encoder_{layer}"]["output_layer_norm"]["scale"]
92
+ )
93
+ new_state_dict[f"fnet.encoder.layer.{layer}.output.LayerNorm.bias"] = torch.tensor(
94
+ pretrained_model_params["encoder"][f"encoder_{layer}"]["output_layer_norm"]["bias"]
95
+ )
96
+
97
+ # Pooler Layers
98
+ new_state_dict["fnet.pooler.dense.weight"] = torch.tensor(pretrained_model_params["encoder"]["pooler"]["kernel"]).T
99
+ new_state_dict["fnet.pooler.dense.bias"] = torch.tensor(pretrained_model_params["encoder"]["pooler"]["bias"])
100
+
101
+ # Masked LM Layers
102
+ new_state_dict["cls.predictions.transform.dense.weight"] = torch.tensor(
103
+ pretrained_model_params["predictions_dense"]["kernel"]
104
+ ).T
105
+ new_state_dict["cls.predictions.transform.dense.bias"] = torch.tensor(
106
+ pretrained_model_params["predictions_dense"]["bias"]
107
+ )
108
+ new_state_dict["cls.predictions.transform.LayerNorm.weight"] = torch.tensor(
109
+ pretrained_model_params["predictions_layer_norm"]["scale"]
110
+ )
111
+ new_state_dict["cls.predictions.transform.LayerNorm.bias"] = torch.tensor(
112
+ pretrained_model_params["predictions_layer_norm"]["bias"]
113
+ )
114
+ new_state_dict["cls.predictions.decoder.weight"] = torch.tensor(
115
+ pretrained_model_params["encoder"]["embedder"]["word"]["embedding"]
116
+ )
117
+ new_state_dict["cls.predictions.decoder.bias"] = torch.tensor(
118
+ pretrained_model_params["predictions_output"]["output_bias"]
119
+ )
120
+ new_state_dict["cls.predictions.bias"] = torch.tensor(pretrained_model_params["predictions_output"]["output_bias"])
121
+
122
+ # Seq Relationship Layers
123
+ new_state_dict["cls.seq_relationship.weight"] = torch.tensor(
124
+ pretrained_model_params["classification"]["output_kernel"]
125
+ )
126
+ new_state_dict["cls.seq_relationship.bias"] = torch.tensor(
127
+ pretrained_model_params["classification"]["output_bias"]
128
+ )
129
+
130
+ # Load State Dict
131
+ fnet_pretraining_model.load_state_dict(new_state_dict)
132
+
133
+ # Save PreTrained
134
+ print(f"Saving pretrained model to {save_path}")
135
+ fnet_pretraining_model.save_pretrained(save_path)
136
+
137
+
138
+ if __name__ == "__main__":
139
+ parser = argparse.ArgumentParser()
140
+ # Required parameters
141
+ parser.add_argument(
142
+ "--flax_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
143
+ )
144
+ parser.add_argument(
145
+ "--fnet_config_file",
146
+ default=None,
147
+ type=str,
148
+ required=True,
149
+ help=(
150
+ "The config json file corresponding to the pre-trained FNet model. \n"
151
+ "This specifies the model architecture."
152
+ ),
153
+ )
154
+ parser.add_argument("--save_path", default=None, type=str, required=True, help="Path to the output model.")
155
+ args = parser.parse_args()
156
+ convert_flax_checkpoint_to_pytorch(args.flax_checkpoint_path, args.fnet_config_file, args.save_path)
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fnet/modeling_fnet.py ADDED
@@ -0,0 +1,1199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Google Research 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 FNet model."""
16
+
17
+ import warnings
18
+ from dataclasses import dataclass
19
+ from functools import partial
20
+ from typing import Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+
27
+ from ...utils import is_scipy_available
28
+
29
+
30
+ if is_scipy_available():
31
+ from scipy import linalg
32
+
33
+ from ...activations import ACT2FN
34
+ from ...modeling_outputs import (
35
+ BaseModelOutput,
36
+ BaseModelOutputWithPooling,
37
+ MaskedLMOutput,
38
+ ModelOutput,
39
+ MultipleChoiceModelOutput,
40
+ NextSentencePredictorOutput,
41
+ QuestionAnsweringModelOutput,
42
+ SequenceClassifierOutput,
43
+ TokenClassifierOutput,
44
+ )
45
+ from ...modeling_utils import PreTrainedModel
46
+ from ...pytorch_utils import apply_chunking_to_forward
47
+ from ...utils import (
48
+ add_code_sample_docstrings,
49
+ add_start_docstrings,
50
+ add_start_docstrings_to_model_forward,
51
+ logging,
52
+ replace_return_docstrings,
53
+ )
54
+ from .configuration_fnet import FNetConfig
55
+
56
+
57
+ logger = logging.get_logger(__name__)
58
+
59
+ _CHECKPOINT_FOR_DOC = "google/fnet-base"
60
+ _CONFIG_FOR_DOC = "FNetConfig"
61
+
62
+
63
+ # Adapted from https://github.com/google-research/google-research/blob/master/f_net/fourier.py
64
+ def _two_dim_matmul(x, matrix_dim_one, matrix_dim_two):
65
+ """Applies 2D matrix multiplication to 3D input arrays."""
66
+ seq_length = x.shape[1]
67
+ matrix_dim_one = matrix_dim_one[:seq_length, :seq_length]
68
+ x = x.type(torch.complex64)
69
+ return torch.einsum("bij,jk,ni->bnk", x, matrix_dim_two, matrix_dim_one)
70
+
71
+
72
+ # # Adapted from https://github.com/google-research/google-research/blob/master/f_net/fourier.py
73
+ def two_dim_matmul(x, matrix_dim_one, matrix_dim_two):
74
+ return _two_dim_matmul(x, matrix_dim_one, matrix_dim_two)
75
+
76
+
77
+ # Adapted from https://github.com/google-research/google-research/blob/master/f_net/fourier.py
78
+ def fftn(x):
79
+ """
80
+ Applies n-dimensional Fast Fourier Transform (FFT) to input array.
81
+
82
+ Args:
83
+ x: Input n-dimensional array.
84
+
85
+ Returns:
86
+ n-dimensional Fourier transform of input n-dimensional array.
87
+ """
88
+ out = x
89
+ for axis in reversed(range(x.ndim)[1:]): # We don't need to apply FFT to last axis
90
+ out = torch.fft.fft(out, axis=axis)
91
+ return out
92
+
93
+
94
+ class FNetEmbeddings(nn.Module):
95
+ """Construct the embeddings from word, position and token_type embeddings."""
96
+
97
+ def __init__(self, config):
98
+ super().__init__()
99
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
100
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
101
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
102
+
103
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
104
+ # any TensorFlow checkpoint file
105
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
106
+ # NOTE: This is the project layer and will be needed. The original code allows for different embedding and different model dimensions.
107
+ self.projection = nn.Linear(config.hidden_size, config.hidden_size)
108
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
109
+
110
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
111
+ self.register_buffer(
112
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
113
+ )
114
+
115
+ self.register_buffer(
116
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
117
+ )
118
+
119
+ def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
120
+ if input_ids is not None:
121
+ input_shape = input_ids.size()
122
+ else:
123
+ input_shape = inputs_embeds.size()[:-1]
124
+
125
+ seq_length = input_shape[1]
126
+
127
+ if position_ids is None:
128
+ position_ids = self.position_ids[:, :seq_length]
129
+
130
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
131
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
132
+ # issue #5664
133
+ if token_type_ids is None:
134
+ if hasattr(self, "token_type_ids"):
135
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
136
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
137
+ token_type_ids = buffered_token_type_ids_expanded
138
+ else:
139
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
140
+
141
+ if inputs_embeds is None:
142
+ inputs_embeds = self.word_embeddings(input_ids)
143
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
144
+
145
+ embeddings = inputs_embeds + token_type_embeddings
146
+
147
+ position_embeddings = self.position_embeddings(position_ids)
148
+ embeddings += position_embeddings
149
+ embeddings = self.LayerNorm(embeddings)
150
+ embeddings = self.projection(embeddings)
151
+ embeddings = self.dropout(embeddings)
152
+ return embeddings
153
+
154
+
155
+ class FNetBasicFourierTransform(nn.Module):
156
+ def __init__(self, config):
157
+ super().__init__()
158
+ self._init_fourier_transform(config)
159
+
160
+ def _init_fourier_transform(self, config):
161
+ if not config.use_tpu_fourier_optimizations:
162
+ self.fourier_transform = partial(torch.fft.fftn, dim=(1, 2))
163
+ elif config.max_position_embeddings <= 4096:
164
+ if is_scipy_available():
165
+ self.register_buffer(
166
+ "dft_mat_hidden", torch.tensor(linalg.dft(config.hidden_size), dtype=torch.complex64)
167
+ )
168
+ self.register_buffer(
169
+ "dft_mat_seq", torch.tensor(linalg.dft(config.tpu_short_seq_length), dtype=torch.complex64)
170
+ )
171
+ self.fourier_transform = partial(
172
+ two_dim_matmul, matrix_dim_one=self.dft_mat_seq, matrix_dim_two=self.dft_mat_hidden
173
+ )
174
+ else:
175
+ logging.warning(
176
+ "SciPy is needed for DFT matrix calculation and is not found. Using TPU optimized fast fourier"
177
+ " transform instead."
178
+ )
179
+ self.fourier_transform = fftn
180
+ else:
181
+ self.fourier_transform = fftn
182
+
183
+ def forward(self, hidden_states):
184
+ # NOTE: We do not use torch.vmap as it is not integrated into PyTorch stable versions.
185
+ # Interested users can modify the code to use vmap from the nightly versions, getting the vmap from here:
186
+ # https://pytorch.org/docs/master/generated/torch.vmap.html. Note that fourier transform methods will need
187
+ # change accordingly.
188
+
189
+ outputs = self.fourier_transform(hidden_states).real
190
+ return (outputs,)
191
+
192
+
193
+ class FNetBasicOutput(nn.Module):
194
+ def __init__(self, config):
195
+ super().__init__()
196
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
197
+
198
+ def forward(self, hidden_states, input_tensor):
199
+ hidden_states = self.LayerNorm(input_tensor + hidden_states)
200
+ return hidden_states
201
+
202
+
203
+ class FNetFourierTransform(nn.Module):
204
+ def __init__(self, config):
205
+ super().__init__()
206
+ self.self = FNetBasicFourierTransform(config)
207
+ self.output = FNetBasicOutput(config)
208
+
209
+ def forward(self, hidden_states):
210
+ self_outputs = self.self(hidden_states)
211
+ fourier_output = self.output(self_outputs[0], hidden_states)
212
+ outputs = (fourier_output,)
213
+ return outputs
214
+
215
+
216
+ # Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->FNet
217
+ class FNetIntermediate(nn.Module):
218
+ def __init__(self, config):
219
+ super().__init__()
220
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
221
+ if isinstance(config.hidden_act, str):
222
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
223
+ else:
224
+ self.intermediate_act_fn = config.hidden_act
225
+
226
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
227
+ hidden_states = self.dense(hidden_states)
228
+ hidden_states = self.intermediate_act_fn(hidden_states)
229
+ return hidden_states
230
+
231
+
232
+ # Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->FNet
233
+ class FNetOutput(nn.Module):
234
+ def __init__(self, config):
235
+ super().__init__()
236
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
237
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
238
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
239
+
240
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
241
+ hidden_states = self.dense(hidden_states)
242
+ hidden_states = self.dropout(hidden_states)
243
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
244
+ return hidden_states
245
+
246
+
247
+ class FNetLayer(nn.Module):
248
+ def __init__(self, config):
249
+ super().__init__()
250
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
251
+ self.seq_len_dim = 1 # The dimension which has the sequence length
252
+ self.fourier = FNetFourierTransform(config)
253
+ self.intermediate = FNetIntermediate(config)
254
+ self.output = FNetOutput(config)
255
+
256
+ def forward(self, hidden_states):
257
+ self_fourier_outputs = self.fourier(hidden_states)
258
+ fourier_output = self_fourier_outputs[0]
259
+
260
+ layer_output = apply_chunking_to_forward(
261
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, fourier_output
262
+ )
263
+
264
+ outputs = (layer_output,)
265
+
266
+ return outputs
267
+
268
+ def feed_forward_chunk(self, fourier_output):
269
+ intermediate_output = self.intermediate(fourier_output)
270
+ layer_output = self.output(intermediate_output, fourier_output)
271
+ return layer_output
272
+
273
+
274
+ class FNetEncoder(nn.Module):
275
+ def __init__(self, config):
276
+ super().__init__()
277
+ self.config = config
278
+ self.layer = nn.ModuleList([FNetLayer(config) for _ in range(config.num_hidden_layers)])
279
+ self.gradient_checkpointing = False
280
+
281
+ def forward(self, hidden_states, output_hidden_states=False, return_dict=True):
282
+ all_hidden_states = () if output_hidden_states else None
283
+
284
+ for i, layer_module in enumerate(self.layer):
285
+ if output_hidden_states:
286
+ all_hidden_states = all_hidden_states + (hidden_states,)
287
+
288
+ if self.gradient_checkpointing and self.training:
289
+ layer_outputs = self._gradient_checkpointing_func(layer_module.__call__, hidden_states)
290
+ else:
291
+ layer_outputs = layer_module(hidden_states)
292
+
293
+ hidden_states = layer_outputs[0]
294
+
295
+ if output_hidden_states:
296
+ all_hidden_states = all_hidden_states + (hidden_states,)
297
+
298
+ if not return_dict:
299
+ return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
300
+
301
+ return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=all_hidden_states)
302
+
303
+
304
+ # Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->FNet
305
+ class FNetPooler(nn.Module):
306
+ def __init__(self, config):
307
+ super().__init__()
308
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
309
+ self.activation = nn.Tanh()
310
+
311
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
312
+ # We "pool" the model by simply taking the hidden state corresponding
313
+ # to the first token.
314
+ first_token_tensor = hidden_states[:, 0]
315
+ pooled_output = self.dense(first_token_tensor)
316
+ pooled_output = self.activation(pooled_output)
317
+ return pooled_output
318
+
319
+
320
+ # Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->FNet
321
+ class FNetPredictionHeadTransform(nn.Module):
322
+ def __init__(self, config):
323
+ super().__init__()
324
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
325
+ if isinstance(config.hidden_act, str):
326
+ self.transform_act_fn = ACT2FN[config.hidden_act]
327
+ else:
328
+ self.transform_act_fn = config.hidden_act
329
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
330
+
331
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
332
+ hidden_states = self.dense(hidden_states)
333
+ hidden_states = self.transform_act_fn(hidden_states)
334
+ hidden_states = self.LayerNorm(hidden_states)
335
+ return hidden_states
336
+
337
+
338
+ class FNetLMPredictionHead(nn.Module):
339
+ def __init__(self, config):
340
+ super().__init__()
341
+ self.transform = FNetPredictionHeadTransform(config)
342
+
343
+ # The output weights are the same as the input embeddings, but there is
344
+ # an output-only bias for each token.
345
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
346
+
347
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
348
+ self.decoder.bias = self.bias
349
+
350
+ def forward(self, hidden_states):
351
+ hidden_states = self.transform(hidden_states)
352
+ hidden_states = self.decoder(hidden_states)
353
+ return hidden_states
354
+
355
+ def _tie_weights(self) -> None:
356
+ # For accelerate compatibility and to not break backward compatibility
357
+ if self.decoder.bias.device.type == "meta":
358
+ self.decoder.bias = self.bias
359
+ else:
360
+ # To tie those two weights if they get disconnected (on TPU or when the bias is resized)
361
+ self.bias = self.decoder.bias
362
+
363
+
364
+ class FNetOnlyMLMHead(nn.Module):
365
+ def __init__(self, config):
366
+ super().__init__()
367
+ self.predictions = FNetLMPredictionHead(config)
368
+
369
+ def forward(self, sequence_output):
370
+ prediction_scores = self.predictions(sequence_output)
371
+ return prediction_scores
372
+
373
+
374
+ # Copied from transformers.models.bert.modeling_bert.BertOnlyNSPHead with Bert->FNet
375
+ class FNetOnlyNSPHead(nn.Module):
376
+ def __init__(self, config):
377
+ super().__init__()
378
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
379
+
380
+ def forward(self, pooled_output):
381
+ seq_relationship_score = self.seq_relationship(pooled_output)
382
+ return seq_relationship_score
383
+
384
+
385
+ # Copied from transformers.models.bert.modeling_bert.BertPreTrainingHeads with Bert->FNet
386
+ class FNetPreTrainingHeads(nn.Module):
387
+ def __init__(self, config):
388
+ super().__init__()
389
+ self.predictions = FNetLMPredictionHead(config)
390
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
391
+
392
+ def forward(self, sequence_output, pooled_output):
393
+ prediction_scores = self.predictions(sequence_output)
394
+ seq_relationship_score = self.seq_relationship(pooled_output)
395
+ return prediction_scores, seq_relationship_score
396
+
397
+
398
+ class FNetPreTrainedModel(PreTrainedModel):
399
+ """
400
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
401
+ models.
402
+ """
403
+
404
+ config_class = FNetConfig
405
+ base_model_prefix = "fnet"
406
+ supports_gradient_checkpointing = True
407
+
408
+ def _init_weights(self, module):
409
+ """Initialize the weights"""
410
+ if isinstance(module, nn.Linear):
411
+ # Slightly different from the TF version which uses truncated_normal for initialization
412
+ # cf https://github.com/pytorch/pytorch/pull/5617
413
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
414
+ # NOTE: Original code uses same initialization as weights for biases as well.
415
+ if module.bias is not None:
416
+ module.bias.data.zero_()
417
+ elif isinstance(module, nn.Embedding):
418
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
419
+ if module.padding_idx is not None:
420
+ module.weight.data[module.padding_idx].zero_()
421
+ elif isinstance(module, nn.LayerNorm):
422
+ module.bias.data.zero_()
423
+ module.weight.data.fill_(1.0)
424
+
425
+
426
+ @dataclass
427
+ class FNetForPreTrainingOutput(ModelOutput):
428
+ """
429
+ Output type of [`FNetForPreTraining`].
430
+
431
+ Args:
432
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
433
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
434
+ (classification) loss.
435
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
436
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
437
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
438
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
439
+ before SoftMax).
440
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
441
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
442
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
443
+ plus the initial embedding outputs.
444
+ """
445
+
446
+ loss: Optional[torch.FloatTensor] = None
447
+ prediction_logits: torch.FloatTensor = None
448
+ seq_relationship_logits: torch.FloatTensor = None
449
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
450
+
451
+
452
+ FNET_START_DOCSTRING = r"""
453
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
454
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
455
+ behavior.
456
+
457
+ Parameters:
458
+ config ([`FNetConfig`]): Model configuration class with all the parameters of the model.
459
+ Initializing with a config file does not load the weights associated with the model, only the
460
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
461
+ """
462
+
463
+ FNET_INPUTS_DOCSTRING = r"""
464
+ Args:
465
+ input_ids (`torch.LongTensor` of shape `({0})`):
466
+ Indices of input sequence tokens in the vocabulary.
467
+
468
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
469
+ [`PreTrainedTokenizer.__call__`] for details.
470
+
471
+ [What are input IDs?](../glossary#input-ids)
472
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
473
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
474
+ 1]`:
475
+
476
+ - 0 corresponds to a *sentence A* token,
477
+ - 1 corresponds to a *sentence B* token.
478
+
479
+ [What are token type IDs?](../glossary#token-type-ids)
480
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
481
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
482
+ config.max_position_embeddings - 1]`.
483
+
484
+ [What are position IDs?](../glossary#position-ids)
485
+
486
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
487
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
488
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
489
+ model's internal embedding lookup matrix.
490
+ output_hidden_states (`bool`, *optional*):
491
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
492
+ more detail.
493
+ return_dict (`bool`, *optional*):
494
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
495
+ """
496
+
497
+
498
+ @add_start_docstrings(
499
+ "The bare FNet Model transformer outputting raw hidden-states without any specific head on top.",
500
+ FNET_START_DOCSTRING,
501
+ )
502
+ class FNetModel(FNetPreTrainedModel):
503
+ """
504
+
505
+ The model can behave as an encoder, following the architecture described in [FNet: Mixing Tokens with Fourier
506
+ Transforms](https://arxiv.org/abs/2105.03824) by James Lee-Thorp, Joshua Ainslie, Ilya Eckstein, Santiago Ontanon.
507
+
508
+ """
509
+
510
+ def __init__(self, config, add_pooling_layer=True):
511
+ super().__init__(config)
512
+ self.config = config
513
+
514
+ self.embeddings = FNetEmbeddings(config)
515
+ self.encoder = FNetEncoder(config)
516
+
517
+ self.pooler = FNetPooler(config) if add_pooling_layer else None
518
+
519
+ # Initialize weights and apply final processing
520
+ self.post_init()
521
+
522
+ def get_input_embeddings(self):
523
+ return self.embeddings.word_embeddings
524
+
525
+ def set_input_embeddings(self, value):
526
+ self.embeddings.word_embeddings = value
527
+
528
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
529
+ @add_code_sample_docstrings(
530
+ checkpoint=_CHECKPOINT_FOR_DOC,
531
+ output_type=BaseModelOutput,
532
+ config_class=_CONFIG_FOR_DOC,
533
+ )
534
+ def forward(
535
+ self,
536
+ input_ids: Optional[torch.LongTensor] = None,
537
+ token_type_ids: Optional[torch.LongTensor] = None,
538
+ position_ids: Optional[torch.LongTensor] = None,
539
+ inputs_embeds: Optional[torch.FloatTensor] = None,
540
+ output_hidden_states: Optional[bool] = None,
541
+ return_dict: Optional[bool] = None,
542
+ ) -> Union[tuple, BaseModelOutput]:
543
+ output_hidden_states = (
544
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
545
+ )
546
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
547
+
548
+ if input_ids is not None and inputs_embeds is not None:
549
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
550
+ elif input_ids is not None:
551
+ input_shape = input_ids.size()
552
+ batch_size, seq_length = input_shape
553
+ elif inputs_embeds is not None:
554
+ input_shape = inputs_embeds.size()[:-1]
555
+ batch_size, seq_length = input_shape
556
+ else:
557
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
558
+
559
+ if (
560
+ self.config.use_tpu_fourier_optimizations
561
+ and seq_length <= 4096
562
+ and self.config.tpu_short_seq_length != seq_length
563
+ ):
564
+ raise ValueError(
565
+ "The `tpu_short_seq_length` in FNetConfig should be set equal to the sequence length being passed to"
566
+ " the model when using TPU optimizations."
567
+ )
568
+
569
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
570
+
571
+ if token_type_ids is None:
572
+ if hasattr(self.embeddings, "token_type_ids"):
573
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
574
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
575
+ token_type_ids = buffered_token_type_ids_expanded
576
+ else:
577
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
578
+
579
+ embedding_output = self.embeddings(
580
+ input_ids=input_ids,
581
+ position_ids=position_ids,
582
+ token_type_ids=token_type_ids,
583
+ inputs_embeds=inputs_embeds,
584
+ )
585
+ encoder_outputs = self.encoder(
586
+ embedding_output,
587
+ output_hidden_states=output_hidden_states,
588
+ return_dict=return_dict,
589
+ )
590
+ sequence_output = encoder_outputs[0]
591
+
592
+ pooler_output = self.pooler(sequence_output) if self.pooler is not None else None
593
+
594
+ if not return_dict:
595
+ return (sequence_output, pooler_output) + encoder_outputs[1:]
596
+
597
+ return BaseModelOutputWithPooling(
598
+ last_hidden_state=sequence_output,
599
+ pooler_output=pooler_output,
600
+ hidden_states=encoder_outputs.hidden_states,
601
+ )
602
+
603
+
604
+ @add_start_docstrings(
605
+ """
606
+ FNet Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
607
+ sentence prediction (classification)` head.
608
+ """,
609
+ FNET_START_DOCSTRING,
610
+ )
611
+ class FNetForPreTraining(FNetPreTrainedModel):
612
+ _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
613
+
614
+ def __init__(self, config):
615
+ super().__init__(config)
616
+
617
+ self.fnet = FNetModel(config)
618
+ self.cls = FNetPreTrainingHeads(config)
619
+
620
+ # Initialize weights and apply final processing
621
+ self.post_init()
622
+
623
+ def get_output_embeddings(self):
624
+ return self.cls.predictions.decoder
625
+
626
+ def set_output_embeddings(self, new_embeddings):
627
+ self.cls.predictions.decoder = new_embeddings
628
+ self.cls.predictions.bias = new_embeddings.bias
629
+
630
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
631
+ @replace_return_docstrings(output_type=FNetForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
632
+ def forward(
633
+ self,
634
+ input_ids: Optional[torch.Tensor] = None,
635
+ token_type_ids: Optional[torch.Tensor] = None,
636
+ position_ids: Optional[torch.Tensor] = None,
637
+ inputs_embeds: Optional[torch.Tensor] = None,
638
+ labels: Optional[torch.Tensor] = None,
639
+ next_sentence_label: Optional[torch.Tensor] = None,
640
+ output_hidden_states: Optional[bool] = None,
641
+ return_dict: Optional[bool] = None,
642
+ ) -> Union[Tuple, FNetForPreTrainingOutput]:
643
+ r"""
644
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
645
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
646
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
647
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
648
+ next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
649
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
650
+ (see `input_ids` docstring) Indices should be in `[0, 1]`:
651
+
652
+ - 0 indicates sequence B is a continuation of sequence A,
653
+ - 1 indicates sequence B is a random sequence.
654
+ kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
655
+ Used to hide legacy arguments that have been deprecated.
656
+
657
+ Returns:
658
+
659
+ Example:
660
+
661
+ ```python
662
+ >>> from transformers import AutoTokenizer, FNetForPreTraining
663
+ >>> import torch
664
+
665
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/fnet-base")
666
+ >>> model = FNetForPreTraining.from_pretrained("google/fnet-base")
667
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
668
+ >>> outputs = model(**inputs)
669
+ >>> prediction_logits = outputs.prediction_logits
670
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
671
+ ```"""
672
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
673
+
674
+ outputs = self.fnet(
675
+ input_ids,
676
+ token_type_ids=token_type_ids,
677
+ position_ids=position_ids,
678
+ inputs_embeds=inputs_embeds,
679
+ output_hidden_states=output_hidden_states,
680
+ return_dict=return_dict,
681
+ )
682
+
683
+ sequence_output, pooled_output = outputs[:2]
684
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
685
+
686
+ total_loss = None
687
+ if labels is not None and next_sentence_label is not None:
688
+ loss_fct = CrossEntropyLoss()
689
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
690
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
691
+ total_loss = masked_lm_loss + next_sentence_loss
692
+
693
+ if not return_dict:
694
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
695
+ return ((total_loss,) + output) if total_loss is not None else output
696
+
697
+ return FNetForPreTrainingOutput(
698
+ loss=total_loss,
699
+ prediction_logits=prediction_scores,
700
+ seq_relationship_logits=seq_relationship_score,
701
+ hidden_states=outputs.hidden_states,
702
+ )
703
+
704
+
705
+ @add_start_docstrings("""FNet Model with a `language modeling` head on top.""", FNET_START_DOCSTRING)
706
+ class FNetForMaskedLM(FNetPreTrainedModel):
707
+ _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
708
+
709
+ def __init__(self, config):
710
+ super().__init__(config)
711
+
712
+ self.fnet = FNetModel(config)
713
+ self.cls = FNetOnlyMLMHead(config)
714
+
715
+ # Initialize weights and apply final processing
716
+ self.post_init()
717
+
718
+ def get_output_embeddings(self):
719
+ return self.cls.predictions.decoder
720
+
721
+ def set_output_embeddings(self, new_embeddings):
722
+ self.cls.predictions.decoder = new_embeddings
723
+ self.cls.predictions.bias = new_embeddings.bias
724
+
725
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
726
+ @add_code_sample_docstrings(
727
+ checkpoint=_CHECKPOINT_FOR_DOC,
728
+ output_type=MaskedLMOutput,
729
+ config_class=_CONFIG_FOR_DOC,
730
+ )
731
+ def forward(
732
+ self,
733
+ input_ids: Optional[torch.Tensor] = None,
734
+ token_type_ids: Optional[torch.Tensor] = None,
735
+ position_ids: Optional[torch.Tensor] = None,
736
+ inputs_embeds: Optional[torch.Tensor] = None,
737
+ labels: Optional[torch.Tensor] = None,
738
+ output_hidden_states: Optional[bool] = None,
739
+ return_dict: Optional[bool] = None,
740
+ ) -> Union[Tuple, MaskedLMOutput]:
741
+ r"""
742
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
743
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
744
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
745
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
746
+ """
747
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
748
+
749
+ outputs = self.fnet(
750
+ input_ids,
751
+ token_type_ids=token_type_ids,
752
+ position_ids=position_ids,
753
+ inputs_embeds=inputs_embeds,
754
+ output_hidden_states=output_hidden_states,
755
+ return_dict=return_dict,
756
+ )
757
+
758
+ sequence_output = outputs[0]
759
+ prediction_scores = self.cls(sequence_output)
760
+
761
+ masked_lm_loss = None
762
+ if labels is not None:
763
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
764
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
765
+
766
+ if not return_dict:
767
+ output = (prediction_scores,) + outputs[2:]
768
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
769
+
770
+ return MaskedLMOutput(loss=masked_lm_loss, logits=prediction_scores, hidden_states=outputs.hidden_states)
771
+
772
+
773
+ @add_start_docstrings(
774
+ """FNet Model with a `next sentence prediction (classification)` head on top.""",
775
+ FNET_START_DOCSTRING,
776
+ )
777
+ class FNetForNextSentencePrediction(FNetPreTrainedModel):
778
+ def __init__(self, config):
779
+ super().__init__(config)
780
+
781
+ self.fnet = FNetModel(config)
782
+ self.cls = FNetOnlyNSPHead(config)
783
+
784
+ # Initialize weights and apply final processing
785
+ self.post_init()
786
+
787
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
788
+ @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
789
+ def forward(
790
+ self,
791
+ input_ids: Optional[torch.Tensor] = None,
792
+ token_type_ids: Optional[torch.Tensor] = None,
793
+ position_ids: Optional[torch.Tensor] = None,
794
+ inputs_embeds: Optional[torch.Tensor] = None,
795
+ labels: Optional[torch.Tensor] = None,
796
+ output_hidden_states: Optional[bool] = None,
797
+ return_dict: Optional[bool] = None,
798
+ **kwargs,
799
+ ) -> Union[Tuple, NextSentencePredictorOutput]:
800
+ r"""
801
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
802
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
803
+ (see `input_ids` docstring). Indices should be in `[0, 1]`:
804
+
805
+ - 0 indicates sequence B is a continuation of sequence A,
806
+ - 1 indicates sequence B is a random sequence.
807
+
808
+ Returns:
809
+
810
+ Example:
811
+
812
+ ```python
813
+ >>> from transformers import AutoTokenizer, FNetForNextSentencePrediction
814
+ >>> import torch
815
+
816
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/fnet-base")
817
+ >>> model = FNetForNextSentencePrediction.from_pretrained("google/fnet-base")
818
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
819
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
820
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
821
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
822
+ >>> logits = outputs.logits
823
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
824
+ ```"""
825
+
826
+ if "next_sentence_label" in kwargs:
827
+ warnings.warn(
828
+ "The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
829
+ " `labels` instead.",
830
+ FutureWarning,
831
+ )
832
+ labels = kwargs.pop("next_sentence_label")
833
+
834
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
835
+
836
+ outputs = self.fnet(
837
+ input_ids,
838
+ token_type_ids=token_type_ids,
839
+ position_ids=position_ids,
840
+ inputs_embeds=inputs_embeds,
841
+ output_hidden_states=output_hidden_states,
842
+ return_dict=return_dict,
843
+ )
844
+
845
+ pooled_output = outputs[1]
846
+
847
+ seq_relationship_scores = self.cls(pooled_output)
848
+
849
+ next_sentence_loss = None
850
+ if labels is not None:
851
+ loss_fct = CrossEntropyLoss()
852
+ next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
853
+
854
+ if not return_dict:
855
+ output = (seq_relationship_scores,) + outputs[2:]
856
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
857
+
858
+ return NextSentencePredictorOutput(
859
+ loss=next_sentence_loss,
860
+ logits=seq_relationship_scores,
861
+ hidden_states=outputs.hidden_states,
862
+ )
863
+
864
+
865
+ @add_start_docstrings(
866
+ """
867
+ FNet Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
868
+ output) e.g. for GLUE tasks.
869
+ """,
870
+ FNET_START_DOCSTRING,
871
+ )
872
+ class FNetForSequenceClassification(FNetPreTrainedModel):
873
+ def __init__(self, config):
874
+ super().__init__(config)
875
+ self.num_labels = config.num_labels
876
+ self.fnet = FNetModel(config)
877
+
878
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
879
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
880
+
881
+ # Initialize weights and apply final processing
882
+ self.post_init()
883
+
884
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
885
+ @add_code_sample_docstrings(
886
+ checkpoint=_CHECKPOINT_FOR_DOC,
887
+ output_type=SequenceClassifierOutput,
888
+ config_class=_CONFIG_FOR_DOC,
889
+ )
890
+ def forward(
891
+ self,
892
+ input_ids: Optional[torch.Tensor] = None,
893
+ token_type_ids: Optional[torch.Tensor] = None,
894
+ position_ids: Optional[torch.Tensor] = None,
895
+ inputs_embeds: Optional[torch.Tensor] = None,
896
+ labels: Optional[torch.Tensor] = None,
897
+ output_hidden_states: Optional[bool] = None,
898
+ return_dict: Optional[bool] = None,
899
+ ) -> Union[Tuple, SequenceClassifierOutput]:
900
+ r"""
901
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
902
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
903
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
904
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
905
+ """
906
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
907
+
908
+ outputs = self.fnet(
909
+ input_ids,
910
+ token_type_ids=token_type_ids,
911
+ position_ids=position_ids,
912
+ inputs_embeds=inputs_embeds,
913
+ output_hidden_states=output_hidden_states,
914
+ return_dict=return_dict,
915
+ )
916
+
917
+ pooled_output = outputs[1]
918
+ pooled_output = self.dropout(pooled_output)
919
+ logits = self.classifier(pooled_output)
920
+
921
+ loss = None
922
+ if labels is not None:
923
+ if self.config.problem_type is None:
924
+ if self.num_labels == 1:
925
+ self.config.problem_type = "regression"
926
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
927
+ self.config.problem_type = "single_label_classification"
928
+ else:
929
+ self.config.problem_type = "multi_label_classification"
930
+
931
+ if self.config.problem_type == "regression":
932
+ loss_fct = MSELoss()
933
+ if self.num_labels == 1:
934
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
935
+ else:
936
+ loss = loss_fct(logits, labels)
937
+ elif self.config.problem_type == "single_label_classification":
938
+ loss_fct = CrossEntropyLoss()
939
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
940
+ elif self.config.problem_type == "multi_label_classification":
941
+ loss_fct = BCEWithLogitsLoss()
942
+ loss = loss_fct(logits, labels)
943
+ if not return_dict:
944
+ output = (logits,) + outputs[2:]
945
+ return ((loss,) + output) if loss is not None else output
946
+
947
+ return SequenceClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
948
+
949
+
950
+ @add_start_docstrings(
951
+ """
952
+ FNet Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
953
+ softmax) e.g. for RocStories/SWAG tasks.
954
+ """,
955
+ FNET_START_DOCSTRING,
956
+ )
957
+ class FNetForMultipleChoice(FNetPreTrainedModel):
958
+ def __init__(self, config):
959
+ super().__init__(config)
960
+
961
+ self.fnet = FNetModel(config)
962
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
963
+ self.classifier = nn.Linear(config.hidden_size, 1)
964
+
965
+ # Initialize weights and apply final processing
966
+ self.post_init()
967
+
968
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
969
+ @add_code_sample_docstrings(
970
+ checkpoint=_CHECKPOINT_FOR_DOC,
971
+ output_type=MultipleChoiceModelOutput,
972
+ config_class=_CONFIG_FOR_DOC,
973
+ )
974
+ def forward(
975
+ self,
976
+ input_ids: Optional[torch.Tensor] = None,
977
+ token_type_ids: Optional[torch.Tensor] = None,
978
+ position_ids: Optional[torch.Tensor] = None,
979
+ inputs_embeds: Optional[torch.Tensor] = None,
980
+ labels: Optional[torch.Tensor] = None,
981
+ output_hidden_states: Optional[bool] = None,
982
+ return_dict: Optional[bool] = None,
983
+ ) -> Union[Tuple, MultipleChoiceModelOutput]:
984
+ r"""
985
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
986
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
987
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
988
+ `input_ids` above)
989
+ """
990
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
991
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
992
+
993
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
994
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
995
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
996
+ inputs_embeds = (
997
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
998
+ if inputs_embeds is not None
999
+ else None
1000
+ )
1001
+
1002
+ outputs = self.fnet(
1003
+ input_ids,
1004
+ token_type_ids=token_type_ids,
1005
+ position_ids=position_ids,
1006
+ inputs_embeds=inputs_embeds,
1007
+ output_hidden_states=output_hidden_states,
1008
+ return_dict=return_dict,
1009
+ )
1010
+
1011
+ pooled_output = outputs[1]
1012
+
1013
+ pooled_output = self.dropout(pooled_output)
1014
+ logits = self.classifier(pooled_output)
1015
+ reshaped_logits = logits.view(-1, num_choices)
1016
+
1017
+ loss = None
1018
+ if labels is not None:
1019
+ loss_fct = CrossEntropyLoss()
1020
+ loss = loss_fct(reshaped_logits, labels)
1021
+
1022
+ if not return_dict:
1023
+ output = (reshaped_logits,) + outputs[2:]
1024
+ return ((loss,) + output) if loss is not None else output
1025
+
1026
+ return MultipleChoiceModelOutput(loss=loss, logits=reshaped_logits, hidden_states=outputs.hidden_states)
1027
+
1028
+
1029
+ @add_start_docstrings(
1030
+ """
1031
+ FNet Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1032
+ Named-Entity-Recognition (NER) tasks.
1033
+ """,
1034
+ FNET_START_DOCSTRING,
1035
+ )
1036
+ class FNetForTokenClassification(FNetPreTrainedModel):
1037
+ def __init__(self, config):
1038
+ super().__init__(config)
1039
+ self.num_labels = config.num_labels
1040
+
1041
+ self.fnet = FNetModel(config)
1042
+
1043
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1044
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1045
+
1046
+ # Initialize weights and apply final processing
1047
+ self.post_init()
1048
+
1049
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1050
+ @add_code_sample_docstrings(
1051
+ checkpoint=_CHECKPOINT_FOR_DOC,
1052
+ output_type=TokenClassifierOutput,
1053
+ config_class=_CONFIG_FOR_DOC,
1054
+ )
1055
+ def forward(
1056
+ self,
1057
+ input_ids: Optional[torch.Tensor] = None,
1058
+ token_type_ids: Optional[torch.Tensor] = None,
1059
+ position_ids: Optional[torch.Tensor] = None,
1060
+ inputs_embeds: Optional[torch.Tensor] = None,
1061
+ labels: Optional[torch.Tensor] = None,
1062
+ output_hidden_states: Optional[bool] = None,
1063
+ return_dict: Optional[bool] = None,
1064
+ ) -> Union[Tuple, TokenClassifierOutput]:
1065
+ r"""
1066
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1067
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1068
+ """
1069
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1070
+
1071
+ outputs = self.fnet(
1072
+ input_ids,
1073
+ token_type_ids=token_type_ids,
1074
+ position_ids=position_ids,
1075
+ inputs_embeds=inputs_embeds,
1076
+ output_hidden_states=output_hidden_states,
1077
+ return_dict=return_dict,
1078
+ )
1079
+
1080
+ sequence_output = outputs[0]
1081
+
1082
+ sequence_output = self.dropout(sequence_output)
1083
+ logits = self.classifier(sequence_output)
1084
+
1085
+ loss = None
1086
+ if labels is not None:
1087
+ loss_fct = CrossEntropyLoss()
1088
+ # Only keep active parts of the loss
1089
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1090
+
1091
+ if not return_dict:
1092
+ output = (logits,) + outputs[2:]
1093
+ return ((loss,) + output) if loss is not None else output
1094
+
1095
+ return TokenClassifierOutput(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
1096
+
1097
+
1098
+ @add_start_docstrings(
1099
+ """
1100
+ FNet Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1101
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1102
+ """,
1103
+ FNET_START_DOCSTRING,
1104
+ )
1105
+ class FNetForQuestionAnswering(FNetPreTrainedModel):
1106
+ def __init__(self, config):
1107
+ super().__init__(config)
1108
+
1109
+ self.num_labels = config.num_labels
1110
+
1111
+ self.fnet = FNetModel(config)
1112
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1113
+
1114
+ # Initialize weights and apply final processing
1115
+ self.post_init()
1116
+
1117
+ @add_start_docstrings_to_model_forward(FNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1118
+ @add_code_sample_docstrings(
1119
+ checkpoint=_CHECKPOINT_FOR_DOC,
1120
+ output_type=QuestionAnsweringModelOutput,
1121
+ config_class=_CONFIG_FOR_DOC,
1122
+ )
1123
+ def forward(
1124
+ self,
1125
+ input_ids: Optional[torch.Tensor] = None,
1126
+ token_type_ids: Optional[torch.Tensor] = None,
1127
+ position_ids: Optional[torch.Tensor] = None,
1128
+ inputs_embeds: Optional[torch.Tensor] = None,
1129
+ start_positions: Optional[torch.Tensor] = None,
1130
+ end_positions: Optional[torch.Tensor] = None,
1131
+ output_hidden_states: Optional[bool] = None,
1132
+ return_dict: Optional[bool] = None,
1133
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1134
+ r"""
1135
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1136
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1137
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1138
+ are not taken into account for computing the loss.
1139
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1140
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1141
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1142
+ are not taken into account for computing the loss.
1143
+ """
1144
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1145
+
1146
+ outputs = self.fnet(
1147
+ input_ids,
1148
+ token_type_ids=token_type_ids,
1149
+ position_ids=position_ids,
1150
+ inputs_embeds=inputs_embeds,
1151
+ output_hidden_states=output_hidden_states,
1152
+ return_dict=return_dict,
1153
+ )
1154
+
1155
+ sequence_output = outputs[0]
1156
+
1157
+ logits = self.qa_outputs(sequence_output)
1158
+ start_logits, end_logits = logits.split(1, dim=-1)
1159
+ start_logits = start_logits.squeeze(-1).contiguous()
1160
+ end_logits = end_logits.squeeze(-1).contiguous()
1161
+
1162
+ total_loss = None
1163
+ if start_positions is not None and end_positions is not None:
1164
+ # If we are on multi-GPU, split add a dimension
1165
+ if len(start_positions.size()) > 1:
1166
+ start_positions = start_positions.squeeze(-1)
1167
+ if len(end_positions.size()) > 1:
1168
+ end_positions = end_positions.squeeze(-1)
1169
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1170
+ ignored_index = start_logits.size(1)
1171
+ start_positions = start_positions.clamp(0, ignored_index)
1172
+ end_positions = end_positions.clamp(0, ignored_index)
1173
+
1174
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1175
+ start_loss = loss_fct(start_logits, start_positions)
1176
+ end_loss = loss_fct(end_logits, end_positions)
1177
+ total_loss = (start_loss + end_loss) / 2
1178
+
1179
+ if not return_dict:
1180
+ output = (start_logits, end_logits) + outputs[2:]
1181
+ return ((total_loss,) + output) if total_loss is not None else output
1182
+
1183
+ return QuestionAnsweringModelOutput(
1184
+ loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states
1185
+ )
1186
+
1187
+
1188
+ __all__ = [
1189
+ "FNetForMaskedLM",
1190
+ "FNetForMultipleChoice",
1191
+ "FNetForNextSentencePrediction",
1192
+ "FNetForPreTraining",
1193
+ "FNetForQuestionAnswering",
1194
+ "FNetForSequenceClassification",
1195
+ "FNetForTokenClassification",
1196
+ "FNetLayer",
1197
+ "FNetModel",
1198
+ "FNetPreTrainedModel",
1199
+ ]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fnet/tokenization_fnet.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Google Research, Google AI, Google Brain 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
+ """Tokenization classes for FNet model."""
16
+
17
+ import os
18
+ import unicodedata
19
+ from shutil import copyfile
20
+ from typing import Any, Dict, List, Optional, Tuple
21
+
22
+ import sentencepiece as spm
23
+
24
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
25
+ from ...utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
30
+
31
+
32
+ SPIECE_UNDERLINE = "▁"
33
+
34
+
35
+ class FNetTokenizer(PreTrainedTokenizer):
36
+ """
37
+ Construct an FNet tokenizer. Adapted from [`AlbertTokenizer`]. Based on
38
+ [SentencePiece](https://github.com/google/sentencepiece). This tokenizer inherits from [`PreTrainedTokenizer`]
39
+ which contains most of the main methods. Users should refer to this superclass for more information regarding those
40
+ methods.
41
+
42
+ Args:
43
+ vocab_file (`str`):
44
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
45
+ contains the vocabulary necessary to instantiate a tokenizer.
46
+ do_lower_case (`bool`, *optional*, defaults to `False`):
47
+ Whether or not to lowercase the input when tokenizing.
48
+ remove_space (`bool`, *optional*, defaults to `True`):
49
+ Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
50
+ keep_accents (`bool`, *optional*, defaults to `True`):
51
+ Whether or not to keep accents when tokenizing.
52
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
53
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
54
+ token instead.
55
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
56
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
57
+ sequence classification or for a text and a question for question answering. It is also used as the last
58
+ token of a sequence built with special tokens.
59
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
60
+ The token used for padding, for example when batching sequences of different lengths.
61
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
62
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
63
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
64
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
65
+ The token used for masking values. This is the token used when training this model with masked language
66
+ modeling. This is the token which the model will try to predict.
67
+ sp_model_kwargs (`dict`, *optional*):
68
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
69
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
70
+ to set:
71
+
72
+ - `enable_sampling`: Enable subword regularization.
73
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
74
+
75
+ - `nbest_size = {0,1}`: No sampling is performed.
76
+ - `nbest_size > 1`: samples from the nbest_size results.
77
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
78
+ using forward-filtering-and-backward-sampling algorithm.
79
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
80
+ BPE-dropout.
81
+
82
+ Attributes:
83
+ sp_model (`SentencePieceProcessor`):
84
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
85
+ """
86
+
87
+ vocab_files_names = VOCAB_FILES_NAMES
88
+ model_input_names = ["input_ids", "token_type_ids"]
89
+
90
+ def __init__(
91
+ self,
92
+ vocab_file,
93
+ do_lower_case=False,
94
+ remove_space=True,
95
+ keep_accents=True,
96
+ unk_token="<unk>",
97
+ sep_token="[SEP]",
98
+ pad_token="<pad>",
99
+ cls_token="[CLS]",
100
+ mask_token="[MASK]",
101
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
102
+ **kwargs,
103
+ ) -> None:
104
+ # Mask token behave like a normal word, i.e. include the space before it and
105
+ # is included in the raw text, there should be a match in a non-normalized sentence.
106
+ mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token
107
+ cls_token = AddedToken(cls_token, special=True) if isinstance(cls_token, str) else cls_token
108
+ sep_token = AddedToken(sep_token, special=True) if isinstance(sep_token, str) else sep_token
109
+ mask_token = AddedToken(mask_token, special=True) if isinstance(mask_token, str) else mask_token
110
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
111
+
112
+ self.do_lower_case = do_lower_case
113
+ self.remove_space = remove_space
114
+ self.keep_accents = keep_accents
115
+ self.vocab_file = vocab_file
116
+
117
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
118
+ self.sp_model.Load(vocab_file)
119
+
120
+ super().__init__(
121
+ do_lower_case=do_lower_case,
122
+ remove_space=remove_space,
123
+ keep_accents=keep_accents,
124
+ unk_token=unk_token,
125
+ sep_token=sep_token,
126
+ pad_token=pad_token,
127
+ cls_token=cls_token,
128
+ mask_token=mask_token,
129
+ sp_model_kwargs=self.sp_model_kwargs,
130
+ **kwargs,
131
+ )
132
+
133
+ @property
134
+ def vocab_size(self):
135
+ return len(self.sp_model)
136
+
137
+ def get_vocab(self):
138
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
139
+ vocab.update(self.added_tokens_encoder)
140
+ return vocab
141
+
142
+ def __getstate__(self):
143
+ state = self.__dict__.copy()
144
+ state["sp_model"] = None
145
+ return state
146
+
147
+ def __setstate__(self, d):
148
+ self.__dict__ = d
149
+
150
+ # for backward compatibility
151
+ if not hasattr(self, "sp_model_kwargs"):
152
+ self.sp_model_kwargs = {}
153
+
154
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
155
+ self.sp_model.Load(self.vocab_file)
156
+
157
+ def preprocess_text(self, inputs):
158
+ if self.remove_space:
159
+ outputs = " ".join(inputs.strip().split())
160
+ else:
161
+ outputs = inputs
162
+ outputs = outputs.replace("``", '"').replace("''", '"')
163
+
164
+ if not self.keep_accents:
165
+ outputs = unicodedata.normalize("NFKD", outputs)
166
+ outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
167
+ if self.do_lower_case:
168
+ outputs = outputs.lower()
169
+
170
+ return outputs
171
+
172
+ def _tokenize(self, text: str) -> List[str]:
173
+ """Tokenize a string."""
174
+ text = self.preprocess_text(text)
175
+ pieces = self.sp_model.encode(text, out_type=str)
176
+ new_pieces = []
177
+ for piece in pieces:
178
+ if len(piece) > 1 and piece[-1] == str(",") and piece[-2].isdigit():
179
+ cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
180
+ if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
181
+ if len(cur_pieces[0]) == 1:
182
+ cur_pieces = cur_pieces[1:]
183
+ else:
184
+ cur_pieces[0] = cur_pieces[0][1:]
185
+ cur_pieces.append(piece[-1])
186
+ new_pieces.extend(cur_pieces)
187
+ else:
188
+ new_pieces.append(piece)
189
+
190
+ return new_pieces
191
+
192
+ def _convert_token_to_id(self, token):
193
+ """Converts a token (str) in an id using the vocab."""
194
+ return self.sp_model.PieceToId(token)
195
+
196
+ def _convert_id_to_token(self, index):
197
+ """Converts an index (integer) in a token (str) using the vocab."""
198
+ return self.sp_model.IdToPiece(index)
199
+
200
+ # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.convert_tokens_to_string
201
+ def convert_tokens_to_string(self, tokens):
202
+ """Converts a sequence of tokens (string) in a single string."""
203
+ current_sub_tokens = []
204
+ out_string = ""
205
+ prev_is_special = False
206
+ for token in tokens:
207
+ # make sure that special tokens are not decoded using sentencepiece model
208
+ if token in self.all_special_tokens:
209
+ if not prev_is_special:
210
+ out_string += " "
211
+ out_string += self.sp_model.decode(current_sub_tokens) + token
212
+ prev_is_special = True
213
+ current_sub_tokens = []
214
+ else:
215
+ current_sub_tokens.append(token)
216
+ prev_is_special = False
217
+ out_string += self.sp_model.decode(current_sub_tokens)
218
+ return out_string.strip()
219
+
220
+ def _decode(
221
+ self,
222
+ token_ids: List[int],
223
+ skip_special_tokens: bool = False,
224
+ clean_up_tokenization_spaces: bool = None,
225
+ spaces_between_special_tokens: bool = False,
226
+ **kwargs,
227
+ ) -> str:
228
+ text = super()._decode(
229
+ token_ids=token_ids,
230
+ skip_special_tokens=skip_special_tokens,
231
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
232
+ spaces_between_special_tokens=spaces_between_special_tokens,
233
+ **kwargs,
234
+ )
235
+ # Mimic the behavior of the Rust tokenizer:
236
+ # No space after <unk>
237
+ if not spaces_between_special_tokens:
238
+ text = text.replace("<unk> ", "<unk>")
239
+ return text
240
+
241
+ def build_inputs_with_special_tokens(
242
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
243
+ ) -> List[int]:
244
+ """
245
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
246
+ adding special tokens. An FNet sequence has the following format:
247
+
248
+ - single sequence: `[CLS] X [SEP]`
249
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
250
+
251
+ Args:
252
+ token_ids_0 (`List[int]`):
253
+ List of IDs to which the special tokens will be added.
254
+ token_ids_1 (`List[int]`, *optional*):
255
+ Optional second list of IDs for sequence pairs.
256
+
257
+ Returns:
258
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
259
+ """
260
+ sep = [self.sep_token_id]
261
+ cls = [self.cls_token_id]
262
+ if token_ids_1 is None:
263
+ return cls + token_ids_0 + sep
264
+ return cls + token_ids_0 + sep + token_ids_1 + sep
265
+
266
+ def get_special_tokens_mask(
267
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
268
+ ) -> List[int]:
269
+ """
270
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
271
+ special tokens using the tokenizer `prepare_for_model` method.
272
+
273
+ Args:
274
+ token_ids_0 (`List[int]`):
275
+ List of IDs.
276
+ token_ids_1 (`List[int]`, *optional*):
277
+ Optional second list of IDs for sequence pairs.
278
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
279
+ Whether or not the token list is already formatted with special tokens for the model.
280
+
281
+ Returns:
282
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
283
+ """
284
+
285
+ if already_has_special_tokens:
286
+ return super().get_special_tokens_mask(
287
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
288
+ )
289
+
290
+ if token_ids_1 is not None:
291
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
292
+ return [1] + ([0] * len(token_ids_0)) + [1]
293
+
294
+ def create_token_type_ids_from_sequences(
295
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
296
+ ) -> List[int]:
297
+ """
298
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. An FNet sequence
299
+ pair mask has the following format: :
300
+
301
+ ```
302
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence |
303
+ ```
304
+
305
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
306
+
307
+ Args:
308
+ token_ids_0 (`List[int]`):
309
+ List of IDs.
310
+ token_ids_1 (`List[int]`, *optional*):
311
+ Optional second list of IDs for sequence pairs.
312
+
313
+ Returns:
314
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
315
+ """
316
+ sep = [self.sep_token_id]
317
+ cls = [self.cls_token_id]
318
+
319
+ if token_ids_1 is None:
320
+ return len(cls + token_ids_0 + sep) * [0]
321
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
322
+
323
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
324
+ if not os.path.isdir(save_directory):
325
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
326
+ return
327
+ out_vocab_file = os.path.join(
328
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
329
+ )
330
+
331
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
332
+ copyfile(self.vocab_file, out_vocab_file)
333
+ elif not os.path.isfile(self.vocab_file):
334
+ with open(out_vocab_file, "wb") as fi:
335
+ content_spiece_model = self.sp_model.serialized_model_proto()
336
+ fi.write(content_spiece_model)
337
+
338
+ return (out_vocab_file,)
339
+
340
+
341
+ __all__ = ["FNetTokenizer"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fnet/tokenization_fnet_fast.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Google AI, Google Brain 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
+ """Tokenization classes for FNet model."""
16
+
17
+ import os
18
+ from shutil import copyfile
19
+ from typing import List, Optional, Tuple
20
+
21
+ from ...tokenization_utils import AddedToken
22
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
23
+ from ...utils import is_sentencepiece_available, logging
24
+
25
+
26
+ if is_sentencepiece_available():
27
+ from .tokenization_fnet import FNetTokenizer
28
+ else:
29
+ FNetTokenizer = None
30
+
31
+ logger = logging.get_logger(__name__)
32
+ VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
33
+
34
+
35
+ SPIECE_UNDERLINE = "▁"
36
+
37
+
38
+ class FNetTokenizerFast(PreTrainedTokenizerFast):
39
+ """
40
+ Construct a "fast" FNetTokenizer (backed by HuggingFace's *tokenizers* library). Adapted from
41
+ [`AlbertTokenizerFast`]. Based on
42
+ [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models). This
43
+ tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should refer to
44
+ this superclass for more information regarding those methods
45
+
46
+ Args:
47
+ vocab_file (`str`):
48
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
49
+ contains the vocabulary necessary to instantiate a tokenizer.
50
+ do_lower_case (`bool`, *optional*, defaults to `False`):
51
+ Whether or not to lowercase the input when tokenizing.
52
+ remove_space (`bool`, *optional*, defaults to `True`):
53
+ Whether or not to strip the text when tokenizing (removing excess spaces before and after the string).
54
+ keep_accents (`bool`, *optional*, defaults to `True`):
55
+ Whether or not to keep accents when tokenizing.
56
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
57
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
58
+ token instead.
59
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
60
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
61
+ sequence classification or for a text and a question for question answering. It is also used as the last
62
+ token of a sequence built with special tokens.
63
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
64
+ The token used for padding, for example when batching sequences of different lengths.
65
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
66
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
67
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
68
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
69
+ The token used for masking values. This is the token used when training this model with masked language
70
+ modeling. This is the token which the model will try to predict.
71
+ """
72
+
73
+ vocab_files_names = VOCAB_FILES_NAMES
74
+ model_input_names = ["input_ids", "token_type_ids"]
75
+ slow_tokenizer_class = FNetTokenizer
76
+
77
+ def __init__(
78
+ self,
79
+ vocab_file=None,
80
+ tokenizer_file=None,
81
+ do_lower_case=False,
82
+ remove_space=True,
83
+ keep_accents=True,
84
+ unk_token="<unk>",
85
+ sep_token="[SEP]",
86
+ pad_token="<pad>",
87
+ cls_token="[CLS]",
88
+ mask_token="[MASK]",
89
+ **kwargs,
90
+ ):
91
+ # Mask token behave like a normal word, i.e. include the space before it and
92
+ # is included in the raw text, there should be a match in a non-normalized sentence.
93
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
94
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
95
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
96
+
97
+ super().__init__(
98
+ vocab_file,
99
+ tokenizer_file=tokenizer_file,
100
+ do_lower_case=do_lower_case,
101
+ remove_space=remove_space,
102
+ keep_accents=keep_accents,
103
+ unk_token=unk_token,
104
+ sep_token=sep_token,
105
+ pad_token=pad_token,
106
+ cls_token=cls_token,
107
+ mask_token=mask_token,
108
+ **kwargs,
109
+ )
110
+
111
+ self.do_lower_case = do_lower_case
112
+ self.remove_space = remove_space
113
+ self.keep_accents = keep_accents
114
+ self.vocab_file = vocab_file
115
+
116
+ @property
117
+ def can_save_slow_tokenizer(self) -> bool:
118
+ return os.path.isfile(self.vocab_file) if self.vocab_file else False
119
+
120
+ def build_inputs_with_special_tokens(
121
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
122
+ ) -> List[int]:
123
+ """
124
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
125
+ adding special tokens. An FNet sequence has the following format:
126
+
127
+ - single sequence: `[CLS] X [SEP]`
128
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
129
+
130
+ Args:
131
+ token_ids_0 (`List[int]`):
132
+ List of IDs to which the special tokens will be added
133
+ token_ids_1 (`List[int]`, *optional*):
134
+ Optional second list of IDs for sequence pairs.
135
+
136
+ Returns:
137
+ `List[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
138
+ """
139
+ sep = [self.sep_token_id]
140
+ cls = [self.cls_token_id]
141
+ if token_ids_1 is None:
142
+ return cls + token_ids_0 + sep
143
+ return cls + token_ids_0 + sep + token_ids_1 + sep
144
+
145
+ def create_token_type_ids_from_sequences(
146
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
147
+ ) -> List[int]:
148
+ """
149
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An FNet
150
+ sequence pair mask has the following format:
151
+
152
+ ```
153
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
154
+ | first sequence | second sequence |
155
+ ```
156
+
157
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
158
+
159
+ Args:
160
+ token_ids_0 (`List[int]`):
161
+ List of ids.
162
+ token_ids_1 (`List[int]`, *optional*):
163
+ Optional second list of IDs for sequence pairs.
164
+
165
+ Returns:
166
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
167
+ """
168
+ sep = [self.sep_token_id]
169
+ cls = [self.cls_token_id]
170
+
171
+ if token_ids_1 is None:
172
+ return len(cls + token_ids_0 + sep) * [0]
173
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
174
+
175
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
176
+ if not os.path.isdir(save_directory):
177
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
178
+ return
179
+ out_vocab_file = os.path.join(
180
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
181
+ )
182
+
183
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
184
+ copyfile(self.vocab_file, out_vocab_file)
185
+
186
+ return (out_vocab_file,)
187
+
188
+
189
+ __all__ = ["FNetTokenizerFast"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/focalnet/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_focalnet import *
22
+ from .modeling_focalnet import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/focalnet/configuration_focalnet.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """FocalNet model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+ from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class FocalNetConfig(BackboneConfigMixin, PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`FocalNetModel`]. It is used to instantiate a
28
+ FocalNet model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of the FocalNet
30
+ [microsoft/focalnet-tiny](https://huggingface.co/microsoft/focalnet-tiny) architecture.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+ Args:
36
+ image_size (`int`, *optional*, defaults to 224):
37
+ The size (resolution) of each image.
38
+ patch_size (`int`, *optional*, defaults to 4):
39
+ The size (resolution) of each patch in the embeddings layer.
40
+ num_channels (`int`, *optional*, defaults to 3):
41
+ The number of input channels.
42
+ embed_dim (`int`, *optional*, defaults to 96):
43
+ Dimensionality of patch embedding.
44
+ use_conv_embed (`bool`, *optional*, defaults to `False`):
45
+ Whether to use convolutional embedding. The authors noted that using convolutional embedding usually
46
+ improve the performance, but it's not used by default.
47
+ hidden_sizes (`List[int]`, *optional*, defaults to `[192, 384, 768, 768]`):
48
+ Dimensionality (hidden size) at each stage.
49
+ depths (`list(int)`, *optional*, defaults to `[2, 2, 6, 2]`):
50
+ Depth (number of layers) of each stage in the encoder.
51
+ focal_levels (`list(int)`, *optional*, defaults to `[2, 2, 2, 2]`):
52
+ Number of focal levels in each layer of the respective stages in the encoder.
53
+ focal_windows (`list(int)`, *optional*, defaults to `[3, 3, 3, 3]`):
54
+ Focal window size in each layer of the respective stages in the encoder.
55
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
56
+ The non-linear activation function (function or string) in the encoder. If string, `"gelu"`, `"relu"`,
57
+ `"selu"` and `"gelu_new"` are supported.
58
+ mlp_ratio (`float`, *optional*, defaults to 4.0):
59
+ Ratio of MLP hidden dimensionality to embedding dimensionality.
60
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
61
+ The dropout probability for all fully connected layers in the embeddings and encoder.
62
+ drop_path_rate (`float`, *optional*, defaults to 0.1):
63
+ Stochastic depth rate.
64
+ use_layerscale (`bool`, *optional*, defaults to `False`):
65
+ Whether to use layer scale in the encoder.
66
+ layerscale_value (`float`, *optional*, defaults to 0.0001):
67
+ The initial value of the layer scale.
68
+ use_post_layernorm (`bool`, *optional*, defaults to `False`):
69
+ Whether to use post layer normalization in the encoder.
70
+ use_post_layernorm_in_modulation (`bool`, *optional*, defaults to `False`):
71
+ Whether to use post layer normalization in the modulation layer.
72
+ normalize_modulator (`bool`, *optional*, defaults to `False`):
73
+ Whether to normalize the modulator.
74
+ initializer_range (`float`, *optional*, defaults to 0.02):
75
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
76
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
77
+ The epsilon used by the layer normalization layers.
78
+ encoder_stride (`int`, *optional*, defaults to 32):
79
+ Factor to increase the spatial resolution by in the decoder head for masked image modeling.
80
+ out_features (`List[str]`, *optional*):
81
+ If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
82
+ (depending on how many stages the model has). If unset and `out_indices` is set, will default to the
83
+ corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
84
+ same order as defined in the `stage_names` attribute.
85
+ out_indices (`List[int]`, *optional*):
86
+ If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
87
+ many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
88
+ If unset and `out_features` is unset, will default to the last stage. Must be in the
89
+ same order as defined in the `stage_names` attribute.
90
+
91
+ Example:
92
+
93
+ ```python
94
+ >>> from transformers import FocalNetConfig, FocalNetModel
95
+
96
+ >>> # Initializing a FocalNet microsoft/focalnet-tiny style configuration
97
+ >>> configuration = FocalNetConfig()
98
+
99
+ >>> # Initializing a model (with random weights) from the microsoft/focalnet-tiny style configuration
100
+ >>> model = FocalNetModel(configuration)
101
+
102
+ >>> # Accessing the model configuration
103
+ >>> configuration = model.config
104
+ ```"""
105
+
106
+ model_type = "focalnet"
107
+
108
+ def __init__(
109
+ self,
110
+ image_size=224,
111
+ patch_size=4,
112
+ num_channels=3,
113
+ embed_dim=96,
114
+ use_conv_embed=False,
115
+ hidden_sizes=[192, 384, 768, 768],
116
+ depths=[2, 2, 6, 2],
117
+ focal_levels=[2, 2, 2, 2],
118
+ focal_windows=[3, 3, 3, 3],
119
+ hidden_act="gelu",
120
+ mlp_ratio=4.0,
121
+ hidden_dropout_prob=0.0,
122
+ drop_path_rate=0.1,
123
+ use_layerscale=False,
124
+ layerscale_value=1e-4,
125
+ use_post_layernorm=False,
126
+ use_post_layernorm_in_modulation=False,
127
+ normalize_modulator=False,
128
+ initializer_range=0.02,
129
+ layer_norm_eps=1e-5,
130
+ encoder_stride=32,
131
+ out_features=None,
132
+ out_indices=None,
133
+ **kwargs,
134
+ ):
135
+ super().__init__(**kwargs)
136
+
137
+ self.image_size = image_size
138
+ self.patch_size = patch_size
139
+ self.num_channels = num_channels
140
+ self.embed_dim = embed_dim
141
+ self.use_conv_embed = use_conv_embed
142
+ self.hidden_sizes = hidden_sizes
143
+ self.depths = depths
144
+ self.focal_levels = focal_levels
145
+ self.focal_windows = focal_windows
146
+ self.hidden_act = hidden_act
147
+ self.mlp_ratio = mlp_ratio
148
+ self.hidden_dropout_prob = hidden_dropout_prob
149
+ self.drop_path_rate = drop_path_rate
150
+ self.use_layerscale = use_layerscale
151
+ self.layerscale_value = layerscale_value
152
+ self.use_post_layernorm = use_post_layernorm
153
+ self.use_post_layernorm_in_modulation = use_post_layernorm_in_modulation
154
+ self.normalize_modulator = normalize_modulator
155
+ self.initializer_range = initializer_range
156
+ self.layer_norm_eps = layer_norm_eps
157
+ self.encoder_stride = encoder_stride
158
+ self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
159
+ self._out_features, self._out_indices = get_aligned_output_features_output_indices(
160
+ out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
161
+ )
162
+
163
+
164
+ __all__ = ["FocalNetConfig"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/focalnet/convert_focalnet_to_hf_format.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Convert FocalNet checkpoints from the original repository. URL: https://github.com/microsoft/FocalNet/tree/main"""
16
+
17
+ import argparse
18
+ import json
19
+
20
+ import requests
21
+ import torch
22
+ from huggingface_hub import hf_hub_download
23
+ from PIL import Image
24
+ from torchvision import transforms
25
+
26
+ from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification
27
+ from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling
28
+
29
+
30
+ def get_focalnet_config(model_name):
31
+ depths = [2, 2, 6, 2] if "tiny" in model_name else [2, 2, 18, 2]
32
+ use_conv_embed = True if "large" in model_name or "huge" in model_name else False
33
+ use_post_layernorm = True if "large" in model_name or "huge" in model_name else False
34
+ use_layerscale = True if "large" in model_name or "huge" in model_name else False
35
+
36
+ if "large" in model_name or "xlarge" in model_name or "huge" in model_name:
37
+ if "fl3" in model_name:
38
+ focal_levels = [3, 3, 3, 3]
39
+ focal_windows = [5, 5, 5, 5]
40
+ elif "fl4" in model_name:
41
+ focal_levels = [4, 4, 4, 4]
42
+ focal_windows = [3, 3, 3, 3]
43
+
44
+ if "tiny" in model_name or "small" in model_name or "base" in model_name:
45
+ focal_windows = [3, 3, 3, 3]
46
+ if "lrf" in model_name:
47
+ focal_levels = [3, 3, 3, 3]
48
+ else:
49
+ focal_levels = [2, 2, 2, 2]
50
+
51
+ if "tiny" in model_name:
52
+ embed_dim = 96
53
+ elif "small" in model_name:
54
+ embed_dim = 96
55
+ elif "base" in model_name:
56
+ embed_dim = 128
57
+ elif "large" in model_name:
58
+ embed_dim = 192
59
+ elif "xlarge" in model_name:
60
+ embed_dim = 256
61
+ elif "huge" in model_name:
62
+ embed_dim = 352
63
+
64
+ # set label information
65
+ repo_id = "huggingface/label-files"
66
+ if "large" in model_name or "huge" in model_name:
67
+ filename = "imagenet-22k-id2label.json"
68
+ else:
69
+ filename = "imagenet-1k-id2label.json"
70
+
71
+ id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
72
+ id2label = {int(k): v for k, v in id2label.items()}
73
+ label2id = {v: k for k, v in id2label.items()}
74
+
75
+ config = FocalNetConfig(
76
+ embed_dim=embed_dim,
77
+ depths=depths,
78
+ focal_levels=focal_levels,
79
+ focal_windows=focal_windows,
80
+ use_conv_embed=use_conv_embed,
81
+ id2label=id2label,
82
+ label2id=label2id,
83
+ use_post_layernorm=use_post_layernorm,
84
+ use_layerscale=use_layerscale,
85
+ )
86
+
87
+ return config
88
+
89
+
90
+ def rename_key(name):
91
+ if "patch_embed.proj" in name:
92
+ name = name.replace("patch_embed.proj", "embeddings.patch_embeddings.projection")
93
+ if "patch_embed.norm" in name:
94
+ name = name.replace("patch_embed.norm", "embeddings.norm")
95
+ if "layers" in name:
96
+ name = "encoder." + name
97
+ if "encoder.layers" in name:
98
+ name = name.replace("encoder.layers", "encoder.stages")
99
+ if "downsample.proj" in name:
100
+ name = name.replace("downsample.proj", "downsample.projection")
101
+ if "blocks" in name:
102
+ name = name.replace("blocks", "layers")
103
+ if "modulation.f.weight" in name or "modulation.f.bias" in name:
104
+ name = name.replace("modulation.f", "modulation.projection_in")
105
+ if "modulation.h.weight" in name or "modulation.h.bias" in name:
106
+ name = name.replace("modulation.h", "modulation.projection_context")
107
+ if "modulation.proj.weight" in name or "modulation.proj.bias" in name:
108
+ name = name.replace("modulation.proj", "modulation.projection_out")
109
+
110
+ if name == "norm.weight":
111
+ name = "layernorm.weight"
112
+ if name == "norm.bias":
113
+ name = "layernorm.bias"
114
+
115
+ if "head" in name:
116
+ name = name.replace("head", "classifier")
117
+ else:
118
+ name = "focalnet." + name
119
+
120
+ return name
121
+
122
+
123
+ def convert_focalnet_checkpoint(model_name, pytorch_dump_folder_path, push_to_hub=False):
124
+ # fmt: off
125
+ model_name_to_url = {
126
+ "focalnet-tiny": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth",
127
+ "focalnet-tiny-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth",
128
+ "focalnet-small": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth",
129
+ "focalnet-small-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth",
130
+ "focalnet-base": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth",
131
+ "focalnet-base-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth",
132
+ "focalnet-large-lrf-fl3": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth",
133
+ "focalnet-large-lrf-fl4": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth",
134
+ "focalnet-xlarge-lrf-fl3": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth",
135
+ "focalnet-xlarge-lrf-fl4": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth",
136
+ }
137
+ # fmt: on
138
+
139
+ checkpoint_url = model_name_to_url[model_name]
140
+ print("Checkpoint URL: ", checkpoint_url)
141
+ state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")["model"]
142
+
143
+ # rename keys
144
+ for key in state_dict.copy().keys():
145
+ val = state_dict.pop(key)
146
+ state_dict[rename_key(key)] = val
147
+
148
+ config = get_focalnet_config(model_name)
149
+ model = FocalNetForImageClassification(config)
150
+ model.eval()
151
+
152
+ # load state dict
153
+ model.load_state_dict(state_dict)
154
+
155
+ # verify conversion
156
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
157
+
158
+ processor = BitImageProcessor(
159
+ do_resize=True,
160
+ size={"shortest_edge": 256},
161
+ resample=PILImageResampling.BILINEAR,
162
+ do_center_crop=True,
163
+ crop_size=224,
164
+ do_normalize=True,
165
+ image_mean=IMAGENET_DEFAULT_MEAN,
166
+ image_std=IMAGENET_DEFAULT_STD,
167
+ )
168
+ image = Image.open(requests.get(url, stream=True).raw)
169
+ inputs = processor(images=image, return_tensors="pt")
170
+
171
+ image_transforms = transforms.Compose(
172
+ [
173
+ transforms.Resize(256),
174
+ transforms.CenterCrop(224),
175
+ transforms.ToTensor(),
176
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
177
+ ]
178
+ )
179
+
180
+ original_pixel_values = image_transforms(image).unsqueeze(0)
181
+
182
+ # verify pixel_values
183
+ assert torch.allclose(inputs.pixel_values, original_pixel_values, atol=1e-4)
184
+
185
+ outputs = model(**inputs)
186
+
187
+ predicted_class_idx = outputs.logits.argmax(-1).item()
188
+ print("Predicted class:", model.config.id2label[predicted_class_idx])
189
+
190
+ print("First values of logits:", outputs.logits[0, :3])
191
+
192
+ if model_name == "focalnet-tiny":
193
+ expected_slice = torch.tensor([0.2166, -0.4368, 0.2191])
194
+ elif model_name == "focalnet-tiny-lrf":
195
+ expected_slice = torch.tensor([1.1669, 0.0125, -0.1695])
196
+ elif model_name == "focalnet-small":
197
+ expected_slice = torch.tensor([0.4917, -0.0430, 0.1341])
198
+ elif model_name == "focalnet-small-lrf":
199
+ expected_slice = torch.tensor([-0.2588, -0.5342, -0.2331])
200
+ elif model_name == "focalnet-base":
201
+ expected_slice = torch.tensor([-0.1655, -0.4090, -0.1730])
202
+ elif model_name == "focalnet-base-lrf":
203
+ expected_slice = torch.tensor([0.5306, -0.0483, -0.3928])
204
+ assert torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)
205
+ print("Looks ok!")
206
+
207
+ if pytorch_dump_folder_path is not None:
208
+ print(f"Saving model and processor of {model_name} to {pytorch_dump_folder_path}")
209
+ model.save_pretrained(pytorch_dump_folder_path)
210
+ processor.save_pretrained(pytorch_dump_folder_path)
211
+
212
+ if push_to_hub:
213
+ print(f"Pushing model and processor of {model_name} to the hub...")
214
+ model.push_to_hub(f"{model_name}")
215
+ processor.push_to_hub(f"{model_name}")
216
+
217
+
218
+ if __name__ == "__main__":
219
+ parser = argparse.ArgumentParser()
220
+ # Required parameters
221
+ parser.add_argument(
222
+ "--model_name",
223
+ default="focalnet-tiny",
224
+ type=str,
225
+ help="Name of the FocalNet model you'd like to convert.",
226
+ )
227
+ parser.add_argument(
228
+ "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
229
+ )
230
+ parser.add_argument(
231
+ "--push_to_hub",
232
+ action="store_true",
233
+ help="Whether to push the model and processor to the hub.",
234
+ )
235
+
236
+ args = parser.parse_args()
237
+ convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/focalnet/modeling_focalnet.py ADDED
@@ -0,0 +1,1038 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft Research 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 FocalNet model."""
16
+
17
+ import collections.abc
18
+ import math
19
+ from dataclasses import dataclass
20
+ from typing import Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+
27
+ from ...activations import ACT2FN
28
+ from ...modeling_outputs import BackboneOutput
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...utils import (
31
+ ModelOutput,
32
+ add_code_sample_docstrings,
33
+ add_start_docstrings,
34
+ add_start_docstrings_to_model_forward,
35
+ logging,
36
+ replace_return_docstrings,
37
+ )
38
+ from ...utils.backbone_utils import BackboneMixin
39
+ from .configuration_focalnet import FocalNetConfig
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+ # General docstring
45
+ _CONFIG_FOR_DOC = "FocalNetConfig"
46
+
47
+ # Base docstring
48
+ _CHECKPOINT_FOR_DOC = "microsoft/focalnet-tiny"
49
+ _EXPECTED_OUTPUT_SHAPE = [1, 49, 768]
50
+
51
+ # Image classification docstring
52
+ _IMAGE_CLASS_CHECKPOINT = "microsoft/focalnet-tiny"
53
+ _IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
54
+
55
+
56
+ @dataclass
57
+ class FocalNetEncoderOutput(ModelOutput):
58
+ """
59
+ FocalNet encoder's outputs, with potential hidden states.
60
+
61
+ Args:
62
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
63
+ Sequence of hidden-states at the output of the last layer of the model.
64
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
65
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
66
+ shape `(batch_size, sequence_length, hidden_size)`.
67
+
68
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
69
+
70
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
71
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
72
+ shape `(batch_size, hidden_size, height, width)`.
73
+
74
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
75
+ include the spatial dimensions.
76
+ """
77
+
78
+ last_hidden_state: torch.FloatTensor = None
79
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
80
+ reshaped_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
81
+
82
+
83
+ @dataclass
84
+ class FocalNetModelOutput(ModelOutput):
85
+ """
86
+ FocalNet model's outputs that also contains a pooling of the last hidden states.
87
+
88
+ Args:
89
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
90
+ Sequence of hidden-states at the output of the last layer of the model.
91
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
92
+ Average pooling of the last layer hidden-state.
93
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
94
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
95
+ shape `(batch_size, sequence_length, hidden_size)`.
96
+
97
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
98
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
99
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
100
+ shape `(batch_size, hidden_size, height, width)`.
101
+
102
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
103
+ include the spatial dimensions.
104
+ """
105
+
106
+ last_hidden_state: torch.FloatTensor = None
107
+ pooler_output: Optional[torch.FloatTensor] = None
108
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
109
+ reshaped_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
110
+
111
+
112
+ @dataclass
113
+ class FocalNetMaskedImageModelingOutput(ModelOutput):
114
+ """
115
+ FocalNet masked image model outputs.
116
+
117
+ Args:
118
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `bool_masked_pos` is provided):
119
+ Masked image modeling (MLM) loss.
120
+ reconstruction (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
121
+ Reconstructed pixel values.
122
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
123
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
124
+ shape `(batch_size, sequence_length, hidden_size)`.
125
+
126
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
127
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
128
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
129
+ shape `(batch_size, hidden_size, height, width)`.
130
+
131
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
132
+ include the spatial dimensions.
133
+ """
134
+
135
+ loss: Optional[torch.FloatTensor] = None
136
+ reconstruction: torch.FloatTensor = None
137
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
138
+ reshaped_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
139
+
140
+
141
+ @dataclass
142
+ class FocalNetImageClassifierOutput(ModelOutput):
143
+ """
144
+ FocalNet outputs for image classification.
145
+
146
+ Args:
147
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
148
+ Classification (or regression if config.num_labels==1) loss.
149
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
150
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
151
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
152
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
153
+ shape `(batch_size, sequence_length, hidden_size)`.
154
+
155
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
156
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
157
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
158
+ shape `(batch_size, hidden_size, height, width)`.
159
+
160
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
161
+ include the spatial dimensions.
162
+ """
163
+
164
+ loss: Optional[torch.FloatTensor] = None
165
+ logits: torch.FloatTensor = None
166
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
167
+ reshaped_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
168
+
169
+
170
+ class FocalNetEmbeddings(nn.Module):
171
+ """
172
+ Construct the patch embeddings and layernorm. Optionally, also the mask token.
173
+ """
174
+
175
+ def __init__(self, config, use_mask_token=False):
176
+ super().__init__()
177
+
178
+ self.patch_embeddings = FocalNetPatchEmbeddings(
179
+ config=config,
180
+ image_size=config.image_size,
181
+ patch_size=config.patch_size,
182
+ num_channels=config.num_channels,
183
+ embed_dim=config.embed_dim,
184
+ use_conv_embed=config.use_conv_embed,
185
+ is_stem=True,
186
+ )
187
+ self.patch_grid = self.patch_embeddings.grid_size
188
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.embed_dim)) if use_mask_token else None
189
+
190
+ self.norm = nn.LayerNorm(config.embed_dim, eps=config.layer_norm_eps)
191
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
192
+
193
+ def forward(
194
+ self, pixel_values: Optional[torch.FloatTensor], bool_masked_pos: Optional[torch.BoolTensor] = None
195
+ ) -> Tuple[torch.Tensor]:
196
+ embeddings, output_dimensions = self.patch_embeddings(pixel_values)
197
+ embeddings = self.norm(embeddings)
198
+ batch_size, seq_len, _ = embeddings.size()
199
+
200
+ if bool_masked_pos is not None:
201
+ mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
202
+ # replace the masked visual tokens by mask_tokens
203
+ mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
204
+ embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
205
+
206
+ embeddings = self.dropout(embeddings)
207
+ return embeddings, output_dimensions
208
+
209
+
210
+ class FocalNetPatchEmbeddings(nn.Module):
211
+ def __init__(
212
+ self,
213
+ config,
214
+ image_size,
215
+ patch_size,
216
+ num_channels,
217
+ embed_dim,
218
+ add_norm=False,
219
+ use_conv_embed=False,
220
+ is_stem=False,
221
+ ):
222
+ super().__init__()
223
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
224
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
225
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
226
+ self.image_size = image_size
227
+ self.patch_size = patch_size
228
+ self.num_channels = num_channels
229
+ self.num_patches = num_patches
230
+ self.grid_size = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
231
+
232
+ if use_conv_embed:
233
+ # if we choose to use conv embedding, then we treat the stem and non-stem differently
234
+ if is_stem:
235
+ kernel_size = 7
236
+ padding = 2
237
+ stride = 4
238
+ else:
239
+ kernel_size = 3
240
+ padding = 1
241
+ stride = 2
242
+ self.projection = nn.Conv2d(
243
+ num_channels, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding
244
+ )
245
+ else:
246
+ self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=patch_size)
247
+
248
+ if add_norm:
249
+ self.norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
250
+ else:
251
+ self.norm = None
252
+
253
+ def maybe_pad(self, pixel_values, height, width):
254
+ if width % self.patch_size[1] != 0:
255
+ pad_values = (0, self.patch_size[1] - width % self.patch_size[1])
256
+ pixel_values = nn.functional.pad(pixel_values, pad_values)
257
+ if height % self.patch_size[0] != 0:
258
+ pad_values = (0, 0, 0, self.patch_size[0] - height % self.patch_size[0])
259
+ pixel_values = nn.functional.pad(pixel_values, pad_values)
260
+ return pixel_values
261
+
262
+ def forward(self, pixel_values: Optional[torch.FloatTensor]) -> Tuple[torch.Tensor, Tuple[int]]:
263
+ _, num_channels, height, width = pixel_values.shape
264
+ if num_channels != self.num_channels:
265
+ raise ValueError(
266
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
267
+ )
268
+ # pad the input to be divisible by self.patch_size, if needed
269
+ pixel_values = self.maybe_pad(pixel_values, height, width)
270
+ embeddings = self.projection(pixel_values)
271
+ _, _, height, width = embeddings.shape
272
+ output_dimensions = (height, width)
273
+ embeddings = embeddings.flatten(2).transpose(1, 2)
274
+
275
+ if self.norm is not None:
276
+ embeddings = self.norm(embeddings)
277
+
278
+ return embeddings, output_dimensions
279
+
280
+
281
+ # Copied from transformers.models.beit.modeling_beit.drop_path
282
+ def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
283
+ """
284
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
285
+
286
+ Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
287
+ however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
288
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
289
+ layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
290
+ argument.
291
+ """
292
+ if drop_prob == 0.0 or not training:
293
+ return input
294
+ keep_prob = 1 - drop_prob
295
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
296
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
297
+ random_tensor.floor_() # binarize
298
+ output = input.div(keep_prob) * random_tensor
299
+ return output
300
+
301
+
302
+ # Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->FocalNet
303
+ class FocalNetDropPath(nn.Module):
304
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
305
+
306
+ def __init__(self, drop_prob: Optional[float] = None) -> None:
307
+ super().__init__()
308
+ self.drop_prob = drop_prob
309
+
310
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
311
+ return drop_path(hidden_states, self.drop_prob, self.training)
312
+
313
+ def extra_repr(self) -> str:
314
+ return "p={}".format(self.drop_prob)
315
+
316
+
317
+ class FocalNetModulation(nn.Module):
318
+ def __init__(self, config, index, dim, focal_factor=2, bias=True, projection_dropout=0.0):
319
+ super().__init__()
320
+
321
+ self.dim = dim
322
+ self.focal_window = config.focal_windows[index]
323
+ self.focal_level = config.focal_levels[index]
324
+ self.focal_factor = focal_factor
325
+ self.use_post_layernorm_in_modulation = config.use_post_layernorm_in_modulation
326
+ self.normalize_modulator = config.normalize_modulator
327
+
328
+ self.projection_in = nn.Linear(dim, 2 * dim + (self.focal_level + 1), bias=bias)
329
+ self.projection_context = nn.Conv2d(dim, dim, kernel_size=1, stride=1, bias=bias)
330
+
331
+ self.activation = nn.GELU()
332
+ self.projection_out = nn.Linear(dim, dim)
333
+ self.projection_dropout = nn.Dropout(projection_dropout)
334
+ self.focal_layers = nn.ModuleList()
335
+
336
+ self.kernel_sizes = []
337
+ for k in range(self.focal_level):
338
+ kernel_size = self.focal_factor * k + self.focal_window
339
+ self.focal_layers.append(
340
+ nn.Sequential(
341
+ nn.Conv2d(
342
+ dim, dim, kernel_size=kernel_size, stride=1, groups=dim, padding=kernel_size // 2, bias=False
343
+ ),
344
+ nn.GELU(),
345
+ )
346
+ )
347
+ self.kernel_sizes.append(kernel_size)
348
+ if self.use_post_layernorm_in_modulation:
349
+ self.layernorm = nn.LayerNorm(dim, eps=config.layer_norm_eps)
350
+
351
+ def forward(self, hidden_state):
352
+ """
353
+ Args:
354
+ hidden_state:
355
+ Input features with shape of (batch_size, height, width, num_channels)
356
+ """
357
+ num_channels = hidden_state.shape[-1]
358
+
359
+ # pre linear projection
360
+ x = self.projection_in(hidden_state).permute(0, 3, 1, 2).contiguous()
361
+ q, ctx, self.gates = torch.split(x, (num_channels, num_channels, self.focal_level + 1), 1)
362
+
363
+ # context aggreation
364
+ ctx_all = 0
365
+ for level in range(self.focal_level):
366
+ ctx = self.focal_layers[level](ctx)
367
+ ctx_all = ctx_all + ctx * self.gates[:, level : level + 1]
368
+ ctx_global = self.activation(ctx.mean(2, keepdim=True).mean(3, keepdim=True))
369
+ ctx_all = ctx_all + ctx_global * self.gates[:, self.focal_level :]
370
+
371
+ # normalize context
372
+ if self.normalize_modulator:
373
+ ctx_all = ctx_all / (self.focal_level + 1)
374
+
375
+ # focal modulation
376
+ self.modulator = self.projection_context(ctx_all)
377
+ x_out = q * self.modulator
378
+ x_out = x_out.permute(0, 2, 3, 1).contiguous()
379
+ if self.use_post_layernorm_in_modulation:
380
+ x_out = self.layernorm(x_out)
381
+
382
+ # post linear porjection
383
+ x_out = self.projection_out(x_out)
384
+ x_out = self.projection_dropout(x_out)
385
+ return x_out
386
+
387
+
388
+ class FocalNetMlp(nn.Module):
389
+ def __init__(self, config, in_features, hidden_features=None, out_features=None, drop=0.0):
390
+ super().__init__()
391
+ out_features = out_features or in_features
392
+ hidden_features = hidden_features or in_features
393
+ self.fc1 = nn.Linear(in_features, hidden_features)
394
+ self.activation = ACT2FN[config.hidden_act]
395
+ self.fc2 = nn.Linear(hidden_features, out_features)
396
+ self.drop = nn.Dropout(drop)
397
+
398
+ def forward(self, hidden_state):
399
+ hidden_state = self.fc1(hidden_state)
400
+ hidden_state = self.activation(hidden_state)
401
+ hidden_state = self.drop(hidden_state)
402
+ hidden_state = self.fc2(hidden_state)
403
+ hidden_state = self.drop(hidden_state)
404
+ return hidden_state
405
+
406
+
407
+ class FocalNetLayer(nn.Module):
408
+ r"""Focal Modulation Network layer (block).
409
+
410
+ Args:
411
+ config (`FocalNetConfig`):
412
+ Model config.
413
+ index (`int`):
414
+ Layer index.
415
+ dim (`int`):
416
+ Number of input channels.
417
+ input_resolution (`Tuple[int]`):
418
+ Input resulotion.
419
+ drop_path (`float`, *optional*, defaults to 0.0):
420
+ Stochastic depth rate.
421
+ """
422
+
423
+ def __init__(self, config, index, dim, input_resolution, drop_path=0.0):
424
+ super().__init__()
425
+
426
+ self.config = config
427
+
428
+ # layer-specific attributes
429
+ self.dim = dim
430
+ self.input_resolution = input_resolution
431
+
432
+ # general attributes
433
+ self.drop = config.hidden_dropout_prob
434
+ self.use_post_layernorm = config.use_post_layernorm
435
+
436
+ self.norm1 = nn.LayerNorm(dim, eps=config.layer_norm_eps)
437
+ self.modulation = FocalNetModulation(
438
+ config=config,
439
+ index=index,
440
+ dim=dim,
441
+ projection_dropout=self.drop,
442
+ )
443
+
444
+ self.drop_path = FocalNetDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
445
+ self.norm2 = nn.LayerNorm(dim, eps=config.layer_norm_eps)
446
+ mlp_hidden_dim = int(dim * config.mlp_ratio)
447
+ self.mlp = FocalNetMlp(config=config, in_features=dim, hidden_features=mlp_hidden_dim, drop=self.drop)
448
+
449
+ self.gamma_1 = 1.0
450
+ self.gamma_2 = 1.0
451
+ if config.use_layerscale:
452
+ self.gamma_1 = nn.Parameter(config.layerscale_value * torch.ones((dim)), requires_grad=True)
453
+ self.gamma_2 = nn.Parameter(config.layerscale_value * torch.ones((dim)), requires_grad=True)
454
+
455
+ def forward(self, hidden_state, input_dimensions):
456
+ height, width = input_dimensions
457
+ batch_size, _, num_channels = hidden_state.shape
458
+ shortcut = hidden_state
459
+
460
+ # Focal Modulation
461
+ hidden_state = hidden_state if self.use_post_layernorm else self.norm1(hidden_state)
462
+ hidden_state = hidden_state.view(batch_size, height, width, num_channels)
463
+ hidden_state = self.modulation(hidden_state).view(batch_size, height * width, num_channels)
464
+ hidden_state = hidden_state if not self.use_post_layernorm else self.norm1(hidden_state)
465
+
466
+ # FFN
467
+ hidden_state = shortcut + self.drop_path(self.gamma_1 * hidden_state)
468
+ hidden_state = hidden_state + self.drop_path(
469
+ self.gamma_2
470
+ * (self.norm2(self.mlp(hidden_state)) if self.use_post_layernorm else self.mlp(self.norm2(hidden_state)))
471
+ )
472
+
473
+ return hidden_state
474
+
475
+
476
+ class FocalNetStage(nn.Module):
477
+ def __init__(self, config, index, input_resolution):
478
+ super().__init__()
479
+
480
+ self.config = config
481
+ self.num_stages = len(config.depths)
482
+
483
+ embed_dim = [config.embed_dim * (2**i) for i in range(self.num_stages)]
484
+ dim = embed_dim[index]
485
+ out_dim = embed_dim[index + 1] if (index < self.num_stages - 1) else None
486
+ downsample = FocalNetPatchEmbeddings if (index < self.num_stages - 1) else None
487
+
488
+ # stochastic depth decay rule
489
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths))]
490
+ drop_path = dpr[sum(config.depths[:index]) : sum(config.depths[: index + 1])]
491
+
492
+ self.layers = nn.ModuleList(
493
+ [
494
+ FocalNetLayer(
495
+ config=config,
496
+ index=index,
497
+ dim=dim,
498
+ input_resolution=input_resolution,
499
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
500
+ )
501
+ for i in range(config.depths[index])
502
+ ]
503
+ )
504
+
505
+ if downsample is not None:
506
+ self.downsample = downsample(
507
+ config=config,
508
+ image_size=input_resolution,
509
+ patch_size=2,
510
+ num_channels=dim,
511
+ embed_dim=out_dim,
512
+ add_norm=True,
513
+ use_conv_embed=config.use_conv_embed,
514
+ is_stem=False,
515
+ )
516
+ else:
517
+ self.downsample = None
518
+
519
+ self.pointing = False
520
+
521
+ def forward(self, hidden_states: torch.Tensor, input_dimensions: Tuple[int, int]) -> Tuple[torch.Tensor]:
522
+ height, width = input_dimensions
523
+ for layer_module in self.layers:
524
+ hidden_states = layer_module(hidden_states, input_dimensions)
525
+
526
+ hidden_states_before_downsampling = hidden_states
527
+ if self.downsample is not None:
528
+ height, width = input_dimensions
529
+ hidden_states = hidden_states.transpose(1, 2).reshape(
530
+ hidden_states_before_downsampling.shape[0], -1, height, width
531
+ )
532
+ hidden_states, output_dimensions = self.downsample(hidden_states)
533
+
534
+ else:
535
+ output_dimensions = (height, width, height, width)
536
+
537
+ stage_outputs = (hidden_states, hidden_states_before_downsampling, output_dimensions)
538
+
539
+ return stage_outputs
540
+
541
+
542
+ class FocalNetEncoder(nn.Module):
543
+ def __init__(self, config, grid_size):
544
+ super().__init__()
545
+ self.num_stages = len(config.depths)
546
+ self.config = config
547
+
548
+ self.stages = nn.ModuleList(
549
+ [
550
+ FocalNetStage(
551
+ config=config,
552
+ index=i_layer,
553
+ input_resolution=(grid_size[0] // (2**i_layer), grid_size[1] // (2**i_layer)),
554
+ )
555
+ for i_layer in range(self.num_stages)
556
+ ]
557
+ )
558
+
559
+ self.gradient_checkpointing = False
560
+
561
+ def forward(
562
+ self,
563
+ hidden_states: torch.Tensor,
564
+ input_dimensions: Tuple[int, int],
565
+ output_hidden_states: Optional[bool] = False,
566
+ output_hidden_states_before_downsampling: Optional[bool] = False,
567
+ return_dict: Optional[bool] = True,
568
+ ) -> Union[Tuple, FocalNetEncoderOutput]:
569
+ all_hidden_states = () if output_hidden_states else None
570
+ all_reshaped_hidden_states = () if output_hidden_states else None
571
+
572
+ if output_hidden_states:
573
+ batch_size, _, hidden_size = hidden_states.shape
574
+ # rearrange b (h w) c -> b c h w
575
+ reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
576
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
577
+ all_hidden_states += (hidden_states,)
578
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
579
+
580
+ for i, stage_module in enumerate(self.stages):
581
+ if self.gradient_checkpointing and self.training:
582
+ stage_outputs = self._gradient_checkpointing_func(
583
+ stage_module.__call__,
584
+ hidden_states,
585
+ input_dimensions,
586
+ )
587
+ else:
588
+ stage_outputs = stage_module(hidden_states, input_dimensions)
589
+
590
+ hidden_states = stage_outputs[0]
591
+ hidden_states_before_downsampling = stage_outputs[1]
592
+ output_dimensions = stage_outputs[2]
593
+
594
+ input_dimensions = (output_dimensions[-2], output_dimensions[-1])
595
+
596
+ if output_hidden_states and output_hidden_states_before_downsampling:
597
+ batch_size, _, hidden_size = hidden_states_before_downsampling.shape
598
+ # rearrange b (h w) c -> b c h w
599
+ # here we use the original (not downsampled) height and width
600
+ reshaped_hidden_state = hidden_states_before_downsampling.view(
601
+ batch_size, *(output_dimensions[0], output_dimensions[1]), hidden_size
602
+ )
603
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
604
+ all_hidden_states += (hidden_states_before_downsampling,)
605
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
606
+ elif output_hidden_states and not output_hidden_states_before_downsampling:
607
+ batch_size, _, hidden_size = hidden_states.shape
608
+ # rearrange b (h w) c -> b c h w
609
+ reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
610
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
611
+ all_hidden_states += (hidden_states,)
612
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
613
+
614
+ if not return_dict:
615
+ return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
616
+
617
+ return FocalNetEncoderOutput(
618
+ last_hidden_state=hidden_states,
619
+ hidden_states=all_hidden_states,
620
+ reshaped_hidden_states=all_reshaped_hidden_states,
621
+ )
622
+
623
+
624
+ # Copied from transformers.models.swin.modeling_swin.SwinPreTrainedModel with Swin->FocalNet,swin->focalnet
625
+ class FocalNetPreTrainedModel(PreTrainedModel):
626
+ """
627
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
628
+ models.
629
+ """
630
+
631
+ config_class = FocalNetConfig
632
+ base_model_prefix = "focalnet"
633
+ main_input_name = "pixel_values"
634
+ supports_gradient_checkpointing = True
635
+ _no_split_modules = ["FocalNetStage"]
636
+
637
+ def _init_weights(self, module):
638
+ """Initialize the weights"""
639
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
640
+ # Slightly different from the TF version which uses truncated_normal for initialization
641
+ # cf https://github.com/pytorch/pytorch/pull/5617
642
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
643
+ if module.bias is not None:
644
+ module.bias.data.zero_()
645
+ elif isinstance(module, nn.LayerNorm):
646
+ module.bias.data.zero_()
647
+ module.weight.data.fill_(1.0)
648
+
649
+
650
+ FOCALNET_START_DOCSTRING = r"""
651
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
652
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
653
+ behavior.
654
+
655
+ Parameters:
656
+ config ([`FocalNetConfig`]): Model configuration class with all the parameters of the model.
657
+ Initializing with a config file does not load the weights associated with the model, only the
658
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
659
+ """
660
+
661
+ FOCALNET_INPUTS_DOCSTRING = r"""
662
+ Args:
663
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
664
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
665
+ [`AutoImageProcessor.__call__`] for details.
666
+
667
+ output_hidden_states (`bool`, *optional*):
668
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
669
+ more detail.
670
+ return_dict (`bool`, *optional*):
671
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
672
+ """
673
+
674
+
675
+ @add_start_docstrings(
676
+ "The bare FocalNet Model outputting raw hidden-states without any specific head on top.",
677
+ FOCALNET_START_DOCSTRING,
678
+ )
679
+ class FocalNetModel(FocalNetPreTrainedModel):
680
+ def __init__(self, config, add_pooling_layer=True, use_mask_token=False):
681
+ super().__init__(config)
682
+ self.config = config
683
+ self.num_stages = len(config.depths)
684
+ self.num_features = int(config.embed_dim * 2 ** (self.num_stages - 1))
685
+
686
+ self.embeddings = FocalNetEmbeddings(config, use_mask_token=use_mask_token)
687
+ self.encoder = FocalNetEncoder(config, self.embeddings.patch_grid)
688
+
689
+ self.layernorm = nn.LayerNorm(self.num_features, eps=config.layer_norm_eps)
690
+ self.pooler = nn.AdaptiveAvgPool1d(1) if add_pooling_layer else None
691
+
692
+ # Initialize weights and apply final processing
693
+ self.post_init()
694
+
695
+ def get_input_embeddings(self):
696
+ return self.embeddings.patch_embeddings
697
+
698
+ @add_start_docstrings_to_model_forward(FOCALNET_INPUTS_DOCSTRING)
699
+ @add_code_sample_docstrings(
700
+ checkpoint=_CHECKPOINT_FOR_DOC,
701
+ output_type=FocalNetModelOutput,
702
+ config_class=_CONFIG_FOR_DOC,
703
+ modality="vision",
704
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
705
+ )
706
+ def forward(
707
+ self,
708
+ pixel_values: Optional[torch.FloatTensor] = None,
709
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
710
+ output_hidden_states: Optional[bool] = None,
711
+ return_dict: Optional[bool] = None,
712
+ ) -> Union[Tuple, FocalNetModelOutput]:
713
+ r"""
714
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
715
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
716
+ """
717
+ output_hidden_states = (
718
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
719
+ )
720
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
721
+
722
+ if pixel_values is None:
723
+ raise ValueError("You have to specify pixel_values")
724
+
725
+ embedding_output, input_dimensions = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
726
+
727
+ encoder_outputs = self.encoder(
728
+ embedding_output,
729
+ input_dimensions,
730
+ output_hidden_states=output_hidden_states,
731
+ return_dict=return_dict,
732
+ )
733
+
734
+ sequence_output = encoder_outputs[0]
735
+ sequence_output = self.layernorm(sequence_output)
736
+
737
+ pooled_output = None
738
+ if self.pooler is not None:
739
+ pooled_output = self.pooler(sequence_output.transpose(1, 2))
740
+ pooled_output = torch.flatten(pooled_output, 1)
741
+
742
+ if not return_dict:
743
+ output = (sequence_output, pooled_output) + encoder_outputs[1:]
744
+
745
+ return output
746
+
747
+ return FocalNetModelOutput(
748
+ last_hidden_state=sequence_output,
749
+ pooler_output=pooled_output,
750
+ hidden_states=encoder_outputs.hidden_states,
751
+ reshaped_hidden_states=encoder_outputs.reshaped_hidden_states,
752
+ )
753
+
754
+
755
+ @add_start_docstrings(
756
+ """FocalNet Model with a decoder on top for masked image modeling.
757
+
758
+ This follows the same implementation as in [SimMIM](https://arxiv.org/abs/2111.09886).
759
+
760
+ <Tip>
761
+
762
+ Note that we provide a script to pre-train this model on custom data in our [examples
763
+ directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).
764
+
765
+ </Tip>
766
+ """,
767
+ FOCALNET_START_DOCSTRING,
768
+ )
769
+ class FocalNetForMaskedImageModeling(FocalNetPreTrainedModel):
770
+ def __init__(self, config):
771
+ super().__init__(config)
772
+
773
+ self.focalnet = FocalNetModel(config, add_pooling_layer=False, use_mask_token=True)
774
+
775
+ self.num_stages = len(config.depths)
776
+ num_features = int(config.embed_dim * 2 ** (self.num_stages - 1))
777
+ self.decoder = nn.Sequential(
778
+ nn.Conv2d(
779
+ in_channels=num_features, out_channels=config.encoder_stride**2 * config.num_channels, kernel_size=1
780
+ ),
781
+ nn.PixelShuffle(config.encoder_stride),
782
+ )
783
+
784
+ # Initialize weights and apply final processing
785
+ self.post_init()
786
+
787
+ @add_start_docstrings_to_model_forward(FOCALNET_INPUTS_DOCSTRING)
788
+ @replace_return_docstrings(output_type=FocalNetMaskedImageModelingOutput, config_class=_CONFIG_FOR_DOC)
789
+ def forward(
790
+ self,
791
+ pixel_values: Optional[torch.FloatTensor] = None,
792
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
793
+ output_hidden_states: Optional[bool] = None,
794
+ return_dict: Optional[bool] = None,
795
+ ) -> Union[Tuple, FocalNetMaskedImageModelingOutput]:
796
+ r"""
797
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
798
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
799
+
800
+ Returns:
801
+
802
+ Examples:
803
+ ```python
804
+ >>> from transformers import AutoImageProcessor, FocalNetConfig, FocalNetForMaskedImageModeling
805
+ >>> import torch
806
+ >>> from PIL import Image
807
+ >>> import requests
808
+
809
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
810
+ >>> image = Image.open(requests.get(url, stream=True).raw)
811
+
812
+ >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/focalnet-base-simmim-window6-192")
813
+ >>> config = FocalNetConfig()
814
+ >>> model = FocalNetForMaskedImageModeling(config)
815
+
816
+ >>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
817
+ >>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
818
+ >>> # create random boolean mask of shape (batch_size, num_patches)
819
+ >>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
820
+
821
+ >>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
822
+ >>> loss, reconstructed_pixel_values = outputs.loss, outputs.logits
823
+ >>> list(reconstructed_pixel_values.shape)
824
+ [1, 3, 192, 192]
825
+ ```"""
826
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
827
+
828
+ outputs = self.focalnet(
829
+ pixel_values,
830
+ bool_masked_pos=bool_masked_pos,
831
+ output_hidden_states=output_hidden_states,
832
+ return_dict=return_dict,
833
+ )
834
+
835
+ sequence_output = outputs[0]
836
+ # Reshape to (batch_size, num_channels, height, width)
837
+ sequence_output = sequence_output.transpose(1, 2)
838
+ batch_size, num_channels, sequence_length = sequence_output.shape
839
+ height = width = math.floor(sequence_length**0.5)
840
+ sequence_output = sequence_output.reshape(batch_size, num_channels, height, width)
841
+
842
+ # Reconstruct pixel values
843
+ reconstructed_pixel_values = self.decoder(sequence_output)
844
+
845
+ masked_im_loss = None
846
+ if bool_masked_pos is not None:
847
+ size = self.config.image_size // self.config.patch_size
848
+ bool_masked_pos = bool_masked_pos.reshape(-1, size, size)
849
+ mask = (
850
+ bool_masked_pos.repeat_interleave(self.config.patch_size, 1)
851
+ .repeat_interleave(self.config.patch_size, 2)
852
+ .unsqueeze(1)
853
+ .contiguous()
854
+ )
855
+ reconstruction_loss = nn.functional.l1_loss(pixel_values, reconstructed_pixel_values, reduction="none")
856
+ masked_im_loss = (reconstruction_loss * mask).sum() / (mask.sum() + 1e-5) / self.config.num_channels
857
+
858
+ if not return_dict:
859
+ output = (reconstructed_pixel_values,) + outputs[2:]
860
+ return ((masked_im_loss,) + output) if masked_im_loss is not None else output
861
+
862
+ return FocalNetMaskedImageModelingOutput(
863
+ loss=masked_im_loss,
864
+ reconstruction=reconstructed_pixel_values,
865
+ hidden_states=outputs.hidden_states,
866
+ reshaped_hidden_states=outputs.reshaped_hidden_states,
867
+ )
868
+
869
+
870
+ @add_start_docstrings(
871
+ """
872
+ FocalNet Model with an image classification head on top (a linear layer on top of the pooled output) e.g. for
873
+ ImageNet.
874
+ """,
875
+ FOCALNET_START_DOCSTRING,
876
+ )
877
+ class FocalNetForImageClassification(FocalNetPreTrainedModel):
878
+ # Copied from transformers.models.swin.modeling_swin.SwinForImageClassification.__init__ with Swin->FocalNet, swin->focalnet
879
+ def __init__(self, config):
880
+ super().__init__(config)
881
+
882
+ self.num_labels = config.num_labels
883
+ self.focalnet = FocalNetModel(config)
884
+
885
+ # Classifier head
886
+ self.classifier = (
887
+ nn.Linear(self.focalnet.num_features, config.num_labels) if config.num_labels > 0 else nn.Identity()
888
+ )
889
+
890
+ # Initialize weights and apply final processing
891
+ self.post_init()
892
+
893
+ @add_start_docstrings_to_model_forward(FOCALNET_INPUTS_DOCSTRING)
894
+ @add_code_sample_docstrings(
895
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
896
+ output_type=FocalNetImageClassifierOutput,
897
+ config_class=_CONFIG_FOR_DOC,
898
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
899
+ )
900
+ def forward(
901
+ self,
902
+ pixel_values: Optional[torch.FloatTensor] = None,
903
+ labels: Optional[torch.LongTensor] = None,
904
+ output_hidden_states: Optional[bool] = None,
905
+ return_dict: Optional[bool] = None,
906
+ ) -> Union[Tuple, FocalNetImageClassifierOutput]:
907
+ r"""
908
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
909
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
910
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
911
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
912
+ """
913
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
914
+
915
+ outputs = self.focalnet(
916
+ pixel_values,
917
+ output_hidden_states=output_hidden_states,
918
+ return_dict=return_dict,
919
+ )
920
+
921
+ pooled_output = outputs[1]
922
+
923
+ logits = self.classifier(pooled_output)
924
+
925
+ loss = None
926
+ if labels is not None:
927
+ if self.config.problem_type is None:
928
+ if self.num_labels == 1:
929
+ self.config.problem_type = "regression"
930
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
931
+ self.config.problem_type = "single_label_classification"
932
+ else:
933
+ self.config.problem_type = "multi_label_classification"
934
+
935
+ if self.config.problem_type == "regression":
936
+ loss_fct = MSELoss()
937
+ if self.num_labels == 1:
938
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
939
+ else:
940
+ loss = loss_fct(logits, labels)
941
+ elif self.config.problem_type == "single_label_classification":
942
+ loss_fct = CrossEntropyLoss()
943
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
944
+ elif self.config.problem_type == "multi_label_classification":
945
+ loss_fct = BCEWithLogitsLoss()
946
+ loss = loss_fct(logits, labels)
947
+
948
+ if not return_dict:
949
+ output = (logits,) + outputs[2:]
950
+ return ((loss,) + output) if loss is not None else output
951
+
952
+ return FocalNetImageClassifierOutput(
953
+ loss=loss,
954
+ logits=logits,
955
+ hidden_states=outputs.hidden_states,
956
+ reshaped_hidden_states=outputs.reshaped_hidden_states,
957
+ )
958
+
959
+
960
+ @add_start_docstrings(
961
+ """
962
+ FocalNet backbone, to be used with frameworks like X-Decoder.
963
+ """,
964
+ FOCALNET_START_DOCSTRING,
965
+ )
966
+ class FocalNetBackbone(FocalNetPreTrainedModel, BackboneMixin):
967
+ def __init__(self, config: FocalNetConfig):
968
+ super().__init__(config)
969
+ super()._init_backbone(config)
970
+
971
+ self.num_features = [config.embed_dim] + config.hidden_sizes
972
+ self.focalnet = FocalNetModel(config)
973
+
974
+ # initialize weights and apply final processing
975
+ self.post_init()
976
+
977
+ @add_start_docstrings_to_model_forward(FOCALNET_INPUTS_DOCSTRING)
978
+ @replace_return_docstrings(output_type=BackboneOutput, config_class=_CONFIG_FOR_DOC)
979
+ def forward(
980
+ self,
981
+ pixel_values: torch.Tensor,
982
+ output_hidden_states: Optional[bool] = None,
983
+ return_dict: Optional[bool] = None,
984
+ ) -> BackboneOutput:
985
+ """
986
+ Returns:
987
+
988
+ Examples:
989
+
990
+ ```python
991
+ >>> from transformers import AutoImageProcessor, AutoBackbone
992
+ >>> import torch
993
+ >>> from PIL import Image
994
+ >>> import requests
995
+
996
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
997
+ >>> image = Image.open(requests.get(url, stream=True).raw)
998
+
999
+ >>> processor = AutoImageProcessor.from_pretrained("microsoft/focalnet-tiny-lrf")
1000
+ >>> model = AutoBackbone.from_pretrained("microsoft/focalnet-tiny-lrf")
1001
+
1002
+ >>> inputs = processor(image, return_tensors="pt")
1003
+ >>> outputs = model(**inputs)
1004
+ ```"""
1005
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1006
+ output_hidden_states = (
1007
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1008
+ )
1009
+
1010
+ outputs = self.focalnet(pixel_values, output_hidden_states=True, return_dict=True)
1011
+
1012
+ hidden_states = outputs.reshaped_hidden_states
1013
+
1014
+ feature_maps = ()
1015
+ for idx, stage in enumerate(self.stage_names):
1016
+ if stage in self.out_features:
1017
+ feature_maps += (hidden_states[idx],)
1018
+
1019
+ if not return_dict:
1020
+ output = (feature_maps,)
1021
+ if output_hidden_states:
1022
+ output += (outputs.hidden_states,)
1023
+ return output
1024
+
1025
+ return BackboneOutput(
1026
+ feature_maps=feature_maps,
1027
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
1028
+ attentions=None,
1029
+ )
1030
+
1031
+
1032
+ __all__ = [
1033
+ "FocalNetForImageClassification",
1034
+ "FocalNetForMaskedImageModeling",
1035
+ "FocalNetBackbone",
1036
+ "FocalNetModel",
1037
+ "FocalNetPreTrainedModel",
1038
+ ]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fsmt/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_fsmt import *
22
+ from .modeling_fsmt import *
23
+ from .tokenization_fsmt import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fsmt/configuration_fsmt.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019-present, Facebook, Inc 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
+ """FSMT configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class DecoderConfig(PretrainedConfig):
25
+ r"""
26
+ Configuration class for FSMT's decoder specific things. note: this is a private helper class
27
+ """
28
+
29
+ model_type = "fsmt_decoder"
30
+
31
+ def __init__(self, vocab_size=0, bos_token_id=0):
32
+ super().__init__()
33
+ self.vocab_size = vocab_size
34
+ self.bos_token_id = bos_token_id
35
+
36
+
37
+ class FSMTConfig(PretrainedConfig):
38
+ r"""
39
+ This is the configuration class to store the configuration of a [`FSMTModel`]. It is used to instantiate a FSMT
40
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
41
+ defaults will yield a similar configuration to that of the FSMT
42
+ [facebook/wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru) architecture.
43
+
44
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
45
+ documentation from [`PretrainedConfig`] for more information.
46
+
47
+ Args:
48
+ langs (`List[str]`):
49
+ A list with source language and target_language (e.g., ['en', 'ru']).
50
+ src_vocab_size (`int`):
51
+ Vocabulary size of the encoder. Defines the number of different tokens that can be represented by the
52
+ `inputs_ids` passed to the forward method in the encoder.
53
+ tgt_vocab_size (`int`):
54
+ Vocabulary size of the decoder. Defines the number of different tokens that can be represented by the
55
+ `inputs_ids` passed to the forward method in the decoder.
56
+ d_model (`int`, *optional*, defaults to 1024):
57
+ Dimensionality of the layers and the pooler layer.
58
+ encoder_layers (`int`, *optional*, defaults to 12):
59
+ Number of encoder layers.
60
+ decoder_layers (`int`, *optional*, defaults to 12):
61
+ Number of decoder layers.
62
+ encoder_attention_heads (`int`, *optional*, defaults to 16):
63
+ Number of attention heads for each attention layer in the Transformer encoder.
64
+ decoder_attention_heads (`int`, *optional*, defaults to 16):
65
+ Number of attention heads for each attention layer in the Transformer decoder.
66
+ decoder_ffn_dim (`int`, *optional*, defaults to 4096):
67
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
68
+ encoder_ffn_dim (`int`, *optional*, defaults to 4096):
69
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
70
+ activation_function (`str` or `Callable`, *optional*, defaults to `"relu"`):
71
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
72
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
73
+ dropout (`float`, *optional*, defaults to 0.1):
74
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
75
+ attention_dropout (`float`, *optional*, defaults to 0.0):
76
+ The dropout ratio for the attention probabilities.
77
+ activation_dropout (`float`, *optional*, defaults to 0.0):
78
+ The dropout ratio for activations inside the fully connected layer.
79
+ max_position_embeddings (`int`, *optional*, defaults to 1024):
80
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
81
+ just in case (e.g., 512 or 1024 or 2048).
82
+ init_std (`float`, *optional*, defaults to 0.02):
83
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
84
+ scale_embedding (`bool`, *optional*, defaults to `True`):
85
+ Scale embeddings by diving by sqrt(d_model).
86
+ bos_token_id (`int`, *optional*, defaults to 0)
87
+ Beginning of stream token id.
88
+ pad_token_id (`int`, *optional*, defaults to 1)
89
+ Padding token id.
90
+ eos_token_id (`int`, *optional*, defaults to 2)
91
+ End of stream token id.
92
+ decoder_start_token_id (`int`, *optional*):
93
+ This model starts decoding with `eos_token_id`
94
+ encoder_layerdrop (`float`, *optional*, defaults to 0.0):
95
+ Google "layerdrop arxiv", as its not explainable in one line.
96
+ decoder_layerdrop (`float`, *optional*, defaults to 0.0):
97
+ Google "layerdrop arxiv", as its not explainable in one line.
98
+ is_encoder_decoder (`bool`, *optional*, defaults to `True`):
99
+ Whether this is an encoder/decoder model.
100
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
101
+ Whether to tie input and output embeddings.
102
+ num_beams (`int`, *optional*, defaults to 5)
103
+ Number of beams for beam search that will be used by default in the `generate` method of the model. 1 means
104
+ no beam search.
105
+ length_penalty (`float`, *optional*, defaults to 1)
106
+ Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to
107
+ the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log
108
+ likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while
109
+ `length_penalty` < 0.0 encourages shorter sequences.
110
+ early_stopping (`bool`, *optional*, defaults to `False`)
111
+ Flag that will be used by default in the `generate` method of the model. Whether to stop the beam search
112
+ when at least `num_beams` sentences are finished per batch or not.
113
+ use_cache (`bool`, *optional*, defaults to `True`):
114
+ Whether or not the model should return the last key/values attentions (not used by all models).
115
+ forced_eos_token_id (`int`, *optional*, defaults to 2):
116
+ The id of the token to force as the last generated token when `max_length` is reached. Usually set to
117
+ `eos_token_id`.
118
+
119
+ Examples:
120
+
121
+ ```python
122
+ >>> from transformers import FSMTConfig, FSMTModel
123
+
124
+ >>> # Initializing a FSMT facebook/wmt19-en-ru style configuration
125
+ >>> config = FSMTConfig()
126
+
127
+ >>> # Initializing a model (with random weights) from the configuration
128
+ >>> model = FSMTModel(config)
129
+
130
+ >>> # Accessing the model configuration
131
+ >>> configuration = model.config
132
+ ```"""
133
+
134
+ model_type = "fsmt"
135
+ attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
136
+
137
+ # update the defaults from config file
138
+ def __init__(
139
+ self,
140
+ langs=["en", "de"],
141
+ src_vocab_size=42024,
142
+ tgt_vocab_size=42024,
143
+ activation_function="relu",
144
+ d_model=1024,
145
+ max_length=200,
146
+ max_position_embeddings=1024,
147
+ encoder_ffn_dim=4096,
148
+ encoder_layers=12,
149
+ encoder_attention_heads=16,
150
+ encoder_layerdrop=0.0,
151
+ decoder_ffn_dim=4096,
152
+ decoder_layers=12,
153
+ decoder_attention_heads=16,
154
+ decoder_layerdrop=0.0,
155
+ attention_dropout=0.0,
156
+ dropout=0.1,
157
+ activation_dropout=0.0,
158
+ init_std=0.02,
159
+ decoder_start_token_id=2,
160
+ is_encoder_decoder=True,
161
+ scale_embedding=True,
162
+ tie_word_embeddings=False,
163
+ num_beams=5,
164
+ length_penalty=1.0,
165
+ early_stopping=False,
166
+ use_cache=True,
167
+ pad_token_id=1,
168
+ bos_token_id=0,
169
+ eos_token_id=2,
170
+ forced_eos_token_id=2,
171
+ **common_kwargs,
172
+ ):
173
+ self.langs = langs
174
+ self.src_vocab_size = src_vocab_size
175
+ self.tgt_vocab_size = tgt_vocab_size
176
+ self.d_model = d_model # encoder_embed_dim and decoder_embed_dim
177
+
178
+ self.encoder_ffn_dim = encoder_ffn_dim
179
+ self.encoder_layers = self.num_hidden_layers = encoder_layers
180
+ self.encoder_attention_heads = encoder_attention_heads
181
+ self.encoder_layerdrop = encoder_layerdrop
182
+ self.decoder_layerdrop = decoder_layerdrop
183
+ self.decoder_ffn_dim = decoder_ffn_dim
184
+ self.decoder_layers = decoder_layers
185
+ self.decoder_attention_heads = decoder_attention_heads
186
+ self.max_position_embeddings = max_position_embeddings
187
+ self.init_std = init_std # Normal(0, this parameter)
188
+ self.activation_function = activation_function
189
+
190
+ self.decoder = DecoderConfig(vocab_size=tgt_vocab_size, bos_token_id=eos_token_id)
191
+ if "decoder" in common_kwargs:
192
+ del common_kwargs["decoder"]
193
+
194
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
195
+
196
+ # 3 Types of Dropout
197
+ self.attention_dropout = attention_dropout
198
+ self.activation_dropout = activation_dropout
199
+ self.dropout = dropout
200
+
201
+ self.use_cache = use_cache
202
+ super().__init__(
203
+ pad_token_id=pad_token_id,
204
+ bos_token_id=bos_token_id,
205
+ eos_token_id=eos_token_id,
206
+ decoder_start_token_id=decoder_start_token_id,
207
+ is_encoder_decoder=is_encoder_decoder,
208
+ tie_word_embeddings=tie_word_embeddings,
209
+ forced_eos_token_id=forced_eos_token_id,
210
+ max_length=max_length,
211
+ num_beams=num_beams,
212
+ length_penalty=length_penalty,
213
+ early_stopping=early_stopping,
214
+ **common_kwargs,
215
+ )
216
+
217
+
218
+ __all__ = ["FSMTConfig"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fsmt/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 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
+ # Note: if you intend to run this script make sure you look under scripts/fsmt/
17
+ # to locate the appropriate script to do the work correctly. There is a set of scripts to:
18
+ # - download and prepare data and run the conversion script
19
+ # - perform eval to get the best hparam into the config
20
+ # - generate model_cards - useful if you have multiple models from the same paper
21
+
22
+ import argparse
23
+ import json
24
+ import os
25
+ import re
26
+ from collections import OrderedDict
27
+ from os.path import basename, dirname
28
+
29
+ import fairseq
30
+ import torch
31
+ from fairseq import hub_utils
32
+ from fairseq.data.dictionary import Dictionary
33
+
34
+ from transformers import FSMTConfig, FSMTForConditionalGeneration
35
+ from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES
36
+ from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE
37
+ from transformers.utils import WEIGHTS_NAME, logging
38
+
39
+
40
+ logging.set_verbosity_warning()
41
+
42
+ json_indent = 2
43
+
44
+ # based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping`
45
+ # values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults:
46
+ #
47
+ # * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users)
48
+ # * `early_stopping`: `False` consistently scored better
49
+ # * `length_penalty` varied, so will assign the best one depending on the model
50
+ best_score_hparams = {
51
+ # fairseq:
52
+ "wmt19-ru-en": {"length_penalty": 1.1},
53
+ "wmt19-en-ru": {"length_penalty": 1.15},
54
+ "wmt19-en-de": {"length_penalty": 1.0},
55
+ "wmt19-de-en": {"length_penalty": 1.1},
56
+ # allenai:
57
+ "wmt16-en-de-dist-12-1": {"length_penalty": 0.6},
58
+ "wmt16-en-de-dist-6-1": {"length_penalty": 0.6},
59
+ "wmt16-en-de-12-1": {"length_penalty": 0.8},
60
+ "wmt19-de-en-6-6-base": {"length_penalty": 0.6},
61
+ "wmt19-de-en-6-6-big": {"length_penalty": 0.6},
62
+ }
63
+
64
+ # this remaps the different models to their organization names
65
+ org_names = {}
66
+ for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
67
+ org_names[m] = "facebook"
68
+ for m in [
69
+ "wmt16-en-de-dist-12-1",
70
+ "wmt16-en-de-dist-6-1",
71
+ "wmt16-en-de-12-1",
72
+ "wmt19-de-en-6-6-base",
73
+ "wmt19-de-en-6-6-big",
74
+ ]:
75
+ org_names[m] = "allenai"
76
+
77
+
78
+ def rewrite_dict_keys(d):
79
+ # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up,
80
+ # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7}
81
+ d2 = dict((re.sub(r"@@$", "", k), v) if k.endswith("@@") else (re.sub(r"$", "</w>", k), v) for k, v in d.items())
82
+ keep_keys = "<s> <pad> </s> <unk>".split()
83
+ # restore the special tokens
84
+ for k in keep_keys:
85
+ del d2[f"{k}</w>"]
86
+ d2[k] = d[k] # restore
87
+ return d2
88
+
89
+
90
+ def convert_fsmt_checkpoint_to_pytorch(fsmt_checkpoint_path, pytorch_dump_folder_path):
91
+ # prep
92
+ assert os.path.exists(fsmt_checkpoint_path)
93
+ os.makedirs(pytorch_dump_folder_path, exist_ok=True)
94
+ print(f"Writing results to {pytorch_dump_folder_path}")
95
+
96
+ # handle various types of models
97
+
98
+ checkpoint_file = basename(fsmt_checkpoint_path)
99
+ fsmt_folder_path = dirname(fsmt_checkpoint_path)
100
+
101
+ cls = fairseq.model_parallel.models.transformer.ModelParallelTransformerModel
102
+ models = cls.hub_models()
103
+ kwargs = {"bpe": "fastbpe", "tokenizer": "moses"}
104
+ data_name_or_path = "."
105
+ # note: since the model dump is old, fairseq has upgraded its model some
106
+ # time later, and it does a whole lot of rewrites and splits on the saved
107
+ # weights, therefore we can't use torch.load() directly on the model file.
108
+ # see: upgrade_state_dict(state_dict) in fairseq_model.py
109
+ print(f"using checkpoint {checkpoint_file}")
110
+ chkpt = hub_utils.from_pretrained(
111
+ fsmt_folder_path, checkpoint_file, data_name_or_path, archive_map=models, **kwargs
112
+ )
113
+
114
+ args = vars(chkpt["args"]["model"])
115
+
116
+ src_lang = args["source_lang"]
117
+ tgt_lang = args["target_lang"]
118
+
119
+ data_root = dirname(pytorch_dump_folder_path)
120
+ model_dir = basename(pytorch_dump_folder_path)
121
+
122
+ # dicts
123
+ src_dict_file = os.path.join(fsmt_folder_path, f"dict.{src_lang}.txt")
124
+ tgt_dict_file = os.path.join(fsmt_folder_path, f"dict.{tgt_lang}.txt")
125
+
126
+ src_dict = Dictionary.load(src_dict_file)
127
+ src_vocab = rewrite_dict_keys(src_dict.indices)
128
+ src_vocab_size = len(src_vocab)
129
+ src_vocab_file = os.path.join(pytorch_dump_folder_path, "vocab-src.json")
130
+ print(f"Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records")
131
+ with open(src_vocab_file, "w", encoding="utf-8") as f:
132
+ f.write(json.dumps(src_vocab, ensure_ascii=False, indent=json_indent))
133
+
134
+ # detect whether this is a do_lower_case situation, which can be derived by checking whether we
135
+ # have at least one uppercase letter in the source vocab
136
+ do_lower_case = True
137
+ for k in src_vocab.keys():
138
+ if not k.islower():
139
+ do_lower_case = False
140
+ break
141
+
142
+ tgt_dict = Dictionary.load(tgt_dict_file)
143
+ tgt_vocab = rewrite_dict_keys(tgt_dict.indices)
144
+ tgt_vocab_size = len(tgt_vocab)
145
+ tgt_vocab_file = os.path.join(pytorch_dump_folder_path, "vocab-tgt.json")
146
+ print(f"Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records")
147
+ with open(tgt_vocab_file, "w", encoding="utf-8") as f:
148
+ f.write(json.dumps(tgt_vocab, ensure_ascii=False, indent=json_indent))
149
+
150
+ # merges_file (bpecodes)
151
+ merges_file = os.path.join(pytorch_dump_folder_path, VOCAB_FILES_NAMES["merges_file"])
152
+ for fn in ["bpecodes", "code"]: # older fairseq called the merges file "code"
153
+ fsmt_merges_file = os.path.join(fsmt_folder_path, fn)
154
+ if os.path.exists(fsmt_merges_file):
155
+ break
156
+ with open(fsmt_merges_file, encoding="utf-8") as fin:
157
+ merges = fin.read()
158
+ merges = re.sub(r" \d+$", "", merges, 0, re.M) # remove frequency number
159
+ print(f"Generating {merges_file}")
160
+ with open(merges_file, "w", encoding="utf-8") as fout:
161
+ fout.write(merges)
162
+
163
+ # model config
164
+ fsmt_model_config_file = os.path.join(pytorch_dump_folder_path, "config.json")
165
+
166
+ # validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe -
167
+ # may have to modify the tokenizer if a different type is used by a future model
168
+ assert args["bpe"] == "fastbpe", f"need to extend tokenizer to support bpe={args['bpe']}"
169
+ assert args["tokenizer"] == "moses", f"need to extend tokenizer to support bpe={args['tokenizer']}"
170
+
171
+ model_conf = {
172
+ "architectures": ["FSMTForConditionalGeneration"],
173
+ "model_type": "fsmt",
174
+ "activation_dropout": args["activation_dropout"],
175
+ "activation_function": "relu",
176
+ "attention_dropout": args["attention_dropout"],
177
+ "d_model": args["decoder_embed_dim"],
178
+ "dropout": args["dropout"],
179
+ "init_std": 0.02,
180
+ "max_position_embeddings": args["max_source_positions"],
181
+ "num_hidden_layers": args["encoder_layers"],
182
+ "src_vocab_size": src_vocab_size,
183
+ "tgt_vocab_size": tgt_vocab_size,
184
+ "langs": [src_lang, tgt_lang],
185
+ "encoder_attention_heads": args["encoder_attention_heads"],
186
+ "encoder_ffn_dim": args["encoder_ffn_embed_dim"],
187
+ "encoder_layerdrop": args["encoder_layerdrop"],
188
+ "encoder_layers": args["encoder_layers"],
189
+ "decoder_attention_heads": args["decoder_attention_heads"],
190
+ "decoder_ffn_dim": args["decoder_ffn_embed_dim"],
191
+ "decoder_layerdrop": args["decoder_layerdrop"],
192
+ "decoder_layers": args["decoder_layers"],
193
+ "bos_token_id": 0,
194
+ "pad_token_id": 1,
195
+ "eos_token_id": 2,
196
+ "is_encoder_decoder": True,
197
+ "scale_embedding": not args["no_scale_embedding"],
198
+ "tie_word_embeddings": args["share_all_embeddings"],
199
+ }
200
+
201
+ # good hparam defaults to start with
202
+ model_conf["num_beams"] = 5
203
+ model_conf["early_stopping"] = False
204
+ if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]:
205
+ model_conf["length_penalty"] = best_score_hparams[model_dir]["length_penalty"]
206
+ else:
207
+ model_conf["length_penalty"] = 1.0
208
+
209
+ print(f"Generating {fsmt_model_config_file}")
210
+ with open(fsmt_model_config_file, "w", encoding="utf-8") as f:
211
+ f.write(json.dumps(model_conf, ensure_ascii=False, indent=json_indent))
212
+
213
+ # tokenizer config
214
+ fsmt_tokenizer_config_file = os.path.join(pytorch_dump_folder_path, TOKENIZER_CONFIG_FILE)
215
+
216
+ tokenizer_conf = {
217
+ "langs": [src_lang, tgt_lang],
218
+ "model_max_length": 1024,
219
+ "do_lower_case": do_lower_case,
220
+ }
221
+
222
+ print(f"Generating {fsmt_tokenizer_config_file}")
223
+ with open(fsmt_tokenizer_config_file, "w", encoding="utf-8") as f:
224
+ f.write(json.dumps(tokenizer_conf, ensure_ascii=False, indent=json_indent))
225
+
226
+ # model
227
+ model = chkpt["models"][0]
228
+ model_state_dict = model.state_dict()
229
+
230
+ # rename keys to start with 'model.'
231
+ model_state_dict = OrderedDict(("model." + k, v) for k, v in model_state_dict.items())
232
+
233
+ # remove unneeded keys
234
+ ignore_keys = [
235
+ "model.model",
236
+ "model.encoder.version",
237
+ "model.decoder.version",
238
+ "model.encoder_embed_tokens.weight",
239
+ "model.decoder_embed_tokens.weight",
240
+ "model.encoder.embed_positions._float_tensor",
241
+ "model.decoder.embed_positions._float_tensor",
242
+ ]
243
+ for k in ignore_keys:
244
+ model_state_dict.pop(k, None)
245
+
246
+ config = FSMTConfig.from_pretrained(pytorch_dump_folder_path)
247
+ model_new = FSMTForConditionalGeneration(config)
248
+
249
+ # check that it loads ok
250
+ model_new.load_state_dict(model_state_dict, strict=False)
251
+
252
+ # save
253
+ pytorch_weights_dump_path = os.path.join(pytorch_dump_folder_path, WEIGHTS_NAME)
254
+ print(f"Generating {pytorch_weights_dump_path}")
255
+ torch.save(model_state_dict, pytorch_weights_dump_path)
256
+
257
+ print("Conversion is done!")
258
+ print("\nLast step is to upload the files to s3")
259
+ print(f"cd {data_root}")
260
+ print(f"transformers-cli upload {model_dir}")
261
+
262
+
263
+ if __name__ == "__main__":
264
+ parser = argparse.ArgumentParser()
265
+ # Required parameters
266
+ parser.add_argument(
267
+ "--fsmt_checkpoint_path",
268
+ default=None,
269
+ type=str,
270
+ required=True,
271
+ help=(
272
+ "Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,"
273
+ " bpecodes, etc."
274
+ ),
275
+ )
276
+ parser.add_argument(
277
+ "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
278
+ )
279
+ args = parser.parse_args()
280
+ convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fsmt/modeling_fsmt.py ADDED
@@ -0,0 +1,1369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Facebook AI Research 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
+ #
16
+ # Original implementation: https://github.com/pytorch/fairseq/tree/master/examples/wmt19
17
+ # Authors:
18
+ # - @alexeib Alexei Baevski
19
+ # - @edunov Sergey Edunov
20
+ # - @michaelauli Michael Auli
21
+ # - @myleott Myle Ott
22
+ # - @nng555 Nathan Ng
23
+ # - David Grangier
24
+ # - Kyra Yee
25
+ #
26
+ # Paper: Facebook FAIR's WMT19 News Translation Task Submission https://arxiv.org/abs/1907.06616
27
+ #
28
+ """PyTorch Fairseq model, ported from https://github.com/pytorch/fairseq/tree/master/examples/wmt19"""
29
+
30
+ import math
31
+ from typing import Any, Dict, List, Optional, Tuple, Union
32
+
33
+ import torch
34
+ from torch import Tensor, nn
35
+ from torch.nn import CrossEntropyLoss, LayerNorm
36
+
37
+ from ...activations import ACT2FN
38
+ from ...generation import GenerationMixin
39
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
40
+ from ...modeling_outputs import (
41
+ BaseModelOutput,
42
+ BaseModelOutputWithPastAndCrossAttentions,
43
+ Seq2SeqLMOutput,
44
+ Seq2SeqModelOutput,
45
+ )
46
+ from ...modeling_utils import PreTrainedModel
47
+ from ...utils import (
48
+ add_code_sample_docstrings,
49
+ add_end_docstrings,
50
+ add_start_docstrings,
51
+ add_start_docstrings_to_model_forward,
52
+ logging,
53
+ replace_return_docstrings,
54
+ )
55
+ from .configuration_fsmt import FSMTConfig
56
+
57
+
58
+ logger = logging.get_logger(__name__)
59
+
60
+ _CHECKPOINT_FOR_DOC = "facebook/wmt19-ru-en"
61
+ _CONFIG_FOR_DOC = "FSMTConfig"
62
+
63
+ # See all FSMT models at https://huggingface.co/models?filter=fsmt
64
+
65
+ # Porting notes:
66
+ # this one is modeled after BartModel*
67
+ #
68
+ # Currently only translation (fairseq also has weights for LM)
69
+ #
70
+ # fairseq provides weights for ru-en, en-ru and de-en, en-de pairs. All have been ported.
71
+ # - ru-en, en-ru use asymmetric vocab
72
+ # - de-en, en-de use a merged single vocab (but the code works as if they are separate)
73
+ #
74
+ # Differences with Bart:
75
+ # - not using bos token
76
+ # - 2 separate vocabs (src and target)
77
+ # - embed weights aren't tied
78
+ # - uses a model Ensemble (but that part isn't ported/implemented yet) - so we
79
+ # aren't getting as good of a BLEU score
80
+ # - uses a projection layer at the end of the decoder
81
+ # - doesn't use final_logits_bias
82
+ # - beam search: stops as soon as num_beams == len(hypos) (whereas transformers
83
+ # is not satisfied there and will continue searching until the next cycles
84
+ # aren't promising something better), comparing BLEU scores - the transformers
85
+ # algorithm is slightly superior, therefore using the latter. But if you want
86
+ # to match fairseq outputs, you need to pass ``early_stopping=True`` to ``generate()``.
87
+ #
88
+ # SinusoidalPositionalEmbedding is slightly different from Bart's - generates
89
+ # different embeddings. This implementation is copied verbatim from fairseq with
90
+ # some small changes to make it work here.
91
+ #
92
+ # Other changes:
93
+ # - doesn't support use_cache as Bart's version does
94
+ #
95
+ #
96
+ # FSMTConfig changes with BartConfig
97
+ #
98
+ # Differences with BART:
99
+ # - src/tgt vocabs aren't shared
100
+ # - token embeddings aren't shared
101
+ # - needs a language pair
102
+ # - scale_embedding are True
103
+ #
104
+ # some unused args were removed too
105
+ #
106
+ #
107
+ # TODO:
108
+ # - port model ensemble (fs uses 4 model checkpoints)
109
+ # - solve beam search discrepancies
110
+ # docstyle-ignore
111
+
112
+ """
113
+
114
+ Here is how to compare BLEU scores against fairseq implementation:
115
+
116
+ # en-ru
117
+
118
+ export PAIR=en-ru
119
+ export DATA_DIR=data/$PAIR
120
+ export SAVE_DIR=data/$PAIR
121
+ export BS=8
122
+ export NUM_BEAMS=50
123
+ mkdir -p $DATA_DIR
124
+ sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
125
+ sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
126
+ echo $PAIR
127
+ PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
128
+
129
+ # (fairseq BLEU: 36.4 http://matrix.statmt.org/matrix/output/1914?score_id=37605)
130
+
131
+
132
+ # ru-en
133
+
134
+ export PAIR=ru-en
135
+ export DATA_DIR=data/$PAIR
136
+ export SAVE_DIR=data/$PAIR
137
+ export BS=8
138
+ export NUM_BEAMS=50
139
+ mkdir -p $DATA_DIR
140
+ sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
141
+ sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
142
+ PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
143
+
144
+
145
+ # (fairseq BLEU: 41.3 http://matrix.statmt.org/matrix/output/1907?run_id=6937)
146
+
147
+
148
+ # de-en
149
+
150
+ export PAIR=de-en
151
+ export DATA_DIR=data/$PAIR
152
+ export SAVE_DIR=data/$PAIR
153
+ export BS=8
154
+ export NUM_BEAMS=50
155
+ mkdir -p $DATA_DIR
156
+ sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
157
+ sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
158
+ echo $PAIR
159
+ PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
160
+
161
+ # (fairseq BLEU: 42.3 http://matrix.statmt.org/matrix/output/1902?run_id=6750)
162
+
163
+
164
+
165
+ # en-de
166
+
167
+ export PAIR=en-de
168
+ export DATA_DIR=data/$PAIR
169
+ export SAVE_DIR=data/$PAIR
170
+ export BS=8
171
+ mkdir -p $DATA_DIR
172
+ sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
173
+ sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
174
+ echo $PAIR
175
+ PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
176
+
177
+ # (fairseq BLEU: 43.1 http://matrix.statmt.org/matrix/output/1909?run_id=6862)
178
+
179
+ """
180
+
181
+
182
+ FSMT_START_DOCSTRING = r"""
183
+
184
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
185
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
186
+ etc.)
187
+
188
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
189
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
190
+ and behavior.
191
+
192
+ Parameters:
193
+ config ([`FSMTConfig`]): Model configuration class with all the parameters of the model.
194
+ Initializing with a config file does not load the weights associated with the model, only the
195
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
196
+
197
+ """
198
+ FSMT_GENERATION_EXAMPLE = r"""
199
+ Translation example::
200
+
201
+ ```python
202
+ >>> from transformers import AutoTokenizer, FSMTForConditionalGeneration
203
+
204
+ >>> mname = "facebook/wmt19-ru-en"
205
+ >>> model = FSMTForConditionalGeneration.from_pretrained(mname)
206
+ >>> tokenizer = AutoTokenizer.from_pretrained(mname)
207
+
208
+ >>> src_text = "Машинное обучение - это здорово, не так ли?"
209
+ >>> input_ids = tokenizer(src_text, return_tensors="pt").input_ids
210
+ >>> outputs = model.generate(input_ids, num_beams=5, num_return_sequences=3)
211
+ >>> tokenizer.decode(outputs[0], skip_special_tokens=True)
212
+ "Machine learning is great, isn't it?"
213
+ ```
214
+
215
+ """
216
+
217
+ FSMT_INPUTS_DOCSTRING = r"""
218
+ Args:
219
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
220
+ Indices of input sequence tokens in the vocabulary.
221
+
222
+ Indices can be obtained using [`FSTMTokenizer`]. See [`PreTrainedTokenizer.encode`] and
223
+ [`PreTrainedTokenizer.__call__`] for details.
224
+
225
+ [What are input IDs?](../glossary#input-ids)
226
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
227
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
228
+
229
+ - 1 for tokens that are **not masked**,
230
+ - 0 for tokens that are **masked**.
231
+
232
+ [What are attention masks?](../glossary#attention-mask)
233
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
234
+ Indices of decoder input sequence tokens in the vocabulary.
235
+
236
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
237
+ [`PreTrainedTokenizer.__call__`] for details.
238
+
239
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
240
+
241
+ FSMT uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
242
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
243
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
244
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
245
+ be used by default.
246
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
247
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
248
+
249
+ - 1 indicates the head is **not masked**,
250
+ - 0 indicates the head is **masked**.
251
+
252
+ decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
253
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
254
+
255
+ - 1 indicates the head is **not masked**,
256
+ - 0 indicates the head is **masked**.
257
+
258
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
259
+ Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
260
+ 1]`:
261
+
262
+ - 1 indicates the head is **not masked**,
263
+ - 0 indicates the head is **masked**.
264
+
265
+ encoder_outputs (`Tuple(torch.FloatTensor)`, *optional*):
266
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
267
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)` is a sequence of hidden-states at
268
+ the output of the last layer of the encoder. Used in the cross-attention of the decoder.
269
+ past_key_values (`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)`):
270
+ Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding.
271
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
272
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
273
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
274
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
275
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
276
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
277
+ model's internal embedding lookup matrix.
278
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
279
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
280
+ representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
281
+ input (see `past_key_values`). This is useful if you want more control over how to convert
282
+ `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
283
+
284
+ If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
285
+ of `inputs_embeds`.
286
+ use_cache (`bool`, *optional*, defaults to `True`):
287
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
288
+ `past_key_values`).
289
+ output_attentions (`bool`, *optional*):
290
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
291
+ tensors for more detail.
292
+ output_hidden_states (`bool`, *optional*):
293
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
294
+ more detail.
295
+ return_dict (`bool`, *optional*):
296
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
297
+ """
298
+
299
+
300
+ def invert_mask(attention_mask):
301
+ """Turns 1->0, 0->1, False->True, True-> False"""
302
+ assert attention_mask.dim() == 2
303
+ return attention_mask.eq(0)
304
+
305
+
306
+ def triu_onnx(x, diagonal=0):
307
+ l = x.shape[0]
308
+ arange = torch.arange(l, device=x.device)
309
+ mask = arange.expand(l, l)
310
+ arange = arange.unsqueeze(-1)
311
+ if diagonal:
312
+ arange = arange + diagonal
313
+ mask = mask >= arange
314
+ return x.masked_fill(mask == 0, 0)
315
+
316
+
317
+ def _prepare_fsmt_decoder_inputs(
318
+ config,
319
+ input_ids,
320
+ decoder_input_ids=None,
321
+ decoder_padding_mask=None,
322
+ causal_mask_dtype=torch.float32,
323
+ ):
324
+ """
325
+ Prepare masks that ignore padding tokens in the decoder and a causal mask for the decoder if none are provided.
326
+ This mimics the default behavior in fairseq. To override it pass in masks. Note: this is not called during
327
+ generation
328
+ """
329
+ pad_token_id = config.pad_token_id
330
+ if decoder_input_ids is None:
331
+ decoder_input_ids = shift_tokens_right(input_ids, pad_token_id)
332
+ bsz, tgt_len = decoder_input_ids.size()
333
+ if decoder_padding_mask is None:
334
+ decoder_padding_mask = make_padding_mask(decoder_input_ids, pad_token_id)
335
+ else:
336
+ decoder_padding_mask = invert_mask(decoder_padding_mask)
337
+ causal_mask = triu_onnx(fill_with_neg_inf(torch.zeros(tgt_len, tgt_len, dtype=causal_mask_dtype)), 1).to(
338
+ device=decoder_input_ids.device
339
+ )
340
+ return decoder_input_ids, decoder_padding_mask, causal_mask
341
+
342
+
343
+ class PretrainedFSMTModel(PreTrainedModel):
344
+ config_class = FSMTConfig
345
+ base_model_prefix = "model"
346
+
347
+ def _init_weights(self, module):
348
+ std = self.config.init_std
349
+ if isinstance(module, nn.Linear):
350
+ module.weight.data.normal_(mean=0.0, std=std)
351
+ if module.bias is not None:
352
+ module.bias.data.zero_()
353
+ elif isinstance(module, SinusoidalPositionalEmbedding):
354
+ pass
355
+ elif isinstance(module, nn.Embedding):
356
+ module.weight.data.normal_(mean=0.0, std=std)
357
+ if module.padding_idx is not None:
358
+ module.weight.data[module.padding_idx].zero_()
359
+
360
+ @property
361
+ def dummy_inputs(self):
362
+ pad_token = self.config.pad_token_id
363
+ input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
364
+ dummy_inputs = {
365
+ "attention_mask": input_ids.ne(pad_token),
366
+ "input_ids": input_ids,
367
+ }
368
+ return dummy_inputs
369
+
370
+
371
+ def _make_linear_from_emb(emb):
372
+ vocab_size, emb_size = emb.weight.shape
373
+ lin_layer = nn.Linear(vocab_size, emb_size, bias=False)
374
+ lin_layer.weight.data = emb.weight.data
375
+ return lin_layer
376
+
377
+
378
+ # Helper Functions, mostly for making masks
379
+ def _check_shapes(shape_1, shape2):
380
+ if shape_1 != shape2:
381
+ raise AssertionError(f"shape mismatch: {shape_1} != {shape2}")
382
+
383
+
384
+ def shift_tokens_right(input_ids, pad_token_id):
385
+ """Shift input ids one token to the right, and wrap the last non pad token (usually <eos>)."""
386
+
387
+ # replace possible -100 values in labels by `pad_token_id`
388
+ input_ids.masked_fill_(input_ids == -100, pad_token_id)
389
+
390
+ prev_output_tokens = input_ids.clone()
391
+ index_of_eos = (input_ids.ne(pad_token_id).sum(dim=1) - 1).unsqueeze(-1)
392
+ prev_output_tokens[:, 0] = input_ids.gather(1, index_of_eos).squeeze()
393
+ prev_output_tokens[:, 1:] = input_ids[:, :-1]
394
+ return prev_output_tokens
395
+
396
+
397
+ def make_padding_mask(input_ids, padding_idx=1):
398
+ """True for pad tokens"""
399
+ padding_mask = input_ids.eq(padding_idx)
400
+ if not padding_mask.any():
401
+ padding_mask = None
402
+ return padding_mask
403
+
404
+
405
+ # Helper Modules
406
+
407
+
408
+ class EncoderLayer(nn.Module):
409
+ def __init__(self, config: FSMTConfig):
410
+ super().__init__()
411
+ self.embed_dim = config.d_model
412
+ self.self_attn = Attention(self.embed_dim, config.encoder_attention_heads, dropout=config.attention_dropout)
413
+ self.self_attn_layer_norm = LayerNorm(self.embed_dim)
414
+ self.dropout = config.dropout
415
+ self.activation_fn = ACT2FN[config.activation_function]
416
+ self.activation_dropout = config.activation_dropout
417
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
418
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
419
+ self.final_layer_norm = LayerNorm(self.embed_dim)
420
+
421
+ def forward(self, x, encoder_padding_mask, layer_head_mask, output_attentions=False):
422
+ """
423
+ Args:
424
+ x (`torch.Tensor`): input to the layer of shape *(seq_len, batch, embed_dim)*
425
+ encoder_padding_mask (`torch.ByteTensor`): binary ByteTensor of shape
426
+ *(batch, src_len)* where padding elements are indicated by `1`.
427
+ for t_tgt, t_src is excluded (or masked out), =0 means it is
428
+ included in attention
429
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
430
+ *(config.encoder_attention_heads,)*.
431
+
432
+ Returns:
433
+ encoded output of shape *(seq_len, batch, embed_dim)*
434
+ """
435
+ residual = x
436
+ x, attn_weights = self.self_attn(
437
+ query=x,
438
+ key=x,
439
+ key_padding_mask=encoder_padding_mask,
440
+ layer_head_mask=layer_head_mask,
441
+ output_attentions=output_attentions,
442
+ )
443
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
444
+ x = residual + x
445
+ x = self.self_attn_layer_norm(x)
446
+
447
+ residual = x
448
+ x = self.activation_fn(self.fc1(x))
449
+ x = nn.functional.dropout(x, p=self.activation_dropout, training=self.training)
450
+ x = self.fc2(x)
451
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
452
+ x = residual + x
453
+ x = self.final_layer_norm(x)
454
+ return x, attn_weights
455
+
456
+
457
+ class FSMTEncoder(nn.Module):
458
+ """
459
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a [`EncoderLayer`].
460
+
461
+ Args:
462
+ config: FSMTConfig
463
+ """
464
+
465
+ def __init__(self, config: FSMTConfig, embed_tokens):
466
+ super().__init__()
467
+ self.dropout = config.dropout
468
+ self.layerdrop = config.encoder_layerdrop
469
+ self.padding_idx = embed_tokens.padding_idx
470
+ self.embed_tokens = embed_tokens
471
+ embed_dim = embed_tokens.embedding_dim
472
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
473
+ self.embed_positions = SinusoidalPositionalEmbedding(
474
+ config.max_position_embeddings + self.padding_idx + 1, embed_dim, self.padding_idx
475
+ )
476
+ self.layers = nn.ModuleList([EncoderLayer(config) for _ in range(config.encoder_layers)]) # type: List[EncoderLayer]
477
+
478
+ def forward(
479
+ self,
480
+ input_ids: torch.Tensor,
481
+ attention_mask: Optional[torch.Tensor] = None,
482
+ inputs_embeds: torch.Tensor = None,
483
+ head_mask: Optional[torch.Tensor] = None,
484
+ output_attentions: bool = False,
485
+ output_hidden_states: bool = False,
486
+ return_dict: bool = True,
487
+ ):
488
+ """
489
+ Args:
490
+ input_ids (`torch.LongTensor`): tokens in the source language of shape
491
+ *(batch, src_len)*
492
+ attention_mask (`torch.LongTensor`): indicating which indices are padding tokens
493
+ inputs_embeds (`torch.FloatTensor`):
494
+ embedding vectors of shape *(batch, src_len, embed_dim)*
495
+ head_mask (`torch.Tensor` of shape `(num_layers, num_heads)`, *optional*):
496
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
497
+
498
+ - 1 indicates the head is **not masked**,
499
+ - 0 indicates the head is **masked**.
500
+
501
+ Returns:
502
+ BaseModelOutput or Tuple comprised of:
503
+
504
+ - **x** (`torch.Tensor`): the last encoder layer's output of shape *(src_len, batch, embed_dim)*
505
+ - **encoder_states** (`Tuple(torch.FloatTensor)`): all intermediate hidden states of shape *(src_len,
506
+ batch, embed_dim)*. Only populated if *output_hidden_states:* is True.
507
+ - **all_attentions** (`Tuple(torch.FloatTensor)`): Attention weights for each layer.
508
+ During training might not be of length n_layers because of layer dropout.
509
+ """
510
+ # check attention mask and invert
511
+ if attention_mask is not None:
512
+ attention_mask = invert_mask(attention_mask)
513
+
514
+ if input_ids is not None and inputs_embeds is not None:
515
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
516
+ elif input_ids is not None:
517
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
518
+ embed_pos = self.embed_positions(input_ids)
519
+ elif inputs_embeds is not None:
520
+ inputs_embeds = inputs_embeds * self.embed_scale
521
+
522
+ # We assume zeros hidden states correspond to padding tokens
523
+ # and create `position_ids` where inputs_embeds[:, :, 0] == 0
524
+ position_ids = inputs_embeds[:, :, 0].masked_fill(
525
+ inputs_embeds[:, :, 0].eq(0), self.embed_positions.padding_idx
526
+ )
527
+
528
+ embed_pos = self.embed_positions(position_ids)
529
+ else:
530
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
531
+
532
+ x = inputs_embeds + embed_pos
533
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
534
+
535
+ # B x T x C -> T x B x C
536
+ x = x.transpose(0, 1)
537
+
538
+ encoder_states = () if output_hidden_states else None
539
+ all_attentions = () if output_attentions else None
540
+ # check if head_mask has a correct number of layers specified if desired
541
+ if head_mask is not None:
542
+ assert head_mask.size()[0] == (
543
+ len(self.layers)
544
+ ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
545
+ for idx, encoder_layer in enumerate(self.layers):
546
+ if output_hidden_states:
547
+ x = x.transpose(0, 1) # T x B x C -> B x T x C
548
+ encoder_states += (x,)
549
+ x = x.transpose(0, 1) # B x T x C -> T x B x C
550
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
551
+ dropout_probability = torch.rand([])
552
+ if self.training and (dropout_probability < self.layerdrop): # skip the layer
553
+ attn = None
554
+ else:
555
+ x, attn = encoder_layer(
556
+ x,
557
+ attention_mask,
558
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
559
+ output_attentions=output_attentions,
560
+ )
561
+
562
+ if output_attentions:
563
+ all_attentions = all_attentions + (attn,)
564
+
565
+ # T x B x C -> B x T x C
566
+ x = x.transpose(0, 1)
567
+
568
+ if output_hidden_states:
569
+ encoder_states += (x,)
570
+
571
+ if not return_dict:
572
+ return tuple(v for v in [x, encoder_states, all_attentions] if v is not None)
573
+ return BaseModelOutput(last_hidden_state=x, hidden_states=encoder_states, attentions=all_attentions)
574
+
575
+
576
+ class DecoderLayer(nn.Module):
577
+ def __init__(self, config: FSMTConfig):
578
+ super().__init__()
579
+ self.embed_dim = config.d_model
580
+
581
+ self.self_attn = Attention(
582
+ embed_dim=self.embed_dim,
583
+ num_heads=config.decoder_attention_heads,
584
+ dropout=config.attention_dropout,
585
+ )
586
+ self.dropout = config.dropout
587
+ self.activation_fn = ACT2FN[config.activation_function]
588
+ self.activation_dropout = config.activation_dropout
589
+
590
+ self.self_attn_layer_norm = LayerNorm(self.embed_dim)
591
+ self.encoder_attn = Attention(
592
+ self.embed_dim,
593
+ config.decoder_attention_heads,
594
+ dropout=config.attention_dropout,
595
+ encoder_decoder_attention=True,
596
+ )
597
+ self.encoder_attn_layer_norm = LayerNorm(self.embed_dim)
598
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
599
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
600
+ self.final_layer_norm = LayerNorm(self.embed_dim)
601
+
602
+ def forward(
603
+ self,
604
+ x,
605
+ encoder_hidden_states,
606
+ encoder_attn_mask=None,
607
+ layer_state=None,
608
+ causal_mask=None,
609
+ layer_head_mask=None,
610
+ cross_attn_layer_head_mask=None,
611
+ decoder_padding_mask=None,
612
+ output_attentions=False,
613
+ ):
614
+ residual = x
615
+
616
+ if layer_state is None:
617
+ layer_state = {}
618
+
619
+ # Self Attention
620
+ x, self_attn_weights = self.self_attn(
621
+ query=x,
622
+ key=x,
623
+ layer_state=layer_state, # adds keys to layer state
624
+ key_padding_mask=decoder_padding_mask,
625
+ attn_mask=causal_mask,
626
+ layer_head_mask=layer_head_mask,
627
+ output_attentions=output_attentions,
628
+ )
629
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
630
+ x = residual + x
631
+ x = self.self_attn_layer_norm(x)
632
+
633
+ # Cross attention
634
+ residual = x
635
+ assert self.encoder_attn.cache_key != self.self_attn.cache_key
636
+ x, cross_attn_weights = self.encoder_attn(
637
+ query=x,
638
+ key=encoder_hidden_states,
639
+ key_padding_mask=encoder_attn_mask,
640
+ layer_state=layer_state, # mutates layer state
641
+ layer_head_mask=cross_attn_layer_head_mask,
642
+ output_attentions=output_attentions,
643
+ )
644
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
645
+ x = residual + x
646
+ x = self.encoder_attn_layer_norm(x)
647
+
648
+ # Fully Connected
649
+ residual = x
650
+ x = self.activation_fn(self.fc1(x))
651
+ x = nn.functional.dropout(x, p=self.activation_dropout, training=self.training)
652
+ x = self.fc2(x)
653
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
654
+ x = residual + x
655
+ x = self.final_layer_norm(x)
656
+ return (
657
+ x,
658
+ self_attn_weights,
659
+ layer_state,
660
+ cross_attn_weights,
661
+ ) # layer_state = cache for decoding
662
+
663
+
664
+ class FSMTDecoder(nn.Module):
665
+ """
666
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`DecoderLayer`]
667
+
668
+ Args:
669
+ config: FSMTConfig
670
+ embed_tokens (nn.Embedding): output embedding
671
+ """
672
+
673
+ def __init__(self, config: FSMTConfig, embed_tokens: nn.Embedding):
674
+ super().__init__()
675
+ self.dropout = config.dropout
676
+ self.layerdrop = config.decoder_layerdrop
677
+ self.padding_idx = embed_tokens.padding_idx
678
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
679
+ self.embed_tokens = embed_tokens
680
+ embed_dim = embed_tokens.embedding_dim
681
+ self.embed_positions = SinusoidalPositionalEmbedding(
682
+ config.max_position_embeddings + self.padding_idx + 1, embed_dim, self.padding_idx
683
+ )
684
+ self.layers = nn.ModuleList([DecoderLayer(config) for _ in range(config.decoder_layers)]) # type: List[DecoderLayer]
685
+
686
+ if is_deepspeed_zero3_enabled():
687
+ import deepspeed
688
+
689
+ with deepspeed.zero.GatheredParameters(self.embed_tokens.weight, modifier_rank=None):
690
+ embed_tokens_weight_shape = self.embed_tokens.weight.shape
691
+ else:
692
+ embed_tokens_weight_shape = self.embed_tokens.weight.shape
693
+ self.output_projection = nn.Linear(embed_tokens_weight_shape[1], embed_tokens_weight_shape[0], bias=False)
694
+ self.output_projection.weight = self.embed_tokens.weight
695
+
696
+ def _tie_weights(self):
697
+ self.embed_tokens.weight = self.output_projection.weight
698
+
699
+ def forward(
700
+ self,
701
+ input_ids: torch.Tensor,
702
+ encoder_hidden_states: torch.Tensor,
703
+ encoder_padding_mask: torch.Tensor,
704
+ decoder_padding_mask: torch.Tensor,
705
+ decoder_causal_mask: torch.Tensor,
706
+ head_mask: Optional[torch.Tensor] = None,
707
+ inputs_embeds: Optional[torch.Tensor] = None,
708
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
709
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
710
+ use_cache: bool = False,
711
+ output_attentions: bool = False,
712
+ output_hidden_states: bool = False,
713
+ return_dict: bool = True,
714
+ ):
715
+ """
716
+ Includes several features from "Jointly Learning to Align and Translate with Transformer Models" (Garg et al.,
717
+ EMNLP 2019).
718
+
719
+ Args:
720
+ input_ids (`torch.LongTensor` of shape `(batch, tgt_len)`):
721
+ previous decoder outputs for teacher forcing
722
+ encoder_hidden_states: output from the encoder, used for
723
+ encoder-side attention
724
+ encoder_padding_mask: for ignoring pad tokens
725
+ past_key_values (dict or None): dictionary used for storing state during generation
726
+ head_mask (`torch.Tensor` of shape `(num_layers, num_heads)`, *optional*):
727
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
728
+
729
+ - 1 indicates the head is **not masked**,
730
+ - 0 indicates the head is **masked**.
731
+
732
+ cross_attn_head_mask (`torch.Tensor` of shape `(num_layers, num_heads)`, *optional*):
733
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
734
+
735
+ - 1 indicates the head is **not masked**,
736
+ - 0 indicates the head is **masked**.
737
+
738
+ Returns:
739
+ BaseModelOutputWithPast or tuple:
740
+
741
+ - the decoder's features of shape *(batch, tgt_len, embed_dim)*
742
+ - the cache
743
+ - hidden states
744
+ - attentions
745
+ """
746
+ # check attention mask and invert
747
+ if encoder_padding_mask is not None:
748
+ encoder_padding_mask = invert_mask(encoder_padding_mask)
749
+
750
+ if input_ids is not None and inputs_embeds is not None:
751
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
752
+ elif input_ids is not None:
753
+ # embed positions
754
+ positions = self.embed_positions(input_ids)
755
+ if use_cache:
756
+ input_ids = input_ids[:, -1:]
757
+ positions = positions[:, -1:] # happens after we embed them
758
+ x = self.embed_tokens(input_ids) * self.embed_scale
759
+ elif inputs_embeds is not None:
760
+ # We assume zeros hidden states correspond to padding tokens
761
+ # and create `position_ids` where inputs_embeds[:, :, 0] == 0
762
+ position_ids = inputs_embeds[:, :, 0].masked_fill(
763
+ inputs_embeds[:, :, 0].eq(0), self.embed_positions.padding_idx
764
+ )
765
+ positions = self.embed_positions(position_ids)
766
+ x = inputs_embeds * self.embed_scale
767
+ else:
768
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
769
+
770
+ x += positions
771
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
772
+
773
+ # Convert to FSMT output format: (BS, seq_len, model_dim) -> (seq_len, BS, model_dim)
774
+ x = x.transpose(0, 1)
775
+ encoder_hidden_states = encoder_hidden_states.transpose(0, 1)
776
+
777
+ # decoder layers
778
+ all_hidden_states = () if output_hidden_states else None
779
+ all_self_attns = () if output_attentions else None
780
+ all_cross_attns = () if output_attentions else None
781
+ next_decoder_cache = []
782
+
783
+ # check if head_mask has a correct number of layers specified if desired
784
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
785
+ if attn_mask is not None:
786
+ assert attn_mask.size()[0] == (len(self.layers)), (
787
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
788
+ f" {head_mask.size()[0]}."
789
+ )
790
+ for idx, decoder_layer in enumerate(self.layers):
791
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
792
+ if output_hidden_states:
793
+ x = x.transpose(0, 1)
794
+ all_hidden_states += (x,)
795
+ x = x.transpose(0, 1)
796
+ if self.training:
797
+ dropout_probability = torch.rand([])
798
+ if dropout_probability < self.layerdrop:
799
+ continue
800
+
801
+ layer_state = past_key_values[idx] if past_key_values is not None else None
802
+
803
+ x, layer_self_attn, layer_past, layer_cross_attn = decoder_layer(
804
+ x,
805
+ encoder_hidden_states,
806
+ encoder_attn_mask=encoder_padding_mask,
807
+ decoder_padding_mask=decoder_padding_mask,
808
+ layer_state=layer_state,
809
+ causal_mask=decoder_causal_mask,
810
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
811
+ cross_attn_layer_head_mask=(cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None),
812
+ output_attentions=output_attentions,
813
+ )
814
+
815
+ if use_cache:
816
+ next_decoder_cache.append(layer_past.copy())
817
+
818
+ if output_attentions:
819
+ all_self_attns += (layer_self_attn,)
820
+ all_cross_attns += (layer_cross_attn,)
821
+
822
+ # add hidden states from the last decoder layer
823
+ if output_hidden_states:
824
+ x = x.transpose(0, 1)
825
+ all_hidden_states += (x,)
826
+ x = x.transpose(0, 1)
827
+
828
+ # Convert to standard output format: (seq_len, BS, model_dim) -> (BS, seq_len, model_dim)
829
+ x = x.transpose(0, 1)
830
+ encoder_hidden_states = encoder_hidden_states.transpose(0, 1)
831
+
832
+ x = self.output_projection(x)
833
+
834
+ next_cache = next_decoder_cache if use_cache else None
835
+
836
+ if not return_dict:
837
+ return tuple(
838
+ v for v in [x, next_cache, all_hidden_states, all_self_attns, all_cross_attns] if v is not None
839
+ )
840
+ return BaseModelOutputWithPastAndCrossAttentions(
841
+ last_hidden_state=x,
842
+ past_key_values=next_cache,
843
+ hidden_states=all_hidden_states,
844
+ attentions=all_self_attns,
845
+ cross_attentions=all_cross_attns,
846
+ )
847
+
848
+
849
+ def _reorder_buffer(attn_cache, new_order):
850
+ for k, input_buffer_k in attn_cache.items():
851
+ if input_buffer_k is not None:
852
+ attn_cache[k] = input_buffer_k.index_select(0, new_order)
853
+ return attn_cache
854
+
855
+
856
+ class Attention(nn.Module):
857
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
858
+
859
+ def __init__(
860
+ self,
861
+ embed_dim,
862
+ num_heads,
863
+ dropout=0.0,
864
+ bias=True,
865
+ encoder_decoder_attention=False, # otherwise self_attention
866
+ ):
867
+ super().__init__()
868
+ self.embed_dim = embed_dim
869
+ self.num_heads = num_heads
870
+ self.dropout = dropout
871
+ self.head_dim = embed_dim // num_heads
872
+ assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"
873
+ self.scaling = self.head_dim**-0.5
874
+
875
+ self.encoder_decoder_attention = encoder_decoder_attention
876
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
877
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
878
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
879
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
880
+ self.cache_key = "encoder_decoder" if self.encoder_decoder_attention else "self"
881
+
882
+ def _shape(self, tensor, seq_len, bsz):
883
+ return tensor.contiguous().view(seq_len, bsz * self.num_heads, self.head_dim).transpose(0, 1)
884
+
885
+ def forward(
886
+ self,
887
+ query,
888
+ key: Optional[Tensor],
889
+ key_padding_mask: Optional[Tensor] = None,
890
+ layer_state: Optional[Dict[str, Optional[Tensor]]] = None,
891
+ attn_mask: Optional[Tensor] = None,
892
+ layer_head_mask: Optional[Tensor] = None,
893
+ output_attentions=False,
894
+ ) -> Tuple[Tensor, Optional[Tensor]]:
895
+ """Input shape: Time(SeqLen) x Batch x Channel"""
896
+ static_kv: bool = self.encoder_decoder_attention
897
+ tgt_len, bsz, embed_dim = query.size()
898
+ assert embed_dim == self.embed_dim
899
+ assert list(query.size()) == [tgt_len, bsz, embed_dim]
900
+ # get here for encoder decoder cause of static_kv
901
+ if layer_state is not None: # reuse k,v and encoder_padding_mask
902
+ saved_state = layer_state.get(self.cache_key, {})
903
+ if "prev_key" in saved_state and static_kv:
904
+ # previous time steps are cached - no need to recompute key and value if they are static
905
+ key = None
906
+ else:
907
+ saved_state = None
908
+ layer_state = {}
909
+
910
+ q = self.q_proj(query) * self.scaling
911
+ if static_kv:
912
+ if key is None:
913
+ k = v = None
914
+ else:
915
+ k = self.k_proj(key)
916
+ v = self.v_proj(key)
917
+ else:
918
+ k = self.k_proj(query)
919
+ v = self.v_proj(query)
920
+
921
+ q = self._shape(q, tgt_len, bsz)
922
+ if k is not None:
923
+ k = self._shape(k, -1, bsz)
924
+ if v is not None:
925
+ v = self._shape(v, -1, bsz)
926
+
927
+ if saved_state is not None:
928
+ k, v, key_padding_mask = self._use_saved_state(k, v, saved_state, key_padding_mask, static_kv, bsz)
929
+
930
+ # Update cache
931
+ layer_state[self.cache_key] = {
932
+ "prev_key": k.view(bsz, self.num_heads, -1, self.head_dim),
933
+ "prev_value": v.view(bsz, self.num_heads, -1, self.head_dim),
934
+ "prev_key_padding_mask": key_padding_mask if not static_kv else None,
935
+ }
936
+
937
+ assert k is not None
938
+ src_len = k.size(1)
939
+ attn_weights = torch.bmm(q, k.transpose(1, 2))
940
+ assert attn_weights.size() == (bsz * self.num_heads, tgt_len, src_len)
941
+
942
+ if attn_mask is not None:
943
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_mask
944
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
945
+
946
+ # This is part of a workaround to get around fork/join parallelism not supporting Optional types.
947
+ if key_padding_mask is not None and key_padding_mask.dim() == 0:
948
+ key_padding_mask = None
949
+ assert key_padding_mask is None or key_padding_mask.size()[:2] == (
950
+ bsz,
951
+ src_len,
952
+ )
953
+
954
+ if key_padding_mask is not None: # don't attend to padding symbols
955
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
956
+ reshaped = key_padding_mask.unsqueeze(1).unsqueeze(2)
957
+ attn_weights = attn_weights.masked_fill(reshaped, torch.finfo(attn_weights.dtype).min)
958
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
959
+
960
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
961
+
962
+ if layer_head_mask is not None:
963
+ assert layer_head_mask.size() == (
964
+ self.num_heads,
965
+ ), f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}"
966
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
967
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
968
+
969
+ if output_attentions:
970
+ # make sure that attn_weights are included in graph
971
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
972
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
973
+ else:
974
+ attn_weights_reshaped = None
975
+
976
+ attn_probs = nn.functional.dropout(
977
+ attn_weights,
978
+ p=self.dropout,
979
+ training=self.training,
980
+ )
981
+
982
+ assert v is not None
983
+ attn_output = torch.bmm(attn_probs, v)
984
+ assert attn_output.size() == (bsz * self.num_heads, tgt_len, self.head_dim)
985
+ attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
986
+ attn_output = self.out_proj(attn_output)
987
+
988
+ return attn_output, attn_weights_reshaped
989
+
990
+ def _use_saved_state(self, k, v, saved_state, key_padding_mask, static_kv, bsz):
991
+ # saved states are stored with shape (bsz, num_heads, seq_len, head_dim)
992
+ if "prev_key" in saved_state:
993
+ _prev_key = saved_state["prev_key"]
994
+ assert _prev_key is not None
995
+ prev_key = _prev_key.view(bsz * self.num_heads, -1, self.head_dim)
996
+ if static_kv:
997
+ k = prev_key
998
+ else:
999
+ assert k is not None
1000
+ k = torch.cat([prev_key, k], dim=1)
1001
+ if "prev_value" in saved_state:
1002
+ _prev_value = saved_state["prev_value"]
1003
+ assert _prev_value is not None
1004
+ prev_value = _prev_value.view(bsz * self.num_heads, -1, self.head_dim)
1005
+ if static_kv:
1006
+ v = prev_value
1007
+ else:
1008
+ assert v is not None
1009
+ v = torch.cat([prev_value, v], dim=1)
1010
+ assert k is not None and v is not None
1011
+ prev_key_padding_mask: Optional[Tensor] = saved_state.get("prev_key_padding_mask", None)
1012
+ if prev_key_padding_mask is not None:
1013
+ if static_kv:
1014
+ new_key_padding_mask = prev_key_padding_mask
1015
+ else:
1016
+ new_key_padding_mask = torch.cat([prev_key_padding_mask, key_padding_mask], dim=1)
1017
+ else:
1018
+ new_key_padding_mask = key_padding_mask
1019
+ return k, v, new_key_padding_mask
1020
+
1021
+
1022
+ def fill_with_neg_inf(t):
1023
+ """FP16-compatible function that fills a input_ids with -inf."""
1024
+ return t.float().fill_(torch.finfo(t.dtype).min).type_as(t)
1025
+
1026
+
1027
+ # Public API
1028
+ def _get_shape(t):
1029
+ return getattr(t, "shape", None)
1030
+
1031
+
1032
+ @add_start_docstrings(
1033
+ "The bare FSMT Model outputting raw hidden-states without any specific head on top.",
1034
+ FSMT_START_DOCSTRING,
1035
+ )
1036
+ class FSMTModel(PretrainedFSMTModel):
1037
+ _tied_weights_keys = ["decoder.embed_tokens.weight", "decoder.output_projection.weight"]
1038
+
1039
+ def __init__(self, config: FSMTConfig):
1040
+ super().__init__(config)
1041
+
1042
+ padding_idx = config.pad_token_id
1043
+ encoder_embed_tokens = nn.Embedding(config.src_vocab_size, config.d_model, padding_idx)
1044
+ decoder_embed_tokens = nn.Embedding(config.tgt_vocab_size, config.d_model, padding_idx)
1045
+
1046
+ self.encoder = FSMTEncoder(config, encoder_embed_tokens)
1047
+ self.decoder = FSMTDecoder(config, decoder_embed_tokens)
1048
+
1049
+ # Initialize weights and apply final processing
1050
+ self.post_init()
1051
+
1052
+ def get_encoder(self):
1053
+ return self.encoder
1054
+
1055
+ def get_decoder(self):
1056
+ return self.decoder
1057
+
1058
+ def _tie_weights(self):
1059
+ if self.config.tie_word_embeddings:
1060
+ self._tie_or_clone_weights(self.decoder.embed_tokens, self.get_input_embeddings())
1061
+ self._tie_or_clone_weights(self.decoder.output_projection, self.get_input_embeddings())
1062
+
1063
+ @add_start_docstrings_to_model_forward(FSMT_INPUTS_DOCSTRING)
1064
+ @add_code_sample_docstrings(
1065
+ checkpoint=_CHECKPOINT_FOR_DOC,
1066
+ output_type=Seq2SeqModelOutput,
1067
+ config_class=_CONFIG_FOR_DOC,
1068
+ )
1069
+ def forward(
1070
+ self,
1071
+ input_ids: torch.LongTensor,
1072
+ attention_mask: Optional[torch.Tensor] = None,
1073
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1074
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
1075
+ head_mask: Optional[torch.Tensor] = None,
1076
+ decoder_head_mask: Optional[torch.Tensor] = None,
1077
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1078
+ encoder_outputs: Optional[Tuple[torch.FloatTensor]] = None,
1079
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
1080
+ use_cache: Optional[bool] = None,
1081
+ output_attentions: Optional[bool] = None,
1082
+ output_hidden_states: Optional[bool] = None,
1083
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1084
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1085
+ return_dict: Optional[bool] = None,
1086
+ ) -> Union[Tuple[torch.Tensor], Seq2SeqModelOutput]:
1087
+ if decoder_input_ids is None:
1088
+ use_cache = False
1089
+
1090
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1091
+ output_hidden_states = (
1092
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1093
+ )
1094
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1095
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1096
+
1097
+ # make masks if user doesn't supply
1098
+ if not use_cache and input_ids is not None:
1099
+ decoder_input_ids, decoder_padding_mask, causal_mask = _prepare_fsmt_decoder_inputs(
1100
+ self.config,
1101
+ input_ids,
1102
+ decoder_input_ids=decoder_input_ids,
1103
+ decoder_padding_mask=decoder_attention_mask,
1104
+ causal_mask_dtype=self.decoder.embed_tokens.weight.dtype,
1105
+ )
1106
+ else:
1107
+ decoder_padding_mask, causal_mask = None, None
1108
+
1109
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1110
+ raise ValueError("Make sure that `decoder_input_ids` or `decoder_inputs_embeds` are passed.")
1111
+
1112
+ if encoder_outputs is None:
1113
+ encoder_outputs = self.encoder(
1114
+ input_ids=input_ids,
1115
+ attention_mask=attention_mask,
1116
+ inputs_embeds=inputs_embeds,
1117
+ head_mask=head_mask,
1118
+ output_attentions=output_attentions,
1119
+ output_hidden_states=output_hidden_states,
1120
+ return_dict=return_dict,
1121
+ )
1122
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=False
1123
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1124
+ encoder_outputs = BaseModelOutput(
1125
+ last_hidden_state=encoder_outputs[0],
1126
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1127
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1128
+ )
1129
+
1130
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1131
+ decoder_outputs = self.decoder(
1132
+ decoder_input_ids,
1133
+ encoder_outputs[0],
1134
+ attention_mask,
1135
+ decoder_padding_mask,
1136
+ decoder_causal_mask=causal_mask,
1137
+ inputs_embeds=decoder_inputs_embeds,
1138
+ head_mask=decoder_head_mask,
1139
+ cross_attn_head_mask=cross_attn_head_mask,
1140
+ past_key_values=past_key_values,
1141
+ use_cache=use_cache,
1142
+ output_attentions=output_attentions,
1143
+ output_hidden_states=output_hidden_states,
1144
+ return_dict=return_dict,
1145
+ )
1146
+
1147
+ if not return_dict:
1148
+ return decoder_outputs + encoder_outputs
1149
+
1150
+ return Seq2SeqModelOutput(
1151
+ last_hidden_state=decoder_outputs.last_hidden_state,
1152
+ past_key_values=decoder_outputs.past_key_values,
1153
+ decoder_hidden_states=decoder_outputs.hidden_states,
1154
+ decoder_attentions=decoder_outputs.attentions,
1155
+ cross_attentions=decoder_outputs.cross_attentions,
1156
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1157
+ encoder_hidden_states=encoder_outputs.hidden_states,
1158
+ encoder_attentions=encoder_outputs.attentions,
1159
+ )
1160
+
1161
+ def get_input_embeddings(self):
1162
+ return self.encoder.embed_tokens
1163
+
1164
+ def set_input_embeddings(self, value):
1165
+ self.encoder.embed_tokens = value
1166
+
1167
+ def get_output_embeddings(self):
1168
+ return self.decoder.embed_tokens
1169
+
1170
+ def set_output_embeddings(self, value):
1171
+ self.decoder.embed_tokens = value
1172
+
1173
+
1174
+ @add_start_docstrings(
1175
+ "The FSMT Model with a language modeling head. Can be used for summarization.", FSMT_START_DOCSTRING
1176
+ )
1177
+ class FSMTForConditionalGeneration(PretrainedFSMTModel, GenerationMixin):
1178
+ base_model_prefix = "model"
1179
+ _tied_weights_keys = ["decoder.embed_tokens.weight", "decoder.output_projection.weight"]
1180
+
1181
+ def __init__(self, config: FSMTConfig):
1182
+ super().__init__(config)
1183
+ base_model = FSMTModel(config)
1184
+ self.model = base_model
1185
+
1186
+ # Initialize weights and apply final processing
1187
+ self.post_init()
1188
+
1189
+ @add_start_docstrings_to_model_forward(FSMT_INPUTS_DOCSTRING)
1190
+ @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1191
+ @add_end_docstrings(FSMT_GENERATION_EXAMPLE)
1192
+ def forward(
1193
+ self,
1194
+ input_ids: Optional[torch.LongTensor] = None,
1195
+ attention_mask: Optional[torch.Tensor] = None,
1196
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1197
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
1198
+ head_mask: Optional[torch.Tensor] = None,
1199
+ decoder_head_mask: Optional[torch.Tensor] = None,
1200
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1201
+ encoder_outputs: Optional[Tuple[torch.FloatTensor]] = None,
1202
+ past_key_values: Optional[Tuple[torch.FloatTensor]] = None,
1203
+ inputs_embeds: Optional[torch.Tensor] = None,
1204
+ decoder_inputs_embeds: Optional[torch.Tensor] = None,
1205
+ labels: Optional[torch.LongTensor] = None,
1206
+ use_cache: Optional[bool] = None,
1207
+ output_attentions: Optional[bool] = None,
1208
+ output_hidden_states: Optional[bool] = None,
1209
+ return_dict: Optional[bool] = None,
1210
+ ) -> Union[Tuple[torch.Tensor], Seq2SeqLMOutput]:
1211
+ r"""
1212
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1213
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1214
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1215
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1216
+
1217
+ Returns:
1218
+
1219
+ """
1220
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1221
+
1222
+ if labels is not None:
1223
+ use_cache = False
1224
+
1225
+ outputs = self.model(
1226
+ input_ids,
1227
+ inputs_embeds=inputs_embeds,
1228
+ attention_mask=attention_mask,
1229
+ decoder_input_ids=decoder_input_ids,
1230
+ decoder_inputs_embeds=decoder_inputs_embeds,
1231
+ encoder_outputs=encoder_outputs,
1232
+ decoder_attention_mask=decoder_attention_mask,
1233
+ head_mask=head_mask,
1234
+ decoder_head_mask=decoder_head_mask,
1235
+ cross_attn_head_mask=cross_attn_head_mask,
1236
+ past_key_values=past_key_values,
1237
+ use_cache=use_cache,
1238
+ output_attentions=output_attentions,
1239
+ output_hidden_states=output_hidden_states,
1240
+ return_dict=return_dict,
1241
+ )
1242
+ lm_logits = outputs[0]
1243
+
1244
+ masked_lm_loss = None
1245
+ if labels is not None:
1246
+ loss_fct = CrossEntropyLoss()
1247
+ # TODO(SS): do we need to ignore pad tokens in labels?
1248
+ masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.tgt_vocab_size), labels.view(-1))
1249
+
1250
+ if not return_dict:
1251
+ output = (lm_logits,) + outputs[1:]
1252
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1253
+
1254
+ return Seq2SeqLMOutput(
1255
+ loss=masked_lm_loss,
1256
+ logits=lm_logits,
1257
+ past_key_values=outputs.past_key_values,
1258
+ decoder_hidden_states=outputs.decoder_hidden_states,
1259
+ decoder_attentions=outputs.decoder_attentions,
1260
+ cross_attentions=outputs.cross_attentions,
1261
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1262
+ encoder_hidden_states=outputs.encoder_hidden_states,
1263
+ encoder_attentions=outputs.encoder_attentions,
1264
+ )
1265
+
1266
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
1267
+ return shift_tokens_right(labels, self.config.pad_token_id)
1268
+
1269
+ @staticmethod
1270
+ def _reorder_cache(past_key_values, beam_idx):
1271
+ reordered_past = []
1272
+ for layer_past in past_key_values:
1273
+ # get the correct batch idx from decoder layer's batch dim for cross and self-attn
1274
+ layer_past_new = {
1275
+ attn_key: _reorder_buffer(attn_cache, beam_idx) for attn_key, attn_cache in layer_past.items()
1276
+ }
1277
+ reordered_past.append(layer_past_new)
1278
+ return reordered_past
1279
+
1280
+ def get_encoder(self):
1281
+ return self.model.encoder
1282
+
1283
+ def get_decoder(self):
1284
+ return self.model.decoder
1285
+
1286
+ def get_output_embeddings(self):
1287
+ return self.model.decoder.embed_tokens
1288
+
1289
+ def set_output_embeddings(self, value):
1290
+ self.model.decoder.embed_tokens = value
1291
+
1292
+
1293
+ class SinusoidalPositionalEmbedding(nn.Embedding):
1294
+ """
1295
+ This module produces sinusoidal positional embeddings of any length.
1296
+
1297
+ We don't want to save the weight of this embedding since it's not trained (deterministic) and it can be huge.
1298
+
1299
+ Padding symbols are ignored.
1300
+
1301
+ These embeddings get automatically extended in forward if more positions is needed.
1302
+ """
1303
+
1304
+ def __init__(self, num_positions, embedding_dim, padding_idx):
1305
+ self.make_weight(num_positions, embedding_dim, padding_idx)
1306
+
1307
+ def make_weight(self, num_positions, embedding_dim, padding_idx):
1308
+ weight = self.get_embedding(num_positions, embedding_dim, padding_idx)
1309
+ if not hasattr(self, "weight"):
1310
+ # in ___init__
1311
+ super().__init__(num_positions, embedding_dim, padding_idx, _weight=weight)
1312
+ else:
1313
+ # in forward put the weights on the correct dtype and device of the param
1314
+ weight = weight.to(dtype=self.weight.dtype, device=self.weight.device)
1315
+ self.weight = nn.Parameter(weight)
1316
+ self.weight.detach_()
1317
+ self.weight.requires_grad = False
1318
+
1319
+ @staticmethod
1320
+ def get_embedding(num_embeddings, embedding_dim, padding_idx):
1321
+ """
1322
+ Build sinusoidal embeddings.
1323
+
1324
+ This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of
1325
+ "Attention Is All You Need".
1326
+ """
1327
+ half_dim = embedding_dim // 2
1328
+ emb = math.log(10000) / (half_dim - 1)
1329
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb)
1330
+ emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0)
1331
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
1332
+ if embedding_dim % 2 == 1:
1333
+ # zero pad
1334
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
1335
+ if padding_idx is not None:
1336
+ emb[padding_idx, :] = 0
1337
+ return emb
1338
+
1339
+ @staticmethod
1340
+ def make_positions(tensor, padding_idx: int):
1341
+ """
1342
+ Replace non-padding symbols with their position numbers.
1343
+
1344
+ Position numbers begin at padding_idx+1. Padding symbols are ignored.
1345
+ """
1346
+ # The series of casts and type-conversions here are carefully
1347
+ # balanced to both work with ONNX export and XLA. In particular XLA
1348
+ # prefers ints, cumsum defaults to output longs, and ONNX doesn't know
1349
+ # how to handle the dtype kwarg in cumsum.
1350
+ mask = tensor.ne(padding_idx).int()
1351
+ return (torch.cumsum(mask, dim=1).type_as(mask) * mask).long() + padding_idx
1352
+
1353
+ def forward(
1354
+ self,
1355
+ input,
1356
+ incremental_state: Optional[Any] = None,
1357
+ timestep: Optional[Tensor] = None,
1358
+ ):
1359
+ """Input is expected to be of size [bsz x seqlen]."""
1360
+ bsz, seq_len = input.shape[:2]
1361
+ max_pos = self.padding_idx + 1 + seq_len
1362
+ if max_pos > self.weight.size(0):
1363
+ # expand embeddings if needed
1364
+ self.make_weight(max_pos, self.embedding_dim, self.padding_idx)
1365
+ positions = self.make_positions(input, self.padding_idx)
1366
+ return super().forward(positions)
1367
+
1368
+
1369
+ __all__ = ["FSMTForConditionalGeneration", "FSMTModel", "PretrainedFSMTModel"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fsmt/tokenization_fsmt.py ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2019 The Open AI 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
+ """Tokenization classes for FSMT."""
16
+
17
+ import json
18
+ import os
19
+ import re
20
+ import unicodedata
21
+ from typing import Dict, List, Optional, Tuple
22
+
23
+ from ...tokenization_utils import PreTrainedTokenizer
24
+ from ...utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {
30
+ "src_vocab_file": "vocab-src.json",
31
+ "tgt_vocab_file": "vocab-tgt.json",
32
+ "merges_file": "merges.txt",
33
+ }
34
+
35
+
36
+ def get_pairs(word):
37
+ """
38
+ Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length
39
+ strings)
40
+ """
41
+ pairs = set()
42
+ prev_char = word[0]
43
+ for char in word[1:]:
44
+ pairs.add((prev_char, char))
45
+ prev_char = char
46
+ return pairs
47
+
48
+
49
+ def replace_unicode_punct(text):
50
+ """
51
+ Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/replace-unicode-punctuation.perl
52
+ """
53
+ text = text.replace(",", ",")
54
+ text = re.sub(r"。\s*", ". ", text)
55
+ text = text.replace("、", ",")
56
+ text = text.replace("”", '"')
57
+ text = text.replace("“", '"')
58
+ text = text.replace("∶", ":")
59
+ text = text.replace(":", ":")
60
+ text = text.replace("?", "?")
61
+ text = text.replace("《", '"')
62
+ text = text.replace("》", '"')
63
+ text = text.replace(")", ")")
64
+ text = text.replace("!", "!")
65
+ text = text.replace("(", "(")
66
+ text = text.replace(";", ";")
67
+ text = text.replace("1", "1")
68
+ text = text.replace("」", '"')
69
+ text = text.replace("「", '"')
70
+ text = text.replace("0", "0")
71
+ text = text.replace("3", "3")
72
+ text = text.replace("2", "2")
73
+ text = text.replace("5", "5")
74
+ text = text.replace("6", "6")
75
+ text = text.replace("9", "9")
76
+ text = text.replace("7", "7")
77
+ text = text.replace("8", "8")
78
+ text = text.replace("4", "4")
79
+ text = re.sub(r".\s*", ". ", text)
80
+ text = text.replace("~", "~")
81
+ text = text.replace("’", "'")
82
+ text = text.replace("…", "...")
83
+ text = text.replace("━", "-")
84
+ text = text.replace("〈", "<")
85
+ text = text.replace("〉", ">")
86
+ text = text.replace("【", "[")
87
+ text = text.replace("】", "]")
88
+ text = text.replace("%", "%")
89
+ return text
90
+
91
+
92
+ def remove_non_printing_char(text):
93
+ """
94
+ Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/remove-non-printing-char.perl
95
+ """
96
+ output = []
97
+ for char in text:
98
+ cat = unicodedata.category(char)
99
+ if cat.startswith("C"):
100
+ continue
101
+ output.append(char)
102
+ return "".join(output)
103
+
104
+
105
+ # Porting notes:
106
+ # this one is modeled after XLMTokenizer
107
+ #
108
+ # added:
109
+ # - src_vocab_file,
110
+ # - tgt_vocab_file,
111
+ # - langs,
112
+
113
+
114
+ class FSMTTokenizer(PreTrainedTokenizer):
115
+ """
116
+ Construct an FAIRSEQ Transformer tokenizer. Based on Byte-Pair Encoding. The tokenization process is the following:
117
+
118
+ - Moses preprocessing and tokenization.
119
+ - Normalizing all inputs text.
120
+ - The arguments `special_tokens` and the function `set_special_tokens`, can be used to add additional symbols (like
121
+ "__classify__") to a vocabulary.
122
+ - The argument `langs` defines a pair of languages.
123
+
124
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
125
+ this superclass for more information regarding those methods.
126
+
127
+ Args:
128
+ langs (`List[str]`, *optional*):
129
+ A list of two languages to translate from and to, for instance `["en", "ru"]`.
130
+ src_vocab_file (`str`, *optional*):
131
+ File containing the vocabulary for the source language.
132
+ tgt_vocab_file (`st`, *optional*):
133
+ File containing the vocabulary for the target language.
134
+ merges_file (`str`, *optional*):
135
+ File containing the merges.
136
+ do_lower_case (`bool`, *optional*, defaults to `False`):
137
+ Whether or not to lowercase the input when tokenizing.
138
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
139
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
140
+ token instead.
141
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
142
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
143
+
144
+ <Tip>
145
+
146
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
147
+ sequence. The token used is the `cls_token`.
148
+
149
+ </Tip>
150
+
151
+ sep_token (`str`, *optional*, defaults to `"</s>"`):
152
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
153
+ sequence classification or for a text and a question for question answering. It is also used as the last
154
+ token of a sequence built with special tokens.
155
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
156
+ The token used for padding, for example when batching sequences of different lengths.
157
+
158
+ """
159
+
160
+ vocab_files_names = VOCAB_FILES_NAMES
161
+ model_input_names = ["input_ids", "attention_mask"]
162
+
163
+ def __init__(
164
+ self,
165
+ langs=None,
166
+ src_vocab_file=None,
167
+ tgt_vocab_file=None,
168
+ merges_file=None,
169
+ do_lower_case=False,
170
+ unk_token="<unk>",
171
+ bos_token="<s>",
172
+ sep_token="</s>",
173
+ pad_token="<pad>",
174
+ **kwargs,
175
+ ):
176
+ try:
177
+ import sacremoses
178
+ except ImportError:
179
+ raise ImportError(
180
+ "You need to install sacremoses to use XLMTokenizer. "
181
+ "See https://pypi.org/project/sacremoses/ for installation."
182
+ )
183
+
184
+ self.sm = sacremoses
185
+
186
+ self.src_vocab_file = src_vocab_file
187
+ self.tgt_vocab_file = tgt_vocab_file
188
+ self.merges_file = merges_file
189
+ self.do_lower_case = do_lower_case
190
+
191
+ # cache of sm.MosesPunctNormalizer instance
192
+ self.cache_moses_punct_normalizer = {}
193
+ # cache of sm.MosesTokenizer instance
194
+ self.cache_moses_tokenizer = {}
195
+ self.cache_moses_detokenizer = {}
196
+
197
+ if langs and len(langs) == 2:
198
+ self.src_lang, self.tgt_lang = langs
199
+ else:
200
+ raise ValueError(
201
+ f"arg `langs` needs to be a list of 2 langs, e.g. ['en', 'ru'], but got {langs}. "
202
+ "Usually that means that tokenizer can't find a mapping for the given model path "
203
+ "in and other maps of this tokenizer."
204
+ )
205
+
206
+ with open(src_vocab_file, encoding="utf-8") as src_vocab_handle:
207
+ self.encoder = json.load(src_vocab_handle)
208
+ with open(tgt_vocab_file, encoding="utf-8") as tgt_vocab_handle:
209
+ tgt_vocab = json.load(tgt_vocab_handle)
210
+ self.decoder = {v: k for k, v in tgt_vocab.items()}
211
+ with open(merges_file, encoding="utf-8") as merges_handle:
212
+ merges = merges_handle.read().split("\n")[:-1]
213
+ merges = [tuple(merge.split()[:2]) for merge in merges]
214
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
215
+ self.cache = {}
216
+ super().__init__(
217
+ langs=langs,
218
+ src_vocab_file=src_vocab_file,
219
+ tgt_vocab_file=tgt_vocab_file,
220
+ merges_file=merges_file,
221
+ do_lower_case=do_lower_case,
222
+ unk_token=unk_token,
223
+ bos_token=bos_token,
224
+ sep_token=sep_token,
225
+ pad_token=pad_token,
226
+ **kwargs,
227
+ )
228
+
229
+ # hack override
230
+ def get_vocab(self) -> Dict[str, int]:
231
+ return self.get_src_vocab()
232
+
233
+ # hack override
234
+ @property
235
+ def vocab_size(self) -> int:
236
+ return self.src_vocab_size
237
+
238
+ def moses_punct_norm(self, text, lang):
239
+ if lang not in self.cache_moses_punct_normalizer:
240
+ punct_normalizer = self.sm.MosesPunctNormalizer(lang=lang)
241
+ self.cache_moses_punct_normalizer[lang] = punct_normalizer
242
+ return self.cache_moses_punct_normalizer[lang].normalize(text)
243
+
244
+ def moses_tokenize(self, text, lang):
245
+ if lang not in self.cache_moses_tokenizer:
246
+ moses_tokenizer = self.sm.MosesTokenizer(lang=lang)
247
+ self.cache_moses_tokenizer[lang] = moses_tokenizer
248
+ return self.cache_moses_tokenizer[lang].tokenize(
249
+ text, aggressive_dash_splits=True, return_str=False, escape=True
250
+ )
251
+
252
+ def moses_detokenize(self, tokens, lang):
253
+ if lang not in self.cache_moses_detokenizer:
254
+ moses_detokenizer = self.sm.MosesDetokenizer(lang=lang)
255
+ self.cache_moses_detokenizer[lang] = moses_detokenizer
256
+ return self.cache_moses_detokenizer[lang].detokenize(tokens)
257
+
258
+ def moses_pipeline(self, text, lang):
259
+ text = replace_unicode_punct(text)
260
+ text = self.moses_punct_norm(text, lang)
261
+ text = remove_non_printing_char(text)
262
+ return text
263
+
264
+ @property
265
+ def src_vocab_size(self):
266
+ return len(self.encoder)
267
+
268
+ @property
269
+ def tgt_vocab_size(self):
270
+ return len(self.decoder)
271
+
272
+ def get_src_vocab(self):
273
+ return dict(self.encoder, **self.added_tokens_encoder)
274
+
275
+ def get_tgt_vocab(self):
276
+ return dict(self.decoder, **self.added_tokens_decoder)
277
+
278
+ def bpe(self, token):
279
+ word = tuple(token[:-1]) + (token[-1] + "</w>",)
280
+ if token in self.cache:
281
+ return self.cache[token]
282
+ pairs = get_pairs(word)
283
+
284
+ if not pairs:
285
+ return token + "</w>"
286
+
287
+ while True:
288
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
289
+ if bigram not in self.bpe_ranks:
290
+ break
291
+ first, second = bigram
292
+ new_word = []
293
+ i = 0
294
+ while i < len(word):
295
+ try:
296
+ j = word.index(first, i)
297
+ except ValueError:
298
+ new_word.extend(word[i:])
299
+ break
300
+ else:
301
+ new_word.extend(word[i:j])
302
+ i = j
303
+
304
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
305
+ new_word.append(first + second)
306
+ i += 2
307
+ else:
308
+ new_word.append(word[i])
309
+ i += 1
310
+ new_word = tuple(new_word)
311
+ word = new_word
312
+ if len(word) == 1:
313
+ break
314
+ else:
315
+ pairs = get_pairs(word)
316
+ word = " ".join(word)
317
+ if word == "\n </w>":
318
+ word = "\n</w>"
319
+ self.cache[token] = word
320
+ return word
321
+
322
+ def _tokenize(self, text, lang="en", bypass_tokenizer=False):
323
+ """
324
+ Tokenize a string given language code using Moses.
325
+
326
+ Details of tokenization:
327
+
328
+ - [sacremoses](https://github.com/alvations/sacremoses): port of Moses
329
+ - Install with `pip install sacremoses`
330
+
331
+ Args:
332
+ - lang: ISO language code (default = 'en') (string). Languages should belong of the model supported
333
+ languages. However, we don't enforce it.
334
+ - bypass_tokenizer: Allow users to preprocess and tokenize the sentences externally (default = False)
335
+ (bool). If True, we only apply BPE.
336
+
337
+ Returns:
338
+ List of tokens.
339
+ """
340
+ # ignore `lang` which is currently isn't explicitly passed in tokenization_utils.py and always results in lang=en
341
+ # if lang != self.src_lang:
342
+ # raise ValueError(f"Expected lang={self.src_lang}, but got {lang}")
343
+ lang = self.src_lang
344
+
345
+ if self.do_lower_case:
346
+ text = text.lower()
347
+
348
+ if bypass_tokenizer:
349
+ text = text.split()
350
+ else:
351
+ text = self.moses_pipeline(text, lang=lang)
352
+ text = self.moses_tokenize(text, lang=lang)
353
+
354
+ split_tokens = []
355
+ for token in text:
356
+ if token:
357
+ split_tokens.extend(list(self.bpe(token).split(" ")))
358
+
359
+ return split_tokens
360
+
361
+ def _convert_token_to_id(self, token):
362
+ """Converts a token (str) in an id using the vocab."""
363
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
364
+
365
+ def _convert_id_to_token(self, index):
366
+ """Converts an index (integer) in a token (str) using the vocab."""
367
+ return self.decoder.get(index, self.unk_token)
368
+
369
+ def convert_tokens_to_string(self, tokens):
370
+ """Converts a sequence of tokens (string) in a single string."""
371
+
372
+ # remove BPE
373
+ tokens = [t.replace(" ", "").replace("</w>", " ") for t in tokens]
374
+ tokens = "".join(tokens).split()
375
+ # detokenize
376
+ text = self.moses_detokenize(tokens, self.tgt_lang)
377
+ return text
378
+
379
+ def build_inputs_with_special_tokens(
380
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
381
+ ) -> List[int]:
382
+ """
383
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
384
+ adding special tokens. A FAIRSEQ Transformer sequence has the following format:
385
+
386
+ - single sequence: `<s> X </s>`
387
+ - pair of sequences: `<s> A </s> B </s>`
388
+
389
+ Args:
390
+ token_ids_0 (`List[int]`):
391
+ List of IDs to which the special tokens will be added.
392
+ token_ids_1 (`List[int]`, *optional*):
393
+ Optional second list of IDs for sequence pairs.
394
+
395
+ Returns:
396
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
397
+ """
398
+ sep = [self.sep_token_id]
399
+
400
+ # no bos used in fairseq
401
+ if token_ids_1 is None:
402
+ return token_ids_0 + sep
403
+ return token_ids_0 + sep + token_ids_1 + sep
404
+
405
+ def get_special_tokens_mask(
406
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
407
+ ) -> List[int]:
408
+ """
409
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
410
+ special tokens using the tokenizer `prepare_for_model` method.
411
+
412
+ Args:
413
+ token_ids_0 (`List[int]`):
414
+ List of IDs.
415
+ token_ids_1 (`List[int]`, *optional*):
416
+ Optional second list of IDs for sequence pairs.
417
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
418
+ Whether or not the token list is already formatted with special tokens for the model.
419
+
420
+ Returns:
421
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
422
+ """
423
+
424
+ if already_has_special_tokens:
425
+ return super().get_special_tokens_mask(
426
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
427
+ )
428
+ # no bos used in fairseq
429
+ if token_ids_1 is not None:
430
+ return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
431
+ return ([0] * len(token_ids_0)) + [1]
432
+
433
+ def create_token_type_ids_from_sequences(
434
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
435
+ ) -> List[int]:
436
+ """
437
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A FAIRSEQ
438
+ Transformer sequence pair mask has the following format:
439
+
440
+ ```
441
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
442
+ | first sequence | second sequence |
443
+ ```
444
+
445
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
446
+
447
+ Args:
448
+ token_ids_0 (`List[int]`):
449
+ List of IDs.
450
+ token_ids_1 (`List[int]`, *optional*):
451
+ Optional second list of IDs for sequence pairs.
452
+
453
+ Returns:
454
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
455
+
456
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An
457
+ FAIRSEQ_TRANSFORMER sequence pair mask has the following format:
458
+ """
459
+ sep = [self.sep_token_id]
460
+
461
+ # no bos used in fairseq
462
+ if token_ids_1 is None:
463
+ return len(token_ids_0 + sep) * [0]
464
+ return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
465
+
466
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
467
+ if not os.path.isdir(save_directory):
468
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
469
+ return
470
+
471
+ src_vocab_file = os.path.join(
472
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["src_vocab_file"]
473
+ )
474
+ tgt_vocab_file = os.path.join(
475
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["tgt_vocab_file"]
476
+ )
477
+ merges_file = os.path.join(
478
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
479
+ )
480
+
481
+ with open(src_vocab_file, "w", encoding="utf-8") as f:
482
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
483
+
484
+ with open(tgt_vocab_file, "w", encoding="utf-8") as f:
485
+ tgt_vocab = {v: k for k, v in self.decoder.items()}
486
+ f.write(json.dumps(tgt_vocab, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
487
+
488
+ index = 0
489
+ with open(merges_file, "w", encoding="utf-8") as writer:
490
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
491
+ if index != token_index:
492
+ logger.warning(
493
+ f"Saving vocabulary to {merges_file}: BPE merge indices are not consecutive."
494
+ " Please check that the tokenizer is not corrupted!"
495
+ )
496
+ index = token_index
497
+ writer.write(" ".join(bpe_tokens) + "\n")
498
+ index += 1
499
+
500
+ return src_vocab_file, tgt_vocab_file, merges_file
501
+
502
+ def __getstate__(self):
503
+ state = self.__dict__.copy()
504
+ state["sm"] = None
505
+ return state
506
+
507
+ def __setstate__(self, d):
508
+ self.__dict__ = d
509
+
510
+ try:
511
+ import sacremoses
512
+ except ImportError:
513
+ raise ImportError(
514
+ "You need to install sacremoses to use XLMTokenizer. "
515
+ "See https://pypi.org/project/sacremoses/ for installation."
516
+ )
517
+
518
+ self.sm = sacremoses
519
+
520
+
521
+ __all__ = ["FSMTTokenizer"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/funnel/__init__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_funnel import *
22
+ from .convert_funnel_original_tf_checkpoint_to_pytorch import *
23
+ from .modeling_funnel import *
24
+ from .modeling_tf_funnel import *
25
+ from .tokenization_funnel import *
26
+ from .tokenization_funnel_fast import *
27
+ else:
28
+ import sys
29
+
30
+ _file = globals()["__file__"]
31
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/funnel/configuration_funnel.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020, Hugging Face
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
+ """Funnel Transformer model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class FunnelConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`FunnelModel`] or a [`TFBertModel`]. It is used to
27
+ instantiate a Funnel Transformer model according to the specified arguments, defining the model architecture.
28
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the Funnel
29
+ Transformer [funnel-transformer/small](https://huggingface.co/funnel-transformer/small) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+ Args:
35
+ vocab_size (`int`, *optional*, defaults to 30522):
36
+ Vocabulary size of the Funnel transformer. Defines the number of different tokens that can be represented
37
+ by the `inputs_ids` passed when calling [`FunnelModel`] or [`TFFunnelModel`].
38
+ block_sizes (`List[int]`, *optional*, defaults to `[4, 4, 4]`):
39
+ The sizes of the blocks used in the model.
40
+ block_repeats (`List[int]`, *optional*):
41
+ If passed along, each layer of each block is repeated the number of times indicated.
42
+ num_decoder_layers (`int`, *optional*, defaults to 2):
43
+ The number of layers in the decoder (when not using the base model).
44
+ d_model (`int`, *optional*, defaults to 768):
45
+ Dimensionality of the model's hidden states.
46
+ n_head (`int`, *optional*, defaults to 12):
47
+ Number of attention heads for each attention layer in the Transformer encoder.
48
+ d_head (`int`, *optional*, defaults to 64):
49
+ Dimensionality of the model's heads.
50
+ d_inner (`int`, *optional*, defaults to 3072):
51
+ Inner dimension in the feed-forward blocks.
52
+ hidden_act (`str` or `callable`, *optional*, defaults to `"gelu_new"`):
53
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
54
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
55
+ hidden_dropout (`float`, *optional*, defaults to 0.1):
56
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
57
+ attention_dropout (`float`, *optional*, defaults to 0.1):
58
+ The dropout probability for the attention probabilities.
59
+ activation_dropout (`float`, *optional*, defaults to 0.0):
60
+ The dropout probability used between the two layers of the feed-forward blocks.
61
+ initializer_range (`float`, *optional*, defaults to 0.1):
62
+ The upper bound of the *uniform initializer* for initializing all weight matrices in attention layers.
63
+ initializer_std (`float`, *optional*):
64
+ The standard deviation of the *normal initializer* for initializing the embedding matrix and the weight of
65
+ linear layers. Will default to 1 for the embedding matrix and the value given by Xavier initialization for
66
+ linear layers.
67
+ layer_norm_eps (`float`, *optional*, defaults to 1e-09):
68
+ The epsilon used by the layer normalization layers.
69
+ pooling_type (`str`, *optional*, defaults to `"mean"`):
70
+ Possible values are `"mean"` or `"max"`. The way pooling is performed at the beginning of each block.
71
+ attention_type (`str`, *optional*, defaults to `"relative_shift"`):
72
+ Possible values are `"relative_shift"` or `"factorized"`. The former is faster on CPU/GPU while the latter
73
+ is faster on TPU.
74
+ separate_cls (`bool`, *optional*, defaults to `True`):
75
+ Whether or not to separate the cls token when applying pooling.
76
+ truncate_seq (`bool`, *optional*, defaults to `True`):
77
+ When using `separate_cls`, whether or not to truncate the last token when pooling, to avoid getting a
78
+ sequence length that is not a multiple of 2.
79
+ pool_q_only (`bool`, *optional*, defaults to `True`):
80
+ Whether or not to apply the pooling only to the query or to query, key and values for the attention layers.
81
+ """
82
+
83
+ model_type = "funnel"
84
+ attribute_map = {
85
+ "hidden_size": "d_model",
86
+ "num_attention_heads": "n_head",
87
+ }
88
+
89
+ def __init__(
90
+ self,
91
+ vocab_size=30522,
92
+ block_sizes=[4, 4, 4],
93
+ block_repeats=None,
94
+ num_decoder_layers=2,
95
+ d_model=768,
96
+ n_head=12,
97
+ d_head=64,
98
+ d_inner=3072,
99
+ hidden_act="gelu_new",
100
+ hidden_dropout=0.1,
101
+ attention_dropout=0.1,
102
+ activation_dropout=0.0,
103
+ initializer_range=0.1,
104
+ initializer_std=None,
105
+ layer_norm_eps=1e-9,
106
+ pooling_type="mean",
107
+ attention_type="relative_shift",
108
+ separate_cls=True,
109
+ truncate_seq=True,
110
+ pool_q_only=True,
111
+ **kwargs,
112
+ ):
113
+ self.vocab_size = vocab_size
114
+ self.block_sizes = block_sizes
115
+ self.block_repeats = [1] * len(block_sizes) if block_repeats is None else block_repeats
116
+ assert len(block_sizes) == len(
117
+ self.block_repeats
118
+ ), "`block_sizes` and `block_repeats` should have the same length."
119
+ self.num_decoder_layers = num_decoder_layers
120
+ self.d_model = d_model
121
+ self.n_head = n_head
122
+ self.d_head = d_head
123
+ self.d_inner = d_inner
124
+ self.hidden_act = hidden_act
125
+ self.hidden_dropout = hidden_dropout
126
+ self.attention_dropout = attention_dropout
127
+ self.activation_dropout = activation_dropout
128
+ self.initializer_range = initializer_range
129
+ self.initializer_std = initializer_std
130
+ self.layer_norm_eps = layer_norm_eps
131
+ assert pooling_type in [
132
+ "mean",
133
+ "max",
134
+ ], f"Got {pooling_type} for `pooling_type` but only 'mean' and 'max' are supported."
135
+ self.pooling_type = pooling_type
136
+ assert attention_type in [
137
+ "relative_shift",
138
+ "factorized",
139
+ ], f"Got {attention_type} for `attention_type` but only 'relative_shift' and 'factorized' are supported."
140
+ self.attention_type = attention_type
141
+ self.separate_cls = separate_cls
142
+ self.truncate_seq = truncate_seq
143
+ self.pool_q_only = pool_q_only
144
+
145
+ super().__init__(**kwargs)
146
+
147
+ @property
148
+ def num_hidden_layers(self):
149
+ return sum(self.block_sizes)
150
+
151
+ @num_hidden_layers.setter
152
+ def num_hidden_layers(self, value):
153
+ raise NotImplementedError(
154
+ "This model does not support the setting of `num_hidden_layers`. Please set `block_sizes`."
155
+ )
156
+
157
+ @property
158
+ def num_blocks(self):
159
+ return len(self.block_sizes)
160
+
161
+ @num_blocks.setter
162
+ def num_blocks(self, value):
163
+ raise NotImplementedError("This model does not support the setting of `num_blocks`. Please set `block_sizes`.")
164
+
165
+
166
+ __all__ = ["FunnelConfig"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/funnel/convert_funnel_original_tf_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 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 Funnel checkpoint."""
16
+
17
+ import argparse
18
+
19
+ import torch
20
+
21
+ from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel
22
+ from transformers.utils import logging
23
+
24
+
25
+ logging.set_verbosity_info()
26
+
27
+
28
+ def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, config_file, pytorch_dump_path, base_model):
29
+ # Initialise PyTorch model
30
+ config = FunnelConfig.from_json_file(config_file)
31
+ print(f"Building PyTorch model from configuration: {config}")
32
+ model = FunnelBaseModel(config) if base_model else FunnelModel(config)
33
+
34
+ # Load weights from tf checkpoint
35
+ load_tf_weights_in_funnel(model, config, tf_checkpoint_path)
36
+
37
+ # Save pytorch-model
38
+ print(f"Save PyTorch model to {pytorch_dump_path}")
39
+ torch.save(model.state_dict(), pytorch_dump_path)
40
+
41
+
42
+ if __name__ == "__main__":
43
+ parser = argparse.ArgumentParser()
44
+ # Required parameters
45
+ parser.add_argument(
46
+ "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
47
+ )
48
+ parser.add_argument(
49
+ "--config_file",
50
+ default=None,
51
+ type=str,
52
+ required=True,
53
+ help="The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.",
54
+ )
55
+ parser.add_argument(
56
+ "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
57
+ )
58
+ parser.add_argument(
59
+ "--base_model", action="store_true", help="Whether you want just the base model (no decoder) or not."
60
+ )
61
+ args = parser.parse_args()
62
+ convert_tf_checkpoint_to_pytorch(
63
+ args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model
64
+ )
65
+
66
+
67
+ __all__ = []
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/funnel/modeling_funnel.py ADDED
@@ -0,0 +1,1608 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020-present Google Brain and Carnegie Mellon University 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 Funnel Transformer model."""
16
+
17
+ import os
18
+ from dataclasses import dataclass
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import numpy as np
22
+ import torch
23
+ from torch import nn
24
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
25
+
26
+ from ...activations import ACT2FN
27
+ from ...modeling_outputs import (
28
+ BaseModelOutput,
29
+ MaskedLMOutput,
30
+ MultipleChoiceModelOutput,
31
+ QuestionAnsweringModelOutput,
32
+ SequenceClassifierOutput,
33
+ TokenClassifierOutput,
34
+ )
35
+ from ...modeling_utils import PreTrainedModel
36
+ from ...utils import (
37
+ ModelOutput,
38
+ add_code_sample_docstrings,
39
+ add_start_docstrings,
40
+ add_start_docstrings_to_model_forward,
41
+ logging,
42
+ replace_return_docstrings,
43
+ )
44
+ from .configuration_funnel import FunnelConfig
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+ _CONFIG_FOR_DOC = "FunnelConfig"
50
+ _CHECKPOINT_FOR_DOC = "funnel-transformer/small"
51
+
52
+
53
+ INF = 1e6
54
+
55
+
56
+ def load_tf_weights_in_funnel(model, config, tf_checkpoint_path):
57
+ """Load tf checkpoints in a pytorch model."""
58
+ try:
59
+ import re
60
+
61
+ import numpy as np
62
+ import tensorflow as tf
63
+ except ImportError:
64
+ logger.error(
65
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
66
+ "https://www.tensorflow.org/install/ for installation instructions."
67
+ )
68
+ raise
69
+ tf_path = os.path.abspath(tf_checkpoint_path)
70
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
71
+ # Load weights from TF model
72
+ init_vars = tf.train.list_variables(tf_path)
73
+ names = []
74
+ arrays = []
75
+ for name, shape in init_vars:
76
+ logger.info(f"Loading TF weight {name} with shape {shape}")
77
+ array = tf.train.load_variable(tf_path, name)
78
+ names.append(name)
79
+ arrays.append(array)
80
+
81
+ _layer_map = {
82
+ "k": "k_head",
83
+ "q": "q_head",
84
+ "v": "v_head",
85
+ "o": "post_proj",
86
+ "layer_1": "linear_1",
87
+ "layer_2": "linear_2",
88
+ "rel_attn": "attention",
89
+ "ff": "ffn",
90
+ "kernel": "weight",
91
+ "gamma": "weight",
92
+ "beta": "bias",
93
+ "lookup_table": "weight",
94
+ "word_embedding": "word_embeddings",
95
+ "input": "embeddings",
96
+ }
97
+
98
+ for name, array in zip(names, arrays):
99
+ name = name.split("/")
100
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
101
+ # which are not required for using pretrained model
102
+ if any(
103
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
104
+ for n in name
105
+ ):
106
+ logger.info(f"Skipping {'/'.join(name)}")
107
+ continue
108
+ if name[0] == "generator":
109
+ continue
110
+ pointer = model
111
+ skipped = False
112
+ for m_name in name[1:]:
113
+ if not isinstance(pointer, FunnelPositionwiseFFN) and re.fullmatch(r"layer_\d+", m_name):
114
+ layer_index = int(re.search(r"layer_(\d+)", m_name).groups()[0])
115
+ if layer_index < config.num_hidden_layers:
116
+ block_idx = 0
117
+ while layer_index >= config.block_sizes[block_idx]:
118
+ layer_index -= config.block_sizes[block_idx]
119
+ block_idx += 1
120
+ pointer = pointer.blocks[block_idx][layer_index]
121
+ else:
122
+ layer_index -= config.num_hidden_layers
123
+ pointer = pointer.layers[layer_index]
124
+ elif m_name == "r" and isinstance(pointer, FunnelRelMultiheadAttention):
125
+ pointer = pointer.r_kernel
126
+ break
127
+ elif m_name in _layer_map:
128
+ pointer = getattr(pointer, _layer_map[m_name])
129
+ else:
130
+ try:
131
+ pointer = getattr(pointer, m_name)
132
+ except AttributeError:
133
+ print(f"Skipping {'/'.join(name)}", array.shape)
134
+ skipped = True
135
+ break
136
+ if not skipped:
137
+ if len(pointer.shape) != len(array.shape):
138
+ array = array.reshape(pointer.shape)
139
+ if m_name == "kernel":
140
+ array = np.transpose(array)
141
+ pointer.data = torch.from_numpy(array)
142
+
143
+ return model
144
+
145
+
146
+ class FunnelEmbeddings(nn.Module):
147
+ def __init__(self, config: FunnelConfig) -> None:
148
+ super().__init__()
149
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
150
+ self.layer_norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_eps)
151
+ self.dropout = nn.Dropout(config.hidden_dropout)
152
+
153
+ def forward(
154
+ self, input_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None
155
+ ) -> torch.Tensor:
156
+ if inputs_embeds is None:
157
+ inputs_embeds = self.word_embeddings(input_ids)
158
+ embeddings = self.layer_norm(inputs_embeds)
159
+ embeddings = self.dropout(embeddings)
160
+ return embeddings
161
+
162
+
163
+ class FunnelAttentionStructure(nn.Module):
164
+ """
165
+ Contains helpers for `FunnelRelMultiheadAttention `.
166
+ """
167
+
168
+ cls_token_type_id: int = 2
169
+
170
+ def __init__(self, config: FunnelConfig) -> None:
171
+ super().__init__()
172
+ self.config = config
173
+ self.sin_dropout = nn.Dropout(config.hidden_dropout)
174
+ self.cos_dropout = nn.Dropout(config.hidden_dropout)
175
+ # Track where we are at in terms of pooling from the original input, e.g., by how much the sequence length was
176
+ # divided.
177
+ self.pooling_mult = None
178
+
179
+ def init_attention_inputs(
180
+ self,
181
+ inputs_embeds: torch.Tensor,
182
+ attention_mask: Optional[torch.Tensor] = None,
183
+ token_type_ids: Optional[torch.Tensor] = None,
184
+ ) -> Tuple[torch.Tensor]:
185
+ """Returns the attention inputs associated to the inputs of the model."""
186
+ # inputs_embeds has shape batch_size x seq_len x d_model
187
+ # attention_mask and token_type_ids have shape batch_size x seq_len
188
+ self.pooling_mult = 1
189
+ self.seq_len = seq_len = inputs_embeds.size(1)
190
+ position_embeds = self.get_position_embeds(seq_len, inputs_embeds.dtype, inputs_embeds.device)
191
+ token_type_mat = self.token_type_ids_to_mat(token_type_ids) if token_type_ids is not None else None
192
+ cls_mask = (
193
+ nn.functional.pad(inputs_embeds.new_ones([seq_len - 1, seq_len - 1]), (1, 0, 1, 0))
194
+ if self.config.separate_cls
195
+ else None
196
+ )
197
+ return (position_embeds, token_type_mat, attention_mask, cls_mask)
198
+
199
+ def token_type_ids_to_mat(self, token_type_ids: torch.Tensor) -> torch.Tensor:
200
+ """Convert `token_type_ids` to `token_type_mat`."""
201
+ token_type_mat = token_type_ids[:, :, None] == token_type_ids[:, None]
202
+ # Treat <cls> as in the same segment as both A & B
203
+ cls_ids = token_type_ids == self.cls_token_type_id
204
+ cls_mat = cls_ids[:, :, None] | cls_ids[:, None]
205
+ return cls_mat | token_type_mat
206
+
207
+ def get_position_embeds(
208
+ self, seq_len: int, dtype: torch.dtype, device: torch.device
209
+ ) -> Union[Tuple[torch.Tensor], List[List[torch.Tensor]]]:
210
+ """
211
+ Create and cache inputs related to relative position encoding. Those are very different depending on whether we
212
+ are using the factorized or the relative shift attention:
213
+
214
+ For the factorized attention, it returns the matrices (phi, pi, psi, omega) used in the paper, appendix A.2.2,
215
+ final formula.
216
+
217
+ For the relative shift attention, it returns all possible vectors R used in the paper, appendix A.2.1, final
218
+ formula.
219
+
220
+ Paper link: https://arxiv.org/abs/2006.03236
221
+ """
222
+ d_model = self.config.d_model
223
+ if self.config.attention_type == "factorized":
224
+ # Notations from the paper, appending A.2.2, final formula.
225
+ # We need to create and return the matrices phi, psi, pi and omega.
226
+ pos_seq = torch.arange(0, seq_len, 1.0, dtype=torch.int64, device=device).to(dtype)
227
+ freq_seq = torch.arange(0, d_model // 2, 1.0, dtype=torch.int64, device=device).to(dtype)
228
+ inv_freq = 1 / (10000 ** (freq_seq / (d_model // 2)))
229
+ sinusoid = pos_seq[:, None] * inv_freq[None]
230
+ sin_embed = torch.sin(sinusoid)
231
+ sin_embed_d = self.sin_dropout(sin_embed)
232
+ cos_embed = torch.cos(sinusoid)
233
+ cos_embed_d = self.cos_dropout(cos_embed)
234
+ # This is different from the formula on the paper...
235
+ phi = torch.cat([sin_embed_d, sin_embed_d], dim=-1)
236
+ psi = torch.cat([cos_embed, sin_embed], dim=-1)
237
+ pi = torch.cat([cos_embed_d, cos_embed_d], dim=-1)
238
+ omega = torch.cat([-sin_embed, cos_embed], dim=-1)
239
+ return (phi, pi, psi, omega)
240
+ else:
241
+ # Notations from the paper, appending A.2.1, final formula.
242
+ # We need to create and return all the possible vectors R for all blocks and shifts.
243
+ freq_seq = torch.arange(0, d_model // 2, 1.0, dtype=torch.int64, device=device).to(dtype)
244
+ inv_freq = 1 / (10000 ** (freq_seq / (d_model // 2)))
245
+ # Maximum relative positions for the first input
246
+ rel_pos_id = torch.arange(-seq_len * 2, seq_len * 2, 1.0, dtype=torch.int64, device=device).to(dtype)
247
+ zero_offset = seq_len * 2
248
+ sinusoid = rel_pos_id[:, None] * inv_freq[None]
249
+ sin_embed = self.sin_dropout(torch.sin(sinusoid))
250
+ cos_embed = self.cos_dropout(torch.cos(sinusoid))
251
+ pos_embed = torch.cat([sin_embed, cos_embed], dim=-1)
252
+
253
+ pos = torch.arange(0, seq_len, dtype=torch.int64, device=device).to(dtype)
254
+ pooled_pos = pos
255
+ position_embeds_list = []
256
+ for block_index in range(0, self.config.num_blocks):
257
+ # For each block with block_index > 0, we need two types position embeddings:
258
+ # - Attention(pooled-q, unpooled-kv)
259
+ # - Attention(pooled-q, pooled-kv)
260
+ # For block_index = 0 we only need the second one and leave the first one as None.
261
+
262
+ # First type
263
+ if block_index == 0:
264
+ position_embeds_pooling = None
265
+ else:
266
+ pooled_pos = self.stride_pool_pos(pos, block_index)
267
+
268
+ # construct rel_pos_id
269
+ stride = 2 ** (block_index - 1)
270
+ rel_pos = self.relative_pos(pos, stride, pooled_pos, shift=2)
271
+ rel_pos = rel_pos[:, None] + zero_offset
272
+ rel_pos = rel_pos.expand(rel_pos.size(0), d_model)
273
+ position_embeds_pooling = torch.gather(pos_embed, 0, rel_pos)
274
+
275
+ # Second type
276
+ pos = pooled_pos
277
+ stride = 2**block_index
278
+ rel_pos = self.relative_pos(pos, stride)
279
+
280
+ rel_pos = rel_pos[:, None] + zero_offset
281
+ rel_pos = rel_pos.expand(rel_pos.size(0), d_model)
282
+ position_embeds_no_pooling = torch.gather(pos_embed, 0, rel_pos)
283
+
284
+ position_embeds_list.append([position_embeds_no_pooling, position_embeds_pooling])
285
+ return position_embeds_list
286
+
287
+ def stride_pool_pos(self, pos_id: torch.Tensor, block_index: int):
288
+ """
289
+ Pool `pos_id` while keeping the cls token separate (if `config.separate_cls=True`).
290
+ """
291
+ if self.config.separate_cls:
292
+ # Under separate <cls>, we treat the <cls> as the first token in
293
+ # the previous block of the 1st real block. Since the 1st real
294
+ # block always has position 1, the position of the previous block
295
+ # will be at `1 - 2 ** block_index`.
296
+ cls_pos = pos_id.new_tensor([-(2**block_index) + 1])
297
+ pooled_pos_id = pos_id[1:-1] if self.config.truncate_seq else pos_id[1:]
298
+ return torch.cat([cls_pos, pooled_pos_id[::2]], 0)
299
+ else:
300
+ return pos_id[::2]
301
+
302
+ def relative_pos(self, pos: torch.Tensor, stride: int, pooled_pos=None, shift: int = 1) -> torch.Tensor:
303
+ """
304
+ Build the relative positional vector between `pos` and `pooled_pos`.
305
+ """
306
+ if pooled_pos is None:
307
+ pooled_pos = pos
308
+
309
+ ref_point = pooled_pos[0] - pos[0]
310
+ num_remove = shift * len(pooled_pos)
311
+ max_dist = ref_point + num_remove * stride
312
+ min_dist = pooled_pos[0] - pos[-1]
313
+
314
+ return torch.arange(max_dist, min_dist - 1, -stride, dtype=torch.long, device=pos.device)
315
+
316
+ def stride_pool(
317
+ self,
318
+ tensor: Union[torch.Tensor, Tuple[torch.Tensor], List[torch.Tensor]],
319
+ axis: Union[int, Tuple[int], List[int]],
320
+ ) -> torch.Tensor:
321
+ """
322
+ Perform pooling by stride slicing the tensor along the given axis.
323
+ """
324
+ if tensor is None:
325
+ return None
326
+
327
+ # Do the stride pool recursively if axis is a list or a tuple of ints.
328
+ if isinstance(axis, (list, tuple)):
329
+ for ax in axis:
330
+ tensor = self.stride_pool(tensor, ax)
331
+ return tensor
332
+
333
+ # Do the stride pool recursively if tensor is a list or tuple of tensors.
334
+ if isinstance(tensor, (tuple, list)):
335
+ return type(tensor)(self.stride_pool(x, axis) for x in tensor)
336
+
337
+ # Deal with negative axis
338
+ axis %= tensor.ndim
339
+
340
+ axis_slice = (
341
+ slice(None, -1, 2) if self.config.separate_cls and self.config.truncate_seq else slice(None, None, 2)
342
+ )
343
+ enc_slice = [slice(None)] * axis + [axis_slice]
344
+ if self.config.separate_cls:
345
+ cls_slice = [slice(None)] * axis + [slice(None, 1)]
346
+ tensor = torch.cat([tensor[cls_slice], tensor], axis=axis)
347
+ return tensor[enc_slice]
348
+
349
+ def pool_tensor(
350
+ self, tensor: Union[torch.Tensor, Tuple[torch.Tensor], List[torch.Tensor]], mode: str = "mean", stride: int = 2
351
+ ) -> torch.Tensor:
352
+ """Apply 1D pooling to a tensor of size [B x T (x H)]."""
353
+ if tensor is None:
354
+ return None
355
+
356
+ # Do the pool recursively if tensor is a list or tuple of tensors.
357
+ if isinstance(tensor, (tuple, list)):
358
+ return type(tensor)(self.pool_tensor(tensor, mode=mode, stride=stride) for x in tensor)
359
+
360
+ if self.config.separate_cls:
361
+ suffix = tensor[:, :-1] if self.config.truncate_seq else tensor
362
+ tensor = torch.cat([tensor[:, :1], suffix], dim=1)
363
+
364
+ ndim = tensor.ndim
365
+ if ndim == 2:
366
+ tensor = tensor[:, None, :, None]
367
+ elif ndim == 3:
368
+ tensor = tensor[:, None, :, :]
369
+ # Stride is applied on the second-to-last dimension.
370
+ stride = (stride, 1)
371
+
372
+ if mode == "mean":
373
+ tensor = nn.functional.avg_pool2d(tensor, stride, stride=stride, ceil_mode=True)
374
+ elif mode == "max":
375
+ tensor = nn.functional.max_pool2d(tensor, stride, stride=stride, ceil_mode=True)
376
+ elif mode == "min":
377
+ tensor = -nn.functional.max_pool2d(-tensor, stride, stride=stride, ceil_mode=True)
378
+ else:
379
+ raise NotImplementedError("The supported modes are 'mean', 'max' and 'min'.")
380
+
381
+ if ndim == 2:
382
+ return tensor[:, 0, :, 0]
383
+ elif ndim == 3:
384
+ return tensor[:, 0]
385
+ return tensor
386
+
387
+ def pre_attention_pooling(
388
+ self, output, attention_inputs: Tuple[torch.Tensor]
389
+ ) -> Tuple[torch.Tensor, Tuple[torch.Tensor]]:
390
+ """Pool `output` and the proper parts of `attention_inputs` before the attention layer."""
391
+ position_embeds, token_type_mat, attention_mask, cls_mask = attention_inputs
392
+ if self.config.pool_q_only:
393
+ if self.config.attention_type == "factorized":
394
+ position_embeds = self.stride_pool(position_embeds[:2], 0) + position_embeds[2:]
395
+ token_type_mat = self.stride_pool(token_type_mat, 1)
396
+ cls_mask = self.stride_pool(cls_mask, 0)
397
+ output = self.pool_tensor(output, mode=self.config.pooling_type)
398
+ else:
399
+ self.pooling_mult *= 2
400
+ if self.config.attention_type == "factorized":
401
+ position_embeds = self.stride_pool(position_embeds, 0)
402
+ token_type_mat = self.stride_pool(token_type_mat, [1, 2])
403
+ cls_mask = self.stride_pool(cls_mask, [1, 2])
404
+ attention_mask = self.pool_tensor(attention_mask, mode="min")
405
+ output = self.pool_tensor(output, mode=self.config.pooling_type)
406
+ attention_inputs = (position_embeds, token_type_mat, attention_mask, cls_mask)
407
+ return output, attention_inputs
408
+
409
+ def post_attention_pooling(self, attention_inputs: Tuple[torch.Tensor]) -> Tuple[torch.Tensor]:
410
+ """Pool the proper parts of `attention_inputs` after the attention layer."""
411
+ position_embeds, token_type_mat, attention_mask, cls_mask = attention_inputs
412
+ if self.config.pool_q_only:
413
+ self.pooling_mult *= 2
414
+ if self.config.attention_type == "factorized":
415
+ position_embeds = position_embeds[:2] + self.stride_pool(position_embeds[2:], 0)
416
+ token_type_mat = self.stride_pool(token_type_mat, 2)
417
+ cls_mask = self.stride_pool(cls_mask, 1)
418
+ attention_mask = self.pool_tensor(attention_mask, mode="min")
419
+ attention_inputs = (position_embeds, token_type_mat, attention_mask, cls_mask)
420
+ return attention_inputs
421
+
422
+
423
+ def _relative_shift_gather(positional_attn: torch.Tensor, context_len: int, shift: int) -> torch.Tensor:
424
+ batch_size, n_head, seq_len, max_rel_len = positional_attn.shape
425
+ # max_rel_len = 2 * context_len + shift -1 is the numbers of possible relative positions i-j
426
+
427
+ # What's next is the same as doing the following gather, which might be clearer code but less efficient.
428
+ # idxs = context_len + torch.arange(0, context_len).unsqueeze(0) - torch.arange(0, seq_len).unsqueeze(1)
429
+ # # matrix of context_len + i-j
430
+ # return positional_attn.gather(3, idxs.expand([batch_size, n_head, context_len, context_len]))
431
+
432
+ positional_attn = torch.reshape(positional_attn, [batch_size, n_head, max_rel_len, seq_len])
433
+ positional_attn = positional_attn[:, :, shift:, :]
434
+ positional_attn = torch.reshape(positional_attn, [batch_size, n_head, seq_len, max_rel_len - shift])
435
+ positional_attn = positional_attn[..., :context_len]
436
+ return positional_attn
437
+
438
+
439
+ class FunnelRelMultiheadAttention(nn.Module):
440
+ def __init__(self, config: FunnelConfig, block_index: int) -> None:
441
+ super().__init__()
442
+ self.config = config
443
+ self.block_index = block_index
444
+ d_model, n_head, d_head = config.d_model, config.n_head, config.d_head
445
+
446
+ self.hidden_dropout = nn.Dropout(config.hidden_dropout)
447
+ self.attention_dropout = nn.Dropout(config.attention_dropout)
448
+
449
+ self.q_head = nn.Linear(d_model, n_head * d_head, bias=False)
450
+ self.k_head = nn.Linear(d_model, n_head * d_head)
451
+ self.v_head = nn.Linear(d_model, n_head * d_head)
452
+
453
+ self.r_w_bias = nn.Parameter(torch.zeros([n_head, d_head]))
454
+ self.r_r_bias = nn.Parameter(torch.zeros([n_head, d_head]))
455
+ self.r_kernel = nn.Parameter(torch.zeros([d_model, n_head, d_head]))
456
+ self.r_s_bias = nn.Parameter(torch.zeros([n_head, d_head]))
457
+ self.seg_embed = nn.Parameter(torch.zeros([2, n_head, d_head]))
458
+
459
+ self.post_proj = nn.Linear(n_head * d_head, d_model)
460
+ self.layer_norm = nn.LayerNorm(d_model, eps=config.layer_norm_eps)
461
+ self.scale = 1.0 / (d_head**0.5)
462
+
463
+ def relative_positional_attention(self, position_embeds, q_head, context_len, cls_mask=None):
464
+ """Relative attention score for the positional encodings"""
465
+ # q_head has shape batch_size x sea_len x n_head x d_head
466
+ if self.config.attention_type == "factorized":
467
+ # Notations from the paper, appending A.2.2, final formula (https://arxiv.org/abs/2006.03236)
468
+ # phi and pi have shape seq_len x d_model, psi and omega have shape context_len x d_model
469
+ phi, pi, psi, omega = position_embeds
470
+ # Shape n_head x d_head
471
+ u = self.r_r_bias * self.scale
472
+ # Shape d_model x n_head x d_head
473
+ w_r = self.r_kernel
474
+
475
+ # Shape batch_size x sea_len x n_head x d_model
476
+ q_r_attention = torch.einsum("binh,dnh->bind", q_head + u, w_r)
477
+ q_r_attention_1 = q_r_attention * phi[:, None]
478
+ q_r_attention_2 = q_r_attention * pi[:, None]
479
+
480
+ # Shape batch_size x n_head x seq_len x context_len
481
+ positional_attn = torch.einsum("bind,jd->bnij", q_r_attention_1, psi) + torch.einsum(
482
+ "bind,jd->bnij", q_r_attention_2, omega
483
+ )
484
+ else:
485
+ shift = 2 if q_head.shape[1] != context_len else 1
486
+ # Notations from the paper, appending A.2.1, final formula (https://arxiv.org/abs/2006.03236)
487
+ # Grab the proper positional encoding, shape max_rel_len x d_model
488
+ r = position_embeds[self.block_index][shift - 1]
489
+ # Shape n_head x d_head
490
+ v = self.r_r_bias * self.scale
491
+ # Shape d_model x n_head x d_head
492
+ w_r = self.r_kernel
493
+
494
+ # Shape max_rel_len x n_head x d_model
495
+ r_head = torch.einsum("td,dnh->tnh", r, w_r)
496
+ # Shape batch_size x n_head x seq_len x max_rel_len
497
+ positional_attn = torch.einsum("binh,tnh->bnit", q_head + v, r_head)
498
+ # Shape batch_size x n_head x seq_len x context_len
499
+ positional_attn = _relative_shift_gather(positional_attn, context_len, shift)
500
+
501
+ if cls_mask is not None:
502
+ positional_attn *= cls_mask
503
+ return positional_attn
504
+
505
+ def relative_token_type_attention(self, token_type_mat, q_head, cls_mask=None):
506
+ """Relative attention score for the token_type_ids"""
507
+ if token_type_mat is None:
508
+ return 0
509
+ batch_size, seq_len, context_len = token_type_mat.shape
510
+ # q_head has shape batch_size x seq_len x n_head x d_head
511
+ # Shape n_head x d_head
512
+ r_s_bias = self.r_s_bias * self.scale
513
+
514
+ # Shape batch_size x n_head x seq_len x 2
515
+ token_type_bias = torch.einsum("bind,snd->bnis", q_head + r_s_bias, self.seg_embed)
516
+ # Shape batch_size x n_head x seq_len x context_len
517
+ token_type_mat = token_type_mat[:, None].expand([batch_size, q_head.shape[2], seq_len, context_len])
518
+ # Shapes batch_size x n_head x seq_len
519
+ diff_token_type, same_token_type = torch.split(token_type_bias, 1, dim=-1)
520
+ # Shape batch_size x n_head x seq_len x context_len
521
+ token_type_attn = torch.where(
522
+ token_type_mat, same_token_type.expand(token_type_mat.shape), diff_token_type.expand(token_type_mat.shape)
523
+ )
524
+
525
+ if cls_mask is not None:
526
+ token_type_attn *= cls_mask
527
+ return token_type_attn
528
+
529
+ def forward(
530
+ self,
531
+ query: torch.Tensor,
532
+ key: torch.Tensor,
533
+ value: torch.Tensor,
534
+ attention_inputs: Tuple[torch.Tensor],
535
+ output_attentions: bool = False,
536
+ ) -> Tuple[torch.Tensor, ...]:
537
+ # query has shape batch_size x seq_len x d_model
538
+ # key and value have shapes batch_size x context_len x d_model
539
+ position_embeds, token_type_mat, attention_mask, cls_mask = attention_inputs
540
+
541
+ batch_size, seq_len, _ = query.shape
542
+ context_len = key.shape[1]
543
+ n_head, d_head = self.config.n_head, self.config.d_head
544
+
545
+ # Shape batch_size x seq_len x n_head x d_head
546
+ q_head = self.q_head(query).view(batch_size, seq_len, n_head, d_head)
547
+ # Shapes batch_size x context_len x n_head x d_head
548
+ k_head = self.k_head(key).view(batch_size, context_len, n_head, d_head)
549
+ v_head = self.v_head(value).view(batch_size, context_len, n_head, d_head)
550
+
551
+ q_head = q_head * self.scale
552
+ # Shape n_head x d_head
553
+ r_w_bias = self.r_w_bias * self.scale
554
+ # Shapes batch_size x n_head x seq_len x context_len
555
+ content_score = torch.einsum("bind,bjnd->bnij", q_head + r_w_bias, k_head)
556
+ positional_attn = self.relative_positional_attention(position_embeds, q_head, context_len, cls_mask)
557
+ token_type_attn = self.relative_token_type_attention(token_type_mat, q_head, cls_mask)
558
+
559
+ # merge attention scores
560
+ attn_score = content_score + positional_attn + token_type_attn
561
+
562
+ # precision safe in case of mixed precision training
563
+ dtype = attn_score.dtype
564
+ attn_score = attn_score.float()
565
+ # perform masking
566
+ if attention_mask is not None:
567
+ attn_score = attn_score - INF * (1 - attention_mask[:, None, None].float())
568
+ # attention probability
569
+ attn_prob = torch.softmax(attn_score, dim=-1, dtype=dtype)
570
+ attn_prob = self.attention_dropout(attn_prob)
571
+
572
+ # attention output, shape batch_size x seq_len x n_head x d_head
573
+ attn_vec = torch.einsum("bnij,bjnd->bind", attn_prob, v_head)
574
+
575
+ # Shape shape batch_size x seq_len x d_model
576
+ attn_out = self.post_proj(attn_vec.reshape(batch_size, seq_len, n_head * d_head))
577
+ attn_out = self.hidden_dropout(attn_out)
578
+
579
+ output = self.layer_norm(query + attn_out)
580
+ return (output, attn_prob) if output_attentions else (output,)
581
+
582
+
583
+ class FunnelPositionwiseFFN(nn.Module):
584
+ def __init__(self, config: FunnelConfig) -> None:
585
+ super().__init__()
586
+ self.linear_1 = nn.Linear(config.d_model, config.d_inner)
587
+ self.activation_function = ACT2FN[config.hidden_act]
588
+ self.activation_dropout = nn.Dropout(config.activation_dropout)
589
+ self.linear_2 = nn.Linear(config.d_inner, config.d_model)
590
+ self.dropout = nn.Dropout(config.hidden_dropout)
591
+ self.layer_norm = nn.LayerNorm(config.d_model, config.layer_norm_eps)
592
+
593
+ def forward(self, hidden: torch.Tensor) -> torch.Tensor:
594
+ h = self.linear_1(hidden)
595
+ h = self.activation_function(h)
596
+ h = self.activation_dropout(h)
597
+ h = self.linear_2(h)
598
+ h = self.dropout(h)
599
+ return self.layer_norm(hidden + h)
600
+
601
+
602
+ class FunnelLayer(nn.Module):
603
+ def __init__(self, config: FunnelConfig, block_index: int) -> None:
604
+ super().__init__()
605
+ self.attention = FunnelRelMultiheadAttention(config, block_index)
606
+ self.ffn = FunnelPositionwiseFFN(config)
607
+
608
+ def forward(
609
+ self,
610
+ query: torch.Tensor,
611
+ key: torch.Tensor,
612
+ value: torch.Tensor,
613
+ attention_inputs,
614
+ output_attentions: bool = False,
615
+ ) -> Tuple:
616
+ attn = self.attention(query, key, value, attention_inputs, output_attentions=output_attentions)
617
+ output = self.ffn(attn[0])
618
+ return (output, attn[1]) if output_attentions else (output,)
619
+
620
+
621
+ class FunnelEncoder(nn.Module):
622
+ def __init__(self, config: FunnelConfig) -> None:
623
+ super().__init__()
624
+ self.config = config
625
+ self.attention_structure = FunnelAttentionStructure(config)
626
+ self.blocks = nn.ModuleList(
627
+ [
628
+ nn.ModuleList([FunnelLayer(config, block_index) for _ in range(block_size)])
629
+ for block_index, block_size in enumerate(config.block_sizes)
630
+ ]
631
+ )
632
+
633
+ def forward(
634
+ self,
635
+ inputs_embeds: torch.Tensor,
636
+ attention_mask: Optional[torch.Tensor] = None,
637
+ token_type_ids: Optional[torch.Tensor] = None,
638
+ output_attentions: bool = False,
639
+ output_hidden_states: bool = False,
640
+ return_dict: bool = True,
641
+ ) -> Union[Tuple, BaseModelOutput]:
642
+ # The pooling is not implemented on long tensors, so we convert this mask.
643
+ attention_mask = attention_mask.type_as(inputs_embeds)
644
+ attention_inputs = self.attention_structure.init_attention_inputs(
645
+ inputs_embeds,
646
+ attention_mask=attention_mask,
647
+ token_type_ids=token_type_ids,
648
+ )
649
+ hidden = inputs_embeds
650
+
651
+ all_hidden_states = (inputs_embeds,) if output_hidden_states else None
652
+ all_attentions = () if output_attentions else None
653
+
654
+ for block_index, block in enumerate(self.blocks):
655
+ pooling_flag = hidden.size(1) > (2 if self.config.separate_cls else 1)
656
+ pooling_flag = pooling_flag and block_index > 0
657
+ if pooling_flag:
658
+ pooled_hidden, attention_inputs = self.attention_structure.pre_attention_pooling(
659
+ hidden, attention_inputs
660
+ )
661
+ for layer_index, layer in enumerate(block):
662
+ for repeat_index in range(self.config.block_repeats[block_index]):
663
+ do_pooling = (repeat_index == 0) and (layer_index == 0) and pooling_flag
664
+ if do_pooling:
665
+ query = pooled_hidden
666
+ key = value = hidden if self.config.pool_q_only else pooled_hidden
667
+ else:
668
+ query = key = value = hidden
669
+ layer_output = layer(query, key, value, attention_inputs, output_attentions=output_attentions)
670
+ hidden = layer_output[0]
671
+ if do_pooling:
672
+ attention_inputs = self.attention_structure.post_attention_pooling(attention_inputs)
673
+
674
+ if output_attentions:
675
+ all_attentions = all_attentions + layer_output[1:]
676
+ if output_hidden_states:
677
+ all_hidden_states = all_hidden_states + (hidden,)
678
+
679
+ if not return_dict:
680
+ return tuple(v for v in [hidden, all_hidden_states, all_attentions] if v is not None)
681
+ return BaseModelOutput(last_hidden_state=hidden, hidden_states=all_hidden_states, attentions=all_attentions)
682
+
683
+
684
+ def upsample(
685
+ x: torch.Tensor, stride: int, target_len: int, separate_cls: bool = True, truncate_seq: bool = False
686
+ ) -> torch.Tensor:
687
+ """
688
+ Upsample tensor `x` to match `target_len` by repeating the tokens `stride` time on the sequence length dimension.
689
+ """
690
+ if stride == 1:
691
+ return x
692
+ if separate_cls:
693
+ cls = x[:, :1]
694
+ x = x[:, 1:]
695
+ output = torch.repeat_interleave(x, repeats=stride, dim=1)
696
+ if separate_cls:
697
+ if truncate_seq:
698
+ output = nn.functional.pad(output, (0, 0, 0, stride - 1, 0, 0))
699
+ output = output[:, : target_len - 1]
700
+ output = torch.cat([cls, output], dim=1)
701
+ else:
702
+ output = output[:, :target_len]
703
+ return output
704
+
705
+
706
+ class FunnelDecoder(nn.Module):
707
+ def __init__(self, config: FunnelConfig) -> None:
708
+ super().__init__()
709
+ self.config = config
710
+ self.attention_structure = FunnelAttentionStructure(config)
711
+ self.layers = nn.ModuleList([FunnelLayer(config, 0) for _ in range(config.num_decoder_layers)])
712
+
713
+ def forward(
714
+ self,
715
+ final_hidden: torch.Tensor,
716
+ first_block_hidden: torch.Tensor,
717
+ attention_mask: Optional[torch.Tensor] = None,
718
+ token_type_ids: Optional[torch.Tensor] = None,
719
+ output_attentions: bool = False,
720
+ output_hidden_states: bool = False,
721
+ return_dict: bool = True,
722
+ ) -> Union[Tuple, BaseModelOutput]:
723
+ upsampled_hidden = upsample(
724
+ final_hidden,
725
+ stride=2 ** (len(self.config.block_sizes) - 1),
726
+ target_len=first_block_hidden.shape[1],
727
+ separate_cls=self.config.separate_cls,
728
+ truncate_seq=self.config.truncate_seq,
729
+ )
730
+
731
+ hidden = upsampled_hidden + first_block_hidden
732
+ all_hidden_states = (hidden,) if output_hidden_states else None
733
+ all_attentions = () if output_attentions else None
734
+
735
+ attention_inputs = self.attention_structure.init_attention_inputs(
736
+ hidden,
737
+ attention_mask=attention_mask,
738
+ token_type_ids=token_type_ids,
739
+ )
740
+
741
+ for layer in self.layers:
742
+ layer_output = layer(hidden, hidden, hidden, attention_inputs, output_attentions=output_attentions)
743
+ hidden = layer_output[0]
744
+
745
+ if output_attentions:
746
+ all_attentions = all_attentions + layer_output[1:]
747
+ if output_hidden_states:
748
+ all_hidden_states = all_hidden_states + (hidden,)
749
+
750
+ if not return_dict:
751
+ return tuple(v for v in [hidden, all_hidden_states, all_attentions] if v is not None)
752
+ return BaseModelOutput(last_hidden_state=hidden, hidden_states=all_hidden_states, attentions=all_attentions)
753
+
754
+
755
+ class FunnelDiscriminatorPredictions(nn.Module):
756
+ """Prediction module for the discriminator, made up of two dense layers."""
757
+
758
+ def __init__(self, config: FunnelConfig) -> None:
759
+ super().__init__()
760
+ self.config = config
761
+ self.dense = nn.Linear(config.d_model, config.d_model)
762
+ self.dense_prediction = nn.Linear(config.d_model, 1)
763
+
764
+ def forward(self, discriminator_hidden_states: torch.Tensor) -> torch.Tensor:
765
+ hidden_states = self.dense(discriminator_hidden_states)
766
+ hidden_states = ACT2FN[self.config.hidden_act](hidden_states)
767
+ logits = self.dense_prediction(hidden_states).squeeze(-1)
768
+ return logits
769
+
770
+
771
+ class FunnelPreTrainedModel(PreTrainedModel):
772
+ """
773
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
774
+ models.
775
+ """
776
+
777
+ config_class = FunnelConfig
778
+ load_tf_weights = load_tf_weights_in_funnel
779
+ base_model_prefix = "funnel"
780
+
781
+ def _init_weights(self, module):
782
+ classname = module.__class__.__name__
783
+ if classname.find("Linear") != -1:
784
+ if getattr(module, "weight", None) is not None:
785
+ if self.config.initializer_std is None:
786
+ fan_out, fan_in = module.weight.shape
787
+ std = np.sqrt(1.0 / float(fan_in + fan_out))
788
+ else:
789
+ std = self.config.initializer_std
790
+ nn.init.normal_(module.weight, std=std)
791
+ if getattr(module, "bias", None) is not None:
792
+ nn.init.constant_(module.bias, 0.0)
793
+ elif classname == "FunnelRelMultiheadAttention":
794
+ nn.init.uniform_(module.r_w_bias, b=self.config.initializer_range)
795
+ nn.init.uniform_(module.r_r_bias, b=self.config.initializer_range)
796
+ nn.init.uniform_(module.r_kernel, b=self.config.initializer_range)
797
+ nn.init.uniform_(module.r_s_bias, b=self.config.initializer_range)
798
+ nn.init.uniform_(module.seg_embed, b=self.config.initializer_range)
799
+ elif classname == "FunnelEmbeddings":
800
+ std = 1.0 if self.config.initializer_std is None else self.config.initializer_std
801
+ nn.init.normal_(module.word_embeddings.weight, std=std)
802
+ if module.word_embeddings.padding_idx is not None:
803
+ module.word_embeddings.weight.data[module.word_embeddings.padding_idx].zero_()
804
+
805
+
806
+ class FunnelClassificationHead(nn.Module):
807
+ def __init__(self, config: FunnelConfig, n_labels: int) -> None:
808
+ super().__init__()
809
+ self.linear_hidden = nn.Linear(config.d_model, config.d_model)
810
+ self.dropout = nn.Dropout(config.hidden_dropout)
811
+ self.linear_out = nn.Linear(config.d_model, n_labels)
812
+
813
+ def forward(self, hidden: torch.Tensor) -> torch.Tensor:
814
+ hidden = self.linear_hidden(hidden)
815
+ hidden = torch.tanh(hidden)
816
+ hidden = self.dropout(hidden)
817
+ return self.linear_out(hidden)
818
+
819
+
820
+ @dataclass
821
+ class FunnelForPreTrainingOutput(ModelOutput):
822
+ """
823
+ Output type of [`FunnelForPreTraining`].
824
+
825
+ Args:
826
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
827
+ Total loss of the ELECTRA-style objective.
828
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
829
+ Prediction scores of the head (scores for each token before SoftMax).
830
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
831
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
832
+ shape `(batch_size, sequence_length, hidden_size)`.
833
+
834
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
835
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
836
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
837
+ sequence_length)`.
838
+
839
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
840
+ heads.
841
+ """
842
+
843
+ loss: Optional[torch.FloatTensor] = None
844
+ logits: torch.FloatTensor = None
845
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
846
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
847
+
848
+
849
+ FUNNEL_START_DOCSTRING = r"""
850
+
851
+ The Funnel Transformer model was proposed in [Funnel-Transformer: Filtering out Sequential Redundancy for Efficient
852
+ Language Processing](https://arxiv.org/abs/2006.03236) by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.
853
+
854
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
855
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
856
+ etc.)
857
+
858
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
859
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
860
+ and behavior.
861
+
862
+ Parameters:
863
+ config ([`FunnelConfig`]): Model configuration class with all the parameters of the model.
864
+ Initializing with a config file does not load the weights associated with the model, only the
865
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
866
+ """
867
+
868
+ FUNNEL_INPUTS_DOCSTRING = r"""
869
+ Args:
870
+ input_ids (`torch.LongTensor` of shape `({0})`):
871
+ Indices of input sequence tokens in the vocabulary.
872
+
873
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
874
+ [`PreTrainedTokenizer.__call__`] for details.
875
+
876
+ [What are input IDs?](../glossary#input-ids)
877
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
878
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
879
+
880
+ - 1 for tokens that are **not masked**,
881
+ - 0 for tokens that are **masked**.
882
+
883
+ [What are attention masks?](../glossary#attention-mask)
884
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
885
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
886
+ 1]`:
887
+
888
+ - 0 corresponds to a *sentence A* token,
889
+ - 1 corresponds to a *sentence B* token.
890
+
891
+ [What are token type IDs?](../glossary#token-type-ids)
892
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
893
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
894
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
895
+ model's internal embedding lookup matrix.
896
+ output_attentions (`bool`, *optional*):
897
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
898
+ tensors for more detail.
899
+ output_hidden_states (`bool`, *optional*):
900
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
901
+ more detail.
902
+ return_dict (`bool`, *optional*):
903
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
904
+ """
905
+
906
+
907
+ @add_start_docstrings(
908
+ """
909
+ The base Funnel Transformer Model transformer outputting raw hidden-states without upsampling head (also called
910
+ decoder) or any task-specific head on top.
911
+ """,
912
+ FUNNEL_START_DOCSTRING,
913
+ )
914
+ class FunnelBaseModel(FunnelPreTrainedModel):
915
+ def __init__(self, config: FunnelConfig) -> None:
916
+ super().__init__(config)
917
+
918
+ self.embeddings = FunnelEmbeddings(config)
919
+ self.encoder = FunnelEncoder(config)
920
+
921
+ # Initialize weights and apply final processing
922
+ self.post_init()
923
+
924
+ def get_input_embeddings(self) -> nn.Embedding:
925
+ return self.embeddings.word_embeddings
926
+
927
+ def set_input_embeddings(self, new_embeddings: nn.Embedding) -> None:
928
+ self.embeddings.word_embeddings = new_embeddings
929
+
930
+ @add_start_docstrings_to_model_forward(FUNNEL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
931
+ @add_code_sample_docstrings(
932
+ checkpoint="funnel-transformer/small-base",
933
+ output_type=BaseModelOutput,
934
+ config_class=_CONFIG_FOR_DOC,
935
+ )
936
+ def forward(
937
+ self,
938
+ input_ids: Optional[torch.Tensor] = None,
939
+ attention_mask: Optional[torch.Tensor] = None,
940
+ token_type_ids: Optional[torch.Tensor] = None,
941
+ position_ids: Optional[torch.Tensor] = None,
942
+ head_mask: Optional[torch.Tensor] = None,
943
+ inputs_embeds: Optional[torch.Tensor] = None,
944
+ output_attentions: Optional[bool] = None,
945
+ output_hidden_states: Optional[bool] = None,
946
+ return_dict: Optional[bool] = None,
947
+ ) -> Union[Tuple, BaseModelOutput]:
948
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
949
+ output_hidden_states = (
950
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
951
+ )
952
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
953
+
954
+ if input_ids is not None and inputs_embeds is not None:
955
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
956
+ elif input_ids is not None:
957
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
958
+ input_shape = input_ids.size()
959
+ elif inputs_embeds is not None:
960
+ input_shape = inputs_embeds.size()[:-1]
961
+ else:
962
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
963
+
964
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
965
+
966
+ if attention_mask is None:
967
+ attention_mask = torch.ones(input_shape, device=device)
968
+ if token_type_ids is None:
969
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
970
+
971
+ # TODO: deal with head_mask
972
+ inputs_embeds = self.embeddings(input_ids, inputs_embeds=inputs_embeds)
973
+
974
+ encoder_outputs = self.encoder(
975
+ inputs_embeds,
976
+ attention_mask=attention_mask,
977
+ token_type_ids=token_type_ids,
978
+ output_attentions=output_attentions,
979
+ output_hidden_states=output_hidden_states,
980
+ return_dict=return_dict,
981
+ )
982
+
983
+ return encoder_outputs
984
+
985
+
986
+ @add_start_docstrings(
987
+ "The bare Funnel Transformer Model transformer outputting raw hidden-states without any specific head on top.",
988
+ FUNNEL_START_DOCSTRING,
989
+ )
990
+ class FunnelModel(FunnelPreTrainedModel):
991
+ def __init__(self, config: FunnelConfig) -> None:
992
+ super().__init__(config)
993
+ self.config = config
994
+ self.embeddings = FunnelEmbeddings(config)
995
+ self.encoder = FunnelEncoder(config)
996
+ self.decoder = FunnelDecoder(config)
997
+
998
+ # Initialize weights and apply final processing
999
+ self.post_init()
1000
+
1001
+ def get_input_embeddings(self) -> nn.Embedding:
1002
+ return self.embeddings.word_embeddings
1003
+
1004
+ def set_input_embeddings(self, new_embeddings: nn.Embedding) -> None:
1005
+ self.embeddings.word_embeddings = new_embeddings
1006
+
1007
+ @add_start_docstrings_to_model_forward(FUNNEL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1008
+ @add_code_sample_docstrings(
1009
+ checkpoint=_CHECKPOINT_FOR_DOC,
1010
+ output_type=BaseModelOutput,
1011
+ config_class=_CONFIG_FOR_DOC,
1012
+ )
1013
+ def forward(
1014
+ self,
1015
+ input_ids: Optional[torch.Tensor] = None,
1016
+ attention_mask: Optional[torch.Tensor] = None,
1017
+ token_type_ids: Optional[torch.Tensor] = None,
1018
+ inputs_embeds: Optional[torch.Tensor] = None,
1019
+ output_attentions: Optional[bool] = None,
1020
+ output_hidden_states: Optional[bool] = None,
1021
+ return_dict: Optional[bool] = None,
1022
+ ) -> Union[Tuple, BaseModelOutput]:
1023
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1024
+ output_hidden_states = (
1025
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1026
+ )
1027
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1028
+
1029
+ if input_ids is not None and inputs_embeds is not None:
1030
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1031
+ elif input_ids is not None:
1032
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
1033
+ input_shape = input_ids.size()
1034
+ elif inputs_embeds is not None:
1035
+ input_shape = inputs_embeds.size()[:-1]
1036
+ else:
1037
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1038
+
1039
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1040
+
1041
+ if attention_mask is None:
1042
+ attention_mask = torch.ones(input_shape, device=device)
1043
+ if token_type_ids is None:
1044
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
1045
+
1046
+ # TODO: deal with head_mask
1047
+ inputs_embeds = self.embeddings(input_ids, inputs_embeds=inputs_embeds)
1048
+
1049
+ encoder_outputs = self.encoder(
1050
+ inputs_embeds,
1051
+ attention_mask=attention_mask,
1052
+ token_type_ids=token_type_ids,
1053
+ output_attentions=output_attentions,
1054
+ output_hidden_states=True,
1055
+ return_dict=return_dict,
1056
+ )
1057
+
1058
+ decoder_outputs = self.decoder(
1059
+ final_hidden=encoder_outputs[0],
1060
+ first_block_hidden=encoder_outputs[1][self.config.block_sizes[0]],
1061
+ attention_mask=attention_mask,
1062
+ token_type_ids=token_type_ids,
1063
+ output_attentions=output_attentions,
1064
+ output_hidden_states=output_hidden_states,
1065
+ return_dict=return_dict,
1066
+ )
1067
+
1068
+ if not return_dict:
1069
+ idx = 0
1070
+ outputs = (decoder_outputs[0],)
1071
+ if output_hidden_states:
1072
+ idx += 1
1073
+ outputs = outputs + (encoder_outputs[1] + decoder_outputs[idx],)
1074
+ if output_attentions:
1075
+ idx += 1
1076
+ outputs = outputs + (encoder_outputs[2] + decoder_outputs[idx],)
1077
+ return outputs
1078
+
1079
+ return BaseModelOutput(
1080
+ last_hidden_state=decoder_outputs[0],
1081
+ hidden_states=(encoder_outputs.hidden_states + decoder_outputs.hidden_states)
1082
+ if output_hidden_states
1083
+ else None,
1084
+ attentions=(encoder_outputs.attentions + decoder_outputs.attentions) if output_attentions else None,
1085
+ )
1086
+
1087
+
1088
+ add_start_docstrings(
1089
+ """
1090
+ Funnel Transformer model with a binary classification head on top as used during pretraining for identifying
1091
+ generated tokens.
1092
+ """,
1093
+ FUNNEL_START_DOCSTRING,
1094
+ )
1095
+
1096
+
1097
+ class FunnelForPreTraining(FunnelPreTrainedModel):
1098
+ def __init__(self, config: FunnelConfig) -> None:
1099
+ super().__init__(config)
1100
+
1101
+ self.funnel = FunnelModel(config)
1102
+ self.discriminator_predictions = FunnelDiscriminatorPredictions(config)
1103
+ # Initialize weights and apply final processing
1104
+ self.post_init()
1105
+
1106
+ @add_start_docstrings_to_model_forward(FUNNEL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1107
+ @replace_return_docstrings(output_type=FunnelForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1108
+ def forward(
1109
+ self,
1110
+ input_ids: Optional[torch.Tensor] = None,
1111
+ attention_mask: Optional[torch.Tensor] = None,
1112
+ token_type_ids: Optional[torch.Tensor] = None,
1113
+ inputs_embeds: Optional[torch.Tensor] = None,
1114
+ labels: Optional[torch.Tensor] = None,
1115
+ output_attentions: Optional[bool] = None,
1116
+ output_hidden_states: Optional[bool] = None,
1117
+ return_dict: Optional[bool] = None,
1118
+ ) -> Union[Tuple, FunnelForPreTrainingOutput]:
1119
+ r"""
1120
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1121
+ Labels for computing the ELECTRA-style loss. Input should be a sequence of tokens (see `input_ids`
1122
+ docstring) Indices should be in `[0, 1]`:
1123
+
1124
+ - 0 indicates the token is an original token,
1125
+ - 1 indicates the token was replaced.
1126
+
1127
+ Returns:
1128
+
1129
+ Examples:
1130
+
1131
+ ```python
1132
+ >>> from transformers import AutoTokenizer, FunnelForPreTraining
1133
+ >>> import torch
1134
+
1135
+ >>> tokenizer = AutoTokenizer.from_pretrained("funnel-transformer/small")
1136
+ >>> model = FunnelForPreTraining.from_pretrained("funnel-transformer/small")
1137
+
1138
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1139
+ >>> logits = model(**inputs).logits
1140
+ ```"""
1141
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1142
+
1143
+ discriminator_hidden_states = self.funnel(
1144
+ input_ids,
1145
+ attention_mask=attention_mask,
1146
+ token_type_ids=token_type_ids,
1147
+ inputs_embeds=inputs_embeds,
1148
+ output_attentions=output_attentions,
1149
+ output_hidden_states=output_hidden_states,
1150
+ return_dict=return_dict,
1151
+ )
1152
+ discriminator_sequence_output = discriminator_hidden_states[0]
1153
+
1154
+ logits = self.discriminator_predictions(discriminator_sequence_output)
1155
+
1156
+ loss = None
1157
+ if labels is not None:
1158
+ loss_fct = nn.BCEWithLogitsLoss()
1159
+ if attention_mask is not None:
1160
+ active_loss = attention_mask.view(-1, discriminator_sequence_output.shape[1]) == 1
1161
+ active_logits = logits.view(-1, discriminator_sequence_output.shape[1])[active_loss]
1162
+ active_labels = labels[active_loss]
1163
+ loss = loss_fct(active_logits, active_labels.float())
1164
+ else:
1165
+ loss = loss_fct(logits.view(-1, discriminator_sequence_output.shape[1]), labels.float())
1166
+
1167
+ if not return_dict:
1168
+ output = (logits,) + discriminator_hidden_states[1:]
1169
+ return ((loss,) + output) if loss is not None else output
1170
+
1171
+ return FunnelForPreTrainingOutput(
1172
+ loss=loss,
1173
+ logits=logits,
1174
+ hidden_states=discriminator_hidden_states.hidden_states,
1175
+ attentions=discriminator_hidden_states.attentions,
1176
+ )
1177
+
1178
+
1179
+ @add_start_docstrings("""Funnel Transformer Model with a `language modeling` head on top.""", FUNNEL_START_DOCSTRING)
1180
+ class FunnelForMaskedLM(FunnelPreTrainedModel):
1181
+ _tied_weights_keys = ["lm_head.weight"]
1182
+
1183
+ def __init__(self, config: FunnelConfig) -> None:
1184
+ super().__init__(config)
1185
+
1186
+ self.funnel = FunnelModel(config)
1187
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size)
1188
+
1189
+ # Initialize weights and apply final processing
1190
+ self.post_init()
1191
+
1192
+ def get_output_embeddings(self) -> nn.Linear:
1193
+ return self.lm_head
1194
+
1195
+ def set_output_embeddings(self, new_embeddings: nn.Embedding) -> None:
1196
+ self.lm_head = new_embeddings
1197
+
1198
+ @add_start_docstrings_to_model_forward(FUNNEL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1199
+ @add_code_sample_docstrings(
1200
+ checkpoint=_CHECKPOINT_FOR_DOC,
1201
+ output_type=MaskedLMOutput,
1202
+ config_class=_CONFIG_FOR_DOC,
1203
+ mask="<mask>",
1204
+ )
1205
+ def forward(
1206
+ self,
1207
+ input_ids: Optional[torch.Tensor] = None,
1208
+ attention_mask: Optional[torch.Tensor] = None,
1209
+ token_type_ids: Optional[torch.Tensor] = None,
1210
+ inputs_embeds: Optional[torch.Tensor] = None,
1211
+ labels: Optional[torch.Tensor] = None,
1212
+ output_attentions: Optional[bool] = None,
1213
+ output_hidden_states: Optional[bool] = None,
1214
+ return_dict: Optional[bool] = None,
1215
+ ) -> Union[Tuple, MaskedLMOutput]:
1216
+ r"""
1217
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1218
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1219
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1220
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1221
+ """
1222
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1223
+
1224
+ outputs = self.funnel(
1225
+ input_ids,
1226
+ attention_mask=attention_mask,
1227
+ token_type_ids=token_type_ids,
1228
+ inputs_embeds=inputs_embeds,
1229
+ output_attentions=output_attentions,
1230
+ output_hidden_states=output_hidden_states,
1231
+ return_dict=return_dict,
1232
+ )
1233
+
1234
+ last_hidden_state = outputs[0]
1235
+ prediction_logits = self.lm_head(last_hidden_state)
1236
+
1237
+ masked_lm_loss = None
1238
+ if labels is not None:
1239
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1240
+ masked_lm_loss = loss_fct(prediction_logits.view(-1, self.config.vocab_size), labels.view(-1))
1241
+
1242
+ if not return_dict:
1243
+ output = (prediction_logits,) + outputs[1:]
1244
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1245
+
1246
+ return MaskedLMOutput(
1247
+ loss=masked_lm_loss,
1248
+ logits=prediction_logits,
1249
+ hidden_states=outputs.hidden_states,
1250
+ attentions=outputs.attentions,
1251
+ )
1252
+
1253
+
1254
+ @add_start_docstrings(
1255
+ """
1256
+ Funnel Transformer Model with a sequence classification/regression head on top (two linear layer on top of the
1257
+ first timestep of the last hidden state) e.g. for GLUE tasks.
1258
+ """,
1259
+ FUNNEL_START_DOCSTRING,
1260
+ )
1261
+ class FunnelForSequenceClassification(FunnelPreTrainedModel):
1262
+ def __init__(self, config: FunnelConfig) -> None:
1263
+ super().__init__(config)
1264
+ self.num_labels = config.num_labels
1265
+ self.config = config
1266
+
1267
+ self.funnel = FunnelBaseModel(config)
1268
+ self.classifier = FunnelClassificationHead(config, config.num_labels)
1269
+ # Initialize weights and apply final processing
1270
+ self.post_init()
1271
+
1272
+ @add_start_docstrings_to_model_forward(FUNNEL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1273
+ @add_code_sample_docstrings(
1274
+ checkpoint="funnel-transformer/small-base",
1275
+ output_type=SequenceClassifierOutput,
1276
+ config_class=_CONFIG_FOR_DOC,
1277
+ )
1278
+ def forward(
1279
+ self,
1280
+ input_ids: Optional[torch.Tensor] = None,
1281
+ attention_mask: Optional[torch.Tensor] = None,
1282
+ token_type_ids: Optional[torch.Tensor] = None,
1283
+ inputs_embeds: Optional[torch.Tensor] = None,
1284
+ labels: Optional[torch.Tensor] = None,
1285
+ output_attentions: Optional[bool] = None,
1286
+ output_hidden_states: Optional[bool] = None,
1287
+ return_dict: Optional[bool] = None,
1288
+ ) -> Union[Tuple, SequenceClassifierOutput]:
1289
+ r"""
1290
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1291
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1292
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1293
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1294
+ """
1295
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1296
+
1297
+ outputs = self.funnel(
1298
+ input_ids,
1299
+ attention_mask=attention_mask,
1300
+ token_type_ids=token_type_ids,
1301
+ inputs_embeds=inputs_embeds,
1302
+ output_attentions=output_attentions,
1303
+ output_hidden_states=output_hidden_states,
1304
+ return_dict=return_dict,
1305
+ )
1306
+
1307
+ last_hidden_state = outputs[0]
1308
+ pooled_output = last_hidden_state[:, 0]
1309
+ logits = self.classifier(pooled_output)
1310
+
1311
+ loss = None
1312
+ if labels is not None:
1313
+ if self.config.problem_type is None:
1314
+ if self.num_labels == 1:
1315
+ self.config.problem_type = "regression"
1316
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1317
+ self.config.problem_type = "single_label_classification"
1318
+ else:
1319
+ self.config.problem_type = "multi_label_classification"
1320
+
1321
+ if self.config.problem_type == "regression":
1322
+ loss_fct = MSELoss()
1323
+ if self.num_labels == 1:
1324
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1325
+ else:
1326
+ loss = loss_fct(logits, labels)
1327
+ elif self.config.problem_type == "single_label_classification":
1328
+ loss_fct = CrossEntropyLoss()
1329
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1330
+ elif self.config.problem_type == "multi_label_classification":
1331
+ loss_fct = BCEWithLogitsLoss()
1332
+ loss = loss_fct(logits, labels)
1333
+
1334
+ if not return_dict:
1335
+ output = (logits,) + outputs[1:]
1336
+ return ((loss,) + output) if loss is not None else output
1337
+
1338
+ return SequenceClassifierOutput(
1339
+ loss=loss,
1340
+ logits=logits,
1341
+ hidden_states=outputs.hidden_states,
1342
+ attentions=outputs.attentions,
1343
+ )
1344
+
1345
+
1346
+ @add_start_docstrings(
1347
+ """
1348
+ Funnel Transformer Model with a multiple choice classification head on top (two linear layer on top of the first
1349
+ timestep of the last hidden state, and a softmax) e.g. for RocStories/SWAG tasks.
1350
+ """,
1351
+ FUNNEL_START_DOCSTRING,
1352
+ )
1353
+ class FunnelForMultipleChoice(FunnelPreTrainedModel):
1354
+ def __init__(self, config: FunnelConfig) -> None:
1355
+ super().__init__(config)
1356
+
1357
+ self.funnel = FunnelBaseModel(config)
1358
+ self.classifier = FunnelClassificationHead(config, 1)
1359
+ # Initialize weights and apply final processing
1360
+ self.post_init()
1361
+
1362
+ @add_start_docstrings_to_model_forward(FUNNEL_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
1363
+ @add_code_sample_docstrings(
1364
+ checkpoint="funnel-transformer/small-base",
1365
+ output_type=MultipleChoiceModelOutput,
1366
+ config_class=_CONFIG_FOR_DOC,
1367
+ )
1368
+ def forward(
1369
+ self,
1370
+ input_ids: Optional[torch.Tensor] = None,
1371
+ attention_mask: Optional[torch.Tensor] = None,
1372
+ token_type_ids: Optional[torch.Tensor] = None,
1373
+ inputs_embeds: Optional[torch.Tensor] = None,
1374
+ labels: Optional[torch.Tensor] = None,
1375
+ output_attentions: Optional[bool] = None,
1376
+ output_hidden_states: Optional[bool] = None,
1377
+ return_dict: Optional[bool] = None,
1378
+ ) -> Union[Tuple, MultipleChoiceModelOutput]:
1379
+ r"""
1380
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1381
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1382
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1383
+ `input_ids` above)
1384
+ """
1385
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1386
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1387
+
1388
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1389
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1390
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1391
+ inputs_embeds = (
1392
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1393
+ if inputs_embeds is not None
1394
+ else None
1395
+ )
1396
+
1397
+ outputs = self.funnel(
1398
+ input_ids,
1399
+ attention_mask=attention_mask,
1400
+ token_type_ids=token_type_ids,
1401
+ inputs_embeds=inputs_embeds,
1402
+ output_attentions=output_attentions,
1403
+ output_hidden_states=output_hidden_states,
1404
+ return_dict=return_dict,
1405
+ )
1406
+
1407
+ last_hidden_state = outputs[0]
1408
+ pooled_output = last_hidden_state[:, 0]
1409
+ logits = self.classifier(pooled_output)
1410
+ reshaped_logits = logits.view(-1, num_choices)
1411
+
1412
+ loss = None
1413
+ if labels is not None:
1414
+ loss_fct = CrossEntropyLoss()
1415
+ loss = loss_fct(reshaped_logits, labels)
1416
+
1417
+ if not return_dict:
1418
+ output = (reshaped_logits,) + outputs[1:]
1419
+ return ((loss,) + output) if loss is not None else output
1420
+
1421
+ return MultipleChoiceModelOutput(
1422
+ loss=loss,
1423
+ logits=reshaped_logits,
1424
+ hidden_states=outputs.hidden_states,
1425
+ attentions=outputs.attentions,
1426
+ )
1427
+
1428
+
1429
+ @add_start_docstrings(
1430
+ """
1431
+ Funnel Transformer Model with a token classification head on top (a linear layer on top of the hidden-states
1432
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1433
+ """,
1434
+ FUNNEL_START_DOCSTRING,
1435
+ )
1436
+ class FunnelForTokenClassification(FunnelPreTrainedModel):
1437
+ def __init__(self, config: FunnelConfig) -> None:
1438
+ super().__init__(config)
1439
+ self.num_labels = config.num_labels
1440
+
1441
+ self.funnel = FunnelModel(config)
1442
+ self.dropout = nn.Dropout(config.hidden_dropout)
1443
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1444
+
1445
+ # Initialize weights and apply final processing
1446
+ self.post_init()
1447
+
1448
+ @add_start_docstrings_to_model_forward(FUNNEL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1449
+ @add_code_sample_docstrings(
1450
+ checkpoint=_CHECKPOINT_FOR_DOC,
1451
+ output_type=TokenClassifierOutput,
1452
+ config_class=_CONFIG_FOR_DOC,
1453
+ )
1454
+ def forward(
1455
+ self,
1456
+ input_ids: Optional[torch.Tensor] = None,
1457
+ attention_mask: Optional[torch.Tensor] = None,
1458
+ token_type_ids: Optional[torch.Tensor] = None,
1459
+ inputs_embeds: Optional[torch.Tensor] = None,
1460
+ labels: Optional[torch.Tensor] = None,
1461
+ output_attentions: Optional[bool] = None,
1462
+ output_hidden_states: Optional[bool] = None,
1463
+ return_dict: Optional[bool] = None,
1464
+ ) -> Union[Tuple, TokenClassifierOutput]:
1465
+ r"""
1466
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1467
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1468
+ """
1469
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1470
+
1471
+ outputs = self.funnel(
1472
+ input_ids,
1473
+ attention_mask=attention_mask,
1474
+ token_type_ids=token_type_ids,
1475
+ inputs_embeds=inputs_embeds,
1476
+ output_attentions=output_attentions,
1477
+ output_hidden_states=output_hidden_states,
1478
+ return_dict=return_dict,
1479
+ )
1480
+
1481
+ last_hidden_state = outputs[0]
1482
+ last_hidden_state = self.dropout(last_hidden_state)
1483
+ logits = self.classifier(last_hidden_state)
1484
+
1485
+ loss = None
1486
+ if labels is not None:
1487
+ loss_fct = CrossEntropyLoss()
1488
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1489
+
1490
+ if not return_dict:
1491
+ output = (logits,) + outputs[1:]
1492
+ return ((loss,) + output) if loss is not None else output
1493
+
1494
+ return TokenClassifierOutput(
1495
+ loss=loss,
1496
+ logits=logits,
1497
+ hidden_states=outputs.hidden_states,
1498
+ attentions=outputs.attentions,
1499
+ )
1500
+
1501
+
1502
+ @add_start_docstrings(
1503
+ """
1504
+ Funnel Transformer Model with a span classification head on top for extractive question-answering tasks like SQuAD
1505
+ (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1506
+ """,
1507
+ FUNNEL_START_DOCSTRING,
1508
+ )
1509
+ class FunnelForQuestionAnswering(FunnelPreTrainedModel):
1510
+ def __init__(self, config: FunnelConfig) -> None:
1511
+ super().__init__(config)
1512
+ self.num_labels = config.num_labels
1513
+
1514
+ self.funnel = FunnelModel(config)
1515
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1516
+
1517
+ # Initialize weights and apply final processing
1518
+ self.post_init()
1519
+
1520
+ @add_start_docstrings_to_model_forward(FUNNEL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1521
+ @add_code_sample_docstrings(
1522
+ checkpoint=_CHECKPOINT_FOR_DOC,
1523
+ output_type=QuestionAnsweringModelOutput,
1524
+ config_class=_CONFIG_FOR_DOC,
1525
+ )
1526
+ def forward(
1527
+ self,
1528
+ input_ids: Optional[torch.Tensor] = None,
1529
+ attention_mask: Optional[torch.Tensor] = None,
1530
+ token_type_ids: Optional[torch.Tensor] = None,
1531
+ inputs_embeds: Optional[torch.Tensor] = None,
1532
+ start_positions: Optional[torch.Tensor] = None,
1533
+ end_positions: Optional[torch.Tensor] = None,
1534
+ output_attentions: Optional[bool] = None,
1535
+ output_hidden_states: Optional[bool] = None,
1536
+ return_dict: Optional[bool] = None,
1537
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1538
+ r"""
1539
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1540
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1541
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1542
+ are not taken into account for computing the loss.
1543
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1544
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1545
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1546
+ are not taken into account for computing the loss.
1547
+ """
1548
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1549
+
1550
+ outputs = self.funnel(
1551
+ input_ids,
1552
+ attention_mask=attention_mask,
1553
+ token_type_ids=token_type_ids,
1554
+ inputs_embeds=inputs_embeds,
1555
+ output_attentions=output_attentions,
1556
+ output_hidden_states=output_hidden_states,
1557
+ return_dict=return_dict,
1558
+ )
1559
+
1560
+ last_hidden_state = outputs[0]
1561
+
1562
+ logits = self.qa_outputs(last_hidden_state)
1563
+ start_logits, end_logits = logits.split(1, dim=-1)
1564
+ start_logits = start_logits.squeeze(-1).contiguous()
1565
+ end_logits = end_logits.squeeze(-1).contiguous()
1566
+
1567
+ total_loss = None
1568
+ if start_positions is not None and end_positions is not None:
1569
+ # If we are on multi-GPU, split add a dimension
1570
+ if len(start_positions.size()) > 1:
1571
+ start_positions = start_positions.squeze(-1)
1572
+ if len(end_positions.size()) > 1:
1573
+ end_positions = end_positions.squeeze(-1)
1574
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1575
+ ignored_index = start_logits.size(1)
1576
+ start_positions = start_positions.clamp(0, ignored_index)
1577
+ end_positions = end_positions.clamp(0, ignored_index)
1578
+
1579
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1580
+ start_loss = loss_fct(start_logits, start_positions)
1581
+ end_loss = loss_fct(end_logits, end_positions)
1582
+ total_loss = (start_loss + end_loss) / 2
1583
+
1584
+ if not return_dict:
1585
+ output = (start_logits, end_logits) + outputs[1:]
1586
+ return ((total_loss,) + output) if total_loss is not None else output
1587
+
1588
+ return QuestionAnsweringModelOutput(
1589
+ loss=total_loss,
1590
+ start_logits=start_logits,
1591
+ end_logits=end_logits,
1592
+ hidden_states=outputs.hidden_states,
1593
+ attentions=outputs.attentions,
1594
+ )
1595
+
1596
+
1597
+ __all__ = [
1598
+ "FunnelBaseModel",
1599
+ "FunnelForMaskedLM",
1600
+ "FunnelForMultipleChoice",
1601
+ "FunnelForPreTraining",
1602
+ "FunnelForQuestionAnswering",
1603
+ "FunnelForSequenceClassification",
1604
+ "FunnelForTokenClassification",
1605
+ "FunnelModel",
1606
+ "FunnelPreTrainedModel",
1607
+ "load_tf_weights_in_funnel",
1608
+ ]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/funnel/modeling_tf_funnel.py ADDED
@@ -0,0 +1,1880 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020-present Google Brain and Carnegie Mellon University 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
+ """TF 2.0 Funnel model."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import warnings
20
+ from dataclasses import dataclass
21
+ from typing import 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
+ TFMaskedLMOutput,
30
+ TFMultipleChoiceModelOutput,
31
+ TFQuestionAnsweringModelOutput,
32
+ TFSequenceClassifierOutput,
33
+ TFTokenClassifierOutput,
34
+ )
35
+ from ...modeling_tf_utils import (
36
+ TFMaskedLanguageModelingLoss,
37
+ TFModelInputType,
38
+ TFMultipleChoiceLoss,
39
+ TFPreTrainedModel,
40
+ TFQuestionAnsweringLoss,
41
+ TFSequenceClassificationLoss,
42
+ TFTokenClassificationLoss,
43
+ get_initializer,
44
+ keras,
45
+ keras_serializable,
46
+ unpack_inputs,
47
+ )
48
+ from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
49
+ from ...utils import (
50
+ ModelOutput,
51
+ add_code_sample_docstrings,
52
+ add_start_docstrings,
53
+ add_start_docstrings_to_model_forward,
54
+ logging,
55
+ replace_return_docstrings,
56
+ )
57
+ from .configuration_funnel import FunnelConfig
58
+
59
+
60
+ logger = logging.get_logger(__name__)
61
+
62
+ _CONFIG_FOR_DOC = "FunnelConfig"
63
+
64
+
65
+ INF = 1e6
66
+
67
+
68
+ class TFFunnelEmbeddings(keras.layers.Layer):
69
+ """Construct the embeddings from word, position and token_type embeddings."""
70
+
71
+ def __init__(self, config, **kwargs):
72
+ super().__init__(**kwargs)
73
+
74
+ self.config = config
75
+ self.hidden_size = config.hidden_size
76
+ self.initializer_std = 1.0 if config.initializer_std is None else config.initializer_std
77
+
78
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm")
79
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout)
80
+
81
+ def build(self, input_shape=None):
82
+ with tf.name_scope("word_embeddings"):
83
+ self.weight = self.add_weight(
84
+ name="weight",
85
+ shape=[self.config.vocab_size, self.hidden_size],
86
+ initializer=get_initializer(initializer_range=self.initializer_std),
87
+ )
88
+
89
+ if self.built:
90
+ return
91
+ self.built = True
92
+ if getattr(self, "LayerNorm", None) is not None:
93
+ with tf.name_scope(self.LayerNorm.name):
94
+ self.LayerNorm.build([None, None, self.config.d_model])
95
+
96
+ def call(self, input_ids=None, inputs_embeds=None, training=False):
97
+ """
98
+ Applies embedding based on inputs tensor.
99
+
100
+ Returns:
101
+ final_embeddings (`tf.Tensor`): output embedding tensor.
102
+ """
103
+ assert not (input_ids is None and inputs_embeds is None)
104
+ assert not (input_ids is not None and inputs_embeds is not None)
105
+
106
+ if input_ids is not None:
107
+ check_embeddings_within_bounds(input_ids, self.config.vocab_size)
108
+ inputs_embeds = tf.gather(self.weight, input_ids)
109
+
110
+ final_embeddings = self.LayerNorm(inputs=inputs_embeds)
111
+ final_embeddings = self.dropout(inputs=final_embeddings, training=training)
112
+
113
+ return final_embeddings
114
+
115
+
116
+ class TFFunnelAttentionStructure:
117
+ """
118
+ Contains helpers for `TFFunnelRelMultiheadAttention `.
119
+ """
120
+
121
+ cls_token_type_id: int = 2
122
+
123
+ def __init__(self, config):
124
+ self.d_model = config.d_model
125
+ self.attention_type = config.attention_type
126
+ self.num_blocks = config.num_blocks
127
+ self.separate_cls = config.separate_cls
128
+ self.truncate_seq = config.truncate_seq
129
+ self.pool_q_only = config.pool_q_only
130
+ self.pooling_type = config.pooling_type
131
+
132
+ self.sin_dropout = keras.layers.Dropout(config.hidden_dropout)
133
+ self.cos_dropout = keras.layers.Dropout(config.hidden_dropout)
134
+ # Track where we are at in terms of pooling from the original input, e.g., by how much the sequence length was
135
+ # divided.
136
+ self.pooling_mult = None
137
+
138
+ def init_attention_inputs(self, inputs_embeds, attention_mask=None, token_type_ids=None, training=False):
139
+ """Returns the attention inputs associated to the inputs of the model."""
140
+ # inputs_embeds has shape batch_size x seq_len x d_model
141
+ # attention_mask and token_type_ids have shape batch_size x seq_len
142
+ self.pooling_mult = 1
143
+ self.seq_len = seq_len = shape_list(inputs_embeds)[1]
144
+ position_embeds = self.get_position_embeds(seq_len, training=training)
145
+ token_type_mat = self.token_type_ids_to_mat(token_type_ids) if token_type_ids is not None else None
146
+ cls_mask = (
147
+ tf.pad(tf.ones([seq_len - 1, seq_len - 1], dtype=inputs_embeds.dtype), [[1, 0], [1, 0]])
148
+ if self.separate_cls
149
+ else None
150
+ )
151
+ return (position_embeds, token_type_mat, attention_mask, cls_mask)
152
+
153
+ def token_type_ids_to_mat(self, token_type_ids):
154
+ """Convert `token_type_ids` to `token_type_mat`."""
155
+ token_type_mat = tf.equal(tf.expand_dims(token_type_ids, -1), tf.expand_dims(token_type_ids, -2))
156
+ # Treat <cls> as in the same segment as both A & B
157
+ cls_ids = tf.equal(token_type_ids, tf.constant([self.cls_token_type_id], dtype=token_type_ids.dtype))
158
+ cls_mat = tf.logical_or(tf.expand_dims(cls_ids, -1), tf.expand_dims(cls_ids, -2))
159
+ return tf.logical_or(cls_mat, token_type_mat)
160
+
161
+ def get_position_embeds(self, seq_len, training=False):
162
+ """
163
+ Create and cache inputs related to relative position encoding. Those are very different depending on whether we
164
+ are using the factorized or the relative shift attention:
165
+
166
+ For the factorized attention, it returns the matrices (phi, pi, psi, omega) used in the paper, appendix A.2.2,
167
+ final formula.
168
+
169
+ For the relative shift attention, it returns all possible vectors R used in the paper, appendix A.2.1, final
170
+ formula.
171
+
172
+ Paper link: https://arxiv.org/abs/2006.03236
173
+ """
174
+ if self.attention_type == "factorized":
175
+ # Notations from the paper, appending A.2.2, final formula.
176
+ # We need to create and return the matrices phi, psi, pi and omega.
177
+ pos_seq = tf.range(0, seq_len, 1.0)
178
+ freq_seq = tf.range(0, self.d_model // 2, 1.0)
179
+ inv_freq = 1 / (10000 ** (freq_seq / (self.d_model // 2)))
180
+ sinusoid = tf.einsum("i,d->id", pos_seq, inv_freq)
181
+
182
+ sin_embed = tf.sin(sinusoid)
183
+ sin_embed_d = self.sin_dropout(sin_embed, training=training)
184
+ cos_embed = tf.cos(sinusoid)
185
+ cos_embed_d = self.cos_dropout(cos_embed, training=training)
186
+ # This is different from the formula on the paper...
187
+ phi = tf.concat([sin_embed_d, sin_embed_d], axis=-1)
188
+ psi = tf.concat([cos_embed, sin_embed], axis=-1)
189
+ pi = tf.concat([cos_embed_d, cos_embed_d], axis=-1)
190
+ omega = tf.concat([-sin_embed, cos_embed], axis=-1)
191
+ return (phi, pi, psi, omega)
192
+ else:
193
+ # Notations from the paper, appending A.2.1, final formula.
194
+ # We need to create and return all the possible vectors R for all blocks and shifts.
195
+ freq_seq = tf.range(0, self.d_model // 2, 1.0)
196
+ inv_freq = 1 / (10000 ** (freq_seq / (self.d_model // 2)))
197
+ # Maximum relative positions for the first input
198
+ rel_pos_id = tf.range(-seq_len * 2, seq_len * 2, 1.0)
199
+ zero_offset = seq_len * tf.constant(2)
200
+ sinusoid = tf.einsum("i,d->id", rel_pos_id, inv_freq)
201
+ sin_embed = self.sin_dropout(tf.sin(sinusoid), training=training)
202
+ cos_embed = self.cos_dropout(tf.cos(sinusoid), training=training)
203
+ pos_embed = tf.concat([sin_embed, cos_embed], axis=-1)
204
+
205
+ pos = tf.range(0, seq_len)
206
+ pooled_pos = pos
207
+ position_embeds_list = []
208
+ for block_index in range(0, self.num_blocks):
209
+ # For each block with block_index > 0, we need two types position embeddings:
210
+ # - Attention(pooled-q, unpooled-kv)
211
+ # - Attention(pooled-q, pooled-kv)
212
+ # For block_index = 0 we only need the second one and leave the first one as None.
213
+
214
+ # First type
215
+ position_embeds_pooling = tf.fill([1], value=-1.0)
216
+
217
+ if block_index != 0:
218
+ pooled_pos = self.stride_pool_pos(pos, block_index)
219
+
220
+ # construct rel_pos_id
221
+ stride = 2 ** (block_index - 1)
222
+ rel_pos = self.relative_pos(pos, stride, pooled_pos, shift=2)
223
+ # rel_pos = tf.expand_dims(rel_pos,1) + zero_offset
224
+ # rel_pos = tf.broadcast_to(rel_pos, (rel_pos.shape[0], self.d_model))
225
+ rel_pos = tf.cast(rel_pos, dtype=zero_offset.dtype)
226
+ rel_pos = rel_pos + zero_offset
227
+ position_embeds_pooling = tf.gather(pos_embed, rel_pos, axis=0)
228
+
229
+ # Second type
230
+ pos = pooled_pos
231
+ stride = 2**block_index
232
+ rel_pos = self.relative_pos(pos, stride)
233
+
234
+ # rel_pos = tf.expand_dims(rel_pos,1) + zero_offset
235
+ # rel_pos = tf.broadcast_to(rel_pos, (rel_pos.shape[0], self.d_model))
236
+ rel_pos = tf.cast(rel_pos, dtype=zero_offset.dtype)
237
+ rel_pos = rel_pos + zero_offset
238
+ tf.debugging.assert_less(rel_pos, tf.shape(pos_embed)[0])
239
+ position_embeds_no_pooling = tf.gather(pos_embed, rel_pos, axis=0)
240
+
241
+ position_embeds_list.append([position_embeds_no_pooling, position_embeds_pooling])
242
+ return position_embeds_list
243
+
244
+ def stride_pool_pos(self, pos_id, block_index):
245
+ """
246
+ Pool `pos_id` while keeping the cls token separate (if `self.separate_cls=True`).
247
+ """
248
+ if self.separate_cls:
249
+ # Under separate <cls>, we treat the <cls> as the first token in
250
+ # the previous block of the 1st real block. Since the 1st real
251
+ # block always has position 1, the position of the previous block
252
+ # will be at `1 - 2 ** block_index`.
253
+ cls_pos = tf.constant([-(2**block_index) + 1], dtype=pos_id.dtype)
254
+ pooled_pos_id = pos_id[1:-1] if self.truncate_seq else pos_id[1:]
255
+ return tf.concat([cls_pos, pooled_pos_id[::2]], 0)
256
+ else:
257
+ return pos_id[::2]
258
+
259
+ def relative_pos(self, pos, stride, pooled_pos=None, shift=1):
260
+ """
261
+ Build the relative positional vector between `pos` and `pooled_pos`.
262
+ """
263
+ if pooled_pos is None:
264
+ pooled_pos = pos
265
+
266
+ ref_point = pooled_pos[0] - pos[0]
267
+ num_remove = shift * shape_list(pooled_pos)[0]
268
+ max_dist = ref_point + num_remove * stride
269
+ min_dist = pooled_pos[0] - pos[-1]
270
+
271
+ return tf.range(max_dist, min_dist - 1, -stride)
272
+
273
+ def stride_pool(self, tensor, axis):
274
+ """
275
+ Perform pooling by stride slicing the tensor along the given axis.
276
+ """
277
+ if tensor is None:
278
+ return None
279
+
280
+ # Do the stride pool recursively if axis is a list or a tuple of ints.
281
+ if isinstance(axis, (list, tuple)):
282
+ for ax in axis:
283
+ tensor = self.stride_pool(tensor, ax)
284
+ return tensor
285
+
286
+ # Do the stride pool recursively if tensor is a list or tuple of tensors.
287
+ if isinstance(tensor, (tuple, list)):
288
+ return type(tensor)(self.stride_pool(x, axis) for x in tensor)
289
+
290
+ # Deal with negative axis
291
+ axis %= len(shape_list(tensor))
292
+
293
+ axis_slice = slice(None, -1, 2) if self.separate_cls and self.truncate_seq else slice(None, None, 2)
294
+ enc_slice = [slice(None)] * axis + [axis_slice]
295
+ if self.separate_cls:
296
+ cls_slice = [slice(None)] * axis + [slice(None, 1)]
297
+ tensor = tf.concat([tensor[cls_slice], tensor], axis)
298
+ return tensor[enc_slice]
299
+
300
+ def pool_tensor(self, tensor, mode="mean", stride=2):
301
+ """Apply 1D pooling to a tensor of size [B x T (x H)]."""
302
+ if tensor is None:
303
+ return None
304
+
305
+ # Do the pool recursively if tensor is a list or tuple of tensors.
306
+ if isinstance(tensor, (tuple, list)):
307
+ return type(tensor)(self.pool_tensor(tensor, mode=mode, stride=stride) for x in tensor)
308
+
309
+ if self.separate_cls:
310
+ suffix = tensor[:, :-1] if self.truncate_seq else tensor
311
+ tensor = tf.concat([tensor[:, :1], suffix], axis=1)
312
+
313
+ ndim = len(shape_list(tensor))
314
+ if ndim == 2:
315
+ tensor = tensor[:, :, None]
316
+
317
+ if mode == "mean":
318
+ tensor = tf.nn.avg_pool1d(tensor, stride, strides=stride, data_format="NWC", padding="SAME")
319
+ elif mode == "max":
320
+ tensor = tf.nn.max_pool1d(tensor, stride, strides=stride, data_format="NWC", padding="SAME")
321
+ elif mode == "min":
322
+ tensor = -tf.nn.max_pool1d(-tensor, stride, strides=stride, data_format="NWC", padding="SAME")
323
+ else:
324
+ raise NotImplementedError("The supported modes are 'mean', 'max' and 'min'.")
325
+
326
+ return tf.squeeze(tensor, 2) if ndim == 2 else tensor
327
+
328
+ def pre_attention_pooling(self, output, attention_inputs):
329
+ """Pool `output` and the proper parts of `attention_inputs` before the attention layer."""
330
+ position_embeds, token_type_mat, attention_mask, cls_mask = attention_inputs
331
+ if self.pool_q_only:
332
+ if self.attention_type == "factorized":
333
+ position_embeds = self.stride_pool(position_embeds[:2], 0) + position_embeds[2:]
334
+ token_type_mat = self.stride_pool(token_type_mat, 1)
335
+ cls_mask = self.stride_pool(cls_mask, 0)
336
+ output = self.pool_tensor(output, mode=self.pooling_type)
337
+ else:
338
+ self.pooling_mult *= 2
339
+ if self.attention_type == "factorized":
340
+ position_embeds = self.stride_pool(position_embeds, 0)
341
+ token_type_mat = self.stride_pool(token_type_mat, [1, 2])
342
+ cls_mask = self.stride_pool(cls_mask, [1, 2])
343
+ attention_mask = self.pool_tensor(attention_mask, mode="min")
344
+ output = self.pool_tensor(output, mode=self.pooling_type)
345
+ attention_inputs = (position_embeds, token_type_mat, attention_mask, cls_mask)
346
+ return output, attention_inputs
347
+
348
+ def post_attention_pooling(self, attention_inputs):
349
+ """Pool the proper parts of `attention_inputs` after the attention layer."""
350
+ position_embeds, token_type_mat, attention_mask, cls_mask = attention_inputs
351
+ if self.pool_q_only:
352
+ self.pooling_mult *= 2
353
+ if self.attention_type == "factorized":
354
+ position_embeds = position_embeds[:2] + self.stride_pool(position_embeds[2:], 0)
355
+ token_type_mat = self.stride_pool(token_type_mat, 2)
356
+ cls_mask = self.stride_pool(cls_mask, 1)
357
+ attention_mask = self.pool_tensor(attention_mask, mode="min")
358
+ attention_inputs = (position_embeds, token_type_mat, attention_mask, cls_mask)
359
+ return attention_inputs
360
+
361
+
362
+ def _relative_shift_gather(positional_attn, context_len, shift):
363
+ batch_size, n_head, seq_len, max_rel_len = shape_list(positional_attn)
364
+ # max_rel_len = 2 * context_len + shift -1 is the numbers of possible relative positions i-j
365
+
366
+ # What's next is the same as doing the following gather in PyTorch, which might be clearer code but less efficient.
367
+ # idxs = context_len + torch.arange(0, context_len).unsqueeze(0) - torch.arange(0, seq_len).unsqueeze(1)
368
+ # # matrix of context_len + i-j
369
+ # return positional_attn.gather(3, idxs.expand([batch_size, n_head, context_len, context_len]))
370
+
371
+ positional_attn = tf.reshape(positional_attn, [batch_size, n_head, max_rel_len, seq_len])
372
+ positional_attn = positional_attn[:, :, shift:, :]
373
+ positional_attn = tf.reshape(positional_attn, [batch_size, n_head, seq_len, max_rel_len - shift])
374
+ positional_attn = positional_attn[..., :context_len]
375
+ return positional_attn
376
+
377
+
378
+ class TFFunnelRelMultiheadAttention(keras.layers.Layer):
379
+ def __init__(self, config, block_index, **kwargs):
380
+ super().__init__(**kwargs)
381
+ self.attention_type = config.attention_type
382
+ self.n_head = n_head = config.n_head
383
+ self.d_head = d_head = config.d_head
384
+ self.d_model = d_model = config.d_model
385
+ self.initializer_range = config.initializer_range
386
+ self.block_index = block_index
387
+
388
+ self.hidden_dropout = keras.layers.Dropout(config.hidden_dropout)
389
+ self.attention_dropout = keras.layers.Dropout(config.attention_dropout)
390
+
391
+ initializer = get_initializer(config.initializer_range)
392
+
393
+ self.q_head = keras.layers.Dense(
394
+ n_head * d_head, use_bias=False, kernel_initializer=initializer, name="q_head"
395
+ )
396
+ self.k_head = keras.layers.Dense(n_head * d_head, kernel_initializer=initializer, name="k_head")
397
+ self.v_head = keras.layers.Dense(n_head * d_head, kernel_initializer=initializer, name="v_head")
398
+
399
+ self.post_proj = keras.layers.Dense(d_model, kernel_initializer=initializer, name="post_proj")
400
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm")
401
+ self.scale = 1.0 / (d_head**0.5)
402
+
403
+ def build(self, input_shape=None):
404
+ n_head, d_head, d_model = self.n_head, self.d_head, self.d_model
405
+ initializer = get_initializer(self.initializer_range)
406
+
407
+ self.r_w_bias = self.add_weight(
408
+ shape=(n_head, d_head), initializer=initializer, trainable=True, name="r_w_bias"
409
+ )
410
+ self.r_r_bias = self.add_weight(
411
+ shape=(n_head, d_head), initializer=initializer, trainable=True, name="r_r_bias"
412
+ )
413
+ self.r_kernel = self.add_weight(
414
+ shape=(d_model, n_head, d_head), initializer=initializer, trainable=True, name="r_kernel"
415
+ )
416
+ self.r_s_bias = self.add_weight(
417
+ shape=(n_head, d_head), initializer=initializer, trainable=True, name="r_s_bias"
418
+ )
419
+ self.seg_embed = self.add_weight(
420
+ shape=(2, n_head, d_head), initializer=initializer, trainable=True, name="seg_embed"
421
+ )
422
+
423
+ if self.built:
424
+ return
425
+ self.built = True
426
+ if getattr(self, "q_head", None) is not None:
427
+ with tf.name_scope(self.q_head.name):
428
+ self.q_head.build([None, None, d_model])
429
+ if getattr(self, "k_head", None) is not None:
430
+ with tf.name_scope(self.k_head.name):
431
+ self.k_head.build([None, None, d_model])
432
+ if getattr(self, "v_head", None) is not None:
433
+ with tf.name_scope(self.v_head.name):
434
+ self.v_head.build([None, None, d_model])
435
+ if getattr(self, "post_proj", None) is not None:
436
+ with tf.name_scope(self.post_proj.name):
437
+ self.post_proj.build([None, None, n_head * d_head])
438
+ if getattr(self, "layer_norm", None) is not None:
439
+ with tf.name_scope(self.layer_norm.name):
440
+ self.layer_norm.build([None, None, d_model])
441
+
442
+ def relative_positional_attention(self, position_embeds, q_head, context_len, cls_mask=None):
443
+ """Relative attention score for the positional encodings"""
444
+ # q_head has shape batch_size x sea_len x n_head x d_head
445
+ if self.attention_type == "factorized":
446
+ # Notations from the paper, appending A.2.2, final formula (https://arxiv.org/abs/2006.03236)
447
+ # phi and pi have shape seq_len x d_model, psi and omega have shape context_len x d_model
448
+ phi, pi, psi, omega = position_embeds
449
+ # Shape n_head x d_head
450
+ u = self.r_r_bias * self.scale
451
+ # Shape d_model x n_head x d_head
452
+ w_r = self.r_kernel
453
+
454
+ # Shape batch_size x sea_len x n_head x d_model
455
+ q_r_attention = tf.einsum("binh,dnh->bind", q_head + u, w_r)
456
+ q_r_attention_1 = q_r_attention * phi[:, None]
457
+ q_r_attention_2 = q_r_attention * pi[:, None]
458
+
459
+ # Shape batch_size x n_head x seq_len x context_len
460
+ positional_attn = tf.einsum("bind,jd->bnij", q_r_attention_1, psi) + tf.einsum(
461
+ "bind,jd->bnij", q_r_attention_2, omega
462
+ )
463
+ else:
464
+ # Notations from the paper, appending A.2.1, final formula (https://arxiv.org/abs/2006.03236)
465
+ # Grab the proper positional encoding, shape max_rel_len x d_model
466
+ if shape_list(q_head)[1] != context_len:
467
+ shift = 2
468
+ r = position_embeds[self.block_index][1]
469
+ else:
470
+ shift = 1
471
+ r = position_embeds[self.block_index][0]
472
+ # Shape n_head x d_head
473
+ v = self.r_r_bias * self.scale
474
+ # Shape d_model x n_head x d_head
475
+ w_r = self.r_kernel
476
+
477
+ # Shape max_rel_len x n_head x d_model
478
+ r_head = tf.einsum("td,dnh->tnh", r, w_r)
479
+ # Shape batch_size x n_head x seq_len x max_rel_len
480
+ positional_attn = tf.einsum("binh,tnh->bnit", q_head + v, r_head)
481
+ # Shape batch_size x n_head x seq_len x context_len
482
+ positional_attn = _relative_shift_gather(positional_attn, context_len, shift)
483
+
484
+ if cls_mask is not None:
485
+ positional_attn *= cls_mask
486
+ return positional_attn
487
+
488
+ def relative_token_type_attention(self, token_type_mat, q_head, cls_mask=None):
489
+ """Relative attention score for the token_type_ids"""
490
+ if token_type_mat is None:
491
+ return 0
492
+ batch_size, seq_len, context_len = shape_list(token_type_mat)
493
+ # q_head has shape batch_size x seq_len x n_head x d_head
494
+ # Shape n_head x d_head
495
+ r_s_bias = self.r_s_bias * self.scale
496
+
497
+ # Shape batch_size x n_head x seq_len x 2
498
+ token_type_bias = tf.einsum("bind,snd->bnis", q_head + r_s_bias, self.seg_embed)
499
+ # Shape batch_size x n_head x seq_len x context_len
500
+ token_type_mat = tf.tile(token_type_mat[:, None], [1, shape_list(q_head)[2], 1, 1])
501
+ # token_type_mat = tf.broadcast_to(token_type_mat[:, None], new_shape)
502
+ # Shapes batch_size x n_head x seq_len
503
+ diff_token_type, same_token_type = tf.split(token_type_bias, 2, axis=-1)
504
+ # Shape batch_size x n_head x seq_len x context_len
505
+ token_type_attn = tf.where(
506
+ token_type_mat,
507
+ tf.tile(same_token_type, [1, 1, 1, context_len]),
508
+ tf.tile(diff_token_type, [1, 1, 1, context_len]),
509
+ )
510
+
511
+ if cls_mask is not None:
512
+ token_type_attn *= cls_mask
513
+ return token_type_attn
514
+
515
+ def call(self, query, key, value, attention_inputs, output_attentions=False, training=False):
516
+ # query has shape batch_size x seq_len x d_model
517
+ # key and value have shapes batch_size x context_len x d_model
518
+ position_embeds, token_type_mat, attention_mask, cls_mask = attention_inputs
519
+
520
+ batch_size, seq_len, _ = shape_list(query)
521
+ context_len = shape_list(key)[1]
522
+ n_head, d_head = self.n_head, self.d_head
523
+
524
+ # Shape batch_size x seq_len x n_head x d_head
525
+ q_head = tf.reshape(self.q_head(query), [batch_size, seq_len, n_head, d_head])
526
+ # Shapes batch_size x context_len x n_head x d_head
527
+ k_head = tf.reshape(self.k_head(key), [batch_size, context_len, n_head, d_head])
528
+ v_head = tf.reshape(self.v_head(value), [batch_size, context_len, n_head, d_head])
529
+
530
+ q_head = q_head * self.scale
531
+ # Shape n_head x d_head
532
+ r_w_bias = self.r_w_bias * self.scale
533
+ # Shapes batch_size x n_head x seq_len x context_len
534
+ content_score = tf.einsum("bind,bjnd->bnij", q_head + r_w_bias, k_head)
535
+ positional_attn = self.relative_positional_attention(position_embeds, q_head, context_len, cls_mask)
536
+ token_type_attn = self.relative_token_type_attention(token_type_mat, q_head, cls_mask)
537
+
538
+ # merge attention scores
539
+ attn_score = content_score + positional_attn + token_type_attn
540
+
541
+ # perform masking
542
+ if attention_mask is not None:
543
+ attention_mask = tf.cast(attention_mask, dtype=attn_score.dtype)
544
+ attn_score = attn_score - (INF * (1 - attention_mask[:, None, None]))
545
+
546
+ # attention probability
547
+ attn_prob = stable_softmax(attn_score, axis=-1)
548
+ attn_prob = self.attention_dropout(attn_prob, training=training)
549
+
550
+ # attention output, shape batch_size x seq_len x n_head x d_head
551
+ attn_vec = tf.einsum("bnij,bjnd->bind", attn_prob, v_head)
552
+
553
+ # Shape shape batch_size x seq_len x d_model
554
+ attn_out = self.post_proj(tf.reshape(attn_vec, [batch_size, seq_len, n_head * d_head]))
555
+ attn_out = self.hidden_dropout(attn_out, training=training)
556
+
557
+ output = self.layer_norm(query + attn_out)
558
+ return (output, attn_prob) if output_attentions else (output,)
559
+
560
+
561
+ class TFFunnelPositionwiseFFN(keras.layers.Layer):
562
+ def __init__(self, config, **kwargs):
563
+ super().__init__(**kwargs)
564
+ initializer = get_initializer(config.initializer_range)
565
+ self.linear_1 = keras.layers.Dense(config.d_inner, kernel_initializer=initializer, name="linear_1")
566
+ self.activation_function = get_tf_activation(config.hidden_act)
567
+ self.activation_dropout = keras.layers.Dropout(config.activation_dropout)
568
+ self.linear_2 = keras.layers.Dense(config.d_model, kernel_initializer=initializer, name="linear_2")
569
+ self.dropout = keras.layers.Dropout(config.hidden_dropout)
570
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm")
571
+ self.config = config
572
+
573
+ def call(self, hidden, training=False):
574
+ h = self.linear_1(hidden)
575
+ h = self.activation_function(h)
576
+ h = self.activation_dropout(h, training=training)
577
+ h = self.linear_2(h)
578
+ h = self.dropout(h, training=training)
579
+ return self.layer_norm(hidden + h)
580
+
581
+ def build(self, input_shape=None):
582
+ if self.built:
583
+ return
584
+ self.built = True
585
+ if getattr(self, "linear_1", None) is not None:
586
+ with tf.name_scope(self.linear_1.name):
587
+ self.linear_1.build([None, None, self.config.d_model])
588
+ if getattr(self, "linear_2", None) is not None:
589
+ with tf.name_scope(self.linear_2.name):
590
+ self.linear_2.build([None, None, self.config.d_inner])
591
+ if getattr(self, "layer_norm", None) is not None:
592
+ with tf.name_scope(self.layer_norm.name):
593
+ self.layer_norm.build([None, None, self.config.d_model])
594
+
595
+
596
+ class TFFunnelLayer(keras.layers.Layer):
597
+ def __init__(self, config, block_index, **kwargs):
598
+ super().__init__(**kwargs)
599
+ self.attention = TFFunnelRelMultiheadAttention(config, block_index, name="attention")
600
+ self.ffn = TFFunnelPositionwiseFFN(config, name="ffn")
601
+
602
+ def call(self, query, key, value, attention_inputs, output_attentions=False, training=False):
603
+ attn = self.attention(
604
+ query, key, value, attention_inputs, output_attentions=output_attentions, training=training
605
+ )
606
+ output = self.ffn(attn[0], training=training)
607
+ return (output, attn[1]) if output_attentions else (output,)
608
+
609
+ def build(self, input_shape=None):
610
+ if self.built:
611
+ return
612
+ self.built = True
613
+ if getattr(self, "attention", None) is not None:
614
+ with tf.name_scope(self.attention.name):
615
+ self.attention.build(None)
616
+ if getattr(self, "ffn", None) is not None:
617
+ with tf.name_scope(self.ffn.name):
618
+ self.ffn.build(None)
619
+
620
+
621
+ class TFFunnelEncoder(keras.layers.Layer):
622
+ def __init__(self, config, **kwargs):
623
+ super().__init__(**kwargs)
624
+ self.separate_cls = config.separate_cls
625
+ self.pool_q_only = config.pool_q_only
626
+ self.block_repeats = config.block_repeats
627
+ self.attention_structure = TFFunnelAttentionStructure(config)
628
+ self.blocks = [
629
+ [TFFunnelLayer(config, block_index, name=f"blocks_._{block_index}_._{i}") for i in range(block_size)]
630
+ for block_index, block_size in enumerate(config.block_sizes)
631
+ ]
632
+
633
+ def call(
634
+ self,
635
+ inputs_embeds,
636
+ attention_mask=None,
637
+ token_type_ids=None,
638
+ output_attentions=False,
639
+ output_hidden_states=False,
640
+ return_dict=True,
641
+ training=False,
642
+ ):
643
+ # The pooling is not implemented on long tensors, so we convert this mask.
644
+ # attention_mask = tf.cast(attention_mask, inputs_embeds.dtype)
645
+ attention_inputs = self.attention_structure.init_attention_inputs(
646
+ inputs_embeds,
647
+ attention_mask=attention_mask,
648
+ token_type_ids=token_type_ids,
649
+ training=training,
650
+ )
651
+ hidden = inputs_embeds
652
+
653
+ all_hidden_states = (inputs_embeds,) if output_hidden_states else None
654
+ all_attentions = () if output_attentions else None
655
+
656
+ for block_index, block in enumerate(self.blocks):
657
+ pooling_flag = shape_list(hidden)[1] > (2 if self.separate_cls else 1)
658
+ pooling_flag = pooling_flag and block_index > 0
659
+ pooled_hidden = tf.zeros(shape_list(hidden))
660
+
661
+ if pooling_flag:
662
+ pooled_hidden, attention_inputs = self.attention_structure.pre_attention_pooling(
663
+ hidden, attention_inputs
664
+ )
665
+
666
+ for layer_index, layer in enumerate(block):
667
+ for repeat_index in range(self.block_repeats[block_index]):
668
+ do_pooling = (repeat_index == 0) and (layer_index == 0) and pooling_flag
669
+ if do_pooling:
670
+ query = pooled_hidden
671
+ key = value = hidden if self.pool_q_only else pooled_hidden
672
+ else:
673
+ query = key = value = hidden
674
+ layer_output = layer(
675
+ query, key, value, attention_inputs, output_attentions=output_attentions, training=training
676
+ )
677
+ hidden = layer_output[0]
678
+ if do_pooling:
679
+ attention_inputs = self.attention_structure.post_attention_pooling(attention_inputs)
680
+
681
+ if output_attentions:
682
+ all_attentions = all_attentions + layer_output[1:]
683
+ if output_hidden_states:
684
+ all_hidden_states = all_hidden_states + (hidden,)
685
+
686
+ if not return_dict:
687
+ return tuple(v for v in [hidden, all_hidden_states, all_attentions] if v is not None)
688
+ return TFBaseModelOutput(last_hidden_state=hidden, hidden_states=all_hidden_states, attentions=all_attentions)
689
+
690
+ def build(self, input_shape=None):
691
+ if self.built:
692
+ return
693
+ self.built = True
694
+ for block in self.blocks:
695
+ for layer in block:
696
+ with tf.name_scope(layer.name):
697
+ layer.build(None)
698
+
699
+
700
+ def upsample(x, stride, target_len, separate_cls=True, truncate_seq=False):
701
+ """
702
+ Upsample tensor `x` to match `target_len` by repeating the tokens `stride` time on the sequence length dimension.
703
+ """
704
+ if stride == 1:
705
+ return x
706
+ if separate_cls:
707
+ cls = x[:, :1]
708
+ x = x[:, 1:]
709
+ output = tf.repeat(x, repeats=stride, axis=1)
710
+ if separate_cls:
711
+ if truncate_seq:
712
+ output = tf.pad(output, [[0, 0], [0, stride - 1], [0, 0]])
713
+ output = output[:, : target_len - 1]
714
+ output = tf.concat([cls, output], axis=1)
715
+ else:
716
+ output = output[:, :target_len]
717
+ return output
718
+
719
+
720
+ class TFFunnelDecoder(keras.layers.Layer):
721
+ def __init__(self, config, **kwargs):
722
+ super().__init__(**kwargs)
723
+ self.separate_cls = config.separate_cls
724
+ self.truncate_seq = config.truncate_seq
725
+ self.stride = 2 ** (len(config.block_sizes) - 1)
726
+ self.attention_structure = TFFunnelAttentionStructure(config)
727
+ self.layers = [TFFunnelLayer(config, 0, name=f"layers_._{i}") for i in range(config.num_decoder_layers)]
728
+
729
+ def call(
730
+ self,
731
+ final_hidden,
732
+ first_block_hidden,
733
+ attention_mask=None,
734
+ token_type_ids=None,
735
+ output_attentions=False,
736
+ output_hidden_states=False,
737
+ return_dict=True,
738
+ training=False,
739
+ ):
740
+ upsampled_hidden = upsample(
741
+ final_hidden,
742
+ stride=self.stride,
743
+ target_len=shape_list(first_block_hidden)[1],
744
+ separate_cls=self.separate_cls,
745
+ truncate_seq=self.truncate_seq,
746
+ )
747
+
748
+ hidden = upsampled_hidden + first_block_hidden
749
+ all_hidden_states = (hidden,) if output_hidden_states else None
750
+ all_attentions = () if output_attentions else None
751
+
752
+ attention_inputs = self.attention_structure.init_attention_inputs(
753
+ hidden,
754
+ attention_mask=attention_mask,
755
+ token_type_ids=token_type_ids,
756
+ training=training,
757
+ )
758
+
759
+ for layer in self.layers:
760
+ layer_output = layer(
761
+ hidden, hidden, hidden, attention_inputs, output_attentions=output_attentions, training=training
762
+ )
763
+ hidden = layer_output[0]
764
+
765
+ if output_attentions:
766
+ all_attentions = all_attentions + layer_output[1:]
767
+ if output_hidden_states:
768
+ all_hidden_states = all_hidden_states + (hidden,)
769
+
770
+ if not return_dict:
771
+ return tuple(v for v in [hidden, all_hidden_states, all_attentions] if v is not None)
772
+ return TFBaseModelOutput(last_hidden_state=hidden, hidden_states=all_hidden_states, attentions=all_attentions)
773
+
774
+ def build(self, input_shape=None):
775
+ if self.built:
776
+ return
777
+ self.built = True
778
+ if getattr(self, "layers", None) is not None:
779
+ for layer in self.layers:
780
+ with tf.name_scope(layer.name):
781
+ layer.build(None)
782
+
783
+
784
+ @keras_serializable
785
+ class TFFunnelBaseLayer(keras.layers.Layer):
786
+ """Base model without decoder"""
787
+
788
+ config_class = FunnelConfig
789
+
790
+ def __init__(self, config, **kwargs):
791
+ super().__init__(**kwargs)
792
+
793
+ self.config = config
794
+ self.output_attentions = config.output_attentions
795
+ self.output_hidden_states = config.output_hidden_states
796
+ self.return_dict = config.use_return_dict
797
+
798
+ self.embeddings = TFFunnelEmbeddings(config, name="embeddings")
799
+ self.encoder = TFFunnelEncoder(config, name="encoder")
800
+
801
+ def get_input_embeddings(self):
802
+ return self.embeddings
803
+
804
+ def set_input_embeddings(self, value):
805
+ self.embeddings.weight = value
806
+ self.embeddings.vocab_size = shape_list(value)[0]
807
+
808
+ def _prune_heads(self, heads_to_prune):
809
+ raise NotImplementedError # Not implemented yet in the library fr TF 2.0 models
810
+
811
+ @unpack_inputs
812
+ def call(
813
+ self,
814
+ input_ids=None,
815
+ attention_mask=None,
816
+ token_type_ids=None,
817
+ inputs_embeds=None,
818
+ output_attentions=None,
819
+ output_hidden_states=None,
820
+ return_dict=None,
821
+ training=False,
822
+ ):
823
+ if input_ids is not None and inputs_embeds is not None:
824
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
825
+ elif input_ids is not None:
826
+ input_shape = shape_list(input_ids)
827
+ elif inputs_embeds is not None:
828
+ input_shape = shape_list(inputs_embeds)[:-1]
829
+ else:
830
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
831
+
832
+ if attention_mask is None:
833
+ attention_mask = tf.fill(input_shape, 1)
834
+
835
+ if token_type_ids is None:
836
+ token_type_ids = tf.fill(input_shape, 0)
837
+
838
+ if inputs_embeds is None:
839
+ inputs_embeds = self.embeddings(input_ids, training=training)
840
+
841
+ encoder_outputs = self.encoder(
842
+ inputs_embeds,
843
+ attention_mask=attention_mask,
844
+ token_type_ids=token_type_ids,
845
+ output_attentions=output_attentions,
846
+ output_hidden_states=output_hidden_states,
847
+ return_dict=return_dict,
848
+ training=training,
849
+ )
850
+
851
+ return encoder_outputs
852
+
853
+ def build(self, input_shape=None):
854
+ if self.built:
855
+ return
856
+ self.built = True
857
+ if getattr(self, "embeddings", None) is not None:
858
+ with tf.name_scope(self.embeddings.name):
859
+ self.embeddings.build(None)
860
+ if getattr(self, "encoder", None) is not None:
861
+ with tf.name_scope(self.encoder.name):
862
+ self.encoder.build(None)
863
+
864
+
865
+ @keras_serializable
866
+ class TFFunnelMainLayer(keras.layers.Layer):
867
+ """Base model with decoder"""
868
+
869
+ config_class = FunnelConfig
870
+
871
+ def __init__(self, config, **kwargs):
872
+ super().__init__(**kwargs)
873
+
874
+ self.config = config
875
+ self.block_sizes = config.block_sizes
876
+ self.output_attentions = config.output_attentions
877
+ self.output_hidden_states = config.output_hidden_states
878
+ self.return_dict = config.use_return_dict
879
+
880
+ self.embeddings = TFFunnelEmbeddings(config, name="embeddings")
881
+ self.encoder = TFFunnelEncoder(config, name="encoder")
882
+ self.decoder = TFFunnelDecoder(config, name="decoder")
883
+
884
+ def get_input_embeddings(self):
885
+ return self.embeddings
886
+
887
+ def set_input_embeddings(self, value):
888
+ self.embeddings.weight = value
889
+ self.embeddings.vocab_size = shape_list(value)[0]
890
+
891
+ def _prune_heads(self, heads_to_prune):
892
+ raise NotImplementedError # Not implemented yet in the library fr TF 2.0 models
893
+
894
+ @unpack_inputs
895
+ def call(
896
+ self,
897
+ input_ids=None,
898
+ attention_mask=None,
899
+ token_type_ids=None,
900
+ inputs_embeds=None,
901
+ output_attentions=None,
902
+ output_hidden_states=None,
903
+ return_dict=None,
904
+ training=False,
905
+ ):
906
+ if input_ids is not None and inputs_embeds is not None:
907
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
908
+ elif input_ids is not None:
909
+ input_shape = shape_list(input_ids)
910
+ elif inputs_embeds is not None:
911
+ input_shape = shape_list(inputs_embeds)[:-1]
912
+ else:
913
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
914
+
915
+ if attention_mask is None:
916
+ attention_mask = tf.fill(input_shape, 1)
917
+
918
+ if token_type_ids is None:
919
+ token_type_ids = tf.fill(input_shape, 0)
920
+
921
+ if inputs_embeds is None:
922
+ inputs_embeds = self.embeddings(input_ids, training=training)
923
+
924
+ encoder_outputs = self.encoder(
925
+ inputs_embeds,
926
+ attention_mask=attention_mask,
927
+ token_type_ids=token_type_ids,
928
+ output_attentions=output_attentions,
929
+ output_hidden_states=True,
930
+ return_dict=return_dict,
931
+ training=training,
932
+ )
933
+
934
+ decoder_outputs = self.decoder(
935
+ final_hidden=encoder_outputs[0],
936
+ first_block_hidden=encoder_outputs[1][self.block_sizes[0]],
937
+ attention_mask=attention_mask,
938
+ token_type_ids=token_type_ids,
939
+ output_attentions=output_attentions,
940
+ output_hidden_states=output_hidden_states,
941
+ return_dict=return_dict,
942
+ training=training,
943
+ )
944
+
945
+ if not return_dict:
946
+ idx = 0
947
+ outputs = (decoder_outputs[0],)
948
+ if output_hidden_states:
949
+ idx += 1
950
+ outputs = outputs + (encoder_outputs[1] + decoder_outputs[idx],)
951
+ if output_attentions:
952
+ idx += 1
953
+ outputs = outputs + (encoder_outputs[2] + decoder_outputs[idx],)
954
+ return outputs
955
+
956
+ return TFBaseModelOutput(
957
+ last_hidden_state=decoder_outputs[0],
958
+ hidden_states=(encoder_outputs.hidden_states + decoder_outputs.hidden_states)
959
+ if output_hidden_states
960
+ else None,
961
+ attentions=(encoder_outputs.attentions + decoder_outputs.attentions) if output_attentions else None,
962
+ )
963
+
964
+ def build(self, input_shape=None):
965
+ if self.built:
966
+ return
967
+ self.built = True
968
+ if getattr(self, "embeddings", None) is not None:
969
+ with tf.name_scope(self.embeddings.name):
970
+ self.embeddings.build(None)
971
+ if getattr(self, "encoder", None) is not None:
972
+ with tf.name_scope(self.encoder.name):
973
+ self.encoder.build(None)
974
+ if getattr(self, "decoder", None) is not None:
975
+ with tf.name_scope(self.decoder.name):
976
+ self.decoder.build(None)
977
+
978
+
979
+ class TFFunnelDiscriminatorPredictions(keras.layers.Layer):
980
+ """Prediction module for the discriminator, made up of two dense layers."""
981
+
982
+ def __init__(self, config, **kwargs):
983
+ super().__init__(**kwargs)
984
+ initializer = get_initializer(config.initializer_range)
985
+ self.dense = keras.layers.Dense(config.d_model, kernel_initializer=initializer, name="dense")
986
+ self.activation_function = get_tf_activation(config.hidden_act)
987
+ self.dense_prediction = keras.layers.Dense(1, kernel_initializer=initializer, name="dense_prediction")
988
+ self.config = config
989
+
990
+ def call(self, discriminator_hidden_states):
991
+ hidden_states = self.dense(discriminator_hidden_states)
992
+ hidden_states = self.activation_function(hidden_states)
993
+ logits = tf.squeeze(self.dense_prediction(hidden_states))
994
+ return logits
995
+
996
+ def build(self, input_shape=None):
997
+ if self.built:
998
+ return
999
+ self.built = True
1000
+ if getattr(self, "dense", None) is not None:
1001
+ with tf.name_scope(self.dense.name):
1002
+ self.dense.build([None, None, self.config.d_model])
1003
+ if getattr(self, "dense_prediction", None) is not None:
1004
+ with tf.name_scope(self.dense_prediction.name):
1005
+ self.dense_prediction.build([None, None, self.config.d_model])
1006
+
1007
+
1008
+ class TFFunnelMaskedLMHead(keras.layers.Layer):
1009
+ def __init__(self, config, input_embeddings, **kwargs):
1010
+ super().__init__(**kwargs)
1011
+ self.config = config
1012
+ self.hidden_size = config.hidden_size
1013
+ self.input_embeddings = input_embeddings
1014
+
1015
+ def build(self, input_shape):
1016
+ self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
1017
+
1018
+ super().build(input_shape)
1019
+
1020
+ def get_output_embeddings(self):
1021
+ return self.input_embeddings
1022
+
1023
+ def set_output_embeddings(self, value):
1024
+ self.input_embeddings.weight = value
1025
+ self.input_embeddings.vocab_size = shape_list(value)[0]
1026
+
1027
+ def get_bias(self):
1028
+ return {"bias": self.bias}
1029
+
1030
+ def set_bias(self, value):
1031
+ self.bias = value["bias"]
1032
+ self.config.vocab_size = shape_list(value["bias"])[0]
1033
+
1034
+ def call(self, hidden_states, training=False):
1035
+ seq_length = shape_list(tensor=hidden_states)[1]
1036
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.hidden_size])
1037
+ hidden_states = tf.matmul(a=hidden_states, b=self.input_embeddings.weight, transpose_b=True)
1038
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
1039
+ hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
1040
+
1041
+ return hidden_states
1042
+
1043
+
1044
+ class TFFunnelClassificationHead(keras.layers.Layer):
1045
+ def __init__(self, config, n_labels, **kwargs):
1046
+ super().__init__(**kwargs)
1047
+ initializer = get_initializer(config.initializer_range)
1048
+ self.linear_hidden = keras.layers.Dense(config.d_model, kernel_initializer=initializer, name="linear_hidden")
1049
+ self.dropout = keras.layers.Dropout(config.hidden_dropout)
1050
+ self.linear_out = keras.layers.Dense(n_labels, kernel_initializer=initializer, name="linear_out")
1051
+ self.config = config
1052
+
1053
+ def call(self, hidden, training=False):
1054
+ hidden = self.linear_hidden(hidden)
1055
+ hidden = keras.activations.tanh(hidden)
1056
+ hidden = self.dropout(hidden, training=training)
1057
+ return self.linear_out(hidden)
1058
+
1059
+ def build(self, input_shape=None):
1060
+ if self.built:
1061
+ return
1062
+ self.built = True
1063
+ if getattr(self, "linear_hidden", None) is not None:
1064
+ with tf.name_scope(self.linear_hidden.name):
1065
+ self.linear_hidden.build([None, None, self.config.d_model])
1066
+ if getattr(self, "linear_out", None) is not None:
1067
+ with tf.name_scope(self.linear_out.name):
1068
+ self.linear_out.build([None, None, self.config.d_model])
1069
+
1070
+
1071
+ class TFFunnelPreTrainedModel(TFPreTrainedModel):
1072
+ """
1073
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1074
+ models.
1075
+ """
1076
+
1077
+ config_class = FunnelConfig
1078
+ base_model_prefix = "funnel"
1079
+
1080
+ @property
1081
+ def dummy_inputs(self):
1082
+ # Funnel misbehaves with very small inputs, so we override and make them a bit bigger
1083
+ return {"input_ids": tf.ones((1, 3), dtype=tf.int32)}
1084
+
1085
+
1086
+ @dataclass
1087
+ class TFFunnelForPreTrainingOutput(ModelOutput):
1088
+ """
1089
+ Output type of [`FunnelForPreTraining`].
1090
+
1091
+ Args:
1092
+ logits (`tf.Tensor` of shape `(batch_size, sequence_length)`):
1093
+ Prediction scores of the head (scores for each token before SoftMax).
1094
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1095
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
1096
+ `(batch_size, sequence_length, hidden_size)`.
1097
+
1098
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
1099
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
1100
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
1101
+ sequence_length)`.
1102
+
1103
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
1104
+ heads.
1105
+ """
1106
+
1107
+ logits: tf.Tensor = None
1108
+ hidden_states: Tuple[tf.Tensor] | None = None
1109
+ attentions: Tuple[tf.Tensor] | None = None
1110
+
1111
+
1112
+ FUNNEL_START_DOCSTRING = r"""
1113
+
1114
+ The Funnel Transformer model was proposed in [Funnel-Transformer: Filtering out Sequential Redundancy for Efficient
1115
+ Language Processing](https://arxiv.org/abs/2006.03236) by Zihang Dai, Guokun Lai, Yiming Yang, Quoc V. Le.
1116
+
1117
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
1118
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1119
+ etc.)
1120
+
1121
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
1122
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
1123
+ behavior.
1124
+
1125
+ <Tip>
1126
+
1127
+ TensorFlow models and layers in `transformers` accept two formats as input:
1128
+
1129
+ - having all inputs as keyword arguments (like PyTorch models), or
1130
+ - having all inputs as a list, tuple or dict in the first positional argument.
1131
+
1132
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
1133
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
1134
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
1135
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
1136
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
1137
+ positional argument:
1138
+
1139
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
1140
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
1141
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
1142
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
1143
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
1144
+
1145
+ Note that when creating models and layers with
1146
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
1147
+ about any of this, as you can just pass inputs like you would to any other Python function!
1148
+
1149
+ </Tip>
1150
+
1151
+ Parameters:
1152
+ config ([`XxxConfig`]): Model configuration class with all the parameters of the model.
1153
+ Initializing with a config file does not load the weights associated with the model, only the
1154
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1155
+ """
1156
+
1157
+ FUNNEL_INPUTS_DOCSTRING = r"""
1158
+ Args:
1159
+ input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
1160
+ Indices of input sequence tokens in the vocabulary.
1161
+
1162
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
1163
+ [`PreTrainedTokenizer.encode`] for details.
1164
+
1165
+ [What are input IDs?](../glossary#input-ids)
1166
+ attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
1167
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1168
+
1169
+ - 1 for tokens that are **not masked**,
1170
+ - 0 for tokens that are **masked**.
1171
+
1172
+ [What are attention masks?](../glossary#attention-mask)
1173
+ token_type_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
1174
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1175
+ 1]`:
1176
+
1177
+ - 0 corresponds to a *sentence A* token,
1178
+ - 1 corresponds to a *sentence B* token.
1179
+
1180
+ [What are token type IDs?](../glossary#token-type-ids)
1181
+ inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
1182
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1183
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1184
+ model's internal embedding lookup matrix.
1185
+ output_attentions (`bool`, *optional*):
1186
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1187
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
1188
+ config will be used instead.
1189
+ output_hidden_states (`bool`, *optional*):
1190
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1191
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
1192
+ used instead.
1193
+ return_dict (`bool`, *optional*):
1194
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
1195
+ eager mode, in graph mode the value will always be set to True.
1196
+ training (`bool`, *optional*, defaults to `False`):
1197
+ Whether or not to use the model in training mode (some modules like dropout modules have different
1198
+ behaviors between training and evaluation).
1199
+ """
1200
+
1201
+
1202
+ @add_start_docstrings(
1203
+ """
1204
+ The base Funnel Transformer Model transformer outputting raw hidden-states without upsampling head (also called
1205
+ decoder) or any task-specific head on top.
1206
+ """,
1207
+ FUNNEL_START_DOCSTRING,
1208
+ )
1209
+ class TFFunnelBaseModel(TFFunnelPreTrainedModel):
1210
+ def __init__(self, config: FunnelConfig, *inputs, **kwargs) -> None:
1211
+ super().__init__(config, *inputs, **kwargs)
1212
+ self.funnel = TFFunnelBaseLayer(config, name="funnel")
1213
+
1214
+ @add_start_docstrings_to_model_forward(FUNNEL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1215
+ @add_code_sample_docstrings(
1216
+ checkpoint="funnel-transformer/small-base",
1217
+ output_type=TFBaseModelOutput,
1218
+ config_class=_CONFIG_FOR_DOC,
1219
+ )
1220
+ @unpack_inputs
1221
+ def call(
1222
+ self,
1223
+ input_ids: TFModelInputType | None = None,
1224
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1225
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1226
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1227
+ output_attentions: Optional[bool] = None,
1228
+ output_hidden_states: Optional[bool] = None,
1229
+ return_dict: Optional[bool] = None,
1230
+ training: bool = False,
1231
+ ) -> Union[Tuple[tf.Tensor], TFBaseModelOutput]:
1232
+ return self.funnel(
1233
+ input_ids=input_ids,
1234
+ attention_mask=attention_mask,
1235
+ token_type_ids=token_type_ids,
1236
+ inputs_embeds=inputs_embeds,
1237
+ output_attentions=output_attentions,
1238
+ output_hidden_states=output_hidden_states,
1239
+ return_dict=return_dict,
1240
+ training=training,
1241
+ )
1242
+
1243
+ def serving_output(self, output):
1244
+ # hidden_states and attentions not converted to Tensor with tf.convert_to_tensor as they are all of
1245
+ # different dimensions
1246
+ return TFBaseModelOutput(
1247
+ last_hidden_state=output.last_hidden_state,
1248
+ hidden_states=output.hidden_states,
1249
+ attentions=output.attentions,
1250
+ )
1251
+
1252
+ def build(self, input_shape=None):
1253
+ if self.built:
1254
+ return
1255
+ self.built = True
1256
+ if getattr(self, "funnel", None) is not None:
1257
+ with tf.name_scope(self.funnel.name):
1258
+ self.funnel.build(None)
1259
+
1260
+
1261
+ @add_start_docstrings(
1262
+ "The bare Funnel Transformer Model transformer outputting raw hidden-states without any specific head on top.",
1263
+ FUNNEL_START_DOCSTRING,
1264
+ )
1265
+ class TFFunnelModel(TFFunnelPreTrainedModel):
1266
+ def __init__(self, config: FunnelConfig, *inputs, **kwargs) -> None:
1267
+ super().__init__(config, *inputs, **kwargs)
1268
+ self.funnel = TFFunnelMainLayer(config, name="funnel")
1269
+
1270
+ @unpack_inputs
1271
+ @add_start_docstrings_to_model_forward(FUNNEL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1272
+ @add_code_sample_docstrings(
1273
+ checkpoint="funnel-transformer/small",
1274
+ output_type=TFBaseModelOutput,
1275
+ config_class=_CONFIG_FOR_DOC,
1276
+ )
1277
+ def call(
1278
+ self,
1279
+ input_ids: TFModelInputType | None = None,
1280
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1281
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1282
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1283
+ output_attentions: Optional[bool] = None,
1284
+ output_hidden_states: Optional[bool] = None,
1285
+ return_dict: Optional[bool] = None,
1286
+ training: bool = False,
1287
+ ) -> Union[Tuple[tf.Tensor], TFBaseModelOutput]:
1288
+ return self.funnel(
1289
+ input_ids=input_ids,
1290
+ attention_mask=attention_mask,
1291
+ token_type_ids=token_type_ids,
1292
+ inputs_embeds=inputs_embeds,
1293
+ output_attentions=output_attentions,
1294
+ output_hidden_states=output_hidden_states,
1295
+ return_dict=return_dict,
1296
+ training=training,
1297
+ )
1298
+
1299
+ def serving_output(self, output):
1300
+ # hidden_states and attentions not converted to Tensor with tf.convert_to_tensor as they are all of
1301
+ # different dimensions
1302
+ return TFBaseModelOutput(
1303
+ last_hidden_state=output.last_hidden_state,
1304
+ hidden_states=output.hidden_states,
1305
+ attentions=output.attentions,
1306
+ )
1307
+
1308
+ def build(self, input_shape=None):
1309
+ if self.built:
1310
+ return
1311
+ self.built = True
1312
+ if getattr(self, "funnel", None) is not None:
1313
+ with tf.name_scope(self.funnel.name):
1314
+ self.funnel.build(None)
1315
+
1316
+
1317
+ @add_start_docstrings(
1318
+ """
1319
+ Funnel model with a binary classification head on top as used during pretraining for identifying generated tokens.
1320
+ """,
1321
+ FUNNEL_START_DOCSTRING,
1322
+ )
1323
+ class TFFunnelForPreTraining(TFFunnelPreTrainedModel):
1324
+ def __init__(self, config: FunnelConfig, **kwargs) -> None:
1325
+ super().__init__(config, **kwargs)
1326
+
1327
+ self.funnel = TFFunnelMainLayer(config, name="funnel")
1328
+ self.discriminator_predictions = TFFunnelDiscriminatorPredictions(config, name="discriminator_predictions")
1329
+
1330
+ @unpack_inputs
1331
+ @add_start_docstrings_to_model_forward(FUNNEL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1332
+ @replace_return_docstrings(output_type=TFFunnelForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
1333
+ def call(
1334
+ self,
1335
+ input_ids: TFModelInputType | None = None,
1336
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1337
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1338
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1339
+ output_attentions: Optional[bool] = None,
1340
+ output_hidden_states: Optional[bool] = None,
1341
+ return_dict: Optional[bool] = None,
1342
+ training: bool = False,
1343
+ **kwargs,
1344
+ ) -> Union[Tuple[tf.Tensor], TFFunnelForPreTrainingOutput]:
1345
+ r"""
1346
+ Returns:
1347
+
1348
+ Examples:
1349
+
1350
+ ```python
1351
+ >>> from transformers import AutoTokenizer, TFFunnelForPreTraining
1352
+ >>> import torch
1353
+
1354
+ >>> tokenizer = AutoTokenizer.from_pretrained("funnel-transformer/small")
1355
+ >>> model = TFFunnelForPreTraining.from_pretrained("funnel-transformer/small")
1356
+
1357
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
1358
+ >>> logits = model(inputs).logits
1359
+ ```"""
1360
+ discriminator_hidden_states = self.funnel(
1361
+ input_ids,
1362
+ attention_mask,
1363
+ token_type_ids,
1364
+ inputs_embeds,
1365
+ output_attentions,
1366
+ output_hidden_states,
1367
+ return_dict=return_dict,
1368
+ training=training,
1369
+ )
1370
+ discriminator_sequence_output = discriminator_hidden_states[0]
1371
+ logits = self.discriminator_predictions(discriminator_sequence_output)
1372
+
1373
+ if not return_dict:
1374
+ return (logits,) + discriminator_hidden_states[1:]
1375
+
1376
+ return TFFunnelForPreTrainingOutput(
1377
+ logits=logits,
1378
+ hidden_states=discriminator_hidden_states.hidden_states,
1379
+ attentions=discriminator_hidden_states.attentions,
1380
+ )
1381
+
1382
+ def serving_output(self, output):
1383
+ # hidden_states and attentions not converted to Tensor with tf.convert_to_tensor as they are all of
1384
+ # different dimensions
1385
+ return TFFunnelForPreTrainingOutput(
1386
+ logits=output.logits, hidden_states=output.hidden_states, attentions=output.attentions
1387
+ )
1388
+
1389
+ def build(self, input_shape=None):
1390
+ if self.built:
1391
+ return
1392
+ self.built = True
1393
+ if getattr(self, "funnel", None) is not None:
1394
+ with tf.name_scope(self.funnel.name):
1395
+ self.funnel.build(None)
1396
+ if getattr(self, "discriminator_predictions", None) is not None:
1397
+ with tf.name_scope(self.discriminator_predictions.name):
1398
+ self.discriminator_predictions.build(None)
1399
+
1400
+
1401
+ @add_start_docstrings("""Funnel Model with a `language modeling` head on top.""", FUNNEL_START_DOCSTRING)
1402
+ class TFFunnelForMaskedLM(TFFunnelPreTrainedModel, TFMaskedLanguageModelingLoss):
1403
+ def __init__(self, config: FunnelConfig, *inputs, **kwargs) -> None:
1404
+ super().__init__(config, *inputs, **kwargs)
1405
+
1406
+ self.funnel = TFFunnelMainLayer(config, name="funnel")
1407
+ self.lm_head = TFFunnelMaskedLMHead(config, self.funnel.embeddings, name="lm_head")
1408
+
1409
+ def get_lm_head(self) -> TFFunnelMaskedLMHead:
1410
+ return self.lm_head
1411
+
1412
+ def get_prefix_bias_name(self) -> str:
1413
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
1414
+ return self.name + "/" + self.lm_head.name
1415
+
1416
+ @unpack_inputs
1417
+ @add_start_docstrings_to_model_forward(FUNNEL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1418
+ @add_code_sample_docstrings(
1419
+ checkpoint="funnel-transformer/small",
1420
+ output_type=TFMaskedLMOutput,
1421
+ config_class=_CONFIG_FOR_DOC,
1422
+ )
1423
+ def call(
1424
+ self,
1425
+ input_ids: TFModelInputType | None = None,
1426
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1427
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1428
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1429
+ output_attentions: Optional[bool] = None,
1430
+ output_hidden_states: Optional[bool] = None,
1431
+ return_dict: Optional[bool] = None,
1432
+ labels: np.ndarray | tf.Tensor | None = None,
1433
+ training: bool = False,
1434
+ ) -> Union[Tuple[tf.Tensor], TFMaskedLMOutput]:
1435
+ r"""
1436
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1437
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1438
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1439
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1440
+ """
1441
+ outputs = self.funnel(
1442
+ input_ids,
1443
+ attention_mask,
1444
+ token_type_ids,
1445
+ inputs_embeds,
1446
+ output_attentions,
1447
+ output_hidden_states,
1448
+ return_dict=return_dict,
1449
+ training=training,
1450
+ )
1451
+ sequence_output = outputs[0]
1452
+ prediction_scores = self.lm_head(sequence_output, training=training)
1453
+
1454
+ loss = None if labels is None else self.hf_compute_loss(labels, prediction_scores)
1455
+
1456
+ if not return_dict:
1457
+ output = (prediction_scores,) + outputs[1:]
1458
+ return ((loss,) + output) if loss is not None else output
1459
+
1460
+ return TFMaskedLMOutput(
1461
+ loss=loss,
1462
+ logits=prediction_scores,
1463
+ hidden_states=outputs.hidden_states,
1464
+ attentions=outputs.attentions,
1465
+ )
1466
+
1467
+ def serving_output(self, output: TFMaskedLMOutput) -> TFMaskedLMOutput:
1468
+ # hidden_states and attentions not converted to Tensor with tf.convert_to_tensor as they are all of
1469
+ # different dimensions
1470
+ return TFMaskedLMOutput(logits=output.logits, hidden_states=output.hidden_states, attentions=output.attentions)
1471
+
1472
+ def build(self, input_shape=None):
1473
+ if self.built:
1474
+ return
1475
+ self.built = True
1476
+ if getattr(self, "funnel", None) is not None:
1477
+ with tf.name_scope(self.funnel.name):
1478
+ self.funnel.build(None)
1479
+ if getattr(self, "lm_head", None) is not None:
1480
+ with tf.name_scope(self.lm_head.name):
1481
+ self.lm_head.build(None)
1482
+
1483
+
1484
+ @add_start_docstrings(
1485
+ """
1486
+ Funnel Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
1487
+ output) e.g. for GLUE tasks.
1488
+ """,
1489
+ FUNNEL_START_DOCSTRING,
1490
+ )
1491
+ class TFFunnelForSequenceClassification(TFFunnelPreTrainedModel, TFSequenceClassificationLoss):
1492
+ def __init__(self, config: FunnelConfig, *inputs, **kwargs) -> None:
1493
+ super().__init__(config, *inputs, **kwargs)
1494
+ self.num_labels = config.num_labels
1495
+
1496
+ self.funnel = TFFunnelBaseLayer(config, name="funnel")
1497
+ self.classifier = TFFunnelClassificationHead(config, config.num_labels, name="classifier")
1498
+
1499
+ @unpack_inputs
1500
+ @add_start_docstrings_to_model_forward(FUNNEL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1501
+ @add_code_sample_docstrings(
1502
+ checkpoint="funnel-transformer/small-base",
1503
+ output_type=TFSequenceClassifierOutput,
1504
+ config_class=_CONFIG_FOR_DOC,
1505
+ )
1506
+ def call(
1507
+ self,
1508
+ input_ids: TFModelInputType | None = None,
1509
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1510
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1511
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1512
+ output_attentions: Optional[bool] = None,
1513
+ output_hidden_states: Optional[bool] = None,
1514
+ return_dict: Optional[bool] = None,
1515
+ labels: np.ndarray | tf.Tensor | None = None,
1516
+ training: bool = False,
1517
+ ) -> Union[Tuple[tf.Tensor], TFSequenceClassifierOutput]:
1518
+ r"""
1519
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1520
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1521
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1522
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1523
+ """
1524
+ outputs = self.funnel(
1525
+ input_ids,
1526
+ attention_mask,
1527
+ token_type_ids,
1528
+ inputs_embeds,
1529
+ output_attentions,
1530
+ output_hidden_states,
1531
+ return_dict=return_dict,
1532
+ training=training,
1533
+ )
1534
+ last_hidden_state = outputs[0]
1535
+ pooled_output = last_hidden_state[:, 0]
1536
+ logits = self.classifier(pooled_output, training=training)
1537
+
1538
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1539
+
1540
+ if not return_dict:
1541
+ output = (logits,) + outputs[1:]
1542
+ return ((loss,) + output) if loss is not None else output
1543
+
1544
+ return TFSequenceClassifierOutput(
1545
+ loss=loss,
1546
+ logits=logits,
1547
+ hidden_states=outputs.hidden_states,
1548
+ attentions=outputs.attentions,
1549
+ )
1550
+
1551
+ def serving_output(self, output: TFSequenceClassifierOutput) -> TFSequenceClassifierOutput:
1552
+ # hidden_states and attentions not converted to Tensor with tf.convert_to_tensor as they are all of
1553
+ # different dimensions
1554
+ return TFSequenceClassifierOutput(
1555
+ logits=output.logits, hidden_states=output.hidden_states, attentions=output.attentions
1556
+ )
1557
+
1558
+ def build(self, input_shape=None):
1559
+ if self.built:
1560
+ return
1561
+ self.built = True
1562
+ if getattr(self, "funnel", None) is not None:
1563
+ with tf.name_scope(self.funnel.name):
1564
+ self.funnel.build(None)
1565
+ if getattr(self, "classifier", None) is not None:
1566
+ with tf.name_scope(self.classifier.name):
1567
+ self.classifier.build(None)
1568
+
1569
+
1570
+ @add_start_docstrings(
1571
+ """
1572
+ Funnel Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
1573
+ softmax) e.g. for RocStories/SWAG tasks.
1574
+ """,
1575
+ FUNNEL_START_DOCSTRING,
1576
+ )
1577
+ class TFFunnelForMultipleChoice(TFFunnelPreTrainedModel, TFMultipleChoiceLoss):
1578
+ def __init__(self, config: FunnelConfig, *inputs, **kwargs) -> None:
1579
+ super().__init__(config, *inputs, **kwargs)
1580
+
1581
+ self.funnel = TFFunnelBaseLayer(config, name="funnel")
1582
+ self.classifier = TFFunnelClassificationHead(config, 1, name="classifier")
1583
+
1584
+ @property
1585
+ def dummy_inputs(self):
1586
+ return {"input_ids": tf.ones((3, 3, 4), dtype=tf.int32)}
1587
+
1588
+ @unpack_inputs
1589
+ @add_start_docstrings_to_model_forward(FUNNEL_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
1590
+ @add_code_sample_docstrings(
1591
+ checkpoint="funnel-transformer/small-base",
1592
+ output_type=TFMultipleChoiceModelOutput,
1593
+ config_class=_CONFIG_FOR_DOC,
1594
+ )
1595
+ def call(
1596
+ self,
1597
+ input_ids: TFModelInputType | None = None,
1598
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1599
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1600
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1601
+ output_attentions: Optional[bool] = None,
1602
+ output_hidden_states: Optional[bool] = None,
1603
+ return_dict: Optional[bool] = None,
1604
+ labels: np.ndarray | tf.Tensor | None = None,
1605
+ training: bool = False,
1606
+ ) -> Union[Tuple[tf.Tensor], TFMultipleChoiceModelOutput]:
1607
+ r"""
1608
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1609
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
1610
+ where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
1611
+ """
1612
+ if input_ids is not None:
1613
+ num_choices = shape_list(input_ids)[1]
1614
+ seq_length = shape_list(input_ids)[2]
1615
+ else:
1616
+ num_choices = shape_list(inputs_embeds)[1]
1617
+ seq_length = shape_list(inputs_embeds)[2]
1618
+
1619
+ flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
1620
+ flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None
1621
+ flat_token_type_ids = tf.reshape(token_type_ids, (-1, seq_length)) if token_type_ids is not None else None
1622
+ flat_inputs_embeds = (
1623
+ tf.reshape(inputs_embeds, (-1, seq_length, shape_list(inputs_embeds)[3]))
1624
+ if inputs_embeds is not None
1625
+ else None
1626
+ )
1627
+
1628
+ outputs = self.funnel(
1629
+ flat_input_ids,
1630
+ attention_mask=flat_attention_mask,
1631
+ token_type_ids=flat_token_type_ids,
1632
+ inputs_embeds=flat_inputs_embeds,
1633
+ output_attentions=output_attentions,
1634
+ output_hidden_states=output_hidden_states,
1635
+ return_dict=return_dict,
1636
+ training=training,
1637
+ )
1638
+
1639
+ last_hidden_state = outputs[0]
1640
+ pooled_output = last_hidden_state[:, 0]
1641
+ logits = self.classifier(pooled_output, training=training)
1642
+ reshaped_logits = tf.reshape(logits, (-1, num_choices))
1643
+
1644
+ loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)
1645
+
1646
+ if not return_dict:
1647
+ output = (reshaped_logits,) + outputs[1:]
1648
+ return ((loss,) + output) if loss is not None else output
1649
+
1650
+ return TFMultipleChoiceModelOutput(
1651
+ loss=loss,
1652
+ logits=reshaped_logits,
1653
+ hidden_states=outputs.hidden_states,
1654
+ attentions=outputs.attentions,
1655
+ )
1656
+
1657
+ def serving_output(self, output: TFMultipleChoiceModelOutput) -> TFMultipleChoiceModelOutput:
1658
+ # hidden_states and attentions not converted to Tensor with tf.convert_to_tensor as they are all of
1659
+ # different dimensions
1660
+ return TFMultipleChoiceModelOutput(
1661
+ logits=output.logits, hidden_states=output.hidden_states, attentions=output.attentions
1662
+ )
1663
+
1664
+ def build(self, input_shape=None):
1665
+ if self.built:
1666
+ return
1667
+ self.built = True
1668
+ if getattr(self, "funnel", None) is not None:
1669
+ with tf.name_scope(self.funnel.name):
1670
+ self.funnel.build(None)
1671
+ if getattr(self, "classifier", None) is not None:
1672
+ with tf.name_scope(self.classifier.name):
1673
+ self.classifier.build(None)
1674
+
1675
+
1676
+ @add_start_docstrings(
1677
+ """
1678
+ Funnel Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1679
+ Named-Entity-Recognition (NER) tasks.
1680
+ """,
1681
+ FUNNEL_START_DOCSTRING,
1682
+ )
1683
+ class TFFunnelForTokenClassification(TFFunnelPreTrainedModel, TFTokenClassificationLoss):
1684
+ def __init__(self, config: FunnelConfig, *inputs, **kwargs) -> None:
1685
+ super().__init__(config, *inputs, **kwargs)
1686
+ self.num_labels = config.num_labels
1687
+
1688
+ self.funnel = TFFunnelMainLayer(config, name="funnel")
1689
+ self.dropout = keras.layers.Dropout(config.hidden_dropout)
1690
+ self.classifier = keras.layers.Dense(
1691
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
1692
+ )
1693
+ self.config = config
1694
+
1695
+ @unpack_inputs
1696
+ @add_start_docstrings_to_model_forward(FUNNEL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1697
+ @add_code_sample_docstrings(
1698
+ checkpoint="funnel-transformer/small",
1699
+ output_type=TFTokenClassifierOutput,
1700
+ config_class=_CONFIG_FOR_DOC,
1701
+ )
1702
+ def call(
1703
+ self,
1704
+ input_ids: TFModelInputType | None = None,
1705
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1706
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1707
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1708
+ output_attentions: Optional[bool] = None,
1709
+ output_hidden_states: Optional[bool] = None,
1710
+ return_dict: Optional[bool] = None,
1711
+ labels: np.ndarray | tf.Tensor | None = None,
1712
+ training: bool = False,
1713
+ ) -> Union[Tuple[tf.Tensor], TFTokenClassifierOutput]:
1714
+ r"""
1715
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1716
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1717
+ """
1718
+ outputs = self.funnel(
1719
+ input_ids,
1720
+ attention_mask,
1721
+ token_type_ids,
1722
+ inputs_embeds,
1723
+ output_attentions,
1724
+ output_hidden_states,
1725
+ return_dict=return_dict,
1726
+ training=training,
1727
+ )
1728
+ sequence_output = outputs[0]
1729
+
1730
+ sequence_output = self.dropout(sequence_output, training=training)
1731
+ logits = self.classifier(sequence_output)
1732
+
1733
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1734
+
1735
+ if not return_dict:
1736
+ output = (logits,) + outputs[1:]
1737
+ return ((loss,) + output) if loss is not None else output
1738
+
1739
+ return TFTokenClassifierOutput(
1740
+ loss=loss,
1741
+ logits=logits,
1742
+ hidden_states=outputs.hidden_states,
1743
+ attentions=outputs.attentions,
1744
+ )
1745
+
1746
+ def serving_output(self, output: TFTokenClassifierOutput) -> TFTokenClassifierOutput:
1747
+ # hidden_states and attentions not converted to Tensor with tf.convert_to_tensor as they are all of
1748
+ # different dimensions
1749
+ return TFTokenClassifierOutput(
1750
+ logits=output.logits, hidden_states=output.hidden_states, attentions=output.attentions
1751
+ )
1752
+
1753
+ def build(self, input_shape=None):
1754
+ if self.built:
1755
+ return
1756
+ self.built = True
1757
+ if getattr(self, "funnel", None) is not None:
1758
+ with tf.name_scope(self.funnel.name):
1759
+ self.funnel.build(None)
1760
+ if getattr(self, "classifier", None) is not None:
1761
+ with tf.name_scope(self.classifier.name):
1762
+ self.classifier.build([None, None, self.config.hidden_size])
1763
+
1764
+
1765
+ @add_start_docstrings(
1766
+ """
1767
+ Funnel Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
1768
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1769
+ """,
1770
+ FUNNEL_START_DOCSTRING,
1771
+ )
1772
+ class TFFunnelForQuestionAnswering(TFFunnelPreTrainedModel, TFQuestionAnsweringLoss):
1773
+ def __init__(self, config: FunnelConfig, *inputs, **kwargs) -> None:
1774
+ super().__init__(config, *inputs, **kwargs)
1775
+ self.num_labels = config.num_labels
1776
+
1777
+ self.funnel = TFFunnelMainLayer(config, name="funnel")
1778
+ self.qa_outputs = keras.layers.Dense(
1779
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
1780
+ )
1781
+ self.config = config
1782
+
1783
+ @unpack_inputs
1784
+ @add_start_docstrings_to_model_forward(FUNNEL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1785
+ @add_code_sample_docstrings(
1786
+ checkpoint="funnel-transformer/small",
1787
+ output_type=TFQuestionAnsweringModelOutput,
1788
+ config_class=_CONFIG_FOR_DOC,
1789
+ )
1790
+ def call(
1791
+ self,
1792
+ input_ids: TFModelInputType | None = None,
1793
+ attention_mask: np.ndarray | tf.Tensor | None = None,
1794
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
1795
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
1796
+ output_attentions: Optional[bool] = None,
1797
+ output_hidden_states: Optional[bool] = None,
1798
+ return_dict: Optional[bool] = None,
1799
+ start_positions: np.ndarray | tf.Tensor | None = None,
1800
+ end_positions: np.ndarray | tf.Tensor | None = None,
1801
+ training: bool = False,
1802
+ ) -> Union[Tuple[tf.Tensor], TFQuestionAnsweringModelOutput]:
1803
+ r"""
1804
+ start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1805
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1806
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1807
+ are not taken into account for computing the loss.
1808
+ end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1809
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1810
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1811
+ are not taken into account for computing the loss.
1812
+ """
1813
+
1814
+ outputs = self.funnel(
1815
+ input_ids,
1816
+ attention_mask,
1817
+ token_type_ids,
1818
+ inputs_embeds,
1819
+ output_attentions,
1820
+ output_hidden_states,
1821
+ return_dict=return_dict,
1822
+ training=training,
1823
+ )
1824
+ sequence_output = outputs[0]
1825
+
1826
+ logits = self.qa_outputs(sequence_output)
1827
+ start_logits, end_logits = tf.split(logits, 2, axis=-1)
1828
+ start_logits = tf.squeeze(start_logits, axis=-1)
1829
+ end_logits = tf.squeeze(end_logits, axis=-1)
1830
+
1831
+ loss = None
1832
+ if start_positions is not None and end_positions is not None:
1833
+ labels = {"start_position": start_positions, "end_position": end_positions}
1834
+ loss = self.hf_compute_loss(labels, (start_logits, end_logits))
1835
+
1836
+ if not return_dict:
1837
+ output = (start_logits, end_logits) + outputs[1:]
1838
+ return ((loss,) + output) if loss is not None else output
1839
+
1840
+ return TFQuestionAnsweringModelOutput(
1841
+ loss=loss,
1842
+ start_logits=start_logits,
1843
+ end_logits=end_logits,
1844
+ hidden_states=outputs.hidden_states,
1845
+ attentions=outputs.attentions,
1846
+ )
1847
+
1848
+ def serving_output(self, output: TFQuestionAnsweringModelOutput) -> TFQuestionAnsweringModelOutput:
1849
+ # hidden_states and attentions not converted to Tensor with tf.convert_to_tensor as they are all of
1850
+ # different dimensions
1851
+ return TFQuestionAnsweringModelOutput(
1852
+ start_logits=output.start_logits,
1853
+ end_logits=output.end_logits,
1854
+ hidden_states=output.hidden_states,
1855
+ attentions=output.attentions,
1856
+ )
1857
+
1858
+ def build(self, input_shape=None):
1859
+ if self.built:
1860
+ return
1861
+ self.built = True
1862
+ if getattr(self, "funnel", None) is not None:
1863
+ with tf.name_scope(self.funnel.name):
1864
+ self.funnel.build(None)
1865
+ if getattr(self, "qa_outputs", None) is not None:
1866
+ with tf.name_scope(self.qa_outputs.name):
1867
+ self.qa_outputs.build([None, None, self.config.hidden_size])
1868
+
1869
+
1870
+ __all__ = [
1871
+ "TFFunnelBaseModel",
1872
+ "TFFunnelForMaskedLM",
1873
+ "TFFunnelForMultipleChoice",
1874
+ "TFFunnelForPreTraining",
1875
+ "TFFunnelForQuestionAnswering",
1876
+ "TFFunnelForSequenceClassification",
1877
+ "TFFunnelForTokenClassification",
1878
+ "TFFunnelModel",
1879
+ "TFFunnelPreTrainedModel",
1880
+ ]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/funnel/tokenization_funnel.py ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 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
+ """Tokenization class for Funnel Transformer."""
16
+
17
+ import collections
18
+ import os
19
+ import unicodedata
20
+ from typing import List, Optional, Tuple
21
+
22
+ from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
23
+ from ...utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
29
+
30
+ _model_names = [
31
+ "small",
32
+ "small-base",
33
+ "medium",
34
+ "medium-base",
35
+ "intermediate",
36
+ "intermediate-base",
37
+ "large",
38
+ "large-base",
39
+ "xlarge",
40
+ "xlarge-base",
41
+ ]
42
+
43
+
44
+ # Copied from transformers.models.bert.tokenization_bert.load_vocab
45
+ def load_vocab(vocab_file):
46
+ """Loads a vocabulary file into a dictionary."""
47
+ vocab = collections.OrderedDict()
48
+ with open(vocab_file, "r", encoding="utf-8") as reader:
49
+ tokens = reader.readlines()
50
+ for index, token in enumerate(tokens):
51
+ token = token.rstrip("\n")
52
+ vocab[token] = index
53
+ return vocab
54
+
55
+
56
+ # Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize
57
+ def whitespace_tokenize(text):
58
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
59
+ text = text.strip()
60
+ if not text:
61
+ return []
62
+ tokens = text.split()
63
+ return tokens
64
+
65
+
66
+ class FunnelTokenizer(PreTrainedTokenizer):
67
+ r"""
68
+ Construct a Funnel Transformer tokenizer. Based on WordPiece.
69
+
70
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
71
+ this superclass for more information regarding those methods.
72
+
73
+ Args:
74
+ vocab_file (`str`):
75
+ File containing the vocabulary.
76
+ do_lower_case (`bool`, *optional*, defaults to `True`):
77
+ Whether or not to lowercase the input when tokenizing.
78
+ do_basic_tokenize (`bool`, *optional*, defaults to `True`):
79
+ Whether or not to do basic tokenization before WordPiece.
80
+ never_split (`Iterable`, *optional*):
81
+ Collection of tokens which will never be split during tokenization. Only has an effect when
82
+ `do_basic_tokenize=True`
83
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
84
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
85
+ token instead.
86
+ sep_token (`str`, *optional*, defaults to `"<sep>"`):
87
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
88
+ sequence classification or for a text and a question for question answering. It is also used as the last
89
+ token of a sequence built with special tokens.
90
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
91
+ The token used for padding, for example when batching sequences of different lengths.
92
+ cls_token (`str`, *optional*, defaults to `"<cls>"`):
93
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
94
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
95
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
96
+ The token used for masking values. This is the token used when training this model with masked language
97
+ modeling. This is the token which the model will try to predict.
98
+ bos_token (`str`, *optional*, defaults to `"<s>"`):
99
+ The beginning of sentence token.
100
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
101
+ The end of sentence token.
102
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
103
+ Whether or not to tokenize Chinese characters.
104
+
105
+ This should likely be deactivated for Japanese (see this
106
+ [issue](https://github.com/huggingface/transformers/issues/328)).
107
+ strip_accents (`bool`, *optional*):
108
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
109
+ value for `lowercase` (as in the original BERT).
110
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
111
+ Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
112
+ extra spaces.
113
+ """
114
+
115
+ vocab_files_names = VOCAB_FILES_NAMES
116
+ cls_token_type_id: int = 2
117
+
118
+ def __init__(
119
+ self,
120
+ vocab_file,
121
+ do_lower_case=True,
122
+ do_basic_tokenize=True,
123
+ never_split=None,
124
+ unk_token="<unk>",
125
+ sep_token="<sep>",
126
+ pad_token="<pad>",
127
+ cls_token="<cls>",
128
+ mask_token="<mask>",
129
+ bos_token="<s>",
130
+ eos_token="</s>",
131
+ tokenize_chinese_chars=True,
132
+ strip_accents=None,
133
+ clean_up_tokenization_spaces=True,
134
+ **kwargs,
135
+ ):
136
+ if not os.path.isfile(vocab_file):
137
+ raise ValueError(
138
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
139
+ " model use `tokenizer = FunnelTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
140
+ )
141
+ self.vocab = load_vocab(vocab_file)
142
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
143
+ self.do_basic_tokenize = do_basic_tokenize
144
+ if do_basic_tokenize:
145
+ self.basic_tokenizer = BasicTokenizer(
146
+ do_lower_case=do_lower_case,
147
+ never_split=never_split,
148
+ tokenize_chinese_chars=tokenize_chinese_chars,
149
+ strip_accents=strip_accents,
150
+ )
151
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
152
+
153
+ super().__init__(
154
+ do_lower_case=do_lower_case,
155
+ do_basic_tokenize=do_basic_tokenize,
156
+ never_split=never_split,
157
+ unk_token=unk_token,
158
+ sep_token=sep_token,
159
+ pad_token=pad_token,
160
+ cls_token=cls_token,
161
+ mask_token=mask_token,
162
+ bos_token=bos_token,
163
+ eos_token=eos_token,
164
+ tokenize_chinese_chars=tokenize_chinese_chars,
165
+ strip_accents=strip_accents,
166
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
167
+ **kwargs,
168
+ )
169
+
170
+ @property
171
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.do_lower_case
172
+ def do_lower_case(self):
173
+ return self.basic_tokenizer.do_lower_case
174
+
175
+ @property
176
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.vocab_size
177
+ def vocab_size(self):
178
+ return len(self.vocab)
179
+
180
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.get_vocab
181
+ def get_vocab(self):
182
+ return dict(self.vocab, **self.added_tokens_encoder)
183
+
184
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer._tokenize
185
+ def _tokenize(self, text, split_special_tokens=False):
186
+ split_tokens = []
187
+ if self.do_basic_tokenize:
188
+ for token in self.basic_tokenizer.tokenize(
189
+ text, never_split=self.all_special_tokens if not split_special_tokens else None
190
+ ):
191
+ # If the token is part of the never_split set
192
+ if token in self.basic_tokenizer.never_split:
193
+ split_tokens.append(token)
194
+ else:
195
+ split_tokens += self.wordpiece_tokenizer.tokenize(token)
196
+ else:
197
+ split_tokens = self.wordpiece_tokenizer.tokenize(text)
198
+ return split_tokens
199
+
200
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer._convert_token_to_id
201
+ def _convert_token_to_id(self, token):
202
+ """Converts a token (str) in an id using the vocab."""
203
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
204
+
205
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer._convert_id_to_token
206
+ def _convert_id_to_token(self, index):
207
+ """Converts an index (integer) in a token (str) using the vocab."""
208
+ return self.ids_to_tokens.get(index, self.unk_token)
209
+
210
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.convert_tokens_to_string
211
+ def convert_tokens_to_string(self, tokens):
212
+ """Converts a sequence of tokens (string) in a single string."""
213
+ out_string = " ".join(tokens).replace(" ##", "").strip()
214
+ return out_string
215
+
216
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.build_inputs_with_special_tokens
217
+ def build_inputs_with_special_tokens(
218
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
219
+ ) -> List[int]:
220
+ """
221
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
222
+ adding special tokens. A BERT sequence has the following format:
223
+
224
+ - single sequence: `[CLS] X [SEP]`
225
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
226
+
227
+ Args:
228
+ token_ids_0 (`List[int]`):
229
+ List of IDs to which the special tokens will be added.
230
+ token_ids_1 (`List[int]`, *optional*):
231
+ Optional second list of IDs for sequence pairs.
232
+
233
+ Returns:
234
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
235
+ """
236
+ if token_ids_1 is None:
237
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
238
+ cls = [self.cls_token_id]
239
+ sep = [self.sep_token_id]
240
+ return cls + token_ids_0 + sep + token_ids_1 + sep
241
+
242
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.get_special_tokens_mask
243
+ def get_special_tokens_mask(
244
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
245
+ ) -> List[int]:
246
+ """
247
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
248
+ special tokens using the tokenizer `prepare_for_model` method.
249
+
250
+ Args:
251
+ token_ids_0 (`List[int]`):
252
+ List of IDs.
253
+ token_ids_1 (`List[int]`, *optional*):
254
+ Optional second list of IDs for sequence pairs.
255
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
256
+ Whether or not the token list is already formatted with special tokens for the model.
257
+
258
+ Returns:
259
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
260
+ """
261
+
262
+ if already_has_special_tokens:
263
+ return super().get_special_tokens_mask(
264
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
265
+ )
266
+
267
+ if token_ids_1 is not None:
268
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
269
+ return [1] + ([0] * len(token_ids_0)) + [1]
270
+
271
+ def create_token_type_ids_from_sequences(
272
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
273
+ ) -> List[int]:
274
+ """
275
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A Funnel
276
+ Transformer sequence pair mask has the following format:
277
+
278
+ ```
279
+ 2 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
280
+ | first sequence | second sequence |
281
+ ```
282
+
283
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
284
+
285
+ Args:
286
+ token_ids_0 (`List[int]`):
287
+ List of IDs.
288
+ token_ids_1 (`List[int]`, *optional*):
289
+ Optional second list of IDs for sequence pairs.
290
+
291
+ Returns:
292
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
293
+ """
294
+ sep = [self.sep_token_id]
295
+ cls = [self.cls_token_id]
296
+ if token_ids_1 is None:
297
+ return len(cls) * [self.cls_token_type_id] + len(token_ids_0 + sep) * [0]
298
+ return len(cls) * [self.cls_token_type_id] + len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
299
+
300
+ # Copied from transformers.models.bert.tokenization_bert.BertTokenizer.save_vocabulary
301
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
302
+ index = 0
303
+ if os.path.isdir(save_directory):
304
+ vocab_file = os.path.join(
305
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
306
+ )
307
+ else:
308
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
309
+ with open(vocab_file, "w", encoding="utf-8") as writer:
310
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
311
+ if index != token_index:
312
+ logger.warning(
313
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
314
+ " Please check that the vocabulary is not corrupted!"
315
+ )
316
+ index = token_index
317
+ writer.write(token + "\n")
318
+ index += 1
319
+ return (vocab_file,)
320
+
321
+
322
+ # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
323
+ class BasicTokenizer:
324
+ """
325
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
326
+
327
+ Args:
328
+ do_lower_case (`bool`, *optional*, defaults to `True`):
329
+ Whether or not to lowercase the input when tokenizing.
330
+ never_split (`Iterable`, *optional*):
331
+ Collection of tokens which will never be split during tokenization. Only has an effect when
332
+ `do_basic_tokenize=True`
333
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
334
+ Whether or not to tokenize Chinese characters.
335
+
336
+ This should likely be deactivated for Japanese (see this
337
+ [issue](https://github.com/huggingface/transformers/issues/328)).
338
+ strip_accents (`bool`, *optional*):
339
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
340
+ value for `lowercase` (as in the original BERT).
341
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
342
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
343
+ the full context of the words, such as contractions.
344
+ """
345
+
346
+ def __init__(
347
+ self,
348
+ do_lower_case=True,
349
+ never_split=None,
350
+ tokenize_chinese_chars=True,
351
+ strip_accents=None,
352
+ do_split_on_punc=True,
353
+ ):
354
+ if never_split is None:
355
+ never_split = []
356
+ self.do_lower_case = do_lower_case
357
+ self.never_split = set(never_split)
358
+ self.tokenize_chinese_chars = tokenize_chinese_chars
359
+ self.strip_accents = strip_accents
360
+ self.do_split_on_punc = do_split_on_punc
361
+
362
+ def tokenize(self, text, never_split=None):
363
+ """
364
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
365
+
366
+ Args:
367
+ never_split (`List[str]`, *optional*)
368
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
369
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
370
+ """
371
+ # union() returns a new set by concatenating the two sets.
372
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
373
+ text = self._clean_text(text)
374
+
375
+ # This was added on November 1st, 2018 for the multilingual and Chinese
376
+ # models. This is also applied to the English models now, but it doesn't
377
+ # matter since the English models were not trained on any Chinese data
378
+ # and generally don't have any Chinese data in them (there are Chinese
379
+ # characters in the vocabulary because Wikipedia does have some Chinese
380
+ # words in the English Wikipedia.).
381
+ if self.tokenize_chinese_chars:
382
+ text = self._tokenize_chinese_chars(text)
383
+ # prevents treating the same character with different unicode codepoints as different characters
384
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
385
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
386
+ split_tokens = []
387
+ for token in orig_tokens:
388
+ if token not in never_split:
389
+ if self.do_lower_case:
390
+ token = token.lower()
391
+ if self.strip_accents is not False:
392
+ token = self._run_strip_accents(token)
393
+ elif self.strip_accents:
394
+ token = self._run_strip_accents(token)
395
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
396
+
397
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
398
+ return output_tokens
399
+
400
+ def _run_strip_accents(self, text):
401
+ """Strips accents from a piece of text."""
402
+ text = unicodedata.normalize("NFD", text)
403
+ output = []
404
+ for char in text:
405
+ cat = unicodedata.category(char)
406
+ if cat == "Mn":
407
+ continue
408
+ output.append(char)
409
+ return "".join(output)
410
+
411
+ def _run_split_on_punc(self, text, never_split=None):
412
+ """Splits punctuation on a piece of text."""
413
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
414
+ return [text]
415
+ chars = list(text)
416
+ i = 0
417
+ start_new_word = True
418
+ output = []
419
+ while i < len(chars):
420
+ char = chars[i]
421
+ if _is_punctuation(char):
422
+ output.append([char])
423
+ start_new_word = True
424
+ else:
425
+ if start_new_word:
426
+ output.append([])
427
+ start_new_word = False
428
+ output[-1].append(char)
429
+ i += 1
430
+
431
+ return ["".join(x) for x in output]
432
+
433
+ def _tokenize_chinese_chars(self, text):
434
+ """Adds whitespace around any CJK character."""
435
+ output = []
436
+ for char in text:
437
+ cp = ord(char)
438
+ if self._is_chinese_char(cp):
439
+ output.append(" ")
440
+ output.append(char)
441
+ output.append(" ")
442
+ else:
443
+ output.append(char)
444
+ return "".join(output)
445
+
446
+ def _is_chinese_char(self, cp):
447
+ """Checks whether CP is the codepoint of a CJK character."""
448
+ # This defines a "chinese character" as anything in the CJK Unicode block:
449
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
450
+ #
451
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
452
+ # despite its name. The modern Korean Hangul alphabet is a different block,
453
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
454
+ # space-separated words, so they are not treated specially and handled
455
+ # like the all of the other languages.
456
+ if (
457
+ (cp >= 0x4E00 and cp <= 0x9FFF)
458
+ or (cp >= 0x3400 and cp <= 0x4DBF) #
459
+ or (cp >= 0x20000 and cp <= 0x2A6DF) #
460
+ or (cp >= 0x2A700 and cp <= 0x2B73F) #
461
+ or (cp >= 0x2B740 and cp <= 0x2B81F) #
462
+ or (cp >= 0x2B820 and cp <= 0x2CEAF) #
463
+ or (cp >= 0xF900 and cp <= 0xFAFF)
464
+ or (cp >= 0x2F800 and cp <= 0x2FA1F) #
465
+ ): #
466
+ return True
467
+
468
+ return False
469
+
470
+ def _clean_text(self, text):
471
+ """Performs invalid character removal and whitespace cleanup on text."""
472
+ output = []
473
+ for char in text:
474
+ cp = ord(char)
475
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
476
+ continue
477
+ if _is_whitespace(char):
478
+ output.append(" ")
479
+ else:
480
+ output.append(char)
481
+ return "".join(output)
482
+
483
+
484
+ # Copied from transformers.models.bert.tokenization_bert.WordpieceTokenizer
485
+ class WordpieceTokenizer:
486
+ """Runs WordPiece tokenization."""
487
+
488
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
489
+ self.vocab = vocab
490
+ self.unk_token = unk_token
491
+ self.max_input_chars_per_word = max_input_chars_per_word
492
+
493
+ def tokenize(self, text):
494
+ """
495
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
496
+ tokenization using the given vocabulary.
497
+
498
+ For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.
499
+
500
+ Args:
501
+ text: A single token or whitespace separated tokens. This should have
502
+ already been passed through *BasicTokenizer*.
503
+
504
+ Returns:
505
+ A list of wordpiece tokens.
506
+ """
507
+
508
+ output_tokens = []
509
+ for token in whitespace_tokenize(text):
510
+ chars = list(token)
511
+ if len(chars) > self.max_input_chars_per_word:
512
+ output_tokens.append(self.unk_token)
513
+ continue
514
+
515
+ is_bad = False
516
+ start = 0
517
+ sub_tokens = []
518
+ while start < len(chars):
519
+ end = len(chars)
520
+ cur_substr = None
521
+ while start < end:
522
+ substr = "".join(chars[start:end])
523
+ if start > 0:
524
+ substr = "##" + substr
525
+ if substr in self.vocab:
526
+ cur_substr = substr
527
+ break
528
+ end -= 1
529
+ if cur_substr is None:
530
+ is_bad = True
531
+ break
532
+ sub_tokens.append(cur_substr)
533
+ start = end
534
+
535
+ if is_bad:
536
+ output_tokens.append(self.unk_token)
537
+ else:
538
+ output_tokens.extend(sub_tokens)
539
+ return output_tokens
540
+
541
+
542
+ __all__ = ["FunnelTokenizer"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/funnel/tokenization_funnel_fast.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 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
+ """Tokenization class for Funnel Transformer."""
16
+
17
+ import json
18
+ from typing import List, Optional, Tuple
19
+
20
+ from tokenizers import normalizers
21
+
22
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
23
+ from ...utils import logging
24
+ from .tokenization_funnel import FunnelTokenizer
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
30
+
31
+ _model_names = [
32
+ "small",
33
+ "small-base",
34
+ "medium",
35
+ "medium-base",
36
+ "intermediate",
37
+ "intermediate-base",
38
+ "large",
39
+ "large-base",
40
+ "xlarge",
41
+ "xlarge-base",
42
+ ]
43
+
44
+
45
+ class FunnelTokenizerFast(PreTrainedTokenizerFast):
46
+ r"""
47
+ Construct a "fast" Funnel Transformer tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
48
+
49
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
50
+ refer to this superclass for more information regarding those methods.
51
+
52
+ Args:
53
+ vocab_file (`str`):
54
+ File containing the vocabulary.
55
+ do_lower_case (`bool`, *optional*, defaults to `True`):
56
+ Whether or not to lowercase the input when tokenizing.
57
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
58
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
59
+ token instead.
60
+ sep_token (`str`, *optional*, defaults to `"<sep>"`):
61
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
62
+ sequence classification or for a text and a question for question answering. It is also used as the last
63
+ token of a sequence built with special tokens.
64
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
65
+ The token used for padding, for example when batching sequences of different lengths.
66
+ cls_token (`str`, *optional*, defaults to `"<cls>"`):
67
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
68
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
69
+ mask_token (`str`, *optional*, defaults to `"<mask>"`):
70
+ The token used for masking values. This is the token used when training this model with masked language
71
+ modeling. This is the token which the model will try to predict.
72
+ clean_text (`bool`, *optional*, defaults to `True`):
73
+ Whether or not to clean the text before tokenization by removing any control characters and replacing all
74
+ whitespaces by the classic one.
75
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
76
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
77
+ issue](https://github.com/huggingface/transformers/issues/328)).
78
+ bos_token (`str`, `optional`, defaults to `"<s>"`):
79
+ The beginning of sentence token.
80
+ eos_token (`str`, `optional`, defaults to `"</s>"`):
81
+ The end of sentence token.
82
+ strip_accents (`bool`, *optional*):
83
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
84
+ value for `lowercase` (as in the original BERT).
85
+ wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
86
+ The prefix for subwords.
87
+ """
88
+
89
+ vocab_files_names = VOCAB_FILES_NAMES
90
+ slow_tokenizer_class = FunnelTokenizer
91
+ cls_token_type_id: int = 2
92
+
93
+ def __init__(
94
+ self,
95
+ vocab_file=None,
96
+ tokenizer_file=None,
97
+ do_lower_case=True,
98
+ unk_token="<unk>",
99
+ sep_token="<sep>",
100
+ pad_token="<pad>",
101
+ cls_token="<cls>",
102
+ mask_token="<mask>",
103
+ bos_token="<s>",
104
+ eos_token="</s>",
105
+ clean_text=True,
106
+ tokenize_chinese_chars=True,
107
+ strip_accents=None,
108
+ wordpieces_prefix="##",
109
+ **kwargs,
110
+ ):
111
+ super().__init__(
112
+ vocab_file,
113
+ tokenizer_file=tokenizer_file,
114
+ do_lower_case=do_lower_case,
115
+ unk_token=unk_token,
116
+ sep_token=sep_token,
117
+ pad_token=pad_token,
118
+ cls_token=cls_token,
119
+ mask_token=mask_token,
120
+ bos_token=bos_token,
121
+ eos_token=eos_token,
122
+ clean_text=clean_text,
123
+ tokenize_chinese_chars=tokenize_chinese_chars,
124
+ strip_accents=strip_accents,
125
+ wordpieces_prefix=wordpieces_prefix,
126
+ **kwargs,
127
+ )
128
+
129
+ normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
130
+ if (
131
+ normalizer_state.get("lowercase", do_lower_case) != do_lower_case
132
+ or normalizer_state.get("strip_accents", strip_accents) != strip_accents
133
+ or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
134
+ ):
135
+ normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
136
+ normalizer_state["lowercase"] = do_lower_case
137
+ normalizer_state["strip_accents"] = strip_accents
138
+ normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
139
+ self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
140
+
141
+ self.do_lower_case = do_lower_case
142
+
143
+ # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast.build_inputs_with_special_tokens with BERT->Funnel
144
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
145
+ """
146
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
147
+ adding special tokens. A Funnel sequence has the following format:
148
+
149
+ - single sequence: `[CLS] X [SEP]`
150
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
151
+
152
+ Args:
153
+ token_ids_0 (`List[int]`):
154
+ List of IDs to which the special tokens will be added.
155
+ token_ids_1 (`List[int]`, *optional*):
156
+ Optional second list of IDs for sequence pairs.
157
+
158
+ Returns:
159
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
160
+ """
161
+ output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
162
+
163
+ if token_ids_1 is not None:
164
+ output += token_ids_1 + [self.sep_token_id]
165
+
166
+ return output
167
+
168
+ def create_token_type_ids_from_sequences(
169
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
170
+ ) -> List[int]:
171
+ """
172
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A Funnel
173
+ Transformer sequence pair mask has the following format:
174
+
175
+ ```
176
+ 2 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
177
+ | first sequence | second sequence |
178
+ ```
179
+
180
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
181
+
182
+ Args:
183
+ token_ids_0 (`List[int]`):
184
+ List of IDs.
185
+ token_ids_1 (`List[int]`, *optional*):
186
+ Optional second list of IDs for sequence pairs.
187
+
188
+ Returns:
189
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
190
+ """
191
+ sep = [self.sep_token_id]
192
+ cls = [self.cls_token_id]
193
+ if token_ids_1 is None:
194
+ return len(cls) * [self.cls_token_type_id] + len(token_ids_0 + sep) * [0]
195
+ return len(cls) * [self.cls_token_type_id] + len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
196
+
197
+ # Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast.save_vocabulary
198
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
199
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
200
+ return tuple(files)
201
+
202
+
203
+ __all__ = ["FunnelTokenizerFast"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fuyu/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_fuyu import *
22
+ from .image_processing_fuyu import *
23
+ from .modeling_fuyu import *
24
+ from .processing_fuyu import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fuyu/configuration_fuyu.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Adept AI 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
+ """Fuyu model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+ from ..auto import CONFIG_MAPPING
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class FuyuConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`FuyuForCausalLM`]. It is used to instantiate an
28
+ Fuyu model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of the
30
+ [adept/fuyu-8b](https://huggingface.co/adept/fuyu-8b).
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 262144):
38
+ Vocabulary size of the Fuyu model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`FuyuForCausalLM`]
40
+ hidden_size (`int`, *optional*, defaults to 4096):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 16384):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 36):
45
+ Number of hidden layers in the Transformer encoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 64):
47
+ Number of attention heads for each attention layer in the Transformer encoder.
48
+ hidden_act (`str` or `function`, *optional*, defaults to `"relu2"`):
49
+ The non-linear activation function (function or string) in the decoder.
50
+ max_position_embeddings (`int`, *optional*, defaults to 16384):
51
+ The maximum sequence length that this model might ever be used with.
52
+ image_size (`int`, *optional*, defaults to 300):
53
+ The input image size.
54
+ patch_size (`int`, *optional*, defaults to 30):
55
+ The input vision transformer encoding patch size.
56
+ num_channels (`int`, *optional*, defaults to 3):
57
+ The input image number of channels.
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
61
+ The epsilon used by the rms normalization layers.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
64
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings
65
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
66
+ Whether to tie input and output embeddings.
67
+ rope_theta (`float`, *optional*, defaults to 25000.0):
68
+ The base period of the RoPE embeddings.
69
+ rope_scaling (`Dict`, *optional*):
70
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
71
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
72
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
73
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
74
+ these scaling strategies behave:
75
+ https://www.reddit.com/r/LocalFuyu/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
76
+ experimental feature, subject to breaking API changes in future versions.
77
+ qk_layernorm (`bool`, *optional*, defaults to `True`):
78
+ Whether or not to normalize the Queries and Keys after projecting the hidden states
79
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
80
+ The dropout ratio after applying the MLP to the hidden states.
81
+ attention_dropout (`float`, *optional*, defaults to 0.0):
82
+ The dropout ratio after computing the attention scores.
83
+ partial_rotary_factor (`float`, *optional*, defaults to 0.5):
84
+ Percentage of the query and keys which will have rotary embedding.
85
+
86
+ pad_token_id (`int`, *optional*):
87
+ The id of the *padding* token.
88
+ bos_token_id (`int`, *optional*, defaults to 1):
89
+ The id of the *beginning-of-sequence* token.
90
+ eos_token_id (`Union[int, List[int]]`, *optional*, defaults to 2):
91
+ The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
92
+ text_config (`dict`, *optional*):
93
+ Dictionary of configuration options used to initialize the `language``[`Aut`].
94
+
95
+ ```python
96
+ >>> from transformers import FuyuConfig
97
+
98
+ >>> # Initializing a Fuyu fuyu-7b style configuration
99
+ >>> configuration = FuyuConfig()
100
+ ```"""
101
+
102
+ model_type = "fuyu"
103
+ keys_to_ignore_at_inference = ["past_key_values"]
104
+
105
+ def __init__(
106
+ self,
107
+ vocab_size=262144,
108
+ hidden_size=4096,
109
+ intermediate_size=16384,
110
+ num_hidden_layers=36,
111
+ num_attention_heads=64,
112
+ hidden_act="relu2",
113
+ max_position_embeddings=16384,
114
+ image_size=300,
115
+ patch_size=30,
116
+ num_channels=3,
117
+ initializer_range=0.02,
118
+ layer_norm_eps=1e-5,
119
+ use_cache=True,
120
+ tie_word_embeddings=False,
121
+ rope_theta=25000.0,
122
+ rope_scaling=None,
123
+ qk_layernorm=True,
124
+ hidden_dropout=0.0,
125
+ attention_dropout=0.0,
126
+ partial_rotary_factor=0.5,
127
+ pad_token_id=None,
128
+ bos_token_id=1,
129
+ eos_token_id=2,
130
+ text_config=None,
131
+ **kwargs,
132
+ ):
133
+ if text_config is None:
134
+ text_config = {
135
+ "vocab_size": vocab_size,
136
+ "max_position_embeddings": max_position_embeddings,
137
+ "hidden_size": hidden_size,
138
+ "intermediate_size": intermediate_size,
139
+ "num_hidden_layers": num_hidden_layers,
140
+ "num_attention_heads": num_attention_heads,
141
+ "hidden_act": hidden_act,
142
+ "initializer_range": initializer_range,
143
+ "layer_norm_eps": layer_norm_eps,
144
+ "use_cache": use_cache,
145
+ "rope_theta": rope_theta,
146
+ "rope_scaling": rope_scaling,
147
+ "qk_layernorm": qk_layernorm,
148
+ "hidden_dropout": hidden_dropout,
149
+ "attention_dropout": attention_dropout,
150
+ "partial_rotary_factor": partial_rotary_factor,
151
+ "pad_token_id": pad_token_id,
152
+ "bos_token_id": bos_token_id,
153
+ "eos_token_id": eos_token_id,
154
+ "tie_word_embeddings": tie_word_embeddings,
155
+ }
156
+ logger.info("text_config is None. initializing the text model with default values.")
157
+ text_model_type = text_config["model_type"] if "model_type" in text_config else "persimmon"
158
+ self.text_config = CONFIG_MAPPING[text_model_type](**text_config)
159
+
160
+ self._vocab_size = vocab_size
161
+ self.max_position_embeddings = max_position_embeddings
162
+ self.image_size = image_size
163
+ self.patch_size = patch_size
164
+ self.num_channels = num_channels
165
+ self.hidden_size = hidden_size
166
+ self.intermediate_size = intermediate_size
167
+ self.num_hidden_layers = num_hidden_layers
168
+ self.num_attention_heads = num_attention_heads
169
+ self.hidden_act = hidden_act
170
+ self.initializer_range = initializer_range
171
+ self.layer_norm_eps = layer_norm_eps
172
+ self.use_cache = use_cache
173
+ self.rope_theta = rope_theta
174
+ self.rope_scaling = rope_scaling
175
+ self.qk_layernorm = qk_layernorm
176
+ self.hidden_dropout = hidden_dropout
177
+ self.attention_dropout = attention_dropout
178
+ self.partial_rotary_factor = partial_rotary_factor
179
+ self._rope_scaling_validation()
180
+
181
+ super().__init__(
182
+ pad_token_id=pad_token_id,
183
+ bos_token_id=bos_token_id,
184
+ eos_token_id=eos_token_id,
185
+ tie_word_embeddings=tie_word_embeddings,
186
+ **kwargs,
187
+ )
188
+
189
+ def _rope_scaling_validation(self):
190
+ """
191
+ Validate the `rope_scaling` configuration.
192
+ """
193
+ if self.rope_scaling is None:
194
+ return
195
+
196
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
197
+ raise ValueError(
198
+ "`rope_scaling` must be a dictionary with two fields, `type` and `factor`, " f"got {self.rope_scaling}"
199
+ )
200
+ rope_scaling_type = self.rope_scaling.get("type", None)
201
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
202
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
203
+ raise ValueError(
204
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
205
+ )
206
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
207
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
208
+
209
+
210
+ __all__ = ["FuyuConfig"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fuyu/convert_fuyu_model_weights_to_hf.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Inc. 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
+ import argparse
15
+ import os
16
+ import sys
17
+ import warnings
18
+
19
+ import flatdict
20
+ import torch
21
+
22
+ from transformers import FuyuConfig, FuyuForCausalLM, LlamaTokenizer
23
+
24
+
25
+ try:
26
+ from transformers import LlamaTokenizerFast
27
+
28
+ tokenizer_class = LlamaTokenizerFast
29
+ except ImportError as e:
30
+ warnings.warn(e)
31
+ warnings.warn(
32
+ "The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion"
33
+ )
34
+ tokenizer_class = LlamaTokenizer
35
+
36
+ """
37
+ Sample usage: # TODO fix clone links from persimmon to fuyu
38
+ ```
39
+ git clone https://github.com/adept-ai-labs/adept-inference
40
+ wget https://axtkn4xl5cip.objectstorage.us-phoenix-1.oci.customer-oci.com/n/axtkn4xl5cip/b/adept-public-data/o/8b_base_model_release.tar
41
+ wget https://axtkn4xl5cip.objectstorage.us-phoenix-1.oci.customer-oci.com/n/axtkn4xl5cip/b/adept-public-data/o/8b_chat_model_release.tar
42
+ python src/transformers/models/fuyu/convert_fuyu_weights_to_hf.py --input_dir /path/to/downloaded/fuyu/weights/ --output_dir /output/path
43
+ ```
44
+
45
+ Thereafter, models can be loaded via:
46
+
47
+ ```py
48
+ from transformers import FuyuForCausalLM, FuyuTokenizer
49
+
50
+ model = FuyuForCausalLM.from_pretrained("/output/path")
51
+ tokenizer = FuyuTokenizer.from_pretrained("/output/path")
52
+ ```
53
+
54
+ Important note: you need to be able to host the whole model in RAM to execute this script (even if the biggest versions
55
+ come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM).
56
+ """
57
+
58
+
59
+ KEYS_TO_MODIFY_MAPPING = {
60
+ "self_attention": "self_attn",
61
+ "language_model.encoder": "language_model.model",
62
+ "word_embeddings_for_head": "language_model.lm_head",
63
+ "language_model.embedding.word_embeddings": "language_model.model.embed_tokens",
64
+ "vit_encoder.linear_encoder": "vision_embed_tokens",
65
+ }
66
+
67
+ KEYS_TO_REMOVE = {
68
+ "rotary_emb.inv_freq",
69
+ "image_patch_projection",
70
+ "image_patch_projection.weight",
71
+ "image_patch_projection.bias",
72
+ }
73
+
74
+
75
+ def rename_state_dict(state_dict):
76
+ model_state_dict = {}
77
+ for key, value in state_dict.items():
78
+ for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
79
+ if key_to_modify in key:
80
+ key = key.replace(key_to_modify, new_key)
81
+ # if KEYS_TO_REMOVE in key:
82
+ if key in KEYS_TO_REMOVE:
83
+ continue
84
+ model_state_dict[key] = value
85
+ return model_state_dict
86
+
87
+
88
+ def convert_fuyu_checkpoint(pytorch_dump_folder_path, ada_lib_path, pt_model_path, safe_serialization=False):
89
+ sys.path.insert(0, ada_lib_path)
90
+ model_state_dict_base = torch.load(pt_model_path, map_location="cpu")
91
+ state_dict = flatdict.FlatDict(model_state_dict_base["model"], ".")
92
+ state_dict = rename_state_dict(state_dict)
93
+
94
+ transformers_config = FuyuConfig()
95
+ model = FuyuForCausalLM(transformers_config).to(torch.bfloat16)
96
+ model.load_state_dict(state_dict)
97
+ model.save_pretrained(pytorch_dump_folder_path, safe_serialization=safe_serialization)
98
+ transformers_config.save_pretrained(pytorch_dump_folder_path)
99
+
100
+
101
+ def main():
102
+ parser = argparse.ArgumentParser()
103
+ parser.add_argument(
104
+ "--input_dir",
105
+ help="Location of Fuyu weights, which contains tokenizer.model and model folders",
106
+ )
107
+ parser.add_argument(
108
+ "--pt_model_path",
109
+ help="Location of Fuyu `model_optim_rng.pt`",
110
+ )
111
+ parser.add_argument(
112
+ "--output_dir",
113
+ help="Location to write HF model and tokenizer",
114
+ )
115
+ parser.add_argument(
116
+ "--ada_lib_path",
117
+ help="Location of original source code from adept to deserialize .pt checkpoint",
118
+ )
119
+ parser.add_argument("--safe_serialization", type=bool, help="Whether or not to save using `safetensors`.")
120
+ args = parser.parse_args()
121
+ spm_path = os.path.join(args.input_dir, "adept_vocab.model")
122
+
123
+ convert_fuyu_checkpoint(
124
+ pytorch_dump_folder_path=args.output_dir,
125
+ pt_model_path=args.pt_model_path,
126
+ safe_serialization=args.safe_serialization,
127
+ ada_lib_path=args.ada_lib_path,
128
+ )
129
+ tokenizer = tokenizer_class(spm_path, bos_token="|ENDOFTEXT|", eos_token="|ENDOFTEXT|")
130
+ tokenizer.save_pretrained(args.output_dir)
131
+
132
+
133
+ if __name__ == "__main__":
134
+ main()
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fuyu/image_processing_fuyu.py ADDED
@@ -0,0 +1,724 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Image processor class for Fuyu."""
16
+
17
+ import math
18
+ from typing import Dict, List, Optional, Union
19
+
20
+ import numpy as np
21
+
22
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
23
+ from ...image_transforms import (
24
+ pad,
25
+ resize,
26
+ to_channel_dimension_format,
27
+ )
28
+ from ...image_utils import (
29
+ ChannelDimension,
30
+ ImageInput,
31
+ PILImageResampling,
32
+ get_image_size,
33
+ infer_channel_dimension_format,
34
+ is_scaled_image,
35
+ is_valid_image,
36
+ make_list_of_images,
37
+ to_numpy_array,
38
+ validate_preprocess_arguments,
39
+ )
40
+ from ...utils import (
41
+ TensorType,
42
+ filter_out_non_signature_kwargs,
43
+ is_torch_available,
44
+ is_torch_device,
45
+ is_torch_dtype,
46
+ logging,
47
+ requires_backends,
48
+ )
49
+
50
+
51
+ if is_torch_available():
52
+ import torch
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+
58
+ def make_list_of_list_of_images(
59
+ images: Union[List[List[ImageInput]], List[ImageInput], ImageInput],
60
+ ) -> List[List[ImageInput]]:
61
+ if is_valid_image(images):
62
+ return [[images]]
63
+
64
+ if isinstance(images, list) and all(isinstance(image, list) for image in images):
65
+ return images
66
+
67
+ if isinstance(images, list):
68
+ return [make_list_of_images(image) for image in images]
69
+
70
+ raise ValueError("images must be a list of list of images or a list of images or an image.")
71
+
72
+
73
+ class FuyuBatchFeature(BatchFeature):
74
+ """
75
+ BatchFeature class for Fuyu image processor and processor.
76
+
77
+ The outputs dictionary from the processors contains a mix of tensors and lists of tensors.
78
+ """
79
+
80
+ def convert_to_tensors(self, tensor_type: Optional[Union[str, TensorType]] = None):
81
+ """
82
+ Convert the inner content to tensors.
83
+
84
+ Args:
85
+ tensor_type (`str` or [`~utils.TensorType`], *optional*):
86
+ The type of tensors to use. If `str`, should be one of the values of the enum [`~utils.TensorType`]. If
87
+ `None`, no modification is done.
88
+ """
89
+ if tensor_type is None:
90
+ return self
91
+
92
+ is_tensor, as_tensor = self._get_is_as_tensor_fns(tensor_type=tensor_type)
93
+
94
+ def _convert_tensor(elem):
95
+ if is_tensor(elem):
96
+ return elem
97
+ return as_tensor(elem)
98
+
99
+ def _safe_convert_tensor(elem):
100
+ try:
101
+ return _convert_tensor(elem)
102
+ except: # noqa E722
103
+ if key == "overflowing_values":
104
+ raise ValueError("Unable to create tensor returning overflowing values of different lengths. ")
105
+ raise ValueError(
106
+ "Unable to create tensor, you should probably activate padding "
107
+ "with 'padding=True' to have batched tensors with the same length."
108
+ )
109
+
110
+ # Do the tensor conversion in batch
111
+ for key, value in self.items():
112
+ if isinstance(value, list) and isinstance(value[0], list):
113
+ # List[List[Any]] -> List[List[Tensor]]
114
+ self[key] = [[_safe_convert_tensor(elem) for elem in elems] for elems in value]
115
+ elif isinstance(value, list):
116
+ # List[Any] -> List[Tensor]
117
+ self[key] = [_safe_convert_tensor(elem) for elem in value]
118
+ else:
119
+ # Any -> Tensor
120
+ self[key] = _safe_convert_tensor(value)
121
+ return self
122
+
123
+ def to(self, *args, **kwargs) -> "BatchFeature":
124
+ """
125
+ Send all values to device by calling `v.to(*args, **kwargs)` (PyTorch only). This should support casting in
126
+ different `dtypes` and sending the `BatchFeature` to a different `device`.
127
+
128
+ Args:
129
+ args (`Tuple`):
130
+ Will be passed to the `to(...)` function of the tensors.
131
+ kwargs (`Dict`, *optional*):
132
+ Will be passed to the `to(...)` function of the tensors.
133
+
134
+ Returns:
135
+ [`BatchFeature`]: The same instance after modification.
136
+ """
137
+ requires_backends(self, ["torch"])
138
+ import torch # noqa
139
+
140
+ new_data = {}
141
+ device = kwargs.get("device")
142
+ # Check if the args are a device or a dtype
143
+ if device is None and len(args) > 0:
144
+ # device should be always the first argument
145
+ arg = args[0]
146
+ if is_torch_dtype(arg):
147
+ # The first argument is a dtype
148
+ pass
149
+ elif isinstance(arg, str) or is_torch_device(arg) or isinstance(arg, int):
150
+ device = arg
151
+ else:
152
+ # it's something else
153
+ raise ValueError(f"Attempting to cast a BatchFeature to type {str(arg)}. This is not supported.")
154
+
155
+ def _to(elem):
156
+ # check if v is a floating point
157
+ if torch.is_floating_point(elem):
158
+ # cast and send to device
159
+ return elem.to(*args, **kwargs)
160
+ if device is not None:
161
+ return elem.to(device=device)
162
+
163
+ return elem
164
+
165
+ # We cast only floating point tensors to avoid issues with tokenizers casting `LongTensor` to `FloatTensor`
166
+ for k, v in self.items():
167
+ if isinstance(v, list) and isinstance(v[0], list):
168
+ # Data structure is a list of lists
169
+ new_v = []
170
+ for elems in v:
171
+ new_v.append([_to(elem) for elem in elems])
172
+ new_data[k] = new_v
173
+ elif isinstance(v, list):
174
+ # Data structure is a list
175
+ new_data[k] = [_to(elem) for elem in v]
176
+ else:
177
+ new_data[k] = _to(v)
178
+ self.data = new_data
179
+ return self
180
+
181
+
182
+ class FuyuImageProcessor(BaseImageProcessor):
183
+ """
184
+ This class should handle the image processing part before the main FuyuForCausalLM. In particular, it should
185
+ handle:
186
+
187
+ - Processing Images:
188
+ Taking a batch of images as input. If the images are variable-sized, it resizes them based on the desired patch
189
+ dimensions. The image output is always img_h, img_w of (1080, 1920)
190
+
191
+ Then, it patches up these images using the patchify_image function.
192
+
193
+ - Creating Image Input IDs:
194
+ For each patch, a placeholder ID is given to identify where these patches belong in a token sequence. For
195
+ variable-sized images, each line of patches is terminated with a newline ID.
196
+
197
+ - Image Patch Indices:
198
+ For each image patch, the code maintains an index where these patches should be inserted in a token stream.
199
+
200
+
201
+ Args:
202
+ do_resize (`bool`, *optional*, defaults to `True`):
203
+ Whether to resize the image to `size`.
204
+ size (`Dict[str, int]`, *optional*, defaults to `{"height": 1080, "width": 1920}`):
205
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
206
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
207
+ `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
208
+ do_pad (`bool`, *optional*, defaults to `True`):
209
+ Whether to pad the image to `size`.
210
+ padding_value (`float`, *optional*, defaults to 1.0):
211
+ The value to pad the image with.
212
+ padding_mode (`str`, *optional*, defaults to `"constant"`):
213
+ The padding mode to use when padding the image.
214
+ do_normalize (`bool`, *optional*, defaults to `True`):
215
+ Whether to normalize the image.
216
+ image_mean (`float`, *optional*, defaults to 0.5):
217
+ The mean to use when normalizing the image.
218
+ image_std (`float`, *optional*, defaults to 0.5):
219
+ The standard deviation to use when normalizing the image.
220
+ do_rescale (`bool`, *optional*, defaults to `True`):
221
+ Whether to rescale the image.
222
+ rescale_factor (`float`, *optional*, defaults to `1 / 255`):
223
+ The factor to use when rescaling the image.
224
+ patch_size (`Dict[str, int]`, *optional*, defaults to `{"height": 30, "width": 30}`):
225
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the patches.
226
+ """
227
+
228
+ model_input_names = [
229
+ "images",
230
+ "image_input_ids",
231
+ "image_patches",
232
+ "image_patch_indices_per_batch",
233
+ "image_patch_indices_per_subsequence",
234
+ ]
235
+
236
+ def __init__(
237
+ self,
238
+ do_resize: bool = True,
239
+ size: Optional[Dict[str, int]] = None,
240
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
241
+ do_pad: bool = True,
242
+ padding_value: float = 1.0,
243
+ padding_mode: str = "constant",
244
+ do_normalize: bool = True,
245
+ image_mean: Union[float, List[float]] = 0.5,
246
+ image_std: Union[float, List[float]] = 0.5,
247
+ do_rescale: bool = True,
248
+ rescale_factor: float = 1 / 255,
249
+ patch_size: Optional[Dict[str, int]] = None,
250
+ **kwargs,
251
+ ):
252
+ super().__init__(**kwargs)
253
+ self.do_resize = do_resize
254
+ self.size = size if size is not None else {"height": 1080, "width": 1920}
255
+ self.resample = resample
256
+ self.do_pad = do_pad
257
+ self.padding_value = padding_value
258
+ self.padding_mode = padding_mode
259
+ self.do_normalize = do_normalize
260
+ self.image_mean = image_mean
261
+ self.image_std = image_std
262
+ self.do_rescale = do_rescale
263
+ self.rescale_factor = rescale_factor
264
+ self.patch_size = patch_size if patch_size is not None else {"height": 30, "width": 30}
265
+
266
+ def resize(
267
+ self,
268
+ image: np.ndarray,
269
+ size: Dict[str, int],
270
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
271
+ data_format: Optional[Union[str, ChannelDimension]] = None,
272
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
273
+ **kwargs,
274
+ ) -> np.ndarray:
275
+ """
276
+ Resize an image to `(size["height"], size["width"])`.
277
+
278
+ Args:
279
+ image (`np.ndarray`):
280
+ Image to resize.
281
+ size (`Dict[str, int]`):
282
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
283
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
284
+ `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
285
+ data_format (`ChannelDimension` or `str`, *optional*):
286
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
287
+ image is used. Can be one of:
288
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
289
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
290
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
291
+ input_data_format (`ChannelDimension` or `str`, *optional*):
292
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
293
+ from the input image. Can be one of:
294
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
295
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
296
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
297
+
298
+ Returns:
299
+ `np.ndarray`: The resized image.
300
+ """
301
+ image_height, image_width = get_image_size(image, input_data_format)
302
+ target_height, target_width = size["height"], size["width"]
303
+
304
+ if image_width <= target_width and image_height <= target_height:
305
+ return image
306
+
307
+ height_scale_factor = target_height / image_height
308
+ width_scale_factor = target_width / image_width
309
+ optimal_scale_factor = min(height_scale_factor, width_scale_factor)
310
+
311
+ new_height = int(image_height * optimal_scale_factor)
312
+ new_width = int(image_width * optimal_scale_factor)
313
+
314
+ scaled_image = resize(
315
+ image=image,
316
+ size=(new_height, new_width),
317
+ resample=resample,
318
+ data_format=data_format,
319
+ input_data_format=input_data_format,
320
+ **kwargs,
321
+ )
322
+ return scaled_image
323
+
324
+ def pad_image(
325
+ self,
326
+ image: np.ndarray,
327
+ size: Dict[str, int],
328
+ mode: str = "constant",
329
+ constant_values: float = 1.0,
330
+ data_format: Optional[Union[str, ChannelDimension]] = None,
331
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
332
+ ) -> np.ndarray:
333
+ """
334
+ Pad an image to `(size["height"], size["width"])`.
335
+
336
+ Args:
337
+ image (`np.ndarray`):
338
+ Image to pad.
339
+ size (`Dict[str, int]`):
340
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
341
+ data_format (`ChannelDimension` or `str`, *optional*):
342
+ The data format of the output image. If unset, the same format as the input image is used.
343
+ input_data_format (`ChannelDimension` or `str`, *optional*):
344
+ The channel dimension format of the input image. If not provided, it will be inferred.
345
+ """
346
+ image_height, image_width = get_image_size(image, input_data_format)
347
+ target_height, target_width = size["height"], size["width"]
348
+ padding_top = 0
349
+ padding_left = 0
350
+ padding_bottom = target_height - image_height
351
+ padding_right = target_width - image_width
352
+ padded_image = pad(
353
+ image,
354
+ padding=((padding_top, padding_bottom), (padding_left, padding_right)),
355
+ mode=mode,
356
+ constant_values=constant_values,
357
+ data_format=data_format,
358
+ input_data_format=input_data_format,
359
+ )
360
+ return padded_image
361
+
362
+ @filter_out_non_signature_kwargs()
363
+ def preprocess(
364
+ self,
365
+ images,
366
+ do_resize: Optional[bool] = None,
367
+ size: Optional[Dict[str, int]] = None,
368
+ resample: Optional[PILImageResampling] = None,
369
+ do_pad: Optional[bool] = None,
370
+ padding_value: Optional[float] = None,
371
+ padding_mode: Optional[str] = None,
372
+ do_normalize: Optional[bool] = None,
373
+ image_mean: Optional[float] = None,
374
+ image_std: Optional[float] = None,
375
+ do_rescale: Optional[bool] = None,
376
+ rescale_factor: Optional[float] = None,
377
+ patch_size: Optional[Dict[str, int]] = None,
378
+ data_format: Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST,
379
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
380
+ return_tensors: Optional[TensorType] = None,
381
+ ):
382
+ """
383
+
384
+ Utility function to preprocess the images and extract necessary information about original formats.
385
+
386
+ Args:
387
+ images (`ImageInput`):
388
+ Images to preprocess. Expects a single image, a list or images or a list of lists of images. Pixel
389
+ values range from 0 to 255, or between 0 and 1 if `do_rescale` is `False`.
390
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
391
+ Whether to resize the image to `size`.
392
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
393
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
394
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
395
+ `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
396
+ do_pad (`bool`, *optional*, defaults to `self.do_pad`):
397
+ Whether to pad the image to `size`.
398
+ padding_value (`float`, *optional*, defaults to `self.padding_value`):
399
+ The value to pad the image with.
400
+ padding_mode (`str`, *optional*, defaults to `self.padding_mode`):
401
+ The padding mode to use when padding the image.
402
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
403
+ Whether to normalize the image.
404
+ image_mean (`float`, *optional*, defaults to `self.image_mean`):
405
+ The mean to use when normalizing the image.
406
+ image_std (`float`, *optional*, defaults to `self.image_std`):
407
+ The standard deviation to use when normalizing the image.
408
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
409
+ Whether to rescale the image.
410
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
411
+ The factor to use when rescaling the image.
412
+ patch_size (`Dict[str, int]`, *optional*, defaults to `self.patch_size`):
413
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the patches.
414
+ return_tensors (`str` or `TensorType`, *optional*):
415
+ The type of tensors to return. Can be one of:
416
+ - Unset: Return a list of `np.ndarray`.
417
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
418
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
419
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
420
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
421
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
422
+ The channel dimension format of the output image. Can be one of:
423
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
424
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
425
+ input_data_format (`ChannelDimension` or `str`, *optional*):
426
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
427
+ from the input image. Can be one of:
428
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
429
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
430
+ """
431
+
432
+ do_resize = do_resize if do_resize is not None else self.do_resize
433
+ size = size if size is not None else self.size
434
+ resample = resample if resample is not None else self.resample
435
+ do_pad = do_pad if do_pad is not None else self.do_pad
436
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
437
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
438
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
439
+ image_mean = image_mean if image_mean is not None else self.image_mean
440
+ image_std = image_std if image_std is not None else self.image_std
441
+ padding_value = padding_value if padding_value is not None else self.padding_value
442
+ padding_mode = padding_mode if padding_mode is not None else self.padding_mode
443
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
444
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
445
+ patch_size = patch_size if patch_size is not None else self.patch_size
446
+
447
+ if isinstance(images, list) and any(isinstance(elem, list) and len(elem) >= 2 for elem in images):
448
+ raise ValueError("Multiple images for a single sample are not yet supported.")
449
+
450
+ batch_images = make_list_of_list_of_images(images)
451
+
452
+ validate_preprocess_arguments(
453
+ do_rescale=do_rescale,
454
+ rescale_factor=rescale_factor,
455
+ do_normalize=do_normalize,
456
+ image_mean=image_mean,
457
+ image_std=image_std,
458
+ do_pad=do_pad,
459
+ size_divisibility=size, # There is no pad divisibility in this processor, but pad requires the size arg.
460
+ do_resize=do_resize,
461
+ size=size,
462
+ resample=resample,
463
+ )
464
+ # All transformations expect numpy arrays.
465
+ batch_images = [[to_numpy_array(image) for image in images] for images in batch_images]
466
+
467
+ if do_rescale and is_scaled_image(batch_images[0][0]):
468
+ logger.warning_once(
469
+ "It looks like you are trying to rescale already rescaled images. If the input"
470
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
471
+ )
472
+
473
+ if input_data_format is None:
474
+ # We assume that all images have the same channel dimension format.
475
+ input_data_format = infer_channel_dimension_format(batch_images[0][0])
476
+
477
+ original_image_sizes = [get_image_size(images[0], channel_dim=input_data_format) for images in batch_images]
478
+ size = get_size_dict(size) # for BC
479
+
480
+ if do_resize:
481
+ batch_images = [
482
+ [self.resize(image, size=size, input_data_format=input_data_format) for image in images]
483
+ for images in batch_images
484
+ ]
485
+
486
+ image_sizes = [get_image_size(images[0], channel_dim=input_data_format) for images in batch_images]
487
+ image_unpadded_heights = [[image_size[0]] for image_size in image_sizes]
488
+ image_unpadded_widths = [[image_size[1]] for image_size in image_sizes]
489
+
490
+ # scale_h is the same as scale_w
491
+ image_scale_factors = [
492
+ [resized_size[0] / original_size[0]]
493
+ for original_size, resized_size in zip(original_image_sizes, image_sizes)
494
+ ]
495
+
496
+ if do_pad:
497
+ batch_images = [
498
+ [
499
+ self.pad_image(
500
+ image,
501
+ size=size,
502
+ mode=padding_mode,
503
+ constant_values=padding_value,
504
+ input_data_format=input_data_format,
505
+ )
506
+ for image in images
507
+ ]
508
+ for images in batch_images
509
+ ]
510
+
511
+ if do_rescale:
512
+ batch_images = [
513
+ [self.rescale(image, scale=rescale_factor, input_data_format=input_data_format) for image in images]
514
+ for images in batch_images
515
+ ]
516
+
517
+ if do_normalize:
518
+ batch_images = [
519
+ [
520
+ self.normalize(image, mean=image_mean, std=image_std, input_data_format=input_data_format)
521
+ for image in images
522
+ ]
523
+ for images in batch_images
524
+ ]
525
+
526
+ if data_format is not None:
527
+ batch_images = [
528
+ [to_channel_dimension_format(image, data_format, input_data_format) for image in images]
529
+ for images in batch_images
530
+ ]
531
+
532
+ data = {
533
+ "images": batch_images,
534
+ "image_unpadded_heights": image_unpadded_heights,
535
+ "image_unpadded_widths": image_unpadded_widths,
536
+ "image_scale_factors": image_scale_factors,
537
+ }
538
+ return FuyuBatchFeature(data=data, tensor_type=return_tensors)
539
+
540
+ def get_num_patches(self, image_height: int, image_width: int, patch_size: Dict[str, int] = None) -> int:
541
+ """
542
+ Calculate number of patches required to encode an image.
543
+
544
+ Args:
545
+ image_height (`int`):
546
+ Height of the image.
547
+ image_width (`int`):
548
+ Width of the image.
549
+ patch_size (`Dict[str, int]`, *optional*, defaults to `self.patch_size`):
550
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the patches.
551
+ """
552
+ patch_size = patch_size if patch_size is not None else self.patch_size
553
+ patch_height, patch_width = self.patch_size["height"], self.patch_size["width"]
554
+
555
+ if image_height % patch_height != 0:
556
+ raise ValueError(f"{image_height=} must be divisible by {patch_height}")
557
+ if image_width % patch_width != 0:
558
+ raise ValueError(f"{image_width=} must be divisible by {patch_width}")
559
+
560
+ num_patches_per_dim_h = image_height // patch_height
561
+ num_patches_per_dim_w = image_width // patch_width
562
+ num_patches = num_patches_per_dim_h * num_patches_per_dim_w
563
+ return num_patches
564
+
565
+ def patchify_image(self, image: "torch.Tensor", patch_size: Optional[Dict[str, int]] = None) -> "torch.Tensor":
566
+ """
567
+ Convert an image into a tensor of patches.
568
+
569
+ Args:
570
+ image (`torch.Tensor`):
571
+ Image to convert. Shape: [batch, channels, height, width]
572
+ patch_size (`Dict[str, int]`, *optional*, defaults to `self.patch_size`):
573
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the patches.
574
+ """
575
+ requires_backends(self, ["torch"])
576
+ patch_size = patch_size if patch_size is not None else self.patch_size
577
+ patch_height, patch_width = patch_size["height"], patch_size["width"]
578
+
579
+ # TODO refer to https://github.com/ArthurZucker/transformers/blob/0f0a3fe5ca5697ee58faeb5b53f049af720b5e98/src/transformers/models/vit_mae/modeling_vit_mae.py#L871
580
+ # torch implementation is faster but does not handle non-squares
581
+
582
+ batch_size, channels, _, _ = image.shape
583
+ unfolded_along_height = image.unfold(2, patch_height, patch_height)
584
+ patches = unfolded_along_height.unfold(3, patch_width, patch_width)
585
+ patches = patches.contiguous()
586
+ patches = patches.view(batch_size, channels, -1, patch_height, patch_width)
587
+ patches = patches.permute(0, 2, 3, 4, 1)
588
+ patches = patches.reshape(batch_size, -1, channels * patch_height * patch_width)
589
+ return patches
590
+
591
+ def preprocess_with_tokenizer_info(
592
+ self,
593
+ image_input: "torch.Tensor",
594
+ image_present: "torch.Tensor",
595
+ image_unpadded_h: "torch.Tensor",
596
+ image_unpadded_w: "torch.Tensor",
597
+ image_placeholder_id: int,
598
+ image_newline_id: int,
599
+ variable_sized: bool,
600
+ patch_size: Optional[Dict[str, int]] = None,
601
+ ) -> FuyuBatchFeature:
602
+ """Process images for model input. In particular, variable-sized images are handled here.
603
+
604
+ Args:
605
+ image_input (`torch.Tensor` of shape [batch_size, subsequence_size, num_channels, height, width]):
606
+ Tensor of images padded to model input size.
607
+ image_present (`torch.Tensor` of shape [batch_size, subsequence_size, num_images]):
608
+ Tensor of 1s and 0s indicating whether an image is present.
609
+ image_unpadded_h (`torch.Tensor` of shape [batch_size, subsequence_size]):
610
+ Tensor of unpadded image heights.
611
+ image_unpadded_w (`torch.Tensor` of shape [batch_size, subsequence_size]):
612
+ Tensor of unpadded image widths.
613
+ image_placeholder_id (int):
614
+ The id of the image placeholder token. Comes from an associated tokenizer.
615
+ image_newline_id (int):
616
+ The id of the image newline token. Comes from an associated tokenizer.
617
+ variable_sized (bool):
618
+ Whether to process images as variable-sized.
619
+ patch_size (`Dict[str, int]`, *optional*, defaults to `self.patch_size`):
620
+ Size of the patches.
621
+ """
622
+ requires_backends(self, ["torch"])
623
+
624
+ patch_size = patch_size if patch_size is not None else self.patch_size
625
+ patch_height, patch_width = patch_size["height"], patch_size["width"]
626
+
627
+ # Only images that are present.
628
+ images: List[List[torch.Tensor]] = []
629
+ batch_image_patches: List[List[torch.Tensor]] = []
630
+ # Image input ids for every subsequence, including ones with no image present.
631
+ batch_image_input_ids: List[List[torch.Tensor]] = []
632
+ for batch_index in range(image_input.shape[0]):
633
+ image_input_ids = []
634
+ image_patches = []
635
+ for subseq_index in range(image_input.shape[1]):
636
+ if image_present[batch_index, subseq_index]:
637
+ image = image_input[batch_index, subseq_index]
638
+ image_height, image_width = image.shape[1], image.shape[2]
639
+ if variable_sized:
640
+ # The min() is required here due to floating point issues:
641
+ # math.ceil(torch.tensor(300).cuda() / 30) == 11
642
+ new_h = min(
643
+ image_height,
644
+ math.ceil(image_unpadded_h[batch_index, subseq_index] / patch_height) * patch_height,
645
+ )
646
+ new_w = min(
647
+ image_width,
648
+ math.ceil(image_unpadded_w[batch_index, subseq_index] / patch_width) * patch_width,
649
+ )
650
+ image = image[:, :new_h, :new_w]
651
+ image_height, image_width = new_h, new_w
652
+
653
+ num_patches = self.get_num_patches(image_height=image_height, image_width=image_width)
654
+ tensor_of_image_ids = torch.full(
655
+ [num_patches], image_placeholder_id, dtype=torch.int32, device=image_input.device
656
+ )
657
+ patches = self.patchify_image(image=image.unsqueeze(0)).squeeze(0)
658
+ assert num_patches == patches.shape[0]
659
+
660
+ if variable_sized:
661
+ # Now terminate each line with |NEWLINE|.
662
+ tensor_of_image_ids = tensor_of_image_ids.reshape(-1, image_width // patch_width)
663
+ newline_ids = torch.full(
664
+ [tensor_of_image_ids.shape[0], 1],
665
+ image_newline_id,
666
+ dtype=torch.int32,
667
+ device=image_input.device,
668
+ )
669
+ tensor_of_image_ids = torch.cat([tensor_of_image_ids, newline_ids], dim=1)
670
+ tensor_of_image_ids = tensor_of_image_ids.reshape(-1)
671
+
672
+ images.append([image])
673
+ image_input_ids.append(tensor_of_image_ids)
674
+ image_patches.append(patches)
675
+ else:
676
+ image_input_ids.append(torch.tensor([], dtype=torch.int32, device=image_input.device))
677
+
678
+ batch_image_input_ids.append(image_input_ids)
679
+ batch_image_patches.append(image_patches)
680
+
681
+ # Create image_patch_input_indices, where non-negative values correspond to image patches to be inserted in
682
+ # the stream.
683
+ image_patch_indices_per_batch: List[List[torch.Tensor]] = []
684
+ image_patch_indices_per_subsequence: List[List[torch.Tensor]] = []
685
+
686
+ for sample_image_input_ids in batch_image_input_ids:
687
+ index_offset = 0
688
+ per_batch_indices = []
689
+ per_subsequence_indices = []
690
+ for subseq_image_input_ids in sample_image_input_ids:
691
+ # Indices of image patches.
692
+ patches_mask = subseq_image_input_ids == image_placeholder_id
693
+ num_patches = torch.count_nonzero(patches_mask)
694
+ indices = torch.arange(num_patches, dtype=torch.int64, device=subseq_image_input_ids.device).type_as(
695
+ subseq_image_input_ids
696
+ )
697
+
698
+ # Place those indices in the image input ids token stream, with -1 representing non-index tokens.
699
+ indices_in_stream_per_batch = torch.full_like(subseq_image_input_ids, -1)
700
+ indices_in_stream_per_subsequence = torch.full_like(subseq_image_input_ids, -1)
701
+ patches_inds = torch.nonzero(patches_mask, as_tuple=True)[0]
702
+
703
+ indices_in_stream_per_batch[patches_inds] = indices + index_offset
704
+ indices_in_stream_per_subsequence[patches_inds] = indices
705
+
706
+ per_batch_indices.append(indices_in_stream_per_batch)
707
+ per_subsequence_indices.append(indices_in_stream_per_subsequence)
708
+ index_offset += num_patches
709
+
710
+ image_patch_indices_per_batch.append(per_batch_indices)
711
+ image_patch_indices_per_subsequence.append(per_subsequence_indices)
712
+
713
+ return FuyuBatchFeature(
714
+ data={
715
+ "images": images,
716
+ "image_input_ids": batch_image_input_ids,
717
+ "image_patches": batch_image_patches,
718
+ "image_patch_indices_per_batch": image_patch_indices_per_batch,
719
+ "image_patch_indices_per_subsequence": image_patch_indices_per_subsequence,
720
+ }
721
+ )
722
+
723
+
724
+ __all__ = ["FuyuImageProcessor"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fuyu/modeling_fuyu.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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 Fuyu model."""
16
+
17
+ from typing import List, Optional, Tuple, Union
18
+
19
+ import torch
20
+ import torch.utils.checkpoint
21
+ from torch import nn
22
+
23
+ from ...generation import GenerationMixin
24
+ from ...modeling_outputs import CausalLMOutputWithPast
25
+ from ...modeling_utils import PreTrainedModel
26
+ from ...models.auto.modeling_auto import AutoModelForCausalLM
27
+ from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
28
+ from .configuration_fuyu import FuyuConfig
29
+
30
+
31
+ logger = logging.get_logger(__name__)
32
+
33
+ _CONFIG_FOR_DOC = "FuyuConfig"
34
+
35
+
36
+ FUYU_START_DOCSTRING = r"""
37
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
38
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
39
+ etc.)
40
+
41
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
42
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
43
+ and behavior.
44
+
45
+ Parameters:
46
+ config ([`FuyuConfig`]):
47
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
48
+ load the weights associated with the model, only the configuration. Check out the
49
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
50
+ """
51
+
52
+
53
+ @add_start_docstrings(
54
+ "The bare Fuyu Model outputting raw hidden-states without any specific head on top.",
55
+ FUYU_START_DOCSTRING,
56
+ )
57
+ class FuyuPreTrainedModel(PreTrainedModel):
58
+ config_class = FuyuConfig
59
+ base_model_prefix = "fuyu"
60
+ supports_gradient_checkpointing = True
61
+ _no_split_modules = []
62
+ _skip_keys_device_placement = "past_key_values"
63
+
64
+ def _init_weights(self, module):
65
+ std = self.config.initializer_range
66
+ if isinstance(module, nn.Linear):
67
+ module.weight.data.normal_(mean=0.0, std=std)
68
+ if module.bias is not None:
69
+ module.bias.data.zero_()
70
+ elif isinstance(module, nn.Embedding):
71
+ module.weight.data.normal_(mean=0.0, std=std)
72
+ if module.padding_idx is not None:
73
+ module.weight.data[module.padding_idx].zero_()
74
+
75
+
76
+ FUYU_INPUTS_DOCSTRING = r"""
77
+ Args:
78
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
79
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
80
+ it.
81
+
82
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
83
+ [`PreTrainedTokenizer.__call__`] for details.
84
+
85
+ [What are input IDs?](../glossary#input-ids)
86
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
87
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
88
+
89
+ - 1 for tokens that are **not masked**,
90
+ - 0 for tokens that are **masked**.
91
+
92
+ [What are attention masks?](../glossary#attention-mask)
93
+
94
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
95
+ [`PreTrainedTokenizer.__call__`] for details.
96
+
97
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
98
+ `past_key_values`).
99
+
100
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
101
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
102
+ information on the default strategy.
103
+
104
+ - 1 indicates the head is **not masked**,
105
+ - 0 indicates the head is **masked**.
106
+ image_patches (`torch.FloatTensor` of shape `(batch_size, num_total_patches, patch_size_ x patch_size x num_channels)`, *optional*):
107
+ Image patches to be used as continuous embeddings. The patches are flattened and then projected to the
108
+ hidden size of the model.
109
+ image_patches_indices (`torch.LongTensor` of shape `(batch_size, num_total_patches + number_of_newline_tokens + number_of_text_tokens, patch_size_ x patch_size x num_channels )`, *optional*):
110
+ Indices indicating at which position the image_patches have to be inserted in input_embeds.
111
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
112
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
113
+ config.n_positions - 1]`.
114
+
115
+ [What are position IDs?](../glossary#position-ids)
116
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
117
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
118
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
119
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
120
+
121
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
122
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
123
+
124
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
125
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
126
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
127
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
128
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
129
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
130
+ model's internal embedding lookup matrix.
131
+ use_cache (`bool`, *optional*):
132
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
133
+ `past_key_values`).
134
+ output_attentions (`bool`, *optional*):
135
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
136
+ tensors for more detail.
137
+ output_hidden_states (`bool`, *optional*):
138
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
139
+ more detail.
140
+ return_dict (`bool`, *optional*):
141
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
142
+ """
143
+
144
+
145
+ @add_start_docstrings(
146
+ "Fuyu Model with a language modeling head on top for causal language model conditioned on image patches and text.",
147
+ FUYU_START_DOCSTRING,
148
+ )
149
+ class FuyuForCausalLM(FuyuPreTrainedModel, GenerationMixin):
150
+ def __init__(self, config: FuyuConfig):
151
+ super().__init__(config)
152
+ self.padding_idx = config.pad_token_id
153
+ self.vocab_size = config.text_config.vocab_size
154
+ self.language_model = AutoModelForCausalLM.from_config(
155
+ config.text_config, attn_implementation=config._attn_implementation
156
+ )
157
+
158
+ self.vision_embed_tokens = nn.Linear(
159
+ config.patch_size * config.patch_size * config.num_channels, config.hidden_size
160
+ )
161
+
162
+ self.gradient_checkpointing = False
163
+ # Initialize weights and apply final processing
164
+ self.post_init()
165
+
166
+ def get_input_embeddings(self):
167
+ return self.language_model.get_input_embeddings()
168
+
169
+ def set_input_embeddings(self, value):
170
+ self.language_model.set_input_embeddings(value)
171
+
172
+ def get_output_embeddings(self):
173
+ return self.language_model.get_output_embeddings()
174
+
175
+ def set_output_embeddings(self, new_embeddings):
176
+ self.language_model.set_output_embeddings(new_embeddings)
177
+
178
+ def set_decoder(self, decoder):
179
+ self.language_model.set_decoder(decoder)
180
+
181
+ def get_decoder(self):
182
+ return self.language_model.get_decoder()
183
+
184
+ def tie_weights(self):
185
+ return self.language_model.tie_weights()
186
+
187
+ def gather_continuous_embeddings(
188
+ self,
189
+ word_embeddings: torch.Tensor,
190
+ continuous_embeddings: List[torch.Tensor],
191
+ image_patch_input_indices: torch.Tensor,
192
+ ) -> torch.Tensor:
193
+ """This function places the continuous_embeddings into the word_embeddings at the locations
194
+ indicated by image_patch_input_indices. Different batch elements can have different numbers of continuous
195
+ embeddings.
196
+
197
+ Args:
198
+ word_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
199
+ Tensor of word embeddings.
200
+ continuous_embeddings (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`):
201
+ Tensor of continuous embeddings. The length of the list is the batch size. Each entry is shape
202
+ [num_image_embeddings, hidden], and num_image_embeddings needs to match the number of non-negative
203
+ indices in image_patch_input_indices for that batch element.
204
+ image_patch_input_indices (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
205
+ Tensor of indices of the image patches in the input_ids tensor.
206
+ """
207
+ if not (word_embeddings.shape[0] == len(continuous_embeddings)):
208
+ raise ValueError(
209
+ f"Batch sizes must match! Got {len(continuous_embeddings)=} and {word_embeddings.shape[0]=}"
210
+ )
211
+
212
+ output_embeddings = word_embeddings.clone()
213
+ for batch_idx in range(word_embeddings.shape[0]):
214
+ # First, find the positions of all the non-negative values in image_patch_input_indices, those are the
215
+ # positions in word_embeddings that we want to replace with content from continuous_embeddings.
216
+ dst_indices = torch.nonzero(image_patch_input_indices[batch_idx] >= 0, as_tuple=True)[0]
217
+ # Next look up those indices in image_patch_input_indices to find the indices in continuous_embeddings that we
218
+ # want to use to replace the values in word_embeddings.
219
+ src_indices = image_patch_input_indices[batch_idx][dst_indices]
220
+ # Check if we have more indices than embeddings. Note that we could have fewer indices if images got truncated.
221
+ if src_indices.shape[0] > continuous_embeddings[batch_idx].shape[0]:
222
+ raise ValueError(
223
+ f"Number of continuous embeddings {continuous_embeddings[batch_idx].shape=} does not match "
224
+ f"number of continuous token ids {src_indices.shape=} in batch element {batch_idx}."
225
+ )
226
+ output_embeddings[batch_idx, dst_indices] = continuous_embeddings[batch_idx][src_indices]
227
+ return output_embeddings
228
+
229
+ @add_start_docstrings_to_model_forward(FUYU_INPUTS_DOCSTRING)
230
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
231
+ def forward(
232
+ self,
233
+ input_ids: torch.LongTensor = None,
234
+ image_patches: torch.Tensor = None, # [batch_size, num_total_patches, patch_size_ x patch_size x num_channels ]
235
+ image_patches_indices: torch.Tensor = None,
236
+ attention_mask: Optional[torch.Tensor] = None,
237
+ position_ids: Optional[torch.LongTensor] = None,
238
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
239
+ inputs_embeds: Optional[torch.FloatTensor] = None,
240
+ use_cache: Optional[bool] = None,
241
+ labels: Optional[torch.Tensor] = None,
242
+ output_attentions: Optional[bool] = None,
243
+ output_hidden_states: Optional[bool] = None,
244
+ return_dict: Optional[bool] = None,
245
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
246
+ r"""
247
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
248
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
249
+ config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
250
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
251
+
252
+ Returns:
253
+
254
+ Examples:
255
+
256
+ ```python
257
+ >>> from transformers import FuyuProcessor, FuyuForCausalLM
258
+ >>> from PIL import Image
259
+ >>> import requests
260
+
261
+ >>> processor = FuyuProcessor.from_pretrained("adept/fuyu-8b")
262
+ >>> model = FuyuForCausalLM.from_pretrained("adept/fuyu-8b")
263
+
264
+ >>> url = "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/bus.png"
265
+ >>> image = Image.open(requests.get(url, stream=True).raw)
266
+ >>> prompt = "Generate a coco-style caption.\n"
267
+
268
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
269
+ >>> outputs = model(**inputs)
270
+
271
+ >>> generated_ids = model.generate(**inputs, max_new_tokens=7)
272
+ >>> generation_text = processor.batch_decode(generated_ids[:, -7:], skip_special_tokens=True)
273
+ >>> print(generation_text[0])
274
+ A blue bus parked on the side of a road.
275
+ ```"""
276
+
277
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
278
+ output_hidden_states = (
279
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
280
+ )
281
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
282
+
283
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
284
+
285
+ if input_ids is not None and inputs_embeds is not None:
286
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
287
+ elif input_ids is not None:
288
+ batch_size, seq_length = input_ids.shape
289
+ elif inputs_embeds is not None:
290
+ batch_size, seq_length, _ = inputs_embeds.shape
291
+ else:
292
+ raise ValueError("You have to specify either input_is or inputs_embeds")
293
+
294
+ seq_length_with_past = seq_length
295
+ past_key_values_length = 0
296
+
297
+ if past_key_values is not None:
298
+ past_key_values_length = past_key_values[0][0].shape[2]
299
+ seq_length_with_past = seq_length_with_past + past_key_values_length
300
+
301
+ if position_ids is None:
302
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
303
+ position_ids = torch.arange(
304
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
305
+ )
306
+ position_ids = position_ids.unsqueeze(0)
307
+
308
+ if inputs_embeds is None:
309
+ inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
310
+ if image_patches is not None and past_key_values is None:
311
+ patch_embeddings = [
312
+ self.vision_embed_tokens(patch.to(self.vision_embed_tokens.weight.dtype))
313
+ .squeeze(0)
314
+ .to(inputs_embeds.device)
315
+ for patch in image_patches
316
+ ]
317
+ inputs_embeds = self.gather_continuous_embeddings(
318
+ word_embeddings=inputs_embeds,
319
+ continuous_embeddings=patch_embeddings,
320
+ image_patch_input_indices=image_patches_indices,
321
+ )
322
+
323
+ outputs = self.language_model(
324
+ inputs_embeds=inputs_embeds,
325
+ attention_mask=attention_mask,
326
+ position_ids=position_ids,
327
+ past_key_values=past_key_values,
328
+ output_attentions=output_attentions,
329
+ output_hidden_states=output_hidden_states,
330
+ labels=labels,
331
+ use_cache=use_cache,
332
+ return_dict=return_dict,
333
+ )
334
+
335
+ return outputs
336
+
337
+ def prepare_inputs_for_generation(
338
+ self,
339
+ input_ids,
340
+ past_key_values=None,
341
+ attention_mask=None,
342
+ inputs_embeds=None,
343
+ image_patches=None,
344
+ image_patches_indices=None,
345
+ **kwargs,
346
+ ):
347
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
348
+
349
+ if past_key_values is not None:
350
+ input_ids = input_ids[:, -1:]
351
+
352
+ position_ids = kwargs.get("position_ids", None)
353
+ if attention_mask is not None and position_ids is None:
354
+ # create position_ids on the fly for batch generation
355
+ position_ids = attention_mask.long().cumsum(-1) - 1
356
+ position_ids.masked_fill_(attention_mask == 0, 1)
357
+ if past_key_values:
358
+ position_ids = position_ids[:, -1:]
359
+
360
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
361
+ if inputs_embeds is not None and past_key_values is None:
362
+ model_inputs = {"inputs_embeds": inputs_embeds}
363
+ else:
364
+ model_inputs = {"input_ids": input_ids}
365
+
366
+ if image_patches_indices is not None:
367
+ model_inputs["image_patches_indices"] = image_patches_indices
368
+
369
+ model_inputs.update(
370
+ {
371
+ "position_ids": position_ids,
372
+ "past_key_values": past_key_values,
373
+ "use_cache": kwargs.get("use_cache"),
374
+ "attention_mask": attention_mask,
375
+ "image_patches_indices": image_patches_indices if past_key_values is None else None,
376
+ "image_patches": image_patches if past_key_values is None else None,
377
+ }
378
+ )
379
+ return model_inputs
380
+
381
+ @staticmethod
382
+ def _reorder_cache(past_key_values, beam_idx):
383
+ reordered_past = ()
384
+ for layer_past in past_key_values:
385
+ reordered_past += (
386
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
387
+ )
388
+ return reordered_past
389
+
390
+
391
+ __all__ = ["FuyuForCausalLM", "FuyuPreTrainedModel"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/fuyu/processing_fuyu.py ADDED
@@ -0,0 +1,726 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Image/Text processor class for GIT
17
+ """
18
+
19
+ import re
20
+ from typing import Dict, List, Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+
24
+ from ...image_utils import ImageInput
25
+ from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack, _validate_images_text_input_order
26
+ from ...tokenization_utils_base import PreTokenizedInput, TextInput
27
+ from ...utils import is_torch_available, logging, requires_backends
28
+
29
+
30
+ if is_torch_available():
31
+ from .image_processing_fuyu import FuyuBatchFeature
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ if is_torch_available():
38
+ import torch
39
+
40
+
41
+ TEXT_REPR_BBOX_OPEN = "<box>"
42
+ TEXT_REPR_BBOX_CLOSE = "</box>"
43
+ TEXT_REPR_POINT_OPEN = "<point>"
44
+ TEXT_REPR_POINT_CLOSE = "</point>"
45
+
46
+ TOKEN_BBOX_OPEN_STRING = "<0x00>" # <bbox>
47
+ TOKEN_BBOX_CLOSE_STRING = "<0x01>" # </bbox>
48
+ TOKEN_POINT_OPEN_STRING = "<0x02>" # <point>
49
+ TOKEN_POINT_CLOSE_STRING = "<0x03>" # </point>
50
+ BEGINNING_OF_ANSWER_STRING = "<0x04>" # <boa>
51
+
52
+
53
+ class FuyuProcessorKwargs(ProcessingKwargs, total=False):
54
+ _defaults = {
55
+ "text_kwargs": {
56
+ "add_special_tokens": True,
57
+ "padding": False,
58
+ "stride": 0,
59
+ "return_attention_mask": True,
60
+ "return_overflowing_tokens": False,
61
+ "return_special_tokens_mask": False,
62
+ "return_offsets_mapping": False,
63
+ "return_token_type_ids": False,
64
+ "return_length": False,
65
+ "verbose": True,
66
+ },
67
+ "images_kwargs": {},
68
+ }
69
+
70
+
71
+ def full_unpacked_stream_to_tensor(
72
+ all_bi_tokens_to_place: List[int],
73
+ full_unpacked_stream: List["torch.Tensor"],
74
+ fill_value: int,
75
+ batch_size: int,
76
+ new_seq_len: int,
77
+ offset: int,
78
+ ) -> "torch.Tensor":
79
+ """Takes an unpacked stream of tokens (i.e. a list of tensors, one for each item in the batch) and does
80
+ the required padding to create a single tensor for the batch of shape batch_size x new_seq_len.
81
+ """
82
+
83
+ assert len(all_bi_tokens_to_place) == batch_size
84
+ assert len(full_unpacked_stream) == batch_size
85
+
86
+ # Create padded tensors for the full batch.
87
+ new_padded_tensor = torch.full(
88
+ [batch_size, new_seq_len],
89
+ fill_value=fill_value,
90
+ dtype=full_unpacked_stream[0].dtype,
91
+ device=full_unpacked_stream[0].device,
92
+ )
93
+
94
+ # Place each batch entry into the batch tensor.
95
+ for bi in range(batch_size):
96
+ tokens_to_place = all_bi_tokens_to_place[bi]
97
+ new_padded_tensor[bi, :tokens_to_place] = full_unpacked_stream[bi][offset : tokens_to_place + offset]
98
+
99
+ return new_padded_tensor
100
+
101
+
102
+ def construct_full_unpacked_stream(
103
+ num_real_text_tokens: Union[List[List[int]], "torch.Tensor"],
104
+ input_stream: "torch.Tensor",
105
+ image_tokens: List[List["torch.Tensor"]],
106
+ batch_size: int,
107
+ num_sub_sequences: int,
108
+ ) -> List["torch.Tensor"]:
109
+ """Takes an input_stream tensor of shape B x S x ?. For each subsequence, adds any required
110
+ padding to account for images and then unpacks the subsequences to create a single sequence per item in the batch.
111
+ Returns a list of tensors, one for each item in the batch."""
112
+
113
+ all_bi_stream = []
114
+
115
+ for batch_index in range(batch_size):
116
+ all_si_stream = []
117
+
118
+ # First, construct full token stream (including image placeholder tokens) and loss mask for each subsequence
119
+ # and append to lists. We use lists rather than tensors because each subsequence is variable-sized.
120
+ # TODO Remove this logic in a subsequent release since subsequences are not supported.
121
+ image_adjustment = image_tokens[batch_index][0]
122
+ subsequence_stream = torch.cat([image_adjustment, input_stream[batch_index, 0]], dim=0)
123
+ num_real_tokens = image_adjustment.shape[0] + num_real_text_tokens[batch_index][0]
124
+ all_si_stream.append(subsequence_stream[:num_real_tokens])
125
+ all_bi_stream.append(torch.cat(all_si_stream, dim=0))
126
+
127
+ return all_bi_stream
128
+
129
+
130
+ def _replace_string_repr_with_token_tags(prompt: str) -> str:
131
+ prompt = prompt.replace(TEXT_REPR_POINT_OPEN, TOKEN_POINT_OPEN_STRING)
132
+ prompt = prompt.replace(TEXT_REPR_POINT_CLOSE, TOKEN_POINT_CLOSE_STRING)
133
+ prompt = prompt.replace(TEXT_REPR_BBOX_OPEN, TOKEN_BBOX_OPEN_STRING)
134
+ prompt = prompt.replace(TEXT_REPR_BBOX_CLOSE, TOKEN_BBOX_CLOSE_STRING)
135
+ return prompt
136
+
137
+
138
+ def _segment_prompt_into_text_token_conversions(prompt: str) -> List:
139
+ """
140
+ Given a string prompt, converts the prompt into a list of TextTokenConversions.
141
+ """
142
+ # Wherever, we notice the [TOKEN_OPEN_STRING, TOKEN_CLOSE_STRING], we split the prompt
143
+ prompt_text_list: List = []
144
+ regex_pattern = re.compile(
145
+ f"({TOKEN_BBOX_OPEN_STRING}|{TOKEN_BBOX_CLOSE_STRING}|{TOKEN_POINT_OPEN_STRING}|{TOKEN_POINT_CLOSE_STRING})"
146
+ )
147
+ # Split by the regex pattern
148
+ prompt_split = regex_pattern.split(prompt)
149
+ for i, elem in enumerate(prompt_split):
150
+ if len(elem) == 0 or elem in [
151
+ TOKEN_BBOX_OPEN_STRING,
152
+ TOKEN_BBOX_CLOSE_STRING,
153
+ TOKEN_POINT_OPEN_STRING,
154
+ TOKEN_POINT_CLOSE_STRING,
155
+ ]:
156
+ continue
157
+ prompt_text_list.append(
158
+ (elem, i > 1 and prompt_split[i - 1] in [TOKEN_BBOX_OPEN_STRING, TOKEN_POINT_OPEN_STRING])
159
+ )
160
+ return prompt_text_list
161
+
162
+
163
+ def _transform_coordinates_and_tokenize(prompt: str, scale_factor: float, tokenizer) -> List[int]:
164
+ """
165
+ This function transforms the prompt in the following fashion:
166
+ - <box> <point> and </box> </point> to their respective token mappings
167
+ - extract the coordinates from the tag
168
+ - transform the coordinates into the transformed image space
169
+ - return the prompt tokens with the transformed coordinates and new tags
170
+
171
+ Bounding boxes and points MUST be in the following format: <box>y1, x1, y2, x2</box> <point>x, y</point> The spaces
172
+ and punctuation added above are NOT optional.
173
+ """
174
+ # Make a namedtuple that stores "text" and "is_bbox"
175
+
176
+ # We want to do the following: Tokenize the code normally -> when we see a point or box, tokenize using the tokenize_within_tag function
177
+ # When point or box close tag, continue tokenizing normally
178
+ # First, we replace the point and box tags with their respective tokens
179
+ prompt = _replace_string_repr_with_token_tags(prompt)
180
+ # Tokenize the prompt
181
+ # Convert prompt into a list split
182
+ prompt_text_list = _segment_prompt_into_text_token_conversions(prompt)
183
+ transformed_prompt_tokens: List[int] = []
184
+ for elem in prompt_text_list:
185
+ if elem[1]:
186
+ # This is a location, we need to tokenize it
187
+ within_tag_tokenized = _transform_within_tags(elem[0], scale_factor, tokenizer)
188
+ # Surround the text with the open and close tags
189
+ transformed_prompt_tokens.extend(within_tag_tokenized)
190
+ else:
191
+ transformed_prompt_tokens.extend(tokenizer(elem[0], add_special_tokens=False).input_ids)
192
+ return transformed_prompt_tokens
193
+
194
+
195
+ def _transform_within_tags(text: str, scale_factor: float, tokenizer) -> List[int]:
196
+ """
197
+ Given a bounding box of the fashion <box>1, 2, 3, 4</box> | <point>1, 2</point> This function is responsible for
198
+ converting 1, 2, 3, 4 into tokens of 1 2 3 4 without any commas.
199
+ """
200
+ # Convert the text into a list of strings.
201
+ num_int_strs = text.split(",")
202
+ if len(num_int_strs) == 2:
203
+ # If there are any open or close tags, remove them.
204
+ token_space_open_string = tokenizer.vocab[TOKEN_POINT_OPEN_STRING]
205
+ token_space_close_string = tokenizer.vocab[TOKEN_POINT_CLOSE_STRING]
206
+ else:
207
+ token_space_open_string = tokenizer.vocab[TOKEN_BBOX_OPEN_STRING]
208
+ token_space_close_string = tokenizer.vocab[TOKEN_BBOX_CLOSE_STRING]
209
+
210
+ # Remove all spaces from num_ints
211
+ num_ints = [float(num.strip()) for num in num_int_strs]
212
+ # scale to transformed image siz
213
+ if len(num_ints) == 2:
214
+ num_ints_translated = scale_point_to_transformed_image(x=num_ints[0], y=num_ints[1], scale_factor=scale_factor)
215
+ elif len(num_ints) == 4:
216
+ num_ints_translated = scale_bbox_to_transformed_image(
217
+ top=num_ints[0],
218
+ left=num_ints[1],
219
+ bottom=num_ints[2],
220
+ right=num_ints[3],
221
+ scale_factor=scale_factor,
222
+ )
223
+ else:
224
+ raise ValueError(f"Invalid number of ints: {len(num_ints)}")
225
+ # Tokenize the text, skipping the
226
+ tokens = [tokenizer.vocab[str(num)] for num in num_ints_translated]
227
+ return [token_space_open_string] + tokens + [token_space_close_string]
228
+
229
+
230
+ def _tokenize_prompts_with_image_and_batch(
231
+ tokenizer,
232
+ prompts: List[List[str]],
233
+ scale_factors: Optional[List[List["torch.Tensor"]]],
234
+ max_tokens_to_generate: int,
235
+ max_position_embeddings: int,
236
+ add_BOS: bool, # Same issue with types as above
237
+ add_beginning_of_answer_token: bool,
238
+ ) -> Tuple["torch.Tensor", "torch.Tensor"]:
239
+ """
240
+ Given a set of prompts and number of tokens to generate:
241
+ - tokenize prompts
242
+ - set the sequence length to be the max of length of prompts plus the number of tokens we would like to generate
243
+ - pad all the sequences to this length so we can convert them into a 3D tensor.
244
+ """
245
+
246
+ # If not tool use, tranform the coordinates while tokenizing
247
+ if scale_factors is not None:
248
+ transformed_prompt_tokens = []
249
+ for prompt_seq, scale_factor_seq in zip(prompts, scale_factors):
250
+ transformed_prompt_tokens.append(
251
+ [
252
+ _transform_coordinates_and_tokenize(prompt, scale_factor.item(), tokenizer)
253
+ for prompt, scale_factor in zip(prompt_seq, scale_factor_seq)
254
+ ]
255
+ )
256
+ else:
257
+ transformed_prompt_tokens = [[tokenizer.tokenize(prompt) for prompt in prompt_seq] for prompt_seq in prompts]
258
+
259
+ prompts_tokens = transformed_prompt_tokens
260
+
261
+ if add_BOS:
262
+ bos_token = tokenizer.vocab["<s>"]
263
+ else:
264
+ bos_token = tokenizer.vocab["|ENDOFTEXT|"]
265
+ prompts_tokens = [[[bos_token] + x for x in prompt_seq] for prompt_seq in prompts_tokens]
266
+ if add_beginning_of_answer_token:
267
+ beginning_of_answer = tokenizer.vocab[BEGINNING_OF_ANSWER_STRING]
268
+ # Only add bbox open token to the last subsequence since that is what will be completed
269
+ for token_seq in prompts_tokens:
270
+ token_seq[-1].append(beginning_of_answer)
271
+
272
+ # Now we have a list of list of tokens which each list has a different
273
+ # size. We want to extend this list to:
274
+ # - incorporate the tokens that need to be generated
275
+ # - make all the sequences equal length.
276
+ # Get the prompts length.
277
+
278
+ prompts_length = [[len(x) for x in prompts_tokens_seq] for prompts_tokens_seq in prompts_tokens]
279
+ # Get the max prompts length.
280
+ max_prompt_len: int = np.max(prompts_length)
281
+ # Number of tokens in the each sample of the batch.
282
+ samples_length = min(max_prompt_len + max_tokens_to_generate, max_position_embeddings)
283
+ if max_prompt_len + max_tokens_to_generate > max_position_embeddings:
284
+ logger.warning(
285
+ f"Max subsequence prompt length of {max_prompt_len} + max tokens to generate {max_tokens_to_generate}",
286
+ f"exceeds context length of {max_position_embeddings}. Will generate as many tokens as possible.",
287
+ )
288
+ # Now update the list of list to be of the same size: samples_length.
289
+ for prompt_tokens_seq, prompts_length_seq in zip(prompts_tokens, prompts_length):
290
+ for prompt_tokens, prompt_length in zip(prompt_tokens_seq, prompts_length_seq):
291
+ if len(prompt_tokens) > samples_length:
292
+ raise ValueError("Length of subsequence prompt exceeds sequence length.")
293
+ padding_size = samples_length - prompt_length
294
+ prompt_tokens.extend([tokenizer.vocab["|ENDOFTEXT|"]] * padding_size)
295
+
296
+ # Now we are in a structured format, we can convert to tensors.
297
+ prompts_tokens_tensor = torch.tensor(prompts_tokens, dtype=torch.int64)
298
+ prompts_length_tensor = torch.tensor(prompts_length, dtype=torch.int64)
299
+
300
+ return prompts_tokens_tensor, prompts_length_tensor
301
+
302
+
303
+ # Simplified assuming self.crop_top = self.padding_top = 0
304
+ def original_to_transformed_h_coords(original_coords, scale_h):
305
+ return np.round(original_coords * scale_h).astype(np.int32)
306
+
307
+
308
+ # Simplified assuming self.crop_left = self.padding_left = 0
309
+ def original_to_transformed_w_coords(original_coords, scale_w):
310
+ return np.round(original_coords * scale_w).astype(np.int32)
311
+
312
+
313
+ def scale_point_to_transformed_image(x: float, y: float, scale_factor: float) -> List[int]:
314
+ x_scaled = original_to_transformed_w_coords(np.array([x / 2]), scale_factor)[0]
315
+ y_scaled = original_to_transformed_h_coords(np.array([y / 2]), scale_factor)[0]
316
+ return [x_scaled, y_scaled]
317
+
318
+
319
+ def scale_bbox_to_transformed_image(
320
+ top: float, left: float, bottom: float, right: float, scale_factor: float
321
+ ) -> List[int]:
322
+ top_scaled = original_to_transformed_w_coords(np.array([top / 2]), scale_factor)[0]
323
+ left_scaled = original_to_transformed_h_coords(np.array([left / 2]), scale_factor)[0]
324
+ bottom_scaled = original_to_transformed_w_coords(np.array([bottom / 2]), scale_factor)[0]
325
+ right_scaled = original_to_transformed_h_coords(np.array([right / 2]), scale_factor)[0]
326
+ return [top_scaled, left_scaled, bottom_scaled, right_scaled]
327
+
328
+
329
+ class FuyuProcessor(ProcessorMixin):
330
+ r"""
331
+ Constructs a Fuyu processor which wraps a Fuyu image processor and a Llama tokenizer into a single processor.
332
+
333
+ [`FuyuProcessor`] offers all the functionalities of [`FuyuImageProcessor`] and [`LlamaTokenizerFast`]. See the
334
+ [`~FuyuProcessor.__call__`] and [`~FuyuProcessor.decode`] for more information.
335
+
336
+ Args:
337
+ image_processor ([`FuyuImageProcessor`]):
338
+ The image processor is a required input.
339
+ tokenizer ([`LlamaTokenizerFast`]):
340
+ The tokenizer is a required input.
341
+ """
342
+
343
+ attributes = ["image_processor", "tokenizer"]
344
+ valid_kwargs = []
345
+ image_processor_class = "FuyuImageProcessor"
346
+ tokenizer_class = "AutoTokenizer"
347
+
348
+ def __init__(self, image_processor, tokenizer, **kwargs):
349
+ super().__init__(image_processor=image_processor, tokenizer=tokenizer)
350
+ self.image_processor = image_processor
351
+ self.tokenizer = tokenizer
352
+ self.max_tokens_to_generate = 10
353
+ self.max_position_embeddings = 16384 # TODO Can't derive this from model files: where to set it?
354
+ self.pad_token_id = 0
355
+ self.dummy_image_index = -1
356
+
357
+ def _left_pad_inputs_with_attention_mask(self, model_inputs: List[Dict], return_attention_mask: bool):
358
+ max_length_input_ids = max(entry["input_ids"].shape[1] for entry in model_inputs)
359
+ max_length_image_patch_indices = max(entry["image_patches_indices"].shape[1] for entry in model_inputs)
360
+
361
+ batched_inputs = {"input_ids": [], "image_patches": [], "image_patches_indices": [], "attention_mask": []}
362
+
363
+ for entry in model_inputs:
364
+ for key, tensor in entry.items():
365
+ if key == "input_ids":
366
+ num_padding_tokens = max_length_input_ids - tensor.shape[1]
367
+ padded_input_ids = torch.cat(
368
+ [
369
+ torch.full((tensor.shape[0], num_padding_tokens), self.pad_token_id, dtype=torch.long),
370
+ tensor,
371
+ ],
372
+ dim=1,
373
+ )
374
+ batched_inputs[key].append(padded_input_ids)
375
+
376
+ attention_mask = torch.cat(
377
+ [torch.zeros(tensor.shape[0], num_padding_tokens, dtype=torch.long), torch.ones_like(tensor)],
378
+ dim=1,
379
+ )
380
+ batched_inputs["attention_mask"].append(attention_mask)
381
+
382
+ elif key == "image_patches":
383
+ # For image_patches, we don't pad but just append them to the list.
384
+ batched_inputs[key].append(tensor)
385
+
386
+ else: # for image_patches_indices
387
+ num_padding_indices = max_length_image_patch_indices - tensor.shape[1]
388
+ padded_indices = torch.cat(
389
+ [
390
+ torch.full(
391
+ (tensor.shape[0], num_padding_indices), self.dummy_image_index, dtype=torch.long
392
+ ),
393
+ tensor,
394
+ ],
395
+ dim=1,
396
+ )
397
+ batched_inputs[key].append(padded_indices)
398
+ batched_keys = ["input_ids", "image_patches_indices"]
399
+ if return_attention_mask:
400
+ batched_keys.append("attention_mask")
401
+ for key in batched_keys:
402
+ batched_inputs[key] = torch.cat(batched_inputs[key], dim=0)
403
+
404
+ return batched_inputs
405
+
406
+ def get_sample_encoding(
407
+ self,
408
+ prompts,
409
+ scale_factors,
410
+ image_unpadded_heights,
411
+ image_unpadded_widths,
412
+ image_placeholder_id,
413
+ image_newline_id,
414
+ tensor_batch_images,
415
+ ):
416
+ image_present = torch.ones(1, 1, 1)
417
+ model_image_input = self.image_processor.preprocess_with_tokenizer_info(
418
+ image_input=tensor_batch_images,
419
+ image_present=image_present,
420
+ image_unpadded_h=image_unpadded_heights,
421
+ image_unpadded_w=image_unpadded_widths,
422
+ image_placeholder_id=image_placeholder_id,
423
+ image_newline_id=image_newline_id,
424
+ variable_sized=True,
425
+ )
426
+ # FIXME max_tokens_to_generate is embedded into this processor's call.
427
+ prompt_tokens, prompts_length = _tokenize_prompts_with_image_and_batch(
428
+ tokenizer=self.tokenizer,
429
+ prompts=prompts,
430
+ scale_factors=scale_factors,
431
+ max_tokens_to_generate=self.max_tokens_to_generate,
432
+ max_position_embeddings=self.max_position_embeddings,
433
+ add_BOS=True,
434
+ add_beginning_of_answer_token=True,
435
+ )
436
+ image_padded_unpacked_tokens = construct_full_unpacked_stream(
437
+ num_real_text_tokens=prompts_length,
438
+ input_stream=prompt_tokens,
439
+ image_tokens=model_image_input["image_input_ids"],
440
+ batch_size=1,
441
+ num_sub_sequences=self.subsequence_length,
442
+ )
443
+ # Construct inputs for image patch indices.
444
+ unpacked_image_patch_indices_per_batch = construct_full_unpacked_stream(
445
+ num_real_text_tokens=prompts_length,
446
+ input_stream=torch.full_like(prompt_tokens, -1),
447
+ image_tokens=model_image_input["image_patch_indices_per_batch"],
448
+ batch_size=1,
449
+ num_sub_sequences=self.subsequence_length,
450
+ )
451
+ max_prompt_length = max(x.shape[-1] for x in image_padded_unpacked_tokens)
452
+ max_seq_len_batch = min(max_prompt_length + self.max_tokens_to_generate, self.max_position_embeddings)
453
+ tokens_to_place = min(max_seq_len_batch, max(0, image_padded_unpacked_tokens[0].shape[0]))
454
+
455
+ # Use same packing logic for the image patch indices.
456
+ image_patch_input_indices = full_unpacked_stream_to_tensor(
457
+ all_bi_tokens_to_place=[tokens_to_place],
458
+ full_unpacked_stream=unpacked_image_patch_indices_per_batch,
459
+ fill_value=-1,
460
+ batch_size=1,
461
+ new_seq_len=max_seq_len_batch,
462
+ offset=0,
463
+ )
464
+ image_patches_tensor = torch.stack([img[0] for img in model_image_input["image_patches"]])
465
+ batch_encoding = {
466
+ "input_ids": image_padded_unpacked_tokens[0].unsqueeze(0),
467
+ "image_patches": image_patches_tensor,
468
+ "image_patches_indices": image_patch_input_indices,
469
+ }
470
+ return batch_encoding
471
+
472
+ def __call__(
473
+ self,
474
+ images: ImageInput = None,
475
+ text: Optional[Union[str, List[str], TextInput, PreTokenizedInput]] = None,
476
+ audio=None,
477
+ videos=None,
478
+ **kwargs: Unpack[FuyuProcessorKwargs],
479
+ ) -> "FuyuBatchFeature":
480
+ """
481
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
482
+ and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to
483
+ encode the text. To prepare the image(s), this method forwards the `images` and `kwargs` arguments to
484
+ FuyuImageProcessor's [`~FuyuImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring
485
+ of the above two methods for more information.
486
+
487
+ Args:
488
+ images (`PIL.Image.Image`, `List[PIL.Image.Image]`):
489
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
490
+ tensor. Both channels-first and channels-last formats are supported.
491
+ text (`str`, `List[str]`):
492
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
493
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
494
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
495
+
496
+ Returns:
497
+ [`FuyuBatchEncoding`]: A [`FuyuBatchEncoding`] with the following fields:
498
+
499
+ - **input_ids** -- Tensor of token ids to be fed to a model. Returned when `text` is not `None`.
500
+ - **image_patches** -- List of Tensor of image patches. Returned when `images` is not `None`.
501
+ - **image_patches_indices** -- Tensor of indices where patch embeddings have to be inserted by the model.
502
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model when
503
+ `return_attention_mask=True`.
504
+ """
505
+ requires_backends(self, ["torch"])
506
+
507
+ # --- Check input validity ---
508
+ if text is None and images is None:
509
+ raise ValueError("You have to specify either text or images. Both cannot be None.")
510
+ # check if images and text inputs are reversed for BC
511
+ images, text = _validate_images_text_input_order(images, text)
512
+
513
+ output_kwargs = self._merge_kwargs(
514
+ FuyuProcessorKwargs,
515
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
516
+ **kwargs,
517
+ )
518
+
519
+ if not output_kwargs["text_kwargs"].setdefault("return_attention_mask", True):
520
+ raise ValueError("`return_attention_mask=False` is not supported for this model.")
521
+
522
+ if text is not None and images is None:
523
+ logger.warning("You are processing a text with no associated image. Make sure it is intended.")
524
+ self.current_processor = self.tokenizer
525
+ text_encoding = self.tokenizer(text, **output_kwargs["text_kwargs"])
526
+ return text_encoding
527
+
528
+ if text is None and images is not None:
529
+ logger.warning("You are processing an image with no associated text. Make sure it is intended.")
530
+ prompts = [[""]]
531
+ if text is not None and images is not None:
532
+ if isinstance(text, str):
533
+ prompts = [[text]]
534
+ elif isinstance(text, list):
535
+ prompts = [[text_seq] for text_seq in text]
536
+
537
+ # --- Preprocess images using self.image_processor ---
538
+
539
+ # FIXME - We hard code "pt" here because the rest of the processing assumes torch tensors
540
+ output_kwargs["images_kwargs"]["return_tensors"] = "pt"
541
+ image_encoding = self.image_processor.preprocess(images, **output_kwargs["images_kwargs"])
542
+ batch_images = image_encoding["images"]
543
+ image_unpadded_heights = image_encoding["image_unpadded_heights"]
544
+ image_unpadded_widths = image_encoding["image_unpadded_widths"]
545
+ scale_factors = image_encoding["image_scale_factors"]
546
+ self.subsequence_length = 1 # Each batch contains only one sequence.
547
+ self.batch_size = len(batch_images)
548
+
549
+ # --- Use self.tokenizer to get the ids of special tokens to insert into image ids ---
550
+
551
+ image_placeholder_id = self.tokenizer("|SPEAKER|", add_special_tokens=False)["input_ids"][1]
552
+ image_newline_id = self.tokenizer("|NEWLINE|", add_special_tokens=False)["input_ids"][1]
553
+ tensor_batch_images = torch.stack([img[0] for img in batch_images]).unsqueeze(1)
554
+
555
+ # --- Use self.image_processor again to obtain the full token ids and batch inputs ---
556
+ all_encodings = []
557
+
558
+ for prompt, scale_factor, image_unpadded_height, image_unpadded_width, tensor_batch_image in zip(
559
+ prompts, scale_factors, image_unpadded_heights, image_unpadded_widths, tensor_batch_images
560
+ ):
561
+ sample_encoding = self.get_sample_encoding(
562
+ prompts=[prompt],
563
+ scale_factors=[scale_factor],
564
+ image_unpadded_heights=torch.tensor([image_unpadded_height]),
565
+ image_unpadded_widths=torch.tensor([image_unpadded_width]),
566
+ image_placeholder_id=image_placeholder_id,
567
+ image_newline_id=image_newline_id,
568
+ tensor_batch_images=tensor_batch_image.unsqueeze(0),
569
+ )
570
+ all_encodings.append(sample_encoding)
571
+ batch_encoding = self._left_pad_inputs_with_attention_mask(
572
+ model_inputs=all_encodings, return_attention_mask=True
573
+ )
574
+ return FuyuBatchFeature(data=batch_encoding)
575
+
576
+ def post_process_box_coordinates(self, outputs, target_sizes=None):
577
+ """
578
+ Transforms raw coordinates detected by [`FuyuForCausalLM`] to the original images' coordinate space.
579
+ Coordinates will be returned in "box" format, with the following pattern:
580
+ `<box>top, left, bottom, right</box>`
581
+
582
+ Point coordinates are not supported yet.
583
+
584
+ Args:
585
+ outputs ([`GenerateOutput`]):
586
+ Raw outputs from `generate`.
587
+ target_sizes (`torch.Tensor`, *optional*):
588
+ Tensor of shape (batch_size, 2) where each entry is the (height, width) of the corresponding image in
589
+ the batch. If set, found coordinates in the output sequence are rescaled to the target sizes. If left
590
+ to None, coordinates will not be rescaled.
591
+
592
+ Returns:
593
+ `GenerateOutput`: Same output type returned by `generate`, with output token ids replaced with
594
+ boxed and possible rescaled coordinates.
595
+ """
596
+
597
+ def scale_factor_to_fit(original_size, target_size=None):
598
+ height, width = original_size
599
+ if target_size is None:
600
+ max_height = self.image_processor.size["height"]
601
+ max_width = self.image_processor.size["width"]
602
+ else:
603
+ max_height, max_width = target_size
604
+ if width <= max_width and height <= max_height:
605
+ return 1.0
606
+ return min(max_height / height, max_width / width)
607
+
608
+ def find_delimiters_pair(tokens, start_token, end_token):
609
+ start_id = self.tokenizer.convert_tokens_to_ids(start_token)
610
+ end_id = self.tokenizer.convert_tokens_to_ids(end_token)
611
+
612
+ starting_positions = (tokens == start_id).nonzero(as_tuple=True)[0]
613
+ ending_positions = (tokens == end_id).nonzero(as_tuple=True)[0]
614
+
615
+ if torch.any(starting_positions) and torch.any(ending_positions):
616
+ return (starting_positions[0], ending_positions[0])
617
+ return (None, None)
618
+
619
+ def tokens_to_boxes(tokens, original_size):
620
+ while (pair := find_delimiters_pair(tokens, TOKEN_BBOX_OPEN_STRING, TOKEN_BBOX_CLOSE_STRING)) != (
621
+ None,
622
+ None,
623
+ ):
624
+ start, end = pair
625
+ if end != start + 5:
626
+ continue
627
+
628
+ # Retrieve transformed coordinates from tokens
629
+ coords = self.tokenizer.convert_ids_to_tokens(tokens[start + 1 : end])
630
+
631
+ # Scale back to original image size and multiply by 2
632
+ scale = scale_factor_to_fit(original_size)
633
+ top, left, bottom, right = [2 * int(float(c) / scale) for c in coords]
634
+
635
+ # Replace the IDs so they get detokenized right
636
+ replacement = f" {TEXT_REPR_BBOX_OPEN}{top}, {left}, {bottom}, {right}{TEXT_REPR_BBOX_CLOSE}"
637
+ replacement = self.tokenizer.tokenize(replacement)[1:]
638
+ replacement = self.tokenizer.convert_tokens_to_ids(replacement)
639
+ replacement = torch.tensor(replacement).to(tokens)
640
+
641
+ tokens = torch.cat([tokens[:start], replacement, tokens[end + 1 :]], 0)
642
+ return tokens
643
+
644
+ def tokens_to_points(tokens, original_size):
645
+ while (pair := find_delimiters_pair(tokens, TOKEN_POINT_OPEN_STRING, TOKEN_POINT_CLOSE_STRING)) != (
646
+ None,
647
+ None,
648
+ ):
649
+ start, end = pair
650
+ if end != start + 3:
651
+ continue
652
+
653
+ # Retrieve transformed coordinates from tokens
654
+ coords = self.tokenizer.convert_ids_to_tokens(tokens[start + 1 : end])
655
+
656
+ # Scale back to original image size and multiply by 2
657
+ scale = scale_factor_to_fit(original_size)
658
+ x, y = [2 * int(float(c) / scale) for c in coords]
659
+
660
+ # Replace the IDs so they get detokenized right
661
+ replacement = f" {TEXT_REPR_POINT_OPEN}{x}, {y}{TEXT_REPR_POINT_CLOSE}"
662
+ replacement = self.tokenizer.tokenize(replacement)[1:]
663
+ replacement = self.tokenizer.convert_tokens_to_ids(replacement)
664
+ replacement = torch.tensor(replacement).to(tokens)
665
+
666
+ tokens = torch.cat([tokens[:start], replacement, tokens[end + 1 :]], 0)
667
+ return tokens
668
+
669
+ if target_sizes is None:
670
+ target_sizes = ((self.image_processor.size["height"], self.image_processor.size["width"]),) * len(outputs)
671
+ elif target_sizes.shape[1] != 2:
672
+ raise ValueError("Each element of target_sizes must contain the size (h, w) of each image of the batch")
673
+
674
+ if len(outputs) != len(target_sizes):
675
+ raise ValueError("Make sure that you pass in as many target sizes as output sequences")
676
+
677
+ results = []
678
+ for seq, size in zip(outputs, target_sizes):
679
+ seq = tokens_to_boxes(seq, size)
680
+ seq = tokens_to_points(seq, size)
681
+ results.append(seq)
682
+
683
+ return results
684
+
685
+ def post_process_image_text_to_text(self, generated_outputs):
686
+ """
687
+ Post-processes the output of `FuyuForConditionalGeneration` to only return the text output.
688
+
689
+ Args:
690
+ generated_outputs (`torch.Tensor` or `np.ndarray`):
691
+ The output of the model. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
692
+ containing the token ids of the generated sequences.
693
+
694
+ Returns:
695
+ `List[str]`: The decoded text output.
696
+ """
697
+ beginning_of_answer = self.tokenizer.convert_tokens_to_ids(BEGINNING_OF_ANSWER_STRING)
698
+ # get boa index for each outputted sequence tensor
699
+ # start all generated sequences from the beginning of the answer token, pad to have consistent length
700
+ unpadded_output_sequences = [
701
+ seq[(seq == beginning_of_answer).nonzero(as_tuple=True)[0] + 1 :] for seq in generated_outputs
702
+ ]
703
+ max_len = max(len(seq) for seq in unpadded_output_sequences)
704
+ # convert to torch and pad sequences
705
+ padded_output_sequences = torch.full((len(unpadded_output_sequences), max_len), self.pad_token_id)
706
+ for i, seq in enumerate(unpadded_output_sequences):
707
+ padded_output_sequences[i, : len(seq)] = torch.tensor(seq)
708
+
709
+ return self.batch_decode(padded_output_sequences, skip_special_tokens=True)
710
+
711
+ def batch_decode(self, *args, **kwargs):
712
+ """
713
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
714
+ refer to the docstring of this method for more information.
715
+ """
716
+ return self.tokenizer.batch_decode(*args, **kwargs)
717
+
718
+ def decode(self, *args, **kwargs):
719
+ """
720
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
721
+ the docstring of this method for more information.
722
+ """
723
+ return self.tokenizer.decode(*args, **kwargs)
724
+
725
+
726
+ __all__ = ["FuyuProcessor"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/gemma/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_gemma import *
22
+ from .modeling_flax_gemma import *
23
+ from .modeling_gemma import *
24
+ from .tokenization_gemma import *
25
+ from .tokenization_gemma_fast import *
26
+ else:
27
+ import sys
28
+
29
+ _file = globals()["__file__"]
30
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/gemma/configuration_gemma.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/gemma/modular_gemma.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_gemma.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+
23
+ from ...configuration_utils import PretrainedConfig
24
+
25
+
26
+ class GemmaConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`GemmaModel`]. It is used to instantiate an Gemma
29
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
30
+ defaults will yield a similar configuration to that of the Gemma-7B.
31
+ e.g. [google/gemma-7b](https://huggingface.co/google/gemma-7b)
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+ Args:
35
+ vocab_size (`int`, *optional*, defaults to 256000):
36
+ Vocabulary size of the Gemma model. Defines the number of different tokens that can be represented by the
37
+ `inputs_ids` passed when calling [`GemmaModel`]
38
+ hidden_size (`int`, *optional*, defaults to 3072):
39
+ Dimension of the hidden representations.
40
+ intermediate_size (`int`, *optional*, defaults to 24576):
41
+ Dimension of the MLP representations.
42
+ num_hidden_layers (`int`, *optional*, defaults to 28):
43
+ Number of hidden layers in the Transformer decoder.
44
+ num_attention_heads (`int`, *optional*, defaults to 16):
45
+ Number of attention heads for each attention layer in the Transformer decoder.
46
+ num_key_value_heads (`int`, *optional*, defaults to 16):
47
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
48
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
49
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
50
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
51
+ by meanpooling all the original heads within that group. For more details checkout [this
52
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
53
+ `num_attention_heads`.
54
+ head_dim (`int`, *optional*, defaults to 256):
55
+ The attention head dimension.
56
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
57
+ The legacy activation function. It is overwritten by the `hidden_activation`.
58
+ hidden_activation (`str` or `function`, *optional*):
59
+ The non-linear activation function (function or string) in the decoder. Will default to `"gelu_pytorch_tanh"`
60
+ if not specified. `"gelu_pytorch_tanh"` uses an approximation of the `"gelu"` activation function.
61
+ max_position_embeddings (`int`, *optional*, defaults to 8192):
62
+ The maximum sequence length that this model might ever be used with.
63
+ initializer_range (`float`, *optional*, defaults to 0.02):
64
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
65
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
66
+ The epsilon used by the rms normalization layers.
67
+ use_cache (`bool`, *optional*, defaults to `True`):
68
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
69
+ relevant if `config.is_decoder=True`.
70
+ pad_token_id (`int`, *optional*, defaults to 0):
71
+ Padding token id.
72
+ eos_token_id (`int`, *optional*, defaults to 1):
73
+ End of stream token id.
74
+ bos_token_id (`int`, *optional*, defaults to 2):
75
+ Beginning of stream token id.
76
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
77
+ Whether to tie weight embeddings
78
+ rope_theta (`float`, *optional*, defaults to 10000.0):
79
+ The base period of the RoPE embeddings.
80
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
81
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
82
+ attention_dropout (`float`, *optional*, defaults to 0.0):
83
+ The dropout ratio for the attention probabilities.
84
+ ```python
85
+ >>> from transformers import GemmaModel, GemmaConfig
86
+ >>> # Initializing a Gemma gemma-7b style configuration
87
+ >>> configuration = GemmaConfig()
88
+ >>> # Initializing a model from the gemma-7b style configuration
89
+ >>> model = GemmaModel(configuration)
90
+ >>> # Accessing the model configuration
91
+ >>> configuration = model.config
92
+ ```"""
93
+
94
+ model_type = "gemma"
95
+ keys_to_ignore_at_inference = ["past_key_values"]
96
+
97
+ def __init__(
98
+ self,
99
+ vocab_size=256000,
100
+ hidden_size=3072,
101
+ intermediate_size=24576,
102
+ num_hidden_layers=28,
103
+ num_attention_heads=16,
104
+ num_key_value_heads=16,
105
+ head_dim=256,
106
+ hidden_act="gelu_pytorch_tanh",
107
+ hidden_activation=None,
108
+ max_position_embeddings=8192,
109
+ initializer_range=0.02,
110
+ rms_norm_eps=1e-6,
111
+ use_cache=True,
112
+ pad_token_id=0,
113
+ eos_token_id=1,
114
+ bos_token_id=2,
115
+ tie_word_embeddings=True,
116
+ rope_theta=10000.0,
117
+ attention_bias=False,
118
+ attention_dropout=0.0,
119
+ **kwargs,
120
+ ):
121
+ self.vocab_size = vocab_size
122
+ self.max_position_embeddings = max_position_embeddings
123
+ self.hidden_size = hidden_size
124
+ self.intermediate_size = intermediate_size
125
+ self.num_hidden_layers = num_hidden_layers
126
+ self.num_attention_heads = num_attention_heads
127
+ self.head_dim = head_dim
128
+ self.num_key_value_heads = num_key_value_heads
129
+ self.hidden_act = hidden_act
130
+ self.hidden_activation = hidden_activation
131
+ self.initializer_range = initializer_range
132
+ self.rms_norm_eps = rms_norm_eps
133
+ self.use_cache = use_cache
134
+ self.rope_theta = rope_theta
135
+ self.attention_bias = attention_bias
136
+ self.attention_dropout = attention_dropout
137
+
138
+ super().__init__(
139
+ pad_token_id=pad_token_id,
140
+ bos_token_id=bos_token_id,
141
+ eos_token_id=eos_token_id,
142
+ tie_word_embeddings=tie_word_embeddings,
143
+ **kwargs,
144
+ )
145
+
146
+
147
+ __all__ = ["GemmaConfig"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/gemma/convert_gemma_weights_to_hf.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. 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
+ import argparse
15
+ import os
16
+ import warnings
17
+
18
+ import torch
19
+ from accelerate import init_empty_weights
20
+
21
+ from transformers import GemmaConfig, GemmaForCausalLM, GemmaTokenizer
22
+
23
+
24
+ try:
25
+ from transformers import GemmaTokenizerFast
26
+ except ImportError as e:
27
+ warnings.warn(e)
28
+ warnings.warn(
29
+ "The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion"
30
+ )
31
+ GemmaTokenizerFast = None
32
+
33
+ """
34
+ Sample usage:
35
+
36
+ ```
37
+ python src/transformers/models/gemma/convert_gemma_weights_to_hf.py \
38
+ --input_dir /path/to/downloaded/gemma/weights --model_size 7B --output_dir /output/path
39
+ ```
40
+
41
+ Thereafter, models can be loaded via:
42
+
43
+ ```py
44
+ from transformers import GemmaForCausalLM, GemmaTokenizerFast
45
+
46
+ model = GemmaForCausalLM.from_pretrained("/output/path")
47
+ tokenizer = GemmaTokenizerFast.from_pretrained("/output/path")
48
+ ```
49
+
50
+ Important note: you need to be able to host the whole model in RAM to execute this script (even if the biggest versions
51
+ come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM).
52
+ """
53
+
54
+ gemma_2b_config = GemmaConfig(
55
+ num_hidden_layers=18,
56
+ num_attention_heads=8,
57
+ num_key_value_heads=1,
58
+ hidden_size=2048,
59
+ intermediate_size=16384,
60
+ )
61
+
62
+ gemma_7b_config = GemmaConfig()
63
+
64
+ CONFIG_MAPPING = {"2B": gemma_2b_config, "7B": gemma_7b_config}
65
+ LAYER_NAME_MAPPING = {"embedder.weight": "model.embed_tokens.weight"}
66
+
67
+
68
+ def write_model(save_path, input_base_path, config, safe_serialization=True, push_to_hub=False, dtype=torch.float32):
69
+ num_attn_heads = config.num_attention_heads
70
+ hidden_size = config.hidden_size
71
+ num_kv_heads = config.num_key_value_heads
72
+ head_dim = config.head_dim
73
+
74
+ print(f"Fetching all parameters from the checkpoint at '{input_base_path}'")
75
+ model_state_dict = torch.load(input_base_path, map_location="cpu")["model_state_dict"]
76
+ model_state_dict.pop("freqs_cis")
77
+
78
+ state_dict = {}
79
+ for k, v in model_state_dict.items():
80
+ if "qkv_proj" in k:
81
+ if num_kv_heads == 1:
82
+ v = v.reshape(num_attn_heads + num_kv_heads * 2, head_dim, hidden_size)
83
+ q_proj = v[:num_attn_heads, ...]
84
+ k_proj = v[num_attn_heads : num_attn_heads + num_kv_heads, ...].repeat(num_kv_heads, 1, 1)
85
+ v_proj = v[-num_kv_heads:, ...].repeat(num_kv_heads, 1, 1)
86
+
87
+ state_dict[k.replace("qkv_proj", "q_proj")] = q_proj.reshape(
88
+ num_attn_heads * head_dim, hidden_size
89
+ ).clone()
90
+ state_dict[k.replace("qkv_proj", "k_proj")] = k_proj.reshape(
91
+ num_kv_heads * head_dim, hidden_size
92
+ ).clone()
93
+ state_dict[k.replace("qkv_proj", "v_proj")] = v_proj[0].clone()
94
+ else:
95
+ q_proj, k_proj, v_proj = torch.split(v, v.shape[0] // 3, 0)
96
+ state_dict[k.replace("qkv_proj", "q_proj")] = q_proj.reshape(
97
+ num_attn_heads * head_dim, hidden_size
98
+ ).clone()
99
+ state_dict[k.replace("qkv_proj", "k_proj")] = k_proj.reshape(
100
+ num_kv_heads * head_dim, hidden_size
101
+ ).clone()
102
+ state_dict[k.replace("qkv_proj", "v_proj")] = v_proj.clone()
103
+
104
+ elif k == "embedder.weight":
105
+ state_dict[LAYER_NAME_MAPPING[k]] = v
106
+ state_dict["lm_head.weight"] = v
107
+ else:
108
+ state_dict[k] = v
109
+
110
+ torch.set_default_dtype(dtype)
111
+
112
+ print("Loading the checkpoint in a Gemma model.")
113
+ with init_empty_weights():
114
+ model = GemmaForCausalLM(config)
115
+ model.load_state_dict(state_dict, assign=True, strict=False)
116
+
117
+ model.config.torch_dtype = torch.float32
118
+ del model.config._name_or_path
119
+ print("Saving in the Transformers format.")
120
+
121
+ if push_to_hub:
122
+ print(f"pushing the model to {save_path}")
123
+ model.push_to_hub(save_path, safe_serialization=safe_serialization, private=True)
124
+ else:
125
+ model.save_pretrained(save_path, safe_serialization=safe_serialization)
126
+
127
+
128
+ def write_tokenizer(input_tokenizer_path, save_path, push_to_hub=False):
129
+ # Initialize the tokenizer based on the `spm` model
130
+ tokenizer_class = GemmaTokenizer if GemmaTokenizerFast is None else GemmaTokenizerFast
131
+ print(f"Saving a {tokenizer_class.__name__} to {save_path}.")
132
+ tokenizer = tokenizer_class(input_tokenizer_path)
133
+ if push_to_hub:
134
+ tokenizer.push_to_hub(save_path)
135
+ else:
136
+ tokenizer.save_pretrained(save_path)
137
+
138
+
139
+ def main():
140
+ parser = argparse.ArgumentParser()
141
+ parser.add_argument(
142
+ "--input_checkpoint",
143
+ help="Absolute path to the target Gemma weights.",
144
+ required=True,
145
+ )
146
+ parser.add_argument(
147
+ "--tokenizer_checkpoint",
148
+ help="Location of Gemma tokenizer model",
149
+ )
150
+ parser.add_argument(
151
+ "--model_size",
152
+ default="7B",
153
+ choices=["2B", "7B", "tokenizer_only"],
154
+ help="'f' models correspond to the finetuned versions, and are specific to the Gemma2 official release. For more details on Gemma2, checkout the original repo: https://huggingface.co/google/gemma-7b",
155
+ )
156
+ parser.add_argument(
157
+ "--output_dir",
158
+ default="google/gemma-7b",
159
+ help="Location to write HF model and tokenizer",
160
+ )
161
+ parser.add_argument(
162
+ "--pickle_serialization",
163
+ help="Whether or not to save using `safetensors`.",
164
+ action="store_true",
165
+ default=False,
166
+ )
167
+ parser.add_argument(
168
+ "--convert_tokenizer",
169
+ help="Whether or not to convert the tokenizer as well.",
170
+ action="store_true",
171
+ default=False,
172
+ )
173
+ parser.add_argument(
174
+ "--push_to_hub",
175
+ help="Whether or not to push the model to the hub at `output_dir` instead of saving it locally.",
176
+ action="store_true",
177
+ default=False,
178
+ )
179
+ parser.add_argument(
180
+ "--dtype",
181
+ default="float32",
182
+ help="Target dtype of the converted model",
183
+ )
184
+ args = parser.parse_args()
185
+
186
+ if args.convert_tokenizer:
187
+ if args.tokenizer_checkpoint is None:
188
+ raise ValueError("Path to the tokenizer is required when passing --convert_tokenizer")
189
+
190
+ spm_path = os.path.join(args.tokenizer_checkpoint)
191
+ write_tokenizer(spm_path, args.output_dir, args.push_to_hub)
192
+
193
+ config = CONFIG_MAPPING[args.model_size]
194
+ dtype = getattr(torch, args.dtype)
195
+ write_model(
196
+ config=config,
197
+ input_base_path=args.input_checkpoint,
198
+ save_path=args.output_dir,
199
+ safe_serialization=not args.pickle_serialization,
200
+ push_to_hub=args.push_to_hub,
201
+ dtype=dtype,
202
+ )
203
+
204
+
205
+ if __name__ == "__main__":
206
+ main()
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/gemma/modeling_flax_gemma.py ADDED
@@ -0,0 +1,777 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Google 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 Gemma model."""
16
+
17
+ from typing import Optional, Tuple
18
+
19
+ import flax.linen as nn
20
+ import jax
21
+ import jax.numpy as jnp
22
+ import numpy as np
23
+ from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
24
+ from flax.linen import combine_masks, make_causal_mask
25
+ from flax.linen.attention import dot_product_attention_weights
26
+ from flax.traverse_util import flatten_dict, unflatten_dict
27
+ from jax import lax
28
+
29
+ from ...modeling_flax_outputs import FlaxBaseModelOutput, FlaxCausalLMOutput
30
+ from ...modeling_flax_utils import ACT2FN, FlaxPreTrainedModel, append_call_sample_docstring
31
+ from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging
32
+ from .configuration_gemma import GemmaConfig
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+ _CONFIG_FOR_DOC = "GemmaConfig"
38
+ _CHECKPOINT_FOR_DOC = "google/gemma-2b"
39
+ _REAL_CHECKPOINT_FOR_DOC = "openlm-research/open_llama_3b_v2"
40
+
41
+ GEMMA_START_DOCSTRING = r"""
42
+
43
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
44
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
45
+ etc.)
46
+
47
+ This model is also a Flax Linen
48
+ [flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
49
+ regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
50
+
51
+ Finally, this model supports inherent JAX features such as:
52
+
53
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
54
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
55
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
56
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
57
+
58
+ Parameters:
59
+ config ([`GemmaConfig`]): Model configuration class with all the parameters of the model.
60
+ Initializing with a config file does not load the weights associated with the model, only the
61
+ configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
62
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
63
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16`, or
64
+ `jax.numpy.bfloat16`.
65
+
66
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
67
+ specified all the computation will be performed with the given `dtype`.
68
+
69
+ **Note that this only specifies the dtype of the computation and does not influence the dtype of model
70
+ parameters.**
71
+
72
+ If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
73
+ [`~FlaxPreTrainedModel.to_bf16`].
74
+ """
75
+
76
+ GEMMA_INPUTS_DOCSTRING = r"""
77
+ Args:
78
+ input_ids (`numpy.ndarray` of shape `(batch_size, input_ids_length)`):
79
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
80
+ it.
81
+
82
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
83
+ [`PreTrainedTokenizer.__call__`] for details.
84
+
85
+ [What are input IDs?](../glossary#input-ids)
86
+ attention_mask (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
87
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
88
+
89
+ - 1 for tokens that are **not masked**,
90
+ - 0 for tokens that are **masked**.
91
+
92
+ [What are attention masks?](../glossary#attention-mask)
93
+
94
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
95
+ [`PreTrainedTokenizer.__call__`] for details.
96
+
97
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
98
+ `past_key_values`).
99
+
100
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
101
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
102
+ information on the default strategy.
103
+
104
+ - 1 indicates the head is **not masked**,
105
+ - 0 indicates the head is **masked**.
106
+ position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
107
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
108
+ config.n_positions - 1]`.
109
+
110
+ [What are position IDs?](../glossary#position-ids)
111
+ past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
112
+ Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
113
+ auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
114
+ output_attentions (`bool`, *optional*):
115
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
116
+ tensors for more detail.
117
+ output_hidden_states (`bool`, *optional*):
118
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
119
+ more detail.
120
+ return_dict (`bool`, *optional*):
121
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
122
+ """
123
+
124
+
125
+ def create_sinusoidal_positions(num_pos, dim):
126
+ inv_freq = 1.0 / (10000 ** (np.arange(0, dim, 2)[: (dim // 2)] / dim))
127
+ freqs = np.einsum("i , j -> i j", np.arange(num_pos), inv_freq).astype("float32")
128
+
129
+ emb = np.concatenate((freqs, freqs), axis=-1)
130
+ out = np.concatenate((np.sin(emb)[:, None, :], np.cos(emb)[:, None, :]), axis=-1)
131
+ return jnp.array(out[:, :, :num_pos])
132
+
133
+
134
+ # Copied from transformers.models.llama.modeling_flax_llama.rotate_half
135
+ def rotate_half(tensor):
136
+ """Rotates half the hidden dims of the input."""
137
+ rotate_half_tensor = jnp.concatenate(
138
+ (-tensor[..., tensor.shape[-1] // 2 :], tensor[..., : tensor.shape[-1] // 2]), axis=-1
139
+ )
140
+ return rotate_half_tensor
141
+
142
+
143
+ # Copied from transformers.models.llama.modeling_flax_llama.apply_rotary_pos_emb
144
+ def apply_rotary_pos_emb(tensor, sin_pos, cos_pos):
145
+ return (tensor * cos_pos) + (rotate_half(tensor) * sin_pos)
146
+
147
+
148
+ class FlaxGemmaRMSNorm(nn.Module):
149
+ config: GemmaConfig
150
+ dtype: jnp.dtype = jnp.float32
151
+
152
+ def setup(self):
153
+ self.epsilon = self.config.rms_norm_eps
154
+ self.weight = self.param("weight", lambda _, shape: jnp.ones(shape), self.config.hidden_size)
155
+
156
+ def __call__(self, hidden_states):
157
+ variance = jnp.asarray(hidden_states, dtype=jnp.float32)
158
+ variance = jnp.power(variance, 2)
159
+ variance = variance.mean(-1, keepdims=True)
160
+ # use `jax.numpy.sqrt` as `jax.lax.rsqrt` does not match `torch.rsqrt`
161
+ hidden_states = hidden_states / jnp.sqrt(variance + self.epsilon)
162
+
163
+ return (1 + self.weight) * jnp.asarray(hidden_states, dtype=self.dtype)
164
+
165
+
166
+ # Copied from transformers.models.llama.modeling_flax_llama.FlaxLlamaRotaryEmbedding with Llama->Gemma
167
+ class FlaxGemmaRotaryEmbedding(nn.Module):
168
+ config: GemmaConfig
169
+ dtype: jnp.dtype = jnp.float32
170
+
171
+ # Ignore copy
172
+ def setup(self):
173
+ head_dim = self.config.head_dim
174
+ self.sincos = create_sinusoidal_positions(self.config.max_position_embeddings, head_dim)
175
+
176
+ def __call__(self, key, query, position_ids):
177
+ sincos = self.sincos[position_ids]
178
+ sin_pos, cos_pos = jnp.split(sincos, 2, axis=-1)
179
+
180
+ key = apply_rotary_pos_emb(key, sin_pos, cos_pos)
181
+ query = apply_rotary_pos_emb(query, sin_pos, cos_pos)
182
+
183
+ key = jnp.asarray(key, dtype=self.dtype)
184
+ query = jnp.asarray(query, dtype=self.dtype)
185
+
186
+ return key, query
187
+
188
+
189
+ class FlaxGemmaAttention(nn.Module):
190
+ config: GemmaConfig
191
+ dtype: jnp.dtype = jnp.float32
192
+ causal: bool = True
193
+ is_cross_attention: bool = False
194
+
195
+ def setup(self):
196
+ config = self.config
197
+ self.embed_dim = config.hidden_size
198
+ self.num_heads = config.num_attention_heads
199
+ self.head_dim = config.head_dim
200
+ self.attention_softmax_in_fp32 = self.dtype is not jnp.float32
201
+
202
+ self.num_key_value_heads = config.num_key_value_heads
203
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
204
+
205
+ kernel = jax.nn.initializers.normal(self.config.initializer_range)
206
+ self.q_proj = nn.Dense(
207
+ self.num_heads * self.head_dim, use_bias=config.attention_bias, dtype=self.dtype, kernel_init=kernel
208
+ )
209
+ self.k_proj = nn.Dense(
210
+ self.num_key_value_heads * self.head_dim,
211
+ use_bias=config.attention_bias,
212
+ dtype=self.dtype,
213
+ kernel_init=kernel,
214
+ )
215
+ self.v_proj = nn.Dense(
216
+ self.num_key_value_heads * self.head_dim,
217
+ use_bias=config.attention_bias,
218
+ dtype=self.dtype,
219
+ kernel_init=kernel,
220
+ )
221
+ self.o_proj = nn.Dense(self.embed_dim, use_bias=config.attention_bias, dtype=self.dtype, kernel_init=kernel)
222
+
223
+ self.causal_mask = make_causal_mask(jnp.ones((1, config.max_position_embeddings), dtype="bool"), dtype="bool")
224
+ self.rotary_emb = FlaxGemmaRotaryEmbedding(config, dtype=self.dtype)
225
+
226
+ def _split_heads(self, hidden_states, num_heads):
227
+ return hidden_states.reshape(hidden_states.shape[:2] + (num_heads, self.head_dim))
228
+
229
+ def _merge_heads(self, hidden_states):
230
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.num_heads * self.head_dim,))
231
+
232
+ @nn.compact
233
+ # Copied from transformers.models.gpt_neo.modeling_flax_gpt_neo.FlaxGPTNeoSelfAttention._concatenate_to_cache
234
+ def _concatenate_to_cache(self, key, value, query, attention_mask):
235
+ """
236
+ This function takes projected key, value states from a single input token and concatenates the states to cached
237
+ states from previous steps. This function is slighly adapted from the official Flax repository:
238
+ https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
239
+ """
240
+ # detect if we're initializing by absence of existing cache data.
241
+ is_initialized = self.has_variable("cache", "cached_key")
242
+ cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
243
+ cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
244
+ cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
245
+
246
+ if is_initialized:
247
+ *batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
248
+ # update key, value caches with our new 1d spatial slices
249
+ cur_index = cache_index.value
250
+ indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
251
+ key = lax.dynamic_update_slice(cached_key.value, key, indices)
252
+ value = lax.dynamic_update_slice(cached_value.value, value, indices)
253
+ cached_key.value = key
254
+ cached_value.value = value
255
+ num_updated_cache_vectors = query.shape[1]
256
+ cache_index.value = cache_index.value + num_updated_cache_vectors
257
+ # 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.
258
+ pad_mask = jnp.broadcast_to(
259
+ jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
260
+ tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
261
+ )
262
+ attention_mask = combine_masks(pad_mask, attention_mask)
263
+ return key, value, attention_mask
264
+
265
+ def __call__(
266
+ self,
267
+ hidden_states,
268
+ attention_mask,
269
+ position_ids,
270
+ deterministic: bool = True,
271
+ init_cache: bool = False,
272
+ output_attentions: bool = False,
273
+ ):
274
+ query = self.q_proj(hidden_states)
275
+ key = self.k_proj(hidden_states)
276
+ value = self.v_proj(hidden_states)
277
+
278
+ query = self._split_heads(query, self.num_heads)
279
+ key = self._split_heads(key, self.num_key_value_heads)
280
+ value = self._split_heads(value, self.num_key_value_heads)
281
+
282
+ key, query = self.rotary_emb(key, query, position_ids)
283
+
284
+ query_length, key_length = query.shape[1], key.shape[1]
285
+
286
+ if self.has_variable("cache", "cached_key"):
287
+ mask_shift = self.variables["cache"]["cache_index"]
288
+ max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
289
+ causal_mask = lax.dynamic_slice(
290
+ self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
291
+ )
292
+ else:
293
+ causal_mask = self.causal_mask[:, :, :query_length, :key_length]
294
+
295
+ batch_size = hidden_states.shape[0]
296
+ causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
297
+
298
+ attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
299
+ attention_mask = combine_masks(attention_mask, causal_mask)
300
+
301
+ dropout_rng = None
302
+ if not deterministic and self.config.attention_dropout > 0.0:
303
+ dropout_rng = self.make_rng("dropout")
304
+
305
+ # During fast autoregressive decoding, we feed one position at a time,
306
+ # and cache the keys and values step by step.
307
+ if self.has_variable("cache", "cached_key") or init_cache:
308
+ key, value, attention_mask = self._concatenate_to_cache(key, value, query, attention_mask)
309
+
310
+ # transform boolean mask into float mask
311
+ attention_bias = lax.select(
312
+ attention_mask > 0,
313
+ jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
314
+ jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
315
+ )
316
+
317
+ key = jnp.repeat(key, repeats=self.num_key_value_groups, axis=2)
318
+ value = jnp.repeat(value, repeats=self.num_key_value_groups, axis=2)
319
+
320
+ # usual dot product attention
321
+ attention_dtype = jnp.float32 if self.attention_softmax_in_fp32 else self.dtype
322
+ attn_weights = dot_product_attention_weights(
323
+ query,
324
+ key,
325
+ bias=attention_bias,
326
+ dropout_rng=dropout_rng,
327
+ dropout_rate=self.config.attention_dropout,
328
+ deterministic=deterministic,
329
+ dtype=attention_dtype,
330
+ )
331
+
332
+ if self.attention_softmax_in_fp32:
333
+ attn_weights = attn_weights.astype(self.dtype)
334
+
335
+ attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value)
336
+ attn_output = self._merge_heads(attn_output)
337
+ attn_output = self.o_proj(attn_output)
338
+
339
+ outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)
340
+ return outputs
341
+
342
+
343
+ class FlaxGemmaMLP(nn.Module):
344
+ config: GemmaConfig
345
+ dtype: jnp.dtype = jnp.float32
346
+
347
+ def setup(self):
348
+ embed_dim = self.config.hidden_size
349
+ inner_dim = self.config.intermediate_size if self.config.intermediate_size is not None else 4 * embed_dim
350
+
351
+ kernel_init = jax.nn.initializers.normal(self.config.initializer_range)
352
+ if self.config.hidden_activation is None:
353
+ logger.warning_once(
354
+ "Gemma's activation function should be approximate GeLU and not exact GeLU. "
355
+ "Changing the activation function to `gelu_pytorch_tanh`."
356
+ f"if you want to use the legacy `{self.config.hidden_act}`, "
357
+ f"edit the `model.config` to set `hidden_activation={self.config.hidden_act}` "
358
+ " instead of `hidden_act`. See https://github.com/huggingface/transformers/pull/29402 for more details."
359
+ )
360
+ hidden_activation = "gelu_pytorch_tanh"
361
+ else:
362
+ hidden_activation = self.config.hidden_activation
363
+ self.act = ACT2FN[hidden_activation]
364
+
365
+ self.gate_proj = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, kernel_init=kernel_init)
366
+ self.down_proj = nn.Dense(embed_dim, use_bias=False, dtype=self.dtype, kernel_init=kernel_init)
367
+ self.up_proj = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, kernel_init=kernel_init)
368
+
369
+ def __call__(self, hidden_states):
370
+ up_proj_states = self.up_proj(hidden_states)
371
+ gate_states = self.act(self.gate_proj(hidden_states))
372
+
373
+ hidden_states = self.down_proj(up_proj_states * gate_states)
374
+ return hidden_states
375
+
376
+
377
+ # Copied from transformers.models.llama.modeling_flax_llama.FlaxLlamaDecoderLayer with Llama->Gemma
378
+ class FlaxGemmaDecoderLayer(nn.Module):
379
+ config: GemmaConfig
380
+ dtype: jnp.dtype = jnp.float32
381
+
382
+ def setup(self):
383
+ self.input_layernorm = FlaxGemmaRMSNorm(self.config, dtype=self.dtype)
384
+ self.self_attn = FlaxGemmaAttention(self.config, dtype=self.dtype)
385
+ self.post_attention_layernorm = FlaxGemmaRMSNorm(self.config, dtype=self.dtype)
386
+ self.mlp = FlaxGemmaMLP(self.config, dtype=self.dtype)
387
+
388
+ def __call__(
389
+ self,
390
+ hidden_states,
391
+ attention_mask=None,
392
+ position_ids=None,
393
+ deterministic: bool = True,
394
+ init_cache: bool = False,
395
+ output_attentions: bool = False,
396
+ ):
397
+ residual = hidden_states
398
+ hidden_states = self.input_layernorm(hidden_states)
399
+ outputs = self.self_attn(
400
+ hidden_states,
401
+ attention_mask=attention_mask,
402
+ position_ids=position_ids,
403
+ deterministic=deterministic,
404
+ init_cache=init_cache,
405
+ output_attentions=output_attentions,
406
+ )
407
+ # residual connection
408
+ attn_output = outputs[0]
409
+ hidden_states = residual + attn_output
410
+
411
+ residual = hidden_states
412
+ hidden_states = self.post_attention_layernorm(hidden_states)
413
+ hidden_states = self.mlp(hidden_states)
414
+ # residual connection
415
+ hidden_states = residual + hidden_states
416
+
417
+ return (hidden_states,) + outputs[1:]
418
+
419
+
420
+ # Copied from transformers.models.gpt_neo.modeling_flax_gpt_neo.FlaxGPTNeoPreTrainedModel with GPTNeo->Gemma, GPT_NEO->GEMMA, transformer->model
421
+ class FlaxGemmaPreTrainedModel(FlaxPreTrainedModel):
422
+ """
423
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
424
+ models.
425
+ """
426
+
427
+ config_class = GemmaConfig
428
+ base_model_prefix = "model"
429
+ module_class: nn.Module = None
430
+
431
+ def __init__(
432
+ self,
433
+ config: GemmaConfig,
434
+ input_shape: Tuple = (1, 1),
435
+ seed: int = 0,
436
+ dtype: jnp.dtype = jnp.float32,
437
+ _do_init: bool = True,
438
+ **kwargs,
439
+ ):
440
+ module = self.module_class(config=config, dtype=dtype, **kwargs)
441
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
442
+
443
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
444
+ # init input tensors
445
+ input_ids = jnp.zeros(input_shape, dtype="i4")
446
+ attention_mask = jnp.ones_like(input_ids)
447
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_shape)
448
+ params_rng, dropout_rng = jax.random.split(rng)
449
+ rngs = {"params": params_rng, "dropout": dropout_rng}
450
+
451
+ random_params = self.module.init(rngs, input_ids, attention_mask, position_ids, return_dict=False)["params"]
452
+
453
+ if params is not None:
454
+ random_params = flatten_dict(unfreeze(random_params))
455
+ params = flatten_dict(unfreeze(params))
456
+ for missing_key in self._missing_keys:
457
+ params[missing_key] = random_params[missing_key]
458
+ self._missing_keys = set()
459
+ return freeze(unflatten_dict(params))
460
+ else:
461
+ return random_params
462
+
463
+ def init_cache(self, batch_size, max_length):
464
+ r"""
465
+ Args:
466
+ batch_size (`int`):
467
+ batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
468
+ max_length (`int`):
469
+ maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
470
+ cache.
471
+ """
472
+ # init input variables to retrieve cache
473
+ input_ids = jnp.ones((batch_size, max_length))
474
+ attention_mask = jnp.ones_like(input_ids)
475
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
476
+
477
+ init_variables = self.module.init(
478
+ jax.random.PRNGKey(0), input_ids, attention_mask, position_ids, return_dict=False, init_cache=True
479
+ )
480
+ return unfreeze(init_variables["cache"])
481
+
482
+ @add_start_docstrings_to_model_forward(GEMMA_INPUTS_DOCSTRING)
483
+ def __call__(
484
+ self,
485
+ input_ids,
486
+ attention_mask=None,
487
+ position_ids=None,
488
+ params: dict = None,
489
+ past_key_values: dict = None,
490
+ dropout_rng: jax.random.PRNGKey = None,
491
+ train: bool = False,
492
+ output_attentions: Optional[bool] = None,
493
+ output_hidden_states: Optional[bool] = None,
494
+ return_dict: Optional[bool] = None,
495
+ ):
496
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
497
+ output_hidden_states = (
498
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
499
+ )
500
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
501
+
502
+ batch_size, sequence_length = input_ids.shape
503
+
504
+ if position_ids is None:
505
+ if past_key_values is not None:
506
+ raise ValueError("Make sure to provide `position_ids` when passing `past_key_values`.")
507
+
508
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
509
+
510
+ if attention_mask is None:
511
+ attention_mask = jnp.ones((batch_size, sequence_length))
512
+
513
+ # Handle any PRNG if needed
514
+ rngs = {}
515
+ if dropout_rng is not None:
516
+ rngs["dropout"] = dropout_rng
517
+
518
+ inputs = {"params": params or self.params}
519
+
520
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that it can be changed by FlaxGemmaAttention module
521
+ if past_key_values:
522
+ inputs["cache"] = past_key_values
523
+ mutable = ["cache"]
524
+ else:
525
+ mutable = False
526
+
527
+ outputs = self.module.apply(
528
+ inputs,
529
+ jnp.array(input_ids, dtype="i4"),
530
+ jnp.array(attention_mask, dtype="i4"),
531
+ jnp.array(position_ids, dtype="i4"),
532
+ not train,
533
+ False,
534
+ output_attentions,
535
+ output_hidden_states,
536
+ return_dict,
537
+ rngs=rngs,
538
+ mutable=mutable,
539
+ )
540
+
541
+ # add updated cache to model output
542
+ if past_key_values is not None and return_dict:
543
+ outputs, past_key_values = outputs
544
+ outputs["past_key_values"] = unfreeze(past_key_values["cache"])
545
+ return outputs
546
+ elif past_key_values is not None and not return_dict:
547
+ outputs, past_key_values = outputs
548
+ outputs = outputs[:1] + (unfreeze(past_key_values["cache"]),) + outputs[1:]
549
+
550
+ return outputs
551
+
552
+
553
+ # Copied from transformers.models.llama.modeling_flax_llama.FlaxLlamaLayerCollection with Llama->Gemma
554
+ class FlaxGemmaLayerCollection(nn.Module):
555
+ config: GemmaConfig
556
+ dtype: jnp.dtype = jnp.float32
557
+
558
+ def setup(self):
559
+ self.blocks = [
560
+ FlaxGemmaDecoderLayer(self.config, dtype=self.dtype, name=str(i))
561
+ for i in range(self.config.num_hidden_layers)
562
+ ]
563
+
564
+ def __call__(
565
+ self,
566
+ hidden_states,
567
+ attention_mask=None,
568
+ position_ids=None,
569
+ deterministic: bool = True,
570
+ init_cache: bool = False,
571
+ output_attentions: bool = False,
572
+ output_hidden_states: bool = False,
573
+ return_dict: bool = False,
574
+ ):
575
+ all_attentions = () if output_attentions else None
576
+ all_hidden_states = () if output_hidden_states else None
577
+
578
+ for block in self.blocks:
579
+ if output_hidden_states:
580
+ all_hidden_states += (hidden_states,)
581
+ layer_outputs = block(
582
+ hidden_states,
583
+ attention_mask=attention_mask,
584
+ position_ids=position_ids,
585
+ deterministic=deterministic,
586
+ init_cache=init_cache,
587
+ output_attentions=output_attentions,
588
+ )
589
+ hidden_states = layer_outputs[0]
590
+
591
+ if output_attentions:
592
+ all_attentions += (layer_outputs[1],)
593
+
594
+ # this contains possible `None` values - `FlaxGemmaModule` will filter them out
595
+ outputs = (hidden_states, all_hidden_states, all_attentions)
596
+
597
+ return outputs
598
+
599
+
600
+ # Copied from transformers.models.llama.modeling_flax_llama.FlaxLlamaModule with Llama->Gemma
601
+ class FlaxGemmaModule(nn.Module):
602
+ config: GemmaConfig
603
+ dtype: jnp.dtype = jnp.float32
604
+
605
+ def setup(self):
606
+ self.hidden_size = self.config.hidden_size
607
+ embedding_init = jax.nn.initializers.normal(stddev=self.config.initializer_range)
608
+ self.embed_tokens = nn.Embed(
609
+ self.config.vocab_size,
610
+ self.hidden_size,
611
+ embedding_init=embedding_init,
612
+ dtype=self.dtype,
613
+ )
614
+ self.layers = FlaxGemmaLayerCollection(self.config, dtype=self.dtype)
615
+ self.norm = FlaxGemmaRMSNorm(self.config, dtype=self.dtype)
616
+
617
+ # Ignore copy
618
+ def __call__(
619
+ self,
620
+ input_ids,
621
+ attention_mask=None,
622
+ position_ids=None,
623
+ deterministic=True,
624
+ init_cache: bool = False,
625
+ output_attentions: bool = False,
626
+ output_hidden_states: bool = False,
627
+ return_dict: bool = True,
628
+ ):
629
+ input_embeds = self.embed_tokens(input_ids.astype("i4"))
630
+
631
+ input_embeds = input_embeds * (self.config.hidden_size**0.5)
632
+
633
+ outputs = self.layers(
634
+ input_embeds,
635
+ position_ids=position_ids,
636
+ attention_mask=attention_mask,
637
+ deterministic=deterministic,
638
+ init_cache=init_cache,
639
+ output_attentions=output_attentions,
640
+ output_hidden_states=output_hidden_states,
641
+ return_dict=return_dict,
642
+ )
643
+
644
+ hidden_states = outputs[0]
645
+ hidden_states = self.norm(hidden_states)
646
+
647
+ if output_hidden_states:
648
+ all_hidden_states = outputs[1] + (hidden_states,)
649
+ outputs = (hidden_states, all_hidden_states) + outputs[2:]
650
+ else:
651
+ outputs = (hidden_states,) + outputs[1:]
652
+
653
+ if not return_dict:
654
+ return tuple(v for v in outputs if v is not None)
655
+
656
+ return FlaxBaseModelOutput(
657
+ last_hidden_state=hidden_states,
658
+ hidden_states=outputs[1],
659
+ attentions=outputs[-1],
660
+ )
661
+
662
+
663
+ @add_start_docstrings(
664
+ "The bare Gemma Model transformer outputting raw hidden-states without any specific head on top.",
665
+ GEMMA_START_DOCSTRING,
666
+ )
667
+ # Copied from transformers.models.llama.modeling_flax_llama.FlaxLlamaModel with Llama->Gemma
668
+ class FlaxGemmaModel(FlaxGemmaPreTrainedModel):
669
+ module_class = FlaxGemmaModule
670
+
671
+
672
+ append_call_sample_docstring(
673
+ FlaxGemmaModel,
674
+ _CHECKPOINT_FOR_DOC,
675
+ FlaxBaseModelOutput,
676
+ _CONFIG_FOR_DOC,
677
+ real_checkpoint=_REAL_CHECKPOINT_FOR_DOC,
678
+ )
679
+
680
+
681
+ # Copied from transformers.models.llama.modeling_flax_llama.FlaxLlamaForCausalLMModule with Llama->Gemma
682
+ class FlaxGemmaForCausalLMModule(nn.Module):
683
+ config: GemmaConfig
684
+ dtype: jnp.dtype = jnp.float32
685
+
686
+ def setup(self):
687
+ self.model = FlaxGemmaModule(self.config, dtype=self.dtype)
688
+ self.lm_head = nn.Dense(
689
+ self.config.vocab_size,
690
+ use_bias=False,
691
+ dtype=self.dtype,
692
+ kernel_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
693
+ )
694
+
695
+ # Ignore copy
696
+ def __call__(
697
+ self,
698
+ input_ids,
699
+ attention_mask=None,
700
+ position_ids=None,
701
+ deterministic: bool = True,
702
+ init_cache: bool = False,
703
+ output_attentions: bool = False,
704
+ output_hidden_states: bool = False,
705
+ return_dict: bool = True,
706
+ ):
707
+ outputs = self.model(
708
+ input_ids,
709
+ position_ids=position_ids,
710
+ attention_mask=attention_mask,
711
+ deterministic=deterministic,
712
+ init_cache=init_cache,
713
+ output_attentions=output_attentions,
714
+ output_hidden_states=output_hidden_states,
715
+ return_dict=return_dict,
716
+ )
717
+
718
+ hidden_states = outputs[0]
719
+ if self.config.tie_word_embeddings:
720
+ shared_kernel = self.model.variables["params"]["embed_tokens"]["embedding"].T
721
+ lm_logits = self.lm_head.apply({"params": {"kernel": shared_kernel}}, hidden_states)
722
+ else:
723
+ lm_logits = self.lm_head(hidden_states)
724
+
725
+ if not return_dict:
726
+ return (lm_logits,) + outputs[1:]
727
+
728
+ return FlaxCausalLMOutput(logits=lm_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
729
+
730
+
731
+ @add_start_docstrings(
732
+ """
733
+ The Gemma Model transformer with a language modeling head (linear layer) on top.
734
+ """,
735
+ GEMMA_START_DOCSTRING,
736
+ )
737
+ # Copied from transformers.models.gptj.modeling_flax_gptj.FlaxGPTJForCausalLM with GPTJ->Gemma
738
+ class FlaxGemmaForCausalLM(FlaxGemmaPreTrainedModel):
739
+ module_class = FlaxGemmaForCausalLMModule
740
+
741
+ def prepare_inputs_for_generation(self, input_ids, max_length, attention_mask: Optional[jax.Array] = None):
742
+ # initializing the cache
743
+ batch_size, seq_length = input_ids.shape
744
+
745
+ past_key_values = self.init_cache(batch_size, max_length)
746
+ # Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
747
+ # But since Gemma uses a causal mask, those positions are masked anyways.
748
+ # Thus we can create a single static attention_mask here, which is more efficient for compilation
749
+ extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
750
+ if attention_mask is not None:
751
+ position_ids = attention_mask.cumsum(axis=-1) - 1
752
+ extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, attention_mask, (0, 0))
753
+ else:
754
+ position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
755
+
756
+ return {
757
+ "past_key_values": past_key_values,
758
+ "attention_mask": extended_attention_mask,
759
+ "position_ids": position_ids,
760
+ }
761
+
762
+ def update_inputs_for_generation(self, model_outputs, model_kwargs):
763
+ model_kwargs["past_key_values"] = model_outputs.past_key_values
764
+ model_kwargs["position_ids"] = model_kwargs["position_ids"][:, -1:] + 1
765
+ return model_kwargs
766
+
767
+
768
+ append_call_sample_docstring(
769
+ FlaxGemmaForCausalLM,
770
+ _CHECKPOINT_FOR_DOC,
771
+ FlaxCausalLMOutput,
772
+ _CONFIG_FOR_DOC,
773
+ real_checkpoint=_REAL_CHECKPOINT_FOR_DOC,
774
+ )
775
+
776
+
777
+ __all__ = ["FlaxGemmaForCausalLM", "FlaxGemmaModel", "FlaxGemmaPreTrainedModel"]
tasks/tasksmith-333d8be2d5aa/tests/source/src/transformers/models/gemma/modeling_gemma.py ADDED
@@ -0,0 +1,1068 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/gemma/modular_gemma.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_gemma.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+ from typing import Callable, List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ from torch import nn
26
+
27
+ from ...activations import ACT2FN
28
+ from ...cache_utils import Cache, DynamicCache, StaticCache
29
+ from ...generation import GenerationMixin
30
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
31
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
32
+ from ...modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ SequenceClassifierOutputWithPast,
36
+ TokenClassifierOutput,
37
+ )
38
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS
39
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
40
+ from ...processing_utils import Unpack
41
+ from ...utils import (
42
+ LossKwargs,
43
+ add_code_sample_docstrings,
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ logging,
47
+ replace_return_docstrings,
48
+ )
49
+ from .configuration_gemma import GemmaConfig
50
+
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+ _CHECKPOINT_FOR_DOC = "google/gemma-7b"
55
+ _CONFIG_FOR_DOC = "GemmaConfig"
56
+
57
+
58
+ class GemmaRMSNorm(nn.Module):
59
+ def __init__(self, dim: int, eps: float = 1e-6):
60
+ super().__init__()
61
+ self.eps = eps
62
+ self.weight = nn.Parameter(torch.zeros(dim))
63
+
64
+ def _norm(self, x):
65
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
66
+
67
+ def forward(self, x):
68
+ output = self._norm(x.float())
69
+ # Llama does x.to(float16) * w whilst Gemma is (x * w).to(float16)
70
+ # See https://github.com/huggingface/transformers/pull/29402
71
+ output = output * (1.0 + self.weight.float())
72
+ return output.type_as(x)
73
+
74
+ def extra_repr(self):
75
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
76
+
77
+
78
+ class GemmaMLP(nn.Module):
79
+ def __init__(self, config):
80
+ super().__init__()
81
+ self.config = config
82
+ self.hidden_size = config.hidden_size
83
+ self.intermediate_size = config.intermediate_size
84
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
85
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
86
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
87
+ self.act_fn = ACT2FN[config.hidden_act]
88
+
89
+ def forward(self, x):
90
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
91
+ return down_proj
92
+
93
+
94
+ class GemmaRotaryEmbedding(nn.Module):
95
+ def __init__(self, config: GemmaConfig, device=None):
96
+ super().__init__()
97
+ # BC: "rope_type" was originally "type"
98
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
99
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
100
+ else:
101
+ self.rope_type = "default"
102
+ self.max_seq_len_cached = config.max_position_embeddings
103
+ self.original_max_seq_len = config.max_position_embeddings
104
+
105
+ self.config = config
106
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
107
+
108
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
109
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
110
+ self.original_inv_freq = self.inv_freq
111
+
112
+ def _dynamic_frequency_update(self, position_ids, device):
113
+ """
114
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
115
+ 1 - growing beyond the cached sequence length (allow scaling)
116
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
117
+ """
118
+ seq_len = torch.max(position_ids) + 1
119
+ if seq_len > self.max_seq_len_cached: # growth
120
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
121
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
122
+ self.max_seq_len_cached = seq_len
123
+
124
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
125
+ # This .to() is needed if the model has been moved to a device after being initialized (because
126
+ # the buffer is automatically moved, but not the original copy)
127
+ self.original_inv_freq = self.original_inv_freq.to(device)
128
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
129
+ self.max_seq_len_cached = self.original_max_seq_len
130
+
131
+ @torch.no_grad()
132
+ def forward(self, x, position_ids):
133
+ if "dynamic" in self.rope_type:
134
+ self._dynamic_frequency_update(position_ids, device=x.device)
135
+
136
+ # Core RoPE block
137
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
138
+ position_ids_expanded = position_ids[:, None, :].float()
139
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
140
+ device_type = x.device.type
141
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
142
+ with torch.autocast(device_type=device_type, enabled=False):
143
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
144
+ emb = torch.cat((freqs, freqs), dim=-1)
145
+ cos = emb.cos()
146
+ sin = emb.sin()
147
+
148
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
149
+ cos = cos * self.attention_scaling
150
+ sin = sin * self.attention_scaling
151
+
152
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
153
+
154
+
155
+ def rotate_half(x):
156
+ """Rotates half the hidden dims of the input."""
157
+ x1 = x[..., : x.shape[-1] // 2]
158
+ x2 = x[..., x.shape[-1] // 2 :]
159
+ return torch.cat((-x2, x1), dim=-1)
160
+
161
+
162
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
163
+ """Applies Rotary Position Embedding to the query and key tensors.
164
+
165
+ Args:
166
+ q (`torch.Tensor`): The query tensor.
167
+ k (`torch.Tensor`): The key tensor.
168
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
169
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
170
+ position_ids (`torch.Tensor`, *optional*):
171
+ Deprecated and unused.
172
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
173
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
174
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
175
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
176
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
177
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
178
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
179
+ Returns:
180
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
181
+ """
182
+ cos = cos.unsqueeze(unsqueeze_dim)
183
+ sin = sin.unsqueeze(unsqueeze_dim)
184
+ q_embed = (q * cos) + (rotate_half(q) * sin)
185
+ k_embed = (k * cos) + (rotate_half(k) * sin)
186
+ return q_embed, k_embed
187
+
188
+
189
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
190
+ """
191
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
192
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
193
+ """
194
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
195
+ if n_rep == 1:
196
+ return hidden_states
197
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
198
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
199
+
200
+
201
+ def eager_attention_forward(
202
+ module: nn.Module,
203
+ query: torch.Tensor,
204
+ key: torch.Tensor,
205
+ value: torch.Tensor,
206
+ attention_mask: Optional[torch.Tensor],
207
+ scaling: float,
208
+ dropout: float = 0.0,
209
+ **kwargs,
210
+ ):
211
+ key_states = repeat_kv(key, module.num_key_value_groups)
212
+ value_states = repeat_kv(value, module.num_key_value_groups)
213
+
214
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
215
+ if attention_mask is not None:
216
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
217
+ attn_weights = attn_weights + causal_mask
218
+
219
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
220
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
221
+ attn_output = torch.matmul(attn_weights, value_states)
222
+ attn_output = attn_output.transpose(1, 2).contiguous()
223
+
224
+ return attn_output, attn_weights
225
+
226
+
227
+ class GemmaAttention(nn.Module):
228
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
229
+
230
+ def __init__(self, config: GemmaConfig, layer_idx: int):
231
+ super().__init__()
232
+ self.config = config
233
+ self.layer_idx = layer_idx
234
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
235
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
236
+ self.scaling = self.head_dim**-0.5
237
+ self.attention_dropout = config.attention_dropout
238
+ self.is_causal = True
239
+
240
+ self.q_proj = nn.Linear(
241
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
242
+ )
243
+ self.k_proj = nn.Linear(
244
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
245
+ )
246
+ self.v_proj = nn.Linear(
247
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
248
+ )
249
+ self.o_proj = nn.Linear(
250
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
251
+ )
252
+
253
+ def forward(
254
+ self,
255
+ hidden_states: torch.Tensor,
256
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
257
+ attention_mask: Optional[torch.Tensor],
258
+ past_key_value: Optional[Cache] = None,
259
+ cache_position: Optional[torch.LongTensor] = None,
260
+ **kwargs: Unpack[FlashAttentionKwargs],
261
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
262
+ input_shape = hidden_states.shape[:-1]
263
+ hidden_shape = (*input_shape, -1, self.head_dim)
264
+
265
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
266
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
267
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
268
+
269
+ cos, sin = position_embeddings
270
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
271
+
272
+ if past_key_value is not None:
273
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
274
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
275
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
276
+
277
+ attention_interface: Callable = eager_attention_forward
278
+ if self.config._attn_implementation != "eager":
279
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
280
+ logger.warning_once(
281
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
282
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
283
+ )
284
+ else:
285
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
286
+
287
+ attn_output, attn_weights = attention_interface(
288
+ self,
289
+ query_states,
290
+ key_states,
291
+ value_states,
292
+ attention_mask,
293
+ dropout=0.0 if not self.training else self.attention_dropout,
294
+ scaling=self.scaling,
295
+ **kwargs,
296
+ )
297
+
298
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
299
+ attn_output = self.o_proj(attn_output)
300
+ return attn_output, attn_weights
301
+
302
+
303
+ class GemmaDecoderLayer(nn.Module):
304
+ def __init__(self, config: GemmaConfig, layer_idx: int):
305
+ super().__init__()
306
+ self.hidden_size = config.hidden_size
307
+
308
+ self.self_attn = GemmaAttention(config=config, layer_idx=layer_idx)
309
+
310
+ self.mlp = GemmaMLP(config)
311
+ self.input_layernorm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
312
+ self.post_attention_layernorm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
313
+
314
+ def forward(
315
+ self,
316
+ hidden_states: torch.Tensor,
317
+ attention_mask: Optional[torch.Tensor] = None,
318
+ position_ids: Optional[torch.LongTensor] = None,
319
+ past_key_value: Optional[Cache] = None,
320
+ output_attentions: Optional[bool] = False,
321
+ use_cache: Optional[bool] = False,
322
+ cache_position: Optional[torch.LongTensor] = None,
323
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
324
+ **kwargs: Unpack[FlashAttentionKwargs],
325
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
326
+ residual = hidden_states
327
+
328
+ hidden_states = self.input_layernorm(hidden_states)
329
+
330
+ # Self Attention
331
+ hidden_states, self_attn_weights = self.self_attn(
332
+ hidden_states=hidden_states,
333
+ attention_mask=attention_mask,
334
+ position_ids=position_ids,
335
+ past_key_value=past_key_value,
336
+ output_attentions=output_attentions,
337
+ use_cache=use_cache,
338
+ cache_position=cache_position,
339
+ position_embeddings=position_embeddings,
340
+ **kwargs,
341
+ )
342
+ hidden_states = residual + hidden_states
343
+
344
+ # Fully Connected
345
+ residual = hidden_states
346
+ hidden_states = self.post_attention_layernorm(hidden_states)
347
+ hidden_states = self.mlp(hidden_states)
348
+ hidden_states = residual + hidden_states
349
+
350
+ outputs = (hidden_states,)
351
+ if output_attentions:
352
+ outputs += (self_attn_weights,)
353
+
354
+ return outputs
355
+
356
+
357
+ GEMMA_START_DOCSTRING = r"""
358
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
359
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
360
+ etc.)
361
+
362
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
363
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
364
+ and behavior.
365
+
366
+ Parameters:
367
+ config ([`GemmaConfig`]):
368
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
369
+ load the weights associated with the model, only the configuration. Check out the
370
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
371
+ """
372
+
373
+
374
+ @add_start_docstrings(
375
+ "The bare Gemma Model outputting raw hidden-states without any specific head on top.",
376
+ GEMMA_START_DOCSTRING,
377
+ )
378
+ class GemmaPreTrainedModel(PreTrainedModel):
379
+ config_class = GemmaConfig
380
+ base_model_prefix = "model"
381
+ supports_gradient_checkpointing = True
382
+ _no_split_modules = ["GemmaDecoderLayer"]
383
+ _skip_keys_device_placement = ["past_key_values"]
384
+ _supports_flash_attn_2 = True
385
+ _supports_sdpa = True
386
+ _supports_flex_attn = True
387
+ _supports_cache_class = True
388
+ _supports_quantized_cache = True
389
+ _supports_static_cache = True
390
+
391
+ def _init_weights(self, module):
392
+ std = self.config.initializer_range
393
+ if isinstance(module, nn.Linear):
394
+ module.weight.data.normal_(mean=0.0, std=std)
395
+ if module.bias is not None:
396
+ module.bias.data.zero_()
397
+ elif isinstance(module, nn.Embedding):
398
+ module.weight.data.normal_(mean=0.0, std=std)
399
+ if module.padding_idx is not None:
400
+ module.weight.data[module.padding_idx].zero_()
401
+
402
+
403
+ GEMMA_INPUTS_DOCSTRING = r"""
404
+ Args:
405
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
406
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
407
+ it.
408
+
409
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
410
+ [`PreTrainedTokenizer.__call__`] for details.
411
+
412
+ [What are input IDs?](../glossary#input-ids)
413
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
414
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
415
+
416
+ - 1 for tokens that are **not masked**,
417
+ - 0 for tokens that are **masked**.
418
+
419
+ [What are attention masks?](../glossary#attention-mask)
420
+
421
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
422
+ [`PreTrainedTokenizer.__call__`] for details.
423
+
424
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
425
+ `past_key_values`).
426
+
427
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
428
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
429
+ information on the default strategy.
430
+
431
+ - 1 indicates the head is **not masked**,
432
+ - 0 indicates the head is **masked**.
433
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
434
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
435
+ config.n_positions - 1]`.
436
+
437
+ [What are position IDs?](../glossary#position-ids)
438
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
439
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
440
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
441
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
442
+
443
+ Two formats are allowed:
444
+ - a [`~cache_utils.Cache`] instance, see our
445
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
446
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
447
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
448
+ cache format.
449
+
450
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
451
+ legacy cache format will be returned.
452
+
453
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
454
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
455
+ of shape `(batch_size, sequence_length)`.
456
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
457
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
458
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
459
+ model's internal embedding lookup matrix.
460
+ use_cache (`bool`, *optional*):
461
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
462
+ `past_key_values`).
463
+ output_attentions (`bool`, *optional*):
464
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
465
+ tensors for more detail.
466
+ output_hidden_states (`bool`, *optional*):
467
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
468
+ more detail.
469
+ return_dict (`bool`, *optional*):
470
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
471
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
472
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
473
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
474
+ the complete sequence length.
475
+ """
476
+
477
+
478
+ @add_start_docstrings(
479
+ "The bare Gemma Model outputting raw hidden-states without any specific head on top.",
480
+ GEMMA_START_DOCSTRING,
481
+ )
482
+ class GemmaModel(GemmaPreTrainedModel):
483
+ """
484
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`GemmaDecoderLayer`]
485
+
486
+ Args:
487
+ config: GemmaConfig
488
+ """
489
+
490
+ def __init__(self, config: GemmaConfig):
491
+ super().__init__(config)
492
+ self.padding_idx = config.pad_token_id
493
+ self.vocab_size = config.vocab_size
494
+
495
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
496
+ self.layers = nn.ModuleList(
497
+ [GemmaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
498
+ )
499
+ self.norm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
500
+ self.rotary_emb = GemmaRotaryEmbedding(config=config)
501
+ self.gradient_checkpointing = False
502
+
503
+ # Initialize weights and apply final processing
504
+ self.post_init()
505
+
506
+ def get_input_embeddings(self):
507
+ return self.embed_tokens
508
+
509
+ def set_input_embeddings(self, value):
510
+ self.embed_tokens = value
511
+
512
+ @add_start_docstrings_to_model_forward(GEMMA_INPUTS_DOCSTRING)
513
+ def forward(
514
+ self,
515
+ input_ids: torch.LongTensor = None,
516
+ attention_mask: Optional[torch.Tensor] = None,
517
+ position_ids: Optional[torch.LongTensor] = None,
518
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
519
+ inputs_embeds: Optional[torch.FloatTensor] = None,
520
+ use_cache: Optional[bool] = None,
521
+ output_attentions: Optional[bool] = None,
522
+ output_hidden_states: Optional[bool] = None,
523
+ return_dict: Optional[bool] = None,
524
+ cache_position: Optional[torch.LongTensor] = None,
525
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
526
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
527
+ output_hidden_states = (
528
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
529
+ )
530
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
531
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
532
+
533
+ if (input_ids is None) ^ (inputs_embeds is not None):
534
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
535
+
536
+ if self.gradient_checkpointing and self.training and use_cache:
537
+ logger.warning_once(
538
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
539
+ )
540
+ use_cache = False
541
+
542
+ if inputs_embeds is None:
543
+ inputs_embeds = self.embed_tokens(input_ids)
544
+
545
+ if use_cache and past_key_values is None:
546
+ past_key_values = DynamicCache()
547
+
548
+ if cache_position is None:
549
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
550
+ cache_position = torch.arange(
551
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
552
+ )
553
+
554
+ if position_ids is None:
555
+ position_ids = cache_position.unsqueeze(0)
556
+
557
+ causal_mask = self._update_causal_mask(
558
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
559
+ )
560
+
561
+ # embed positions
562
+ hidden_states = inputs_embeds
563
+
564
+ # create position embeddings to be shared across the decoder layers
565
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
566
+
567
+ # normalized
568
+ # Gemma downcasts the below to float16, causing sqrt(3072)=55.4256 to become 55.5
569
+ # See https://github.com/huggingface/transformers/pull/29402
570
+ normalizer = torch.tensor(self.config.hidden_size**0.5, dtype=hidden_states.dtype)
571
+ hidden_states = hidden_states * normalizer
572
+
573
+ # decoder layers
574
+ all_hidden_states = () if output_hidden_states else None
575
+ all_self_attns = () if output_attentions else None
576
+
577
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
578
+ if output_hidden_states:
579
+ all_hidden_states += (hidden_states,)
580
+
581
+ if self.gradient_checkpointing and self.training:
582
+ layer_outputs = self._gradient_checkpointing_func(
583
+ decoder_layer.__call__,
584
+ hidden_states,
585
+ causal_mask,
586
+ position_ids,
587
+ past_key_values,
588
+ output_attentions,
589
+ use_cache,
590
+ cache_position,
591
+ position_embeddings,
592
+ )
593
+ else:
594
+ layer_outputs = decoder_layer(
595
+ hidden_states,
596
+ attention_mask=causal_mask,
597
+ position_ids=position_ids,
598
+ past_key_value=past_key_values,
599
+ output_attentions=output_attentions,
600
+ use_cache=use_cache,
601
+ cache_position=cache_position,
602
+ position_embeddings=position_embeddings,
603
+ )
604
+
605
+ hidden_states = layer_outputs[0]
606
+
607
+ if output_attentions:
608
+ all_self_attns += (layer_outputs[1],)
609
+
610
+ hidden_states = self.norm(hidden_states)
611
+
612
+ # add hidden states from the last decoder layer
613
+ if output_hidden_states:
614
+ all_hidden_states += (hidden_states,)
615
+
616
+ output = BaseModelOutputWithPast(
617
+ last_hidden_state=hidden_states,
618
+ past_key_values=past_key_values if use_cache else None,
619
+ hidden_states=all_hidden_states,
620
+ attentions=all_self_attns,
621
+ )
622
+ return output if return_dict else output.to_tuple()
623
+
624
+ def _update_causal_mask(
625
+ self,
626
+ attention_mask: torch.Tensor,
627
+ input_tensor: torch.Tensor,
628
+ cache_position: torch.Tensor,
629
+ past_key_values: Cache,
630
+ output_attentions: bool,
631
+ ):
632
+ if self.config._attn_implementation == "flash_attention_2":
633
+ if attention_mask is not None and (attention_mask == 0.0).any():
634
+ return attention_mask
635
+ return None
636
+
637
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
638
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
639
+ # to infer the attention mask.
640
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
641
+ using_static_cache = isinstance(past_key_values, StaticCache)
642
+
643
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
644
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
645
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
646
+ attention_mask,
647
+ inputs_embeds=input_tensor,
648
+ past_key_values_length=past_seen_tokens,
649
+ is_training=self.training,
650
+ ):
651
+ return None
652
+
653
+ dtype, device = input_tensor.dtype, input_tensor.device
654
+ sequence_length = input_tensor.shape[1]
655
+ if using_static_cache:
656
+ target_length = past_key_values.get_max_cache_shape()
657
+ else:
658
+ target_length = (
659
+ attention_mask.shape[-1]
660
+ if isinstance(attention_mask, torch.Tensor)
661
+ else past_seen_tokens + sequence_length + 1
662
+ )
663
+
664
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
665
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
666
+ attention_mask,
667
+ sequence_length=sequence_length,
668
+ target_length=target_length,
669
+ dtype=dtype,
670
+ device=device,
671
+ cache_position=cache_position,
672
+ batch_size=input_tensor.shape[0],
673
+ )
674
+
675
+ if (
676
+ self.config._attn_implementation == "sdpa"
677
+ and attention_mask is not None
678
+ and attention_mask.device.type == "cuda"
679
+ and not output_attentions
680
+ ):
681
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
682
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
683
+ # Details: https://github.com/pytorch/pytorch/issues/110213
684
+ min_dtype = torch.finfo(dtype).min
685
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
686
+
687
+ return causal_mask
688
+
689
+ @staticmethod
690
+ def _prepare_4d_causal_attention_mask_with_cache_position(
691
+ attention_mask: torch.Tensor,
692
+ sequence_length: int,
693
+ target_length: int,
694
+ dtype: torch.dtype,
695
+ device: torch.device,
696
+ cache_position: torch.Tensor,
697
+ batch_size: int,
698
+ **kwargs,
699
+ ):
700
+ """
701
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
702
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
703
+
704
+ Args:
705
+ attention_mask (`torch.Tensor`):
706
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
707
+ `(batch_size, 1, query_length, key_value_length)`.
708
+ sequence_length (`int`):
709
+ The sequence length being processed.
710
+ target_length (`int`):
711
+ The target length: when generating with static cache, the mask should be as long as the static cache,
712
+ to account for the 0 padding, the part of the cache that is not filled yet.
713
+ dtype (`torch.dtype`):
714
+ The dtype to use for the 4D attention mask.
715
+ device (`torch.device`):
716
+ The device to plcae the 4D attention mask on.
717
+ cache_position (`torch.Tensor`):
718
+ Indices depicting the position of the input sequence tokens in the sequence.
719
+ batch_size (`torch.Tensor`):
720
+ Batch size.
721
+ """
722
+ if attention_mask is not None and attention_mask.dim() == 4:
723
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
724
+ causal_mask = attention_mask
725
+ else:
726
+ min_dtype = torch.finfo(dtype).min
727
+ causal_mask = torch.full(
728
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
729
+ )
730
+ if sequence_length != 1:
731
+ causal_mask = torch.triu(causal_mask, diagonal=1)
732
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
733
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
734
+ if attention_mask is not None:
735
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
736
+ mask_length = attention_mask.shape[-1]
737
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
738
+ padding_mask = padding_mask == 0
739
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
740
+ padding_mask, min_dtype
741
+ )
742
+
743
+ return causal_mask
744
+
745
+
746
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
747
+
748
+
749
+ class GemmaForCausalLM(GemmaPreTrainedModel, GenerationMixin):
750
+ _tied_weights_keys = ["lm_head.weight"]
751
+ _tp_plan = {"lm_head": "colwise_rep"}
752
+
753
+ def __init__(self, config):
754
+ super().__init__(config)
755
+ self.model = GemmaModel(config)
756
+ self.vocab_size = config.vocab_size
757
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
758
+
759
+ # Initialize weights and apply final processing
760
+ self.post_init()
761
+
762
+ def get_input_embeddings(self):
763
+ return self.model.embed_tokens
764
+
765
+ def set_input_embeddings(self, value):
766
+ self.model.embed_tokens = value
767
+
768
+ def get_output_embeddings(self):
769
+ return self.lm_head
770
+
771
+ def set_output_embeddings(self, new_embeddings):
772
+ self.lm_head = new_embeddings
773
+
774
+ def set_decoder(self, decoder):
775
+ self.model = decoder
776
+
777
+ def get_decoder(self):
778
+ return self.model
779
+
780
+ @add_start_docstrings_to_model_forward(GEMMA_INPUTS_DOCSTRING)
781
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
782
+ def forward(
783
+ self,
784
+ input_ids: torch.LongTensor = None,
785
+ attention_mask: Optional[torch.Tensor] = None,
786
+ position_ids: Optional[torch.LongTensor] = None,
787
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
788
+ inputs_embeds: Optional[torch.FloatTensor] = None,
789
+ labels: Optional[torch.LongTensor] = None,
790
+ use_cache: Optional[bool] = None,
791
+ output_attentions: Optional[bool] = None,
792
+ output_hidden_states: Optional[bool] = None,
793
+ return_dict: Optional[bool] = None,
794
+ cache_position: Optional[torch.LongTensor] = None,
795
+ num_logits_to_keep: int = 0,
796
+ **kwargs: Unpack[KwargsForCausalLM],
797
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
798
+ r"""
799
+ Args:
800
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
801
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
802
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
803
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
804
+
805
+ num_logits_to_keep (`int`, *optional*):
806
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
807
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
808
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
809
+
810
+ Returns:
811
+
812
+ Example:
813
+
814
+ ```python
815
+ >>> from transformers import AutoTokenizer, GemmaForCausalLM
816
+
817
+ >>> model = GemmaForCausalLM.from_pretrained("google/gemma-7b")
818
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b")
819
+
820
+ >>> prompt = "What is your favorite condiment?"
821
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
822
+
823
+ >>> # Generate
824
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
825
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
826
+ "What is your favorite condiment?"
827
+ ```"""
828
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
829
+ output_hidden_states = (
830
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
831
+ )
832
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
833
+
834
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
835
+ outputs = self.model(
836
+ input_ids=input_ids,
837
+ attention_mask=attention_mask,
838
+ position_ids=position_ids,
839
+ past_key_values=past_key_values,
840
+ inputs_embeds=inputs_embeds,
841
+ use_cache=use_cache,
842
+ output_attentions=output_attentions,
843
+ output_hidden_states=output_hidden_states,
844
+ return_dict=return_dict,
845
+ cache_position=cache_position,
846
+ **kwargs,
847
+ )
848
+
849
+ hidden_states = outputs[0]
850
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
851
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
852
+
853
+ loss = None
854
+ if labels is not None:
855
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
856
+
857
+ if not return_dict:
858
+ output = (logits,) + outputs[1:]
859
+ return (loss,) + output if loss is not None else output
860
+
861
+ return CausalLMOutputWithPast(
862
+ loss=loss,
863
+ logits=logits,
864
+ past_key_values=outputs.past_key_values,
865
+ hidden_states=outputs.hidden_states,
866
+ attentions=outputs.attentions,
867
+ )
868
+
869
+
870
+ @add_start_docstrings(
871
+ """
872
+ The Gemma Model transformer with a sequence classification head on top (linear layer).
873
+
874
+ [`GemmaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
875
+ (e.g. GPT-2) do.
876
+
877
+ Since it does classification on the last token, it requires to know the position of the last token. If a
878
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
879
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
880
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
881
+ each row of the batch).
882
+ """,
883
+ GEMMA_START_DOCSTRING,
884
+ )
885
+ class GemmaForSequenceClassification(GemmaPreTrainedModel):
886
+ def __init__(self, config):
887
+ super().__init__(config)
888
+ self.num_labels = config.num_labels
889
+ self.model = GemmaModel(config)
890
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
891
+
892
+ # Initialize weights and apply final processing
893
+ self.post_init()
894
+
895
+ def get_input_embeddings(self):
896
+ return self.model.embed_tokens
897
+
898
+ def set_input_embeddings(self, value):
899
+ self.model.embed_tokens = value
900
+
901
+ @add_start_docstrings_to_model_forward(GEMMA_INPUTS_DOCSTRING)
902
+ def forward(
903
+ self,
904
+ input_ids: Optional[torch.LongTensor] = None,
905
+ attention_mask: Optional[torch.Tensor] = None,
906
+ position_ids: Optional[torch.LongTensor] = None,
907
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
908
+ inputs_embeds: Optional[torch.FloatTensor] = None,
909
+ labels: Optional[torch.LongTensor] = None,
910
+ use_cache: Optional[bool] = None,
911
+ output_attentions: Optional[bool] = None,
912
+ output_hidden_states: Optional[bool] = None,
913
+ return_dict: Optional[bool] = None,
914
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
915
+ r"""
916
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
917
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
918
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
919
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
920
+ """
921
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
922
+
923
+ transformer_outputs = self.model(
924
+ input_ids,
925
+ attention_mask=attention_mask,
926
+ position_ids=position_ids,
927
+ past_key_values=past_key_values,
928
+ inputs_embeds=inputs_embeds,
929
+ use_cache=use_cache,
930
+ output_attentions=output_attentions,
931
+ output_hidden_states=output_hidden_states,
932
+ return_dict=return_dict,
933
+ )
934
+ hidden_states = transformer_outputs[0]
935
+ logits = self.score(hidden_states)
936
+
937
+ if input_ids is not None:
938
+ batch_size = input_ids.shape[0]
939
+ else:
940
+ batch_size = inputs_embeds.shape[0]
941
+
942
+ if self.config.pad_token_id is None and batch_size != 1:
943
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
944
+ if self.config.pad_token_id is None:
945
+ sequence_lengths = -1
946
+ else:
947
+ if input_ids is not None:
948
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
949
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
950
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
951
+ sequence_lengths = sequence_lengths.to(logits.device)
952
+ else:
953
+ sequence_lengths = -1
954
+
955
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
956
+
957
+ loss = None
958
+ if labels is not None:
959
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
960
+
961
+ if not return_dict:
962
+ output = (pooled_logits,) + transformer_outputs[1:]
963
+ return ((loss,) + output) if loss is not None else output
964
+
965
+ return SequenceClassifierOutputWithPast(
966
+ loss=loss,
967
+ logits=pooled_logits,
968
+ past_key_values=transformer_outputs.past_key_values,
969
+ hidden_states=transformer_outputs.hidden_states,
970
+ attentions=transformer_outputs.attentions,
971
+ )
972
+
973
+
974
+ @add_start_docstrings(
975
+ """
976
+ The Gemma Model transformer with a token classification head on top (a linear layer on top of the hidden-states
977
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
978
+ """,
979
+ GEMMA_START_DOCSTRING,
980
+ )
981
+ class GemmaForTokenClassification(GemmaPreTrainedModel):
982
+ def __init__(self, config):
983
+ super().__init__(config)
984
+ self.num_labels = config.num_labels
985
+ self.model = GemmaModel(config)
986
+ if getattr(config, "classifier_dropout", None) is not None:
987
+ classifier_dropout = config.classifier_dropout
988
+ elif getattr(config, "hidden_dropout", None) is not None:
989
+ classifier_dropout = config.hidden_dropout
990
+ else:
991
+ classifier_dropout = 0.1
992
+ self.dropout = nn.Dropout(classifier_dropout)
993
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
994
+
995
+ # Initialize weights and apply final processing
996
+ self.post_init()
997
+
998
+ def get_input_embeddings(self):
999
+ return self.model.embed_tokens
1000
+
1001
+ def set_input_embeddings(self, value):
1002
+ self.model.embed_tokens = value
1003
+
1004
+ @add_start_docstrings_to_model_forward(GEMMA_INPUTS_DOCSTRING)
1005
+ @add_code_sample_docstrings(
1006
+ checkpoint=_CHECKPOINT_FOR_DOC,
1007
+ output_type=TokenClassifierOutput,
1008
+ config_class=_CONFIG_FOR_DOC,
1009
+ )
1010
+ def forward(
1011
+ self,
1012
+ input_ids: Optional[torch.LongTensor] = None,
1013
+ attention_mask: Optional[torch.Tensor] = None,
1014
+ position_ids: Optional[torch.LongTensor] = None,
1015
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1016
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1017
+ labels: Optional[torch.LongTensor] = None,
1018
+ use_cache: Optional[bool] = None,
1019
+ output_attentions: Optional[bool] = None,
1020
+ output_hidden_states: Optional[bool] = None,
1021
+ return_dict: Optional[bool] = None,
1022
+ ) -> Union[Tuple, TokenClassifierOutput]:
1023
+ r"""
1024
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1025
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1026
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1027
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1028
+ """
1029
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1030
+
1031
+ outputs = self.model(
1032
+ input_ids,
1033
+ attention_mask=attention_mask,
1034
+ position_ids=position_ids,
1035
+ past_key_values=past_key_values,
1036
+ inputs_embeds=inputs_embeds,
1037
+ use_cache=use_cache,
1038
+ output_attentions=output_attentions,
1039
+ output_hidden_states=output_hidden_states,
1040
+ return_dict=return_dict,
1041
+ )
1042
+ sequence_output = outputs[0]
1043
+ sequence_output = self.dropout(sequence_output)
1044
+ logits = self.score(sequence_output)
1045
+
1046
+ loss = None
1047
+ if labels is not None:
1048
+ loss = self.loss_function(logits, labels, self.config)
1049
+
1050
+ if not return_dict:
1051
+ output = (logits,) + outputs[2:]
1052
+ return ((loss,) + output) if loss is not None else output
1053
+
1054
+ return TokenClassifierOutput(
1055
+ loss=loss,
1056
+ logits=logits,
1057
+ hidden_states=outputs.hidden_states,
1058
+ attentions=outputs.attentions,
1059
+ )
1060
+
1061
+
1062
+ __all__ = [
1063
+ "GemmaModel",
1064
+ "GemmaForCausalLM",
1065
+ "GemmaForSequenceClassification",
1066
+ "GemmaForTokenClassification",
1067
+ "GemmaPreTrainedModel",
1068
+ ]